31#include "qgsgdalprovider.h"
73#include <QApplication>
81#include <QFontMetrics>
88#include <QRegularExpression>
93#include "moc_qgsrasterlayer.cpp"
95using namespace Qt::StringLiterals;
104#define ERR( message ) QGS_ERROR_MESSAGE( message, "Raster layer" )
118 , QSTRING_NOT_SET( u
"Not Set"_s )
119 , TRSTRING_NOT_SET( tr(
"Not Set" ) )
131 , QSTRING_NOT_SET( u
"Not Set"_s )
132 , TRSTRING_NOT_SET( tr(
"Not Set" ) )
149 setDataSource( uri, baseName, providerKey, providerOptions, providerFlags );
153 mTemporalProperties->setDefaultsFromDataProviderTemporalCapabilities( mDataProvider->temporalCapabilities() );
175 options.transformContext = mDataProvider->transformContext();
179 layer->mElevationProperties = mElevationProperties->clone();
180 layer->mElevationProperties->setParent( layer.get() );
185 for (
int i = 1; i < mPipe->size(); i++ )
187 if ( mPipe->at( i ) )
188 layer->pipe()->set( mPipe->at( i )->clone() );
190 layer->pipe()->setDataDefinedProperties( mPipe->dataDefinedProperties() );
191 layer->setResamplingStage( mPipe->resamplingStage() );
192 if ( mDataProvider && layer->dataProvider() )
194 layer->dataProvider()->setZoomedInResamplingMethod( mDataProvider->zoomedInResamplingMethod() );
195 layer->dataProvider()->setZoomedOutResamplingMethod( mDataProvider->zoomedOutResamplingMethod() );
198 layer->setLabelsEnabled( mLabelsEnabled );
200 layer->setLabeling( mLabeling->clone() );
202 return layer.release();
209 if ( !mElevationProperties->isEnabled() )
223 const bool myIsValid = QgsGdalProvider::isValidRasterFileName( fileNameQString, retErrMsg );
238 const QFileInfo fi(
name );
244 t = fi.lastModified();
271 if ( !mDataProvider )
273 return mDataProvider->bandCount();
280 if ( !mDataProvider )
282 return mDataProvider->generateBandName( bandNo );
289 if ( !mDataProvider )
291 return mDataProvider->attributeTable( bandNoInt );
298 if ( !mDataProvider )
302 for (
int bandNo = 1; bandNo <=
bandCount(); ++bandNo )
330 return mDataProvider;
337 return mDataProvider;
346 mDataProvider->reloadData();
373 bool restoreOldResamplingStage =
false;
386 restoreOldResamplingStage =
true;
395 drawer.
draw( theQPainter, rasterViewPort, qgsMapToPixel );
397 if ( restoreOldResamplingStage )
402 QgsDebugMsgLevel( u
"total raster draw time (ms): %1"_s.arg( time.elapsed(), 5 ), 4 );
410 return renderer ?
renderer->legendSymbologyItems() : QList< QPair< QString, QColor > >();
418 if ( !mDataProvider )
422 QString myMetadata = u
"<html><head></head>\n<body>\n"_s;
427 myMetadata += u
"<h1>"_s + tr(
"Information from provider" ) + u
"</h1>\n<hr>\n"_s + u
"<table class=\"list-view\">\n"_s;
429 myMetadata += u
"\n"_s
432 u
"<tr><td class=\"highlight\">"_s
440 u
"<tr><td class=\"highlight\">"_s % tr(
"Width" ) % u
"</td><td>"_s;
442 myMetadata += QString::number(
width() );
444 myMetadata += tr(
"n/a" );
445 myMetadata += u
"</td></tr>\n"_s %
448 u
"<tr><td class=\"highlight\">"_s
452 myMetadata += QString::number(
height() );
454 myMetadata += tr(
"n/a" );
455 myMetadata += u
"</td></tr>\n"_s
459 u
"<tr><td class=\"highlight\">"_s % tr(
"Data type" ) % u
"</td><td>"_s;
461 switch ( mDataProvider->sourceDataType( 1 ) )
464 myMetadata += tr(
"Byte - Eight bit unsigned integer" );
467 myMetadata += tr(
"Int8 - Eight bit signed integer" );
470 myMetadata += tr(
"UInt16 - Sixteen bit unsigned integer " );
473 myMetadata += tr(
"Int16 - Sixteen bit signed integer " );
476 myMetadata += tr(
"UInt32 - Thirty two bit unsigned integer " );
479 myMetadata += tr(
"Int32 - Thirty two bit signed integer " );
482 myMetadata += tr(
"Float32 - Thirty two bit floating point " );
485 myMetadata += tr(
"Float64 - Sixty four bit floating point " );
488 myMetadata += tr(
"CInt16 - Complex Int16 " );
491 myMetadata += tr(
"CInt32 - Complex Int32 " );
494 myMetadata += tr(
"CFloat32 - Complex Float32 " );
497 myMetadata += tr(
"CFloat64 - Complex Float64 " );
500 myMetadata += tr(
"Could not determine raster data type." );
502 myMetadata += u
"</td></tr>\n"_s
506 mDataProvider->htmlMetadata()
510 u
"</table>\n<br><br>"_s;
516 myMetadata += u
"<h1>"_s
517 % tr(
"Identification" )
540 u
"</table>\n<br><br><h1>"_s
542 % u
"</h1>\n<hr>\n<table class=\"list-view\">\n"_s
546 u
"<tr><td class=\"highlight\">"_s % tr(
"Band count" ) % u
"</td><td>"_s % QString::number(
bandCount() ) % u
"</td></tr>\n"_s;
549 myMetadata += u
"</table>\n<br><table width=\"100%\" class=\"tabular-view\">\n"_s
567 rowClass = u
"class=\"odd-row\""_s;
569 myMetadata += u
"<tr "_s % rowClass % u
"><td>"_s % QString::number( i ) % u
"</td><td>"_s %
bandName( i ) % u
"</td><td>"_s;
572 myMetadata += QString::number(
dataProvider()->sourceNoDataValue( i ) );
574 myMetadata += tr(
"n/a" );
575 myMetadata +=
"</td>"_L1;
580 myMetadata += u
"<td>"_s % QString::number( myRasterBandStats.
minimumValue,
'f', 10 ) % u
"</td>"_s % u
"<td>"_s % QString::number( myRasterBandStats.
maximumValue,
'f', 10 ) % u
"</td>"_s;
584 myMetadata += u
"<td>"_s % tr(
"n/a" ) % u
"</td><td>"_s % tr(
"n/a" ) % u
"</td>"_s;
587 myMetadata +=
"</tr>\n"_L1;
591 myMetadata += u
"</table>\n<br><br>"_s
640 const QList<QgsColorRampShader::ColorRampItem> myColorRampItemList = mDataProvider->colorTable( bandNumber );
641 if ( !myColorRampItemList.isEmpty() )
647 const int mySize = 100;
648 QPixmap myPalettePixmap( mySize, mySize );
649 QPainter myQPainter( &myPalettePixmap );
651 QImage myQImage = QImage( mySize, mySize, QImage::Format_RGB32 );
653 myPalettePixmap.fill();
655 const double myStep = (
static_cast< double >( myColorRampItemList.size() ) - 1 ) /
static_cast< double >( mySize * mySize );
656 double myValue = 0.0;
657 for (
int myRow = 0; myRow < mySize; myRow++ )
659 QRgb *myLineBuffer =
reinterpret_cast< QRgb *
>( myQImage.scanLine( myRow ) );
660 for (
int myCol = 0; myCol < mySize; myCol++ )
662 myValue = myStep *
static_cast< double >( myCol + myRow * mySize );
664 myShader.
shade( myValue, &c1, &c2, &c3, &c4 );
665 myLineBuffer[myCol] = qRgba( c1, c2, c3, c4 );
669 myQPainter.drawImage( 0, 0, myQImage );
670 return myPalettePixmap;
672 const QPixmap myNullPixmap;
678 const QPixmap myNullPixmap;
695 return mDataProvider->extent().width() / mDataProvider->xSize();
706 return mDataProvider->extent().height() / mDataProvider->ySize();
715 if ( !mPipe->renderer() || mPipe->renderer()->opacity() ==
opacity )
718 mPipe->renderer()->setOpacity(
opacity );
727 return mPipe->renderer() ? mPipe->renderer()->opacity() : 1.0;
730void QgsRasterLayer::init()
753 mPipe = std::make_unique< QgsRasterPipe >();
754 mDataProvider =
nullptr;
770 mDataProvider = qobject_cast< QgsRasterDataProvider * >(
mPreloadedProvider.release() );
774 std::unique_ptr< QgsScopedRuntimeProfile > profile;
776 profile = std::make_unique< QgsScopedRuntimeProfile >( tr(
"Create %1 provider" ).arg( provider ), u
"projectload"_s );
781 if ( !mDataProvider )
788 mDataProvider->setParent(
this );
791 if ( !mPipe->set( mDataProvider ) )
794 mDataProvider =
nullptr;
799 if ( !mDataProvider->isValid() )
812 if ( provider ==
"gdal"_L1 )
843 QgsDebugMsgLevel(
"bandCount = " + QString::number( mDataProvider->bandCount() ), 4 );
845 const int bandCount = mDataProvider->bandCount();
892 QString errorMessage;
893 bool hasRat { mDataProvider->readNativeAttributeTable( &errorMessage ) };
896 errorMessage.clear();
897 QgsDebugMsgLevel(
"Native Raster Raster Attribute Table read failed " + errorMessage, 2 );
898 if ( QFile::exists( mDataProvider->dataSourceUri() +
".vat.dbf" ) )
900 auto rat = std::make_unique<QgsRasterAttributeTable>();
901 hasRat = rat->readFromFile( mDataProvider->dataSourceUri() +
".vat.dbf", &errorMessage );
904 if ( rat->isValid( &errorMessage ) )
906 mDataProvider->setAttributeTable( 1, rat.release() );
907 QgsDebugMsgLevel(
"DBF Raster Attribute Table successfully read from " + mDataProvider->dataSourceUri() +
".vat.dbf", 2 );
911 QgsDebugMsgLevel(
"DBF Raster Attribute Table is not valid, skipping: " + errorMessage, 2 );
916 QgsDebugMsgLevel(
"DBF Raster Attribute Table read failed " + errorMessage, 2 );
925 switch ( mRasterType )
943 const QList<QgsColorRampShader::ColorRampItem> colorTable = mDataProvider->colorTable( 1 );
975 for (
int bandNo = 1; bandNo <= mDataProvider->bandCount(); bandNo++ )
979 if (
auto *lRenderer = mPipe->renderer() )
981 lRenderer->setAlphaBand( bandNo );
1000 if ( resampling ==
"bilinear"_L1 )
1005 else if ( resampling ==
"cubic"_L1 )
1011 if ( resampling ==
"bilinear"_L1 )
1019 mDataProvider->setMaxOversampling( maxOversampling );
1033 mPipe->set( projector );
1061 mElevationProperties->setEnabled(
true );
1075 if ( mDataProvider->supportsSubsetString() )
1088 const bool hadRenderer(
renderer() );
1090 QDomImplementation domImplementation;
1091 QDomDocumentType documentType;
1094 bool loadDefaultStyleFlag =
false;
1097 loadDefaultStyleFlag =
true;
1101 if ( hadRenderer && !loadDefaultStyleFlag )
1103 documentType = domImplementation.createDocumentType( u
"qgis"_s, u
"http://mrcc.com/qgis.dtd"_s, u
"SYSTEM"_s );
1105 QDomDocument doc = QDomDocument( documentType );
1106 QDomElement styleElem = doc.createElement( u
"qgis"_s );
1108 const QgsReadWriteContext writeContext;
1111 QgsDebugError( u
"Could not store symbology for layer %1: %2"_s.arg(
name(), errorMsg ) );
1115 doc.appendChild( styleElem );
1117 mOriginalStyleDocument = doc;
1118 mOriginalStyleElement = styleElem;
1122 if ( mDataProvider )
1123 closeDataProvider();
1127 for (
int i = mPipe->size() - 1; i >= 0; --i )
1137 if ( mDataProvider )
1143 bool defaultLoadedFlag =
false;
1144 bool restoredStyle =
false;
1145 if ( loadDefaultStyleFlag )
1149 else if ( !mOriginalStyleElement.isNull() )
1151 QgsReadWriteContext readContext;
1152 if ( !
readSymbology( mOriginalStyleElement, errorMsg, readContext ) )
1154 QgsDebugError( u
"Could not restore symbology for layer %1: %2"_s.arg(
name() ).arg( errorMsg ) );
1158 restoredStyle =
true;
1165 if ( !defaultLoadedFlag && !restoredStyle )
1172void QgsRasterLayer::writeRasterAttributeTableExternalPaths( QDomNode &layerNode, QDomDocument &doc,
const QgsReadWriteContext &context )
const
1178 QDomElement elem = doc.createElement( u
"FileBasedAttributeTables"_s );
1179 for (
int bandNo = 1; bandNo <=
bandCount(); bandNo++ )
1183 QDomElement ratElem = doc.createElement( u
"AttributeTable"_s );
1184 ratElem.setAttribute( u
"band"_s, bandNo );
1186 elem.appendChild( ratElem );
1189 layerNode.appendChild( elem );
1193void QgsRasterLayer::readRasterAttributeTableExternalPaths(
const QDomNode &layerNode,
QgsReadWriteContext &context )
const
1195 const QDomElement ratsElement = layerNode.firstChildElement( u
"FileBasedAttributeTables"_s );
1196 if ( !ratsElement.isNull() && ratsElement.childNodes().count() > 0 )
1198 const QDomNodeList ratElements { ratsElement.childNodes() };
1199 for (
int idx = 0; idx < ratElements.count(); idx++ )
1201 const QDomNode ratElement { ratElements.at( idx ) };
1202 if ( ratElement.attributes().contains( u
"band"_s ) && ratElement.attributes().contains( u
"path"_s ) )
1205 const int band { ratElement.attributes().namedItem( u
"band"_s ).nodeValue().toInt( &ok ) };
1208 if ( !ok || band <= 0 || band >
bandCount() )
1210 QgsMessageLog::logMessage( tr(
"Error reading raster attribute table: invalid band %1." ).arg( band ), tr(
"Raster" ) );
1214 const QString path { context.
pathResolver().
readPath( ratElement.attributes().namedItem( u
"path"_s ).nodeValue() ) };
1215 if ( !QFile::exists( path ) )
1217 QgsMessageLog::logMessage( tr(
"Error loading raster attribute table, file not found: %1." ).arg( path ), tr(
"Raster" ) );
1221 auto rat = std::make_unique<QgsRasterAttributeTable>();
1222 QString errorMessage;
1223 if ( !rat->readFromFile( path, &errorMessage ) )
1225 QgsMessageLog::logMessage( tr(
"Error loading raster attribute table from path %1: %2" ).arg( path, errorMessage ), tr(
"Raster" ) );
1230 mDataProvider->setAttributeTable( band, rat.release() );
1236void QgsRasterLayer::closeDataProvider()
1241 mPipe->remove( mDataProvider );
1242 mDataProvider =
nullptr;
1256 return mDataProvider ? mDataProvider->ignoreExtents() :
false;
1263 return mTemporalProperties;
1270 return mElevationProperties;
1289 if ( !rasterRenderer || !mDataProvider )
1295 QList<QgsContrastEnhancement *> myEnhancements;
1296 QgsRasterMinMaxOrigin myMinMaxOrigin;
1297 QgsRasterRenderer *myRasterRenderer =
nullptr;
1298 QgsSingleBandGrayRenderer *myGrayRenderer =
nullptr;
1299 QgsSingleBandPseudoColorRenderer *myPseudoColorRenderer =
nullptr;
1300 QgsMultiBandColorRenderer *myMultiBandRenderer =
nullptr;
1301 const QString rendererType = rasterRenderer->
type();
1302 if ( rendererType ==
"singlebandgray"_L1 )
1304 myGrayRenderer =
dynamic_cast<QgsSingleBandGrayRenderer *
>( rasterRenderer );
1305 if ( !myGrayRenderer )
1310 myRasterRenderer = myGrayRenderer;
1313 else if ( rendererType ==
"multibandcolor"_L1 )
1315 myMultiBandRenderer =
dynamic_cast<QgsMultiBandColorRenderer *
>( rasterRenderer );
1316 if ( !myMultiBandRenderer )
1321 myRasterRenderer = myMultiBandRenderer;
1324 else if ( rendererType ==
"singlebandpseudocolor"_L1 )
1326 myPseudoColorRenderer =
dynamic_cast<QgsSingleBandPseudoColorRenderer *
>( rasterRenderer );
1327 if ( !myPseudoColorRenderer )
1331 myBands << myPseudoColorRenderer->
inputBand();
1332 myRasterRenderer = myPseudoColorRenderer;
1333 myMinMaxOrigin = myPseudoColorRenderer->
minMaxOrigin();
1340 for (
const int myBand : std::as_const( myBands ) )
1345 auto myEnhancement = std::make_unique<QgsContrastEnhancement>(
static_cast< Qgis::DataType >( myType ) );
1346 myEnhancement->setContrastEnhancementAlgorithm(
algorithm, generateLookupTableFlag );
1352 if ( rendererType ==
"singlebandpseudocolor"_L1 )
1355 if ( !myPseudoColorRenderer )
1363 bool minMaxChanged {
false };
1364 if ( !std::isnan( min ) )
1367 minMaxChanged =
true;
1370 if ( !std::isnan( max ) )
1373 minMaxChanged =
true;
1376 if ( minMaxChanged && myPseudoColorRenderer->
shader() )
1378 QgsColorRampShader *colorRampShader =
dynamic_cast<QgsColorRampShader *
>( myPseudoColorRenderer->
shader()->rasterShaderFunction() );
1379 if ( colorRampShader )
1387 myEnhancement->setMinimumValue( min );
1388 myEnhancement->setMaximumValue( max );
1389 myEnhancements.append( myEnhancement.release() );
1394 myEnhancements.append(
nullptr );
1399 if ( rendererType ==
"singlebandgray"_L1 && myGrayRenderer )
1401 if ( myEnhancements.first() )
1404 else if ( rendererType ==
"multibandcolor"_L1 && myMultiBandRenderer )
1406 if ( myEnhancements.first() )
1408 if ( myEnhancements.first() )
1410 if ( myEnhancements.first() )
1415 qDeleteAll( myEnhancements );
1422 if ( myRasterRenderer )
1427 if ( rasterRenderer ==
renderer() )
1444 ce = singleBandRenderer->contrastEnhancement();
1477 if ( !
isValid() || !mDataProvider )
1479 QgsDebugMsgLevel( u
"invoked with invalid layer or null mDataProvider"_s, 3 );
1482 if ( !mDataProvider->supportsSubsetString() )
1486 return mDataProvider->subsetString();
1493 if ( !
isValid() || !mDataProvider )
1495 QgsDebugMsgLevel( u
"invoked with invalid layer or null mDataProvider or while editing"_s, 3 );
1500 if ( !mDataProvider->supportsSubsetString() )
1505 if ( subset == mDataProvider->subsetString() )
1508 const bool res = mDataProvider->setSubsetString( subset );
1516 QList<double> minValues;
1517 QList<double> maxValues;
1519 for (
const int bandIdx :
renderer()->usesBands() )
1525 minValues.append( min );
1526 maxValues.append( max );
1543 QString defaultLimits;
1548 key = u
"singleBand"_s;
1556 key = u
"multiBandSingleByte"_s;
1562 key = u
"multiBandMultiByte"_s;
1568 if ( key.isEmpty() )
1570 QgsDebugMsgLevel( u
"No default contrast enhancement for this drawing style"_s, 2 );
1577 const QString myAlgorithmString = mySettings.value(
"/Raster/defaultContrastEnhancementAlgorithm/" + key, defaultAlg ).toString();
1582 const QString myLimitsString = mySettings.value(
"/Raster/defaultContrastEnhancementLimits/" + key, defaultLimits ).toString();
1608 if ( mDataProvider )
1610 QgsDebugMsgLevel( u
"About to mDataProvider->setLayerOrder(layers)."_s, 4 );
1611 mDataProvider->setLayerOrder( layers );
1619 if ( mDataProvider )
1621 QgsDebugMsgLevel( u
"About to mDataProvider->setSubLayerVisibility(name, vis)."_s, 4 );
1622 mDataProvider->setSubLayerVisibility(
name, vis );
1630 if ( !mDataProvider )
1632 return mDataProvider->timestamp();
1639 if (
auto *lRenderer = mPipe->renderer() )
1641 if ( !lRenderer->accept( visitor ) )
1651 return mLabelsEnabled &&
static_cast< bool >( mLabeling );
1658 mLabelsEnabled = enabled;
1665 return mLabeling.get();
1672 return mLabeling.get();
1690 context.setExtraProperties( props );
1710 QDomElement constraintElem = doc.createElement( u
"sld:LayerFeatureConstraints"_s );
1711 node.appendChild( constraintElem );
1713 const QDomElement featureTypeConstraintElem = doc.createElement( u
"sld:FeatureTypeConstraint"_s );
1714 constraintElem.appendChild( featureTypeConstraintElem );
1716 QDomElement userStyleElem = doc.createElement( u
"sld:UserStyle"_s );
1717 node.appendChild( userStyleElem );
1719 if ( !
name().isEmpty() )
1721 QDomElement nameElem = doc.createElement( u
"sld:Name"_s );
1722 nameElem.appendChild( doc.createTextNode(
name() ) );
1723 userStyleElem.appendChild( nameElem );
1729 QDomElement abstractElem = doc.createElement( u
"sld:Abstract"_s );
1730 abstractElem.appendChild( doc.createTextNode(
abstract ) );
1731 userStyleElem.appendChild( abstractElem );
1735 if ( !
title.isEmpty() )
1737 QDomElement titleElem = doc.createElement( u
"sld:Title"_s );
1738 titleElem.appendChild( doc.createTextNode(
title ) );
1739 userStyleElem.appendChild( titleElem );
1742 QDomElement featureTypeStyleElem = doc.createElement( u
"sld:FeatureTypeStyle"_s );
1743 userStyleElem.appendChild( featureTypeStyleElem );
1753 QDomElement typeStyleNameElem = doc.createElement( u
"sld:Name"_s );
1754 featureTypeStyleElem.appendChild( typeStyleNameElem );
1757 QDomElement typeStyleRuleElem = doc.createElement( u
"sld:Rule"_s );
1758 featureTypeStyleElem.appendChild( typeStyleRuleElem );
1766 QDomElement minScaleElem = doc.createElement( u
"sld:MinScaleDenominator"_s );
1767 minScaleElem.appendChild( doc.createTextNode( QString::number(
maximumScale() ) ) );
1768 typeStyleRuleElem.appendChild( minScaleElem );
1771 QDomElement maxScaleElem = doc.createElement( u
"sld:MaxScaleDenominator"_s );
1772 maxScaleElem.appendChild( doc.createTextNode( QString::number(
minimumScale() ) ) );
1773 typeStyleRuleElem.appendChild( maxScaleElem );
1777 mPipe->renderer()->toSld( doc, typeStyleRuleElem, context );
1782 const QDomNodeList elements = typeStyleRuleElem.elementsByTagName( u
"sld:RasterSymbolizer"_s );
1783 if ( elements.size() != 0 )
1786 QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement();
1789 auto vendorOptionWriter = [&]( QString
name, QString value ) {
1790 QDomElement vendorOptionElem = doc.createElement( u
"sld:VendorOption"_s );
1791 vendorOptionElem.setAttribute( u
"name"_s,
name );
1792 vendorOptionElem.appendChild( doc.createTextNode( value ) );
1793 rasterSymbolizerElem.appendChild( vendorOptionElem );
1798 vendorOptionWriter( u
"invertColors"_s, QString::number( 1 ) );
1808 property = u
"lightness"_s;
1811 property = u
"luminosity"_s;
1814 property = u
"average"_s;
1820 if ( !property.isEmpty() )
1821 vendorOptionWriter( u
"grayScale"_s, property );
1827 vendorOptionWriter( u
"colorizeOn"_s, QString::number(
hueSaturationFilter()->colorizeOn() ) );
1828 vendorOptionWriter( u
"colorizeRed"_s, QString::number(
hueSaturationFilter()->colorizeColor().red() ) );
1829 vendorOptionWriter( u
"colorizeGreen"_s, QString::number(
hueSaturationFilter()->colorizeColor().green() ) );
1830 vendorOptionWriter( u
"colorizeBlue"_s, QString::number(
hueSaturationFilter()->colorizeColor().blue() ) );
1832 vendorOptionWriter( u
"colorizeStrength"_s, QString::number(
hueSaturationFilter()->colorizeStrength() / 100.0 ) );
1833 vendorOptionWriter( u
"saturation"_s, QString::number(
hueSaturationFilter()->colorizeColor().saturationF() ) );
1842 const double sF = ( s - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1843 vendorOptionWriter( u
"saturation"_s, QString::number( sF ) );
1852 const double bF = ( b - ( -255.0 ) ) / ( 255.0 - ( -255.0 ) );
1853 vendorOptionWriter( u
"brightness"_s, QString::number( bF ) );
1861 const double cF = (
c - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1862 vendorOptionWriter( u
"contrast"_s, QString::number( cF ) );
1875 if ( newProps.contains( u
"contrast"_s ) )
1878 double contrast = newProps[ u
"contrast"_s ].toDouble();
1879 double percentage = ( contrast - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1880 if ( percentage <= 0.5 )
1883 gamma = percentage / 0.5;
1890 QDomElement globalContrastEnhancementElem = doc.createElement( u
"sld:ContrastEnhancement"_s );
1891 rasterSymolizerElem.appendChild( globalContrastEnhancementElem );
1893 QDomElement gammaValueElem = doc.createElement( u
"sld:GammaValue"_s );
1894 gammaValueElem.appendChild( doc.createTextNode( QString::number( gamma ) ) );
1895 globalContrastEnhancementElem.appendChild( gammaValueElem );
1922 return mPipe->renderer();
1929 return mPipe->resampleFilter();
1936 return mPipe->brightnessFilter();
1943 return mPipe->hueSaturationFilter();
1961 if ( mDataProvider )
1970 if ( !mDataProvider )
1971 return QStringList();
1972 return mDataProvider->subLayers();
1981 QImage image( size, format );
1986 if ( image.format() == QImage::Format_Indexed8 )
1988 image.setColor( 0, bgColor.rgba() );
1993 image.fill( bgColor );
1998 double mapUnitsPerPixel;
2002 if (
extent.width() /
extent.height() >=
static_cast< double >( image.width() ) / image.height() )
2004 mapUnitsPerPixel =
extent.width() / image.width();
2005 y = ( image.height() -
extent.height() / mapUnitsPerPixel ) / 2;
2009 mapUnitsPerPixel =
extent.height() / image.height();
2010 x = ( image.width() -
extent.width() / mapUnitsPerPixel ) / 2;
2013 const double pixelWidth =
extent.width() / mapUnitsPerPixel;
2014 const double pixelHeight =
extent.height() / mapUnitsPerPixel;
2018 rasterViewPort->
mWidth = image.width();
2019 rasterViewPort->
mHeight = image.height();
2027 QPainter *painter =
new QPainter( &image );
2028 draw( painter, rasterViewPort, mapToPixel );
2029 delete rasterViewPort;
2042 Q_UNUSED( errorMessage )
2045 QDomElement rasterRendererElem;
2047 const QDomElement layerElement = layer_node.toElement();
2057 QDomNode pipeNode = layer_node.firstChildElement( u
"pipe"_s );
2058 if ( pipeNode.isNull() )
2060 pipeNode = layer_node;
2064 if ( !layer_node.firstChildElement( u
"rasterproperties"_s ).isNull() )
2067 QDomNode layerNodeCopy = layer_node.cloneNode();
2068 QDomDocument doc = layerNodeCopy.ownerDocument();
2069 QDomElement rasterPropertiesElem = layerNodeCopy.firstChildElement( u
"rasterproperties"_s );
2071 rasterRendererElem = layerNodeCopy.firstChildElement( u
"rasterrenderer"_s );
2076 rasterRendererElem = pipeNode.firstChildElement( u
"rasterrenderer"_s );
2079 if ( !rasterRendererElem.isNull() )
2081 const QString rendererType = rasterRendererElem.attribute( u
"type"_s );
2094 const QDomElement brightnessElem = pipeNode.firstChildElement( u
"brightnesscontrast"_s );
2095 if ( !brightnessElem.isNull() )
2105 const QDomElement hueSaturationElem = pipeNode.firstChildElement( u
"huesaturation"_s );
2106 if ( !hueSaturationElem.isNull() )
2116 const QDomElement resampleElem = pipeNode.firstChildElement( u
"rasterresampler"_s );
2117 if ( !resampleElem.isNull() )
2124 if ( mDataProvider )
2126 const QDomElement providerElem = pipeNode.firstChildElement( u
"provider"_s );
2127 if ( !providerElem.isNull() )
2129 mDataProvider->readXml( providerElem );
2134 const QDomNode resamplingStageElement = pipeNode.namedItem( u
"resamplingStage"_s );
2135 if ( !resamplingStageElement.isNull() )
2137 const QDomElement e = resamplingStageElement.toElement();
2138 if ( e.text() ==
"provider"_L1 )
2140 else if ( e.text() ==
"resamplingFilter"_L1 )
2145 const QDomNode blendModeNode = layer_node.namedItem( u
"blendMode"_s );
2146 if ( !blendModeNode.isNull() )
2148 const QDomElement e = blendModeNode.toElement();
2152 const QDomElement elemDataDefinedProperties = layer_node.firstChildElement( u
"pipe-data-defined-properties"_s );
2153 if ( !elemDataDefinedProperties.isNull() )
2158 if ( categories.testFlag(
Labeling ) )
2162 QDomElement labelingElement = layer_node.firstChildElement( u
"labeling"_s );
2163 if ( !labelingElement.isNull() )
2166 mLabelsEnabled = layer_node.toElement().attribute( u
"labelsEnabled"_s, u
"0"_s ).toInt();
2171 if ( categories.testFlag(
MapTips ) )
2173 QDomElement mapTipElem = layer_node.namedItem( u
"mapTip"_s ).toElement();
2181 readRasterAttributeTableExternalPaths( layer_node, context );
2184 if ( categories.testFlag(
Legend ) )
2188 const QDomElement legendElem = layer_node.firstChildElement( u
"legend"_s );
2190 if ( rasterLegend && !legendElem.isNull() )
2192 rasterLegend->
readXml( legendElem, context );
2194 else if ( rasterLegend )
2211 return readSymbology( node, errorMessage, context, categories );
2222 const QDomNode pkeyNode = layer_node.namedItem( u
"provider"_s );
2224 if ( pkeyNode.isNull() )
2230 const QDomElement pkeyElt = pkeyNode.toElement();
2244 const QDomNode rpNode = layer_node.namedItem( u
"rasterproperties"_s );
2255 QDomElement layerElement = rpNode.firstChildElement( u
"wmsSublayer"_s );
2256 while ( !layerElement.isNull() )
2261 uri.
setParam( u
"layers"_s, layerElement.namedItem( u
"name"_s ).toElement().text() );
2264 uri.
setParam( u
"styles"_s, layerElement.namedItem( u
"style"_s ).toElement().text() );
2266 layerElement = layerElement.nextSiblingElement( u
"wmsSublayer"_s );
2270 uri.
setParam( u
"format"_s, rpNode.namedItem( u
"wmsFormat"_s ).toElement().text() );
2287 const QDomNode extentNode = layer_node.namedItem( u
"extent"_s );
2288 if ( !extentNode.isNull() )
2300 mOriginalStyleElement = layer_node.namedItem( u
"originalStyle"_s ).firstChildElement();
2301 if ( mOriginalStyleElement.isNull() )
2302 mOriginalStyleElement = layer_node.toElement();
2303 mOriginalStyleDocument = layer_node.ownerDocument();
2305 if ( !mDataProvider )
2329 QDomNode stampNode = layer_node.namedItem(
"timestamp" );
2330 if ( !stampNode.isNull() )
2332 QDateTime stamp = QDateTime::fromString( stampNode.toElement().text(), Qt::ISODate );
2334 if ( stamp < mDataProvider->dataTimestamp() )
2337 closeDataProvider();
2340 if ( !
isValid() )
return false;
2346 const QDomElement noDataElement = layer_node.firstChildElement( u
"noData"_s );
2348 const QDomNodeList noDataBandList = noDataElement.elementsByTagName( u
"noDataList"_s );
2350 for (
int i = 0; mDataProvider && i < noDataBandList.size(); ++i )
2352 const QDomElement bandElement = noDataBandList.at( i ).toElement();
2354 const int bandNo = bandElement.attribute( u
"bandNo"_s ).toInt( &ok );
2356 if ( ok && ( bandNo > 0 ) && ( bandNo <= mDataProvider->
bandCount() ) )
2358 mDataProvider->setUseSourceNoDataValue( bandNo, bandElement.attribute( u
"useSrcNoData"_s ).toInt() );
2361 const QDomNodeList rangeList = bandElement.elementsByTagName( u
"noDataRange"_s );
2363 myNoDataRangeList.reserve( rangeList.size() );
2364 for (
int j = 0; j < rangeList.size(); ++j )
2366 const QDomElement rangeElement = rangeList.at( j ).toElement();
2367 const QgsRasterRange myNoDataRange( rangeElement.attribute( u
"min"_s ).toDouble(), rangeElement.attribute( u
"max"_s ).toDouble() );
2368 QgsDebugMsgLevel( u
"min = %1 %2"_s.arg( rangeElement.attribute(
"min" ) ).arg( myNoDataRange.
min() ), 4 );
2369 myNoDataRangeList << myNoDataRange;
2371 mDataProvider->setUserNoDataValue( bandNo, myNoDataRangeList );
2375 readRasterAttributeTableExternalPaths( layer_node, context );
2386 Q_UNUSED( errorMessage )
2389 QDomElement layerElement = layer_node.toElement();
2393 if ( categories.testFlag(
Labeling ) )
2397 QDomElement labelingElement = mLabeling->save( document, context );
2398 layerElement.appendChild( labelingElement );
2400 if ( mLabelsEnabled )
2401 layerElement.setAttribute( u
"labelsEnabled"_s, u
"1"_s );
2405 if ( categories.testFlag(
MapTips ) )
2407 QDomElement mapTipElem = document.createElement( u
"mapTip"_s );
2409 QDomText mapTipText = document.createTextNode(
mapTipTemplate() );
2410 mapTipElem.appendChild( mapTipText );
2411 layer_node.toElement().appendChild( mapTipElem );
2417 writeRasterAttributeTableExternalPaths( layer_node, document, context );
2425 QDomElement pipeElement = document.createElement( u
"pipe"_s );
2427 for (
int i = 0; i < mPipe->size(); i++ )
2432 interface->
writeXml( document, pipeElement );
2435 QDomElement elemDataDefinedProperties = document.createElement( u
"pipe-data-defined-properties"_s );
2437 layer_node.appendChild( elemDataDefinedProperties );
2439 QDomElement resamplingStageElement = document.createElement( u
"resamplingStage"_s );
2441 resamplingStageElement.appendChild( resamplingStageText );
2442 pipeElement.appendChild( resamplingStageElement );
2444 layer_node.appendChild( pipeElement );
2446 if ( !
isValid() && !mOriginalStyleElement.isNull() )
2448 QDomElement originalStyleElement = document.createElement( u
"originalStyle"_s );
2449 originalStyleElement.appendChild( mOriginalStyleElement );
2450 layer_node.appendChild( originalStyleElement );
2454 QDomElement blendModeElement = document.createElement( u
"blendMode"_s );
2456 blendModeElement.appendChild( blendModeText );
2457 layer_node.appendChild( blendModeElement );
2462 QDomElement legendElement =
legend()->
writeXml( document, context );
2463 if ( !legendElement.isNull() )
2464 layer_node.appendChild( legendElement );
2474 return writeSymbology( node, doc, errorMessage, context, categories );
2481 if ( !mDataProvider )
2486 QDomElement mapLayerNode = layer_node.toElement();
2488 if ( mapLayerNode.isNull() ||
"maplayer" != mapLayerNode.nodeName() )
2498 QDomElement provider = document.createElement( u
"provider"_s );
2499 const QDomText providerText = document.createTextNode(
mProviderKey );
2500 provider.appendChild( providerText );
2501 layer_node.appendChild( provider );
2504 QDomElement noData = document.createElement( u
"noData"_s );
2506 for (
int bandNo = 1; bandNo <= mDataProvider->bandCount(); bandNo++ )
2508 QDomElement noDataRangeList = document.createElement( u
"noDataList"_s );
2509 noDataRangeList.setAttribute( u
"bandNo"_s, bandNo );
2510 noDataRangeList.setAttribute( u
"useSrcNoData"_s, mDataProvider->useSourceNoDataValue( bandNo ) );
2512 const auto constUserNoDataValues = mDataProvider->userNoDataValues( bandNo );
2515 QDomElement noDataRange = document.createElement( u
"noDataRange"_s );
2519 noDataRangeList.appendChild( noDataRange );
2522 noData.appendChild( noDataRangeList );
2524 if ( noData.hasChildNodes() )
2526 layer_node.appendChild( noData );
2530 writeRasterAttributeTableExternalPaths( layer_node, document, context );
2536 return writeSymbology( layer_node, document, errorMsg, context );
2558 if ( !mDataProvider )
2560 return mDataProvider->xSize();
2567 if ( !mDataProvider )
2569 return mDataProvider->ySize();
2576 mPipe->setResamplingStage( stage );
2583 return mPipe->resamplingStage();
2586bool QgsRasterLayer::update()
2595 closeDataProvider();
Provides global constants and enumerations for use throughout the application.
static QString version()
Version string.
@ IsBasemapLayer
Layer is considered a 'basemap' layer, and certain properties of the layer should be ignored when cal...
RasterResamplingStage
Stage at which raster resampling occurs.
@ Provider
Resampling occurs in Provider.
@ ResampleFilter
Resampling occurs in ResamplingFilter.
@ ProviderHintBenefitsFromResampling
Provider benefits from resampling and should apply user default resampling settings.
@ ProviderHintCanPerformProviderResampling
Provider can perform resampling (to be opposed to post rendering resampling).
@ ReadLayerMetadata
Provider can read layer metadata from data store. Since QGIS 3.0. See QgsDataProvider::layerMetadata(...
@ SingleBandColorData
Single band containing color data.
@ GrayOrUndefined
Gray or undefined.
RasterRangeLimit
Describes the limits used to compute raster ranges (min/max values).
@ CumulativeCut
Range is [ min + cumulativeCutLower() * (max - min), min + cumulativeCutUpper() * (max - min) ].
@ MinimumMaximum
Real min-max values.
@ Linear
Interpolates the color between two class breaks linearly.
@ Discrete
Assigns the color of the higher class for every pixel between two class breaks.
@ IsBasemapSource
Associated source should be considered a 'basemap' layer. See Qgis::MapLayerProperty::IsBasemapLayer.
@ Bilinear
Bilinear (2x2 kernel) resampling.
@ Cubic
Cubic Convolution Approximation (4x4 kernel) resampling.
RasterDrawingStyle
Raster drawing styles.
@ SingleBandGray
A single band image drawn as a range of gray colors.
@ SingleBandColorData
ARGB values rendered directly.
@ MultiBandColor
A layer containing 2 or more bands, mapped to RGB color space. In the case of a multiband with only t...
@ PalettedColor
A "Palette" image drawn using color table.
@ SingleBandPseudoColor
A single band image drawn using a pseudocolor algorithm.
QFlags< RasterInterfaceCapability > RasterInterfaceCapabilities
Raster interface capabilities.
BlendMode
Blending modes defining the available composition modes that can be used when painting.
@ Size
Original data source size (and thus resolution) is known, it is not always available,...
@ IdentifyValue
Numerical values.
@ IdentifyFeature
WMS GML -> feature.
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
@ ExcludeByDefault
If set, the layer should not be included in legends by default, and must be manually added by a user.
DataType
Raster data types.
@ Float32
Thirty two bit floating point (float).
@ CFloat64
Complex Float64.
@ Int16
Sixteen bit signed integer (qint16).
@ ARGB32_Premultiplied
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32_Premultiplied.
@ Int8
Eight bit signed integer (qint8) (added in QGIS 3.30).
@ UInt16
Sixteen bit unsigned integer (quint16).
@ Byte
Eight bit unsigned integer (quint8).
@ ARGB32
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32.
@ Int32
Thirty two bit signed integer (qint32).
@ Float64
Sixty four bit floating point (double).
@ CFloat32
Complex Float32.
@ UInt32
Thirty two bit unsigned integer (quint32).
@ WholeRaster
Whole raster is used to compute statistics.
@ FixedCanvas
Current extent of the canvas (at the time of computation) is used to compute statistics.
QFlags< MapLayerProperty > MapLayerProperties
Map layer properties.
@ LoadDefaultStyle
Reset the layer's style to the default for the datasource.
@ SkipGetExtent
Skip the extent from provider.
@ TrustDataSource
Trust datasource config (primary key unicity, geometry type and srid, etc). Improves provider load ti...
RasterColorInterpretation
Raster color interpretation.
@ AlphaBand
Alpha (0=transparent, 255=opaque).
@ PaletteIndex
Paletted (see associated color table).
@ ContinuousPalette
Continuous palette, QGIS addition, GRASS.
RasterIdentifyFormat
Raster identify formats.
@ Feature
WMS GML/JSON -> feature.
@ Value
Numerical pixel value.
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
Abstract base class for objects which generate elevation profiles.
Abstract base class for labeling settings for raster layers.
static QgsAbstractRasterLayerLabeling * createFromElement(const QDomElement &element, const QgsReadWriteContext &context)
Tries to create an instance of an implementation based on the XML data.
static QgsRasterRendererRegistry * rasterRendererRegistry()
Returns the application's raster renderer registry, used for managing raster layer renderers.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
Bilinear raster resampler.
Brightness/contrast and gamma correction filter pipe for rasters.
int contrast() const
Returns current contrast level.
int brightness() const
Returns current brightness level.
A ramp shader will color a raster pixel based on a list of values ranges in a ramp.
bool shade(double value, int *returnRedValue, int *returnGreenValue, int *returnBlueValue, int *returnAlphaValue) const override
Generates an new RGBA value based on one input value.
void classifyColorRamp(int classes=0, int band=-1, const QgsRectangle &extent=QgsRectangle(), QgsRasterInterface *input=nullptr)
Classify color ramp shader.
void setColorRampType(Qgis::ShaderInterpolationMethod colorRampType)
Sets the color ramp interpolation method.
void setColorRampItemList(const QList< QgsColorRampShader::ColorRampItem > &list)
Sets a custom color map.
Handles contrast enhancement and clipping.
ContrastEnhancementAlgorithm
This enumerator describes the types of contrast enhancement algorithms that can be used.
@ StretchToMinimumMaximum
Linear histogram.
@ NoEnhancement
Default color scaling algorithm, no scaling is applied.
static QString contrastEnhancementAlgorithmString(ContrastEnhancementAlgorithm algorithm)
Returns a string to serialize ContrastEnhancementAlgorithm.
static ContrastEnhancementAlgorithm contrastEnhancementAlgorithmFromString(const QString &contrastEnhancementString)
Deserialize ContrastEnhancementAlgorithm.
ContrastEnhancementAlgorithm contrastEnhancementAlgorithm() const
Represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
Abstract base class for spatial data provider implementations.
Stores the component parts of a data source URI (e.g.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
void setEncodedUri(const QByteArray &uri)
Sets the complete encoded uri.
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
Color and saturation filter pipe for rasters.
Base class for storage of map layer elevation properties.
static QString typeToString(Qgis::LayerType type)
Converts a map layer type to a string value.
An abstract interface for implementations of legends for one map layer.
virtual void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Reads configuration from a DOM element previously written by writeXml().
virtual QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Writes configuration to a DOM element, to be used later with readXml().
static QgsMapLayerLegend * defaultRasterLegend(QgsRasterLayer *rl)
Create new legend implementation for raster layer.
void setFlag(Qgis::MapLayerLegendFlag flag, bool on=true)
Enables or disables a particular flag (other flags are not affected).
Base class for utility classes that encapsulate information necessary for rendering of map layers.
QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
QString abstract() const
Returns the abstract of the layerused by QGIS Server in GetCapabilities request.
Base class for storage of map layer temporal properties.
void readStyleManager(const QDomNode &layerNode)
Read style manager's configuration (if any). To be called by subclasses.
void setError(const QgsError &error)
Sets error message.
void writeStyleManager(QDomNode &layerNode, QDomDocument &doc) const
Write style manager's configuration (if exists). To be called by subclasses.
QgsMapLayerLegend * legend() const
Can be nullptr.
virtual Q_INVOKABLE QgsRectangle extent() const
Returns the extent of the layer.
QString source() const
Returns the source for the layer.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void setBlendMode(QPainter::CompositionMode blendMode)
Set the blending mode used for rendering a layer.
void configChanged()
Emitted whenever the configuration is changed.
static Qgis::DataProviderReadFlags providerReadFlags(const QDomNode &layerNode, QgsMapLayer::ReadFlags layerReadFlags)
Returns provider read flag deduced from layer read flags layerReadFlags and a dom node layerNode that...
QgsCoordinateReferenceSystem crs
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
virtual QString loadDefaultStyle(bool &resultFlag)
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record...
void setDataSource(const QString &dataSource, const QString &baseName=QString(), const QString &provider=QString(), bool loadDefaultStyleFlag=false)
Updates the data source of the layer.
QString mLayerName
Name of the layer - used for display.
void triggerRepaint(bool deferredUpdate=false)
Will advise the map canvas (and any other interested party) that this layer requires to be repainted.
QString crsHtmlMetadata() const
Returns a HTML fragment containing the layer's CRS metadata, for use in the htmlMetadata() method.
QgsLayerMetadata metadata
Q_DECL_DEPRECATED QString abstract() const
Returns the abstract of the layer used by QGIS Server in GetCapabilities request.
QgsMapLayer(Qgis::LayerType type=Qgis::LayerType::Vector, const QString &name=QString(), const QString &source=QString())
Constructor for QgsMapLayer.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
void statusChanged(const QString &status)
Emit a signal with status (e.g. to be caught by QgisApp and display a msg on status bar).
virtual void setMetadata(const QgsLayerMetadata &metadata)
Sets the layer's metadata store.
QFlags< StyleCategory > StyleCategories
Q_INVOKABLE void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for layer.
QString mProviderKey
Data provider key (name of the data provider).
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
std::unique_ptr< QgsDataProvider > mPreloadedProvider
Optionally used when loading a project, it is released when the layer is effectively created.
void rendererChanged()
Signal emitted when renderer is changed.
Q_DECL_DEPRECATED QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
virtual QgsError error() const
Gets current status error.
QgsMapLayer::LayerFlags flags
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
void opacityChanged(double opacity)
Emitted when the layer's opacity is changed, where opacity is a value between 0 (transparent) and 1 (...
void emitStyleChanged()
Triggers an emission of the styleChanged() signal.
void dataChanged()
Data of layer changed.
void willBeDeleted()
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid...
virtual QgsMapLayer * clone() const =0
Returns a new instance equivalent to this one except for the id which is still unique.
void setName(const QString &name)
Set the display name of the layer.
virtual void setExtent(const QgsRectangle &rect)
Sets the extent.
void appendError(const QgsErrorMessage &error)
Add error message.
QString mDataSource
Data source description string, varies by layer type.
void setMapTipsEnabled(bool enabled)
Enable or disable map tips for this layer.
@ FlagReadExtentFromXml
Read extent from xml and skip get extent from provider.
@ FlagTrustLayerMetadata
Trust layer metadata. Improves layer load time by skipping expensive checks like primary key unicity,...
@ FlagDontResolveLayers
Don't resolve layer paths or create data providers for layers.
void setValid(bool valid)
Sets whether layer is valid or not.
void readCommonStyle(const QDomElement &layerElement, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)
Read style data common to all layer types.
QgsMapLayer::ReadFlags mReadFlags
Read flags. It's up to the subclass to respect these when restoring state from XML.
double minimumScale() const
Returns the minimum map scale (i.e.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
void setMapTipTemplate(const QString &mapTipTemplate)
The mapTip is a pretty, html representation for feature information.
@ AttributeTable
Attribute table settings: choice and order of columns, conditional styling.
@ Rendering
Rendering: scale visibility, simplify method, opacity.
void setProviderType(const QString &providerType)
Sets the providerType (provider key).
QString customPropertyHtmlMetadata() const
Returns an HTML fragment containing custom property information, for use in the htmlMetadata() method...
QString generalHtmlMetadata() const
Returns an HTML fragment containing general metadata information, for use in the htmlMetadata() metho...
void writeCommonStyle(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const
Write style data common to all layer types.
double maximumScale() const
Returns the maximum map scale (i.e.
void invalidateWgs84Extent()
Invalidates the WGS84 extent.
bool mShouldValidateCrs
true if the layer's CRS should be validated and invalid CRSes are not permitted.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
Perform transforms between map coordinates and device coordinates.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Renderer for multiband images with the color components.
int blueBand() const
Returns the band number for the blue channel.
void setGreenContrastEnhancement(QgsContrastEnhancement *ce)
Sets the contrast enhancement to use for the green channel.
void setBlueContrastEnhancement(QgsContrastEnhancement *ce)
Sets the contrast enhancement to use for the blue channel.
void setRedContrastEnhancement(QgsContrastEnhancement *ce)
Sets the contrast enhancement to use for the red channel.
const QgsContrastEnhancement * redContrastEnhancement() const
Returns the contrast enhancement to use for the red channel.
int redBand() const
Returns the band number for the red channel.
int greenBand() const
Returns the band number for the green channel.
static Qgis::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a Qgis::BlendMode corresponding to a QPainter::CompositionMode.
static QPainter::CompositionMode getCompositionMode(Qgis::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a Qgis::BlendMode.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
Encapsulates properties and constraints relating to fetching elevation profiles from different source...
QString absoluteToRelativeUri(const QString &providerKey, const QString &uri, const QgsReadWriteContext &context) const
Converts absolute path(s) to relative path(s) in the given provider-specific URI.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QString relativeToAbsoluteUri(const QString &providerKey, const QString &uri, const QgsReadWriteContext &context) const
Converts relative path(s) to absolute path(s) in the given provider-specific URI.
Represents a Raster Attribute Table (RAT).
QString filePath() const
Returns the (possibly empty) path of the file-based RAT, the path is set when a RAT is read or writte...
The RasterBandStats struct is a container for statistics about a single raster band.
double minimumValue
The minimum cell value in the raster band.
double maximumValue
The maximum cell value in the raster band.
static int typeSize(Qgis::DataType dataType)
Returns the size in bytes for the specified dataType.
static QString printValue(double value, bool localized=false)
Print double value with all necessary significant digits.
Handles elevation related properties for a raster data provider.
Base class for raster data providers.
QDateTime timestamp() const override
Time stamp of data source in the moment when data/metadata were loaded by provider.
QgsRectangle extent() const override=0
Returns the extent of the layer.
QDateTime dataTimestamp() const override
Current time stamp of data source.
void statusChanged(const QString &) const
Emit a message to be displayed on status bar, usually used by network providers (WMS,...
static QString identifyFormatName(Qgis::RasterIdentifyFormat format)
Converts a raster identify format to a string name.
The drawing pipe for raster layers.
void draw(QPainter *p, QgsRasterViewPort *viewPort, const QgsMapToPixel *qgsMapToPixel, QgsRasterBlockFeedback *feedback=nullptr)
Draws raster data.
Base class for processing filters like renderers, reprojector, resampler etc.
Q_DECL_DEPRECATED QgsRasterBandStats bandStatistics(int bandNo, int stats, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0, QgsRasterBlockFeedback *feedback=nullptr)
Returns the band statistics.
Q_DECL_DEPRECATED bool hasStatistics(int bandNo, int stats, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0)
Returns true if histogram is available (cached, already calculated).
virtual void writeXml(QDomDocument &doc, QDomElement &parentElem) const
Write base class members to xml.
virtual QgsRasterInterface * input() const
Current input.
Iterator for sequentially processing raster cells.
Raster layer specific subclass of QgsMapLayerElevationProperties.
Implementation of QgsAbstractProfileGenerator for raster layers.
Implementation of threaded rendering for raster layers.
Implementation of map layer temporal properties for raster layers.
static void computeMinMax(QgsRasterDataProvider *provider, int band, const QgsRasterMinMaxOrigin &mmo, Qgis::RasterRangeLimit limits, const QgsRectangle &extent, int sampleSize, double &min, double &max)
Compute the min max values for provider along band according to MinMaxOrigin parameters mmo and exten...
QString htmlMetadata() const override
Obtain a formatted HTML string containing assorted metadata for this layer.
bool canCreateRasterAttributeTable()
Returns true if the raster renderer is suitable for creation of a raster attribute table.
void subsetStringChanged()
Emitted when the layer's subset string has changed.
Qgis::MapLayerProperties properties() const override
Returns the map layer properties of this layer.
QString encodedSource(const QString &source, const QgsReadWriteContext &context) const override
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to proje...
const QgsAbstractRasterLayerLabeling * labeling() const
Access to const labeling configuration.
Q_DECL_DEPRECATED QgsLegendColorList legendSymbologyItems() const
Returns a list with classification items (Text and color).
QgsMapLayerRenderer * createMapRenderer(QgsRenderContext &rendererContext) override
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
void showStatusMessage(const QString &message)
QgsRasterAttributeTable * attributeTable(int bandNumber) const
Returns the (possibly NULL) raster attribute table for the given band bandNumber.
virtual bool setSubsetString(const QString &subset)
Sets the string (typically sql) used to define a subset of the layer.
QgsRasterResampleFilter * resampleFilter() const
Returns the raster's resample filter.
bool writeSymbology(QDomNode &, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const override
Write the style for the layer into the document provided.
QgsRasterLayer * clone() const override
Returns a new instance equivalent to this one.
void setResamplingStage(Qgis::RasterResamplingStage stage)
Select which stage of the pipe should apply resampling.
Qgis::RasterResamplingStage resamplingStage() const
Returns which stage of the pipe should apply resampling.
static const QgsSettingsEntryBool * settingsRasterDefaultEarlyResampling
int attributeTableCount() const
Returns the number of attribute tables for the raster by counting the number of bands that have an as...
void refreshContrastEnhancement(const QgsRectangle &extent)
Refresh contrast enhancement with new extent.
int height() const
Returns the height of the (unclipped) raster.
static const Qgis::RasterRangeLimit SINGLE_BAND_MIN_MAX_LIMITS
Default enhancement limits for single band raster.
Q_DECL_DEPRECATED void setDataProvider(const QString &provider)
Set the data provider.
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for multiple band raster of type Byte.
int bandCount() const
Returns the number of bands in this layer.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns the layer's temporal properties.
bool ignoreExtents() const
If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the ...
QString decodedSource(const QString &source, const QString &provider, const QgsReadWriteContext &context) const override
Called by readLayerXML(), used by derived classes to decode provider's specific data source from proj...
double opacity() const final
Returns the opacity for the layer, where opacity is a value between 0 (totally transparent) and 1....
void computeMinMax(int band, const QgsRasterMinMaxOrigin &mmo, Qgis::RasterRangeLimit limits, const QgsRectangle &extent, int sampleSize, double &min, double &max)
Compute the min max values along band according to MinMaxOrigin parameters mmo and extent.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
void setSubLayerVisibility(const QString &name, bool vis) override
Set the visibility of the given sublayer name.
static const QgsSettingsEntryDouble * settingsRasterDefaultOversampling
void setLabeling(QgsAbstractRasterLayerLabeling *labeling)
Sets labeling configuration.
virtual QString subsetString() const
Returns the string (typically sql) used to define a subset of the layer.
QgsAbstractProfileGenerator * createProfileGenerator(const QgsProfileRequest &request) override
Given a profile request, returns a new profile generator ready for generating elevation profiles.
QgsBrightnessContrastFilter * brightnessFilter() const
Returns the raster's brightness/contrast filter.
bool writeXml(QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context) const override
Called by writeLayerXML(), used by children to write state specific to them to project files.
bool writeStyle(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const override
Write just the symbology information for the layer into the document.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
void reload() override
Synchronises with changes in the datasource.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the layer.
QImage previewAsImage(QSize size, const QColor &bgColor=Qt::white, QImage::Format format=QImage::Format_ARGB32_Premultiplied)
Draws a preview of the rasterlayer into a QImage.
QStringList subLayers() const override
Returns the sublayers of this layer.
static const Qgis::RasterRangeLimit MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS
Default enhancement limits for multiple band raster of type different from Byte.
void setContrastEnhancement(QgsContrastEnhancement::ContrastEnhancementAlgorithm algorithm, Qgis::RasterRangeLimit limits=Qgis::RasterRangeLimit::MinimumMaximum, const QgsRectangle &extent=QgsRectangle(), int sampleSize=QgsRasterLayer::SAMPLE_SIZE, bool generateLookupTableFlag=true)
Set contrast enhancement algorithm.
static const QgsSettingsEntryString * settingsRasterDefaultZoomedInResampling
void setDefaultContrastEnhancement()
Sets the default contrast enhancement.
QgsRasterRenderer * renderer() const
Returns the raster's renderer.
static const double SAMPLE_SIZE
Default sample size (number of pixels) for estimated statistics/histogram calculation.
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for multiple band raster of type different from Byte.
static const Qgis::RasterRangeLimit MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS
Default enhancement limits for multiple band raster of type Byte.
bool readXml(const QDomNode &layer_node, QgsReadWriteContext &context) override
Called by readLayerXML(), used by children to read state specific to them from project files.
void setLabelsEnabled(bool enabled)
Sets whether labels should be enabled for the layer.
QString bandName(int bandNoInt) const
Returns the name of a band given its number.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
static bool isValidRasterFileName(const QString &fileNameQString, QString &retError)
This helper checks to see whether the file name appears to be a valid raster file name.
bool isSpatial() const override
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
void setOpacity(double opacity) final
Sets the opacity for the layer, where opacity is a value between 0 (totally transparent) and 1....
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
int width() const
Returns the width of the (unclipped) raster.
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
bool readSymbology(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) override
Read the symbology for the current layer from the DOM node supplied.
static const QgsSettingsEntryString * settingsRasterDefaultZoomedOutResampling
void draw(QPainter *theQPainter, QgsRasterViewPort *myRasterViewPort, const QgsMapToPixel *qgsMapToPixel=nullptr)
This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPix...
Q_DECL_DEPRECATED bool writeSld(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QVariantMap &props=QVariantMap()) const
Writes the symbology of the layer into the document provided in SLD 1.0.0 format.
static QDateTime lastModified(const QString &name)
Returns time stamp for given file name.
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm SINGLE_BAND_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for single band raster.
~QgsRasterLayer() override
QDateTime timestamp() const override
Time stamp of data source in the moment when data/metadata were loaded by provider.
void setTransformContext(const QgsCoordinateTransformContext &transformContext) override
Sets the coordinate transform context to transformContext.
void setRenderer(QgsRasterRenderer *renderer)
Sets the raster's renderer.
QgsRasterLayer()
Constructor. Provider is not set.
void setLayerOrder(const QStringList &layers) override
Reorders the previously selected sublayers of this layer from bottom to top.
bool defaultContrastEnhancementSettings(QgsContrastEnhancement::ContrastEnhancementAlgorithm &myAlgorithm, Qgis::RasterRangeLimit &myLimits) const
Returns default contrast enhancement settings for that type of raster.
QgsHueSaturationFilter * hueSaturationFilter() const
Returns the raster's hue/saturation filter.
bool readStyle(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) override
Read the style for the current layer from the DOM node supplied.
QPixmap paletteAsPixmap(int bandNumber=1)
Returns a 100x100 pixmap of the color palette.
Describes the origin of minimum and maximum values in a raster.
static QString limitsString(Qgis::RasterRangeLimit limits)
Returns a string to serialize Limits.
void setLimits(Qgis::RasterRangeLimit limits)
Sets the limits.
void setExtent(Qgis::RasterRangeExtent extent)
Sets the extent.
Qgis::RasterRangeExtent extent() const
Returns the raster extent.
static Qgis::RasterRangeLimit limitsFromString(const QString &limits)
Deserialize Limits.
Qgis::RasterRangeLimit limits() const
Returns the raster limits.
Contains a pipeline of raster interfaces for sequential raster processing.
static QgsPropertiesDefinition propertyDefinitions()
Returns the definitions for data defined properties available for use in raster pipes.
Implements approximate projection support for optimised raster transformation.
Q_DECL_DEPRECATED void setCrs(const QgsCoordinateReferenceSystem &srcCRS, const QgsCoordinateReferenceSystem &destCRS, int srcDatumTransform=-1, int destDatumTransform=-1)
Sets the source and destination CRS.
Represents a range of raster values between min and max, optionally including the min and max value.
double min() const
Returns the minimum value for the range.
Raster renderer pipe that applies colors to a raster.
virtual QString type() const
Returns a unique string representation of the renderer type.
virtual bool canCreateRasterAttributeTable() const
Returns true if the renderer is suitable for attribute table creation.
void setMinMaxOrigin(const QgsRasterMinMaxOrigin &origin)
Sets origin of min/max values.
const QgsRasterMinMaxOrigin & minMaxOrigin() const
Returns const reference to origin of min/max values.
virtual bool refresh(const QgsRectangle &extent, const QList< double > &min, const QList< double > &max, bool forceRefresh=false)
Refreshes the renderer according to the min and max values associated with the extent.
Resample filter pipe for rasters.
Interface for all raster shaders.
void setRasterShaderFunction(QgsRasterShaderFunction *function)
A public method that allows the user to set their own shader function.
Allows entering a context category and takes care of leaving this category on deletion of the class.
A container for the context for various read/write operations on objects.
QgsReadWriteContextCategoryPopper enterCategory(const QString &category, const QString &details=QString()) const
Push a category to the stack.
QgsCoordinateTransformContext transformContext() const
Returns data provider coordinate transform context.
const QgsPathResolver & pathResolver() const
Returns path resolver for conversion between relative and absolute paths.
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be rounded to the spec...
Contains information about the context of a rendering operation.
A boolean settings entry.
static QgsSettingsTreeNode * sTreeRaster
Stores settings for use within QGIS.
Raster renderer pipe for single band gray.
void setContrastEnhancement(QgsContrastEnhancement *ce)
Takes ownership.
int inputBand() const override
Returns the input band for the renderer, or -1 if no input band is available.
Raster renderer pipe for single band pseudocolor.
void setClassificationMin(double min)
void setShader(QgsRasterShader *shader)
Takes ownership of the shader.
void setClassificationMax(double max)
QgsRasterShader * shader()
Returns the raster shader.
int inputBand() const override
Returns the input band for the renderer, or -1 if no input band is available.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
An interface for classes which can visit style entity (e.g.
static void mergeScaleDependencies(double mScaleMinDenom, double mScaleMaxDenom, QVariantMap &props)
Merges the local scale limits, if any, with the ones already in the map, if any.
static QgsRectangle readRectangle(const QDomElement &element)
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
QgsDataProvider * classFactoryFunction_t(const QString *, const QgsDataProvider::ProviderOptions &options)
QList< QPair< QString, QColor > > QgsLegendColorList
QList< QgsRasterRange > QgsRasterRangeList
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS
Setting options for creating vector data providers.
Setting options for loading raster layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
QgsCoordinateTransformContext transformContext
Coordinate transform context.
Registry for raster renderer entries.
QgsRasterRendererCreateFunc rendererCreateFunction
This class provides details of the viewable area that a raster will be rendered into.
qgssize mHeight
Height, number of rows to be rendered.
QgsCoordinateReferenceSystem mDestCRS
Target (map) coordinate system.
QgsPointXY mBottomRightPoint
Coordinate (in output device coordinate system) of bottom right corner of the part of the raster that...
QgsPointXY mTopLeftPoint
Coordinate (in output device coordinate system) of top left corner of the part of the raster that is ...
QgsCoordinateReferenceSystem mSrcCRS
Source (layer) coordinate system.
QgsRectangle mDrawnExtent
Intersection of current map extent and layer extent, in map (destination) CRS.
QgsCoordinateTransformContext mTransformContext
Coordinate transform context.
qgssize mWidth
Width, number of columns to be rendered.