QGIS API Documentation 3.43.0-Master (3ee7834ace6)
qgsvectortilelayerproperties.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectortilelayerproperties.cpp
3 --------------------------------------
4 Date : May 2020
5 Copyright : (C) 2020 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17#include "moc_qgsvectortilelayerproperties.cpp"
18#include "qgshelp.h"
24#include "qgsvectortilelayer.h"
25#include "qgsvectortileutils.h"
26#include "qgsgui.h"
27#include "qgsapplication.h"
28#include "qgsjsonutils.h"
29#include "qgsmetadatawidget.h"
34
35#include <QFileDialog>
36#include <QMenu>
37#include <QMessageBox>
38#include <QDesktopServices>
39#include <QTextStream>
40
41QgsVectorTileLayerProperties::QgsVectorTileLayerProperties( QgsVectorTileLayer *lyr, QgsMapCanvas *canvas, QgsMessageBar *messageBar, QWidget *parent, Qt::WindowFlags flags )
42 : QgsLayerPropertiesDialog( lyr, canvas, QStringLiteral( "VectorTileLayerProperties" ), parent, flags )
43 , mLayer( lyr )
44{
45 setupUi( this );
46
47 mRendererWidget = new QgsVectorTileBasicRendererWidget( nullptr, canvas, messageBar, this );
48 mOptsPage_Style->layout()->addWidget( mRendererWidget );
49 mOptsPage_Style->layout()->setContentsMargins( 0, 0, 0, 0 );
50
51 mLabelingWidget = new QgsVectorTileBasicLabelingWidget( nullptr, canvas, messageBar, this );
52 mOptsPage_Labeling->layout()->addWidget( mLabelingWidget );
53 mOptsPage_Labeling->layout()->setContentsMargins( 0, 0, 0, 0 );
54
55 connect( this, &QDialog::accepted, this, &QgsVectorTileLayerProperties::apply );
56 connect( this, &QDialog::rejected, this, &QgsVectorTileLayerProperties::rollback );
57 connect( buttonBox->button( QDialogButtonBox::Apply ), &QAbstractButton::clicked, this, &QgsVectorTileLayerProperties::apply );
58 connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsVectorTileLayerProperties::showHelp );
59
60 connect( mCrsSelector, &QgsProjectionSelectionWidget::crsChanged, this, &QgsVectorTileLayerProperties::crsChanged );
61
62 // scale based layer visibility related widgets
63 mScaleRangeWidget->setMapCanvas( mCanvas );
64
65 // QgsOptionsDialogBase handles saving/restoring of geometry, splitter and current tab states,
66 // switching vertical tabs between icon/text to icon-only modes (splitter collapsed to left),
67 // and connecting QDialogButtonBox's accepted/rejected signals to dialog's accept/reject slots
68 initOptionsBase( false );
69
70 mSourceGroupBox->hide();
71
72#ifdef WITH_QTWEBKIT
73 // Setup information tab
74
75 const int horizontalDpi = logicalDpiX();
76
77 // Adjust zoom: text is ok, but HTML seems rather big at least on Linux/KDE
78 if ( horizontalDpi > 96 )
79 {
80 mMetadataViewer->setZoomFactor( mMetadataViewer->zoomFactor() * 0.9 );
81 }
82 mMetadataViewer->page()->setLinkDelegationPolicy( QWebPage::LinkDelegationPolicy::DelegateAllLinks );
83 connect( mMetadataViewer->page(), &QWebPage::linkClicked, this, &QgsVectorTileLayerProperties::openUrl );
84 mMetadataViewer->page()->settings()->setAttribute( QWebSettings::DeveloperExtrasEnabled, true );
85 mMetadataViewer->page()->settings()->setAttribute( QWebSettings::JavascriptEnabled, true );
86
87#endif
88 mOptsPage_Information->setContentsMargins( 0, 0, 0, 0 );
89
90 QVBoxLayout *layout = new QVBoxLayout( metadataFrame );
91 layout->setContentsMargins( 0, 0, 0, 0 );
92 metadataFrame->setContentsMargins( 0, 0, 0, 0 );
93 mMetadataWidget = new QgsMetadataWidget( this, mLayer );
94 mMetadataWidget->layout()->setContentsMargins( 0, 0, 0, 0 );
95 mMetadataWidget->setMapCanvas( mCanvas );
96 layout->addWidget( mMetadataWidget );
97 metadataFrame->setLayout( layout );
98 mOptsPage_Metadata->setContentsMargins( 0, 0, 0, 0 );
99
100 setMetadataWidget( mMetadataWidget, mOptsPage_Metadata );
101
102 mMapLayerServerPropertiesWidget->setHasWfsTitle( false );
103
104 // update based on lyr's current state
105 syncToLayer();
106
107 QgsSettings settings;
108 // if dialog hasn't been opened/closed yet, default to Styles tab, which is used most often
109 // this will be read by restoreOptionsBaseUi()
110 if ( !settings.contains( QStringLiteral( "/Windows/VectorTileLayerProperties/tab" ) ) )
111 {
112 settings.setValue( QStringLiteral( "Windows/VectorTileLayerProperties/tab" ), mOptStackedWidget->indexOf( mOptsPage_Style ) );
113 }
114
115 mBtnStyle = new QPushButton( tr( "Style" ) );
116 QMenu *menuStyle = new QMenu( this );
117 menuStyle->addAction( tr( "Load Style…" ), this, &QgsVectorTileLayerProperties::loadStyle );
118 menuStyle->addAction( tr( "Save Style…" ), this, &QgsVectorTileLayerProperties::saveStyleToFile );
119 menuStyle->addSeparator();
120 menuStyle->addAction( tr( "Save as Default" ), this, &QgsVectorTileLayerProperties::saveStyleAsDefault );
121 menuStyle->addAction( tr( "Restore Default" ), this, &QgsVectorTileLayerProperties::loadDefaultStyle );
122 mBtnStyle->setMenu( menuStyle );
123 connect( menuStyle, &QMenu::aboutToShow, this, &QgsVectorTileLayerProperties::aboutToShowStyleMenu );
124
125 buttonBox->addButton( mBtnStyle, QDialogButtonBox::ResetRole );
126
127 mBtnMetadata = new QPushButton( tr( "Metadata" ), this );
128 QMenu *menuMetadata = new QMenu( this );
129 mActionLoadMetadata = menuMetadata->addAction( tr( "Load Metadata…" ), this, &QgsVectorTileLayerProperties::loadMetadataFromFile );
130 mActionSaveMetadataAs = menuMetadata->addAction( tr( "Save Metadata…" ), this, &QgsVectorTileLayerProperties::saveMetadataToFile );
131 mBtnMetadata->setMenu( menuMetadata );
132 buttonBox->addButton( mBtnMetadata, QDialogButtonBox::ResetRole );
133
134 initialize();
135}
136
137void QgsVectorTileLayerProperties::apply()
138{
139 if ( mSourceWidget )
140 {
141 const QString newSource = mSourceWidget->sourceUri();
142 if ( newSource != mLayer->source() )
143 {
144 mLayer->setDataSource( newSource, mLayer->name(), mLayer->providerType(), QgsDataProvider::ProviderOptions() );
145 }
146 }
147
148 mLayer->setName( mLayerOrigNameLineEd->text() );
149 mLayer->setCrs( mCrsSelector->crs() );
150
151 mRendererWidget->apply();
152 mLabelingWidget->apply();
153 mMetadataWidget->acceptMetadata();
154
155 mLayer->setScaleBasedVisibility( chkUseScaleDependentRendering->isChecked() );
156 mLayer->setMinimumScale( mScaleRangeWidget->minimumScale() );
157 mLayer->setMaximumScale( mScaleRangeWidget->maximumScale() );
158
159 mMapLayerServerPropertiesWidget->save();
160}
161
162void QgsVectorTileLayerProperties::syncToLayer()
163{
164 if ( !mLayer )
165 return;
166
167 /*
168 * Information Tab
169 */
171 // Inject the stylesheet
172 const QString html { mLayer->htmlMetadata().replace( QLatin1String( "<head>" ), QStringLiteral( R"raw(<head><style type="text/css">%1</style>)raw" ) ).arg( myStyle ) };
173 mMetadataViewer->setHtml( html );
174
175 /*
176 * Source
177 */
178
179 mLayerOrigNameLineEd->setText( mLayer->name() );
180 mCrsSelector->setCrs( mLayer->crs() );
181
182 if ( !mSourceWidget )
183 {
184 mSourceWidget = QgsGui::sourceWidgetProviderRegistry()->createWidget( mLayer );
185 if ( mSourceWidget )
186 {
187 QHBoxLayout *layout = new QHBoxLayout();
188 layout->addWidget( mSourceWidget );
189 mSourceGroupBox->setLayout( layout );
190 if ( !mSourceWidget->groupTitle().isEmpty() )
191 mSourceGroupBox->setTitle( mSourceWidget->groupTitle() );
192 mSourceGroupBox->show();
193
194 connect( mSourceWidget, &QgsProviderSourceWidget::validChanged, this, [=]( bool isValid ) {
195 buttonBox->button( QDialogButtonBox::Apply )->setEnabled( isValid );
196 buttonBox->button( QDialogButtonBox::Ok )->setEnabled( isValid );
197 } );
198 }
199 }
200
201 if ( mSourceWidget )
202 {
203 mSourceWidget->setMapCanvas( mCanvas );
204 mSourceWidget->setSourceUri( mLayer->source() );
205 }
206
207 /*
208 * Symbology Tab
209 */
210 mRendererWidget->syncToLayer( mLayer );
211
212 /*
213 * Labels Tab
214 */
215 mLabelingWidget->setLayer( mLayer );
216
217 /*
218 * Rendering
219 */
220 chkUseScaleDependentRendering->setChecked( mLayer->hasScaleBasedVisibility() );
221 mScaleRangeWidget->setScaleRange( mLayer->minimumScale(), mLayer->maximumScale() );
222
223 mMapLayerServerPropertiesWidget->setServerProperties( mLayer->serverProperties() );
224}
225
230
232{
233 const QgsSettings settings; // where we keep last used filter in persistent state
234
235 QgsMapLayerLoadStyleDialog dlg( mLayer );
236
237 if ( dlg.exec() )
238 {
239 mOldStyle = mLayer->styleManager()->style( mLayer->styleManager()->currentStyle() );
240 const QgsMapLayer::StyleCategories categories = dlg.styleCategories();
241 const QString type = dlg.fileExtension();
242 if ( type.compare( QLatin1String( "qml" ), Qt::CaseInsensitive ) == 0 )
243 {
244 QString message;
245 bool defaultLoadedFlag = false;
246 const QString filePath = dlg.filePath();
247 message = mLayer->loadNamedStyle( filePath, defaultLoadedFlag, categories );
248
249 //reset if the default style was loaded OK only
250 if ( defaultLoadedFlag )
251 {
252 syncToLayer();
253 }
254 else
255 {
256 //let the user know what went wrong
257 QMessageBox::warning( this, tr( "Load Style" ), message );
258 }
259 }
260 else if ( type.compare( QLatin1String( "json" ), Qt::CaseInsensitive ) == 0 )
261 {
262 QFile file( dlg.filePath() );
263 if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
264 {
265 QMessageBox::warning( this, tr( "Load Style" ), tr( "Could not read %1" ).arg( QDir::toNativeSeparators( dlg.filePath() ) ) );
266 }
267 else
268 {
269 QTextStream in( &file );
270#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
271 in.setCodec( "UTF-8" );
272#endif
273 const QString content = in.readAll();
274
276 // convert automatically from pixel sizes to millimeters, because pixel sizes
277 // are a VERY edge case in QGIS and don't play nice with hidpi map renders or print layouts
279 //assume source uses 96 dpi
280 context.setPixelSizeConversionFactor( 25.4 / 96.0 );
281
282 //load sprites
283 QVariantMap styleDefinition = QgsJsonUtils::parseJson( content ).toMap();
284
285 QFileInfo fi( dlg.filePath() );
286 QgsVectorTileUtils::loadSprites( styleDefinition, context, QStringLiteral( "file://" ) + fi.absolutePath() );
287
289
290 if ( converter.convert( content, &context ) != QgsMapBoxGlStyleConverter::Success )
291 {
292 QMessageBox::warning( this, tr( "Load Style" ), converter.errorMessage() );
293 }
294 else
295 {
297 {
298 mLayer->setRenderer( converter.renderer() );
299 }
301 {
302 mLayer->setLabeling( converter.labeling() );
303 }
304 syncToLayer();
305 }
306 }
307 }
308 activateWindow(); // set focus back to properties dialog
309 }
310}
311
316
317void QgsVectorTileLayerProperties::aboutToShowStyleMenu()
318{
319 QMenu *m = qobject_cast<QMenu *>( sender() );
320
322 // re-add style manager actions!
323 m->addSeparator();
325}
326
327void QgsVectorTileLayerProperties::showHelp()
328{
329 const QVariant helpPage = mOptionsStackedWidget->currentWidget()->property( "helpPage" );
330
331 if ( helpPage.isValid() )
332 {
333 QgsHelp::openHelp( helpPage.toString() );
334 }
335 else
336 {
337 QgsHelp::openHelp( QStringLiteral( "working_with_vector_tiles/vector_tiles_properties.html" ) );
338 }
339}
340
341void QgsVectorTileLayerProperties::crsChanged( const QgsCoordinateReferenceSystem &crs )
342{
343 QgsDatumTransformDialog::run( crs, QgsProject::instance()->crs(), this, mCanvas, tr( "Select Transformation" ) );
344 mLayer->setCrs( crs );
345 mMetadataWidget->crsChanged();
346}
@ Millimeters
Millimeters.
static QString reportStyleSheet(QgsApplication::StyleSheetType styleSheetType=QgsApplication::StyleSheetType::Qt)
Returns a css style sheet for reports, the styleSheetType argument determines what type of stylesheet...
@ WebBrowser
StyleSheet for embedded browsers (QtWebKit), supports full standard CSS.
This class represents a coordinate reference system (CRS).
static bool run(const QgsCoordinateReferenceSystem &sourceCrs=QgsCoordinateReferenceSystem(), const QgsCoordinateReferenceSystem &destinationCrs=QgsCoordinateReferenceSystem(), QWidget *parent=nullptr, QgsMapCanvas *mapCanvas=nullptr, const QString &windowTitle=QString())
Runs the dialog (if required) prompting for the desired transform to use from sourceCrs to destinatio...
static QgsProviderSourceWidgetProviderRegistry * sourceWidgetProviderRegistry()
Returns the registry of provider source widget providers.
Definition qgsgui.cpp:120
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition qgshelp.cpp:39
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
Base class for "layer properties" dialogs, containing common utilities for handling functionality in ...
void saveMetadataToFile()
Allows the user to save the layer's metadata as a file.
virtual void rollback()
Rolls back changes made to the layer.
void saveStyleAsDefault()
Saves the current layer style as the default for the layer.
void setMetadataWidget(QgsMetadataWidget *widget, QWidget *page)
Sets the metadata widget and page associated with the dialog.
void loadDefaultStyle()
Reloads the default style for the layer.
void saveStyleToFile()
Allows the user to save the layer's style to a file.
QgsMapCanvas * mCanvas
Associated map canvas.
QgsMapLayerStyle mOldStyle
Previous layer style.
void loadMetadataFromFile()
Allows the user to load layer metadata from a file.
void initialize()
Initialize the dialog.
void openUrl(const QUrl &url)
Handles opening a url from the dialog.
Context for a MapBox GL style conversion operation.
void setTargetUnit(Qgis::RenderUnit targetUnit)
Sets the target unit type.
void setPixelSizeConversionFactor(double sizeConversionFactor)
Sets the pixel size conversion factor, used to scale the original pixel sizes when converting styles.
Handles conversion of MapBox GL styles to QGIS vector tile renderers and labeling settings.
QgsVectorTileRenderer * renderer() const
Returns a new instance of a vector tile renderer representing the converted style,...
QgsVectorTileLabeling * labeling() const
Returns a new instance of a vector tile labeling representing the converted style,...
Result convert(const QVariantMap &style, QgsMapBoxGlStyleConversionContext *context=nullptr)
Converts a JSON style map, and returns the resultant status of the conversion.
@ Success
Conversion was successful.
QString errorMessage() const
Returns a descriptive error message if an error was encountered during the style conversion,...
Map canvas is a class for displaying all GIS data types on a canvas.
A reusable dialog which allows users to select stored layer styles and categories to load for a map l...
QgsMapLayer::StyleCategories styleCategories() const
Returns the list of selected style categories the user has opted to load.
QString filePath() const
Returns the full path to the selected layer style source file.
QString fileExtension() const
Returns the file extension for the selected layer style source file.
void removesExtraMenuSeparators(QMenu *m)
removes extra separators from the menu
void addStyleManagerActions(QMenu *m, QgsMapLayer *layer)
adds actions to the menu in accordance to the layer
static QgsMapLayerStyleGuiUtils * instance()
returns a singleton instance of this class
QString currentStyle() const
Returns name of the current style.
QgsMapLayerStyle style(const QString &name) const
Returns data of a stored style - accessed by its unique name.
QString name
Definition qgsmaplayer.h:80
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
void setMinimumScale(double scale)
Sets the minimum map scale (i.e.
virtual QString loadNamedStyle(const QString &theURI, bool &resultFlag, bool loadFromLocalDb, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories, Qgis::LoadStyleFlags flags=Qgis::LoadStyleFlags())
Loads a named style from file/local db/datasource db.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:83
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
void setDataSource(const QString &dataSource, const QString &baseName=QString(), const QString &provider=QString(), bool loadDefaultStyleFlag=false)
Updates the data source of the layer.
void setMaximumScale(double scale)
Sets the maximum map scale (i.e.
QFlags< StyleCategory > StyleCategories
void setScaleBasedVisibility(bool enabled)
Sets whether scale based visibility is enabled for the layer.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
void setName(const QString &name)
Set the display name of the layer.
double minimumScale() const
Returns the minimum map scale (i.e.
QgsMapLayerStyleManager * styleManager() const
Gets access to the layer's style manager.
@ Symbology
Symbology.
@ Labeling
Labeling.
double maximumScale() const
Returns the maximum map scale (i.e.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
A bar for displaying non-blocking messages to the user.
A wizard to edit metadata on a map layer.
void acceptMetadata()
Saves the metadata to the layer.
void crsChanged()
If the CRS is updated.
void setMapCanvas(QgsMapCanvas *canvas)
Sets a map canvas associated with the widget.
QStackedWidget * mOptStackedWidget
void initOptionsBase(bool restoreUi=true, const QString &title=QString())
Set up the base ui connections for vertical tabs.
static QgsProject * instance()
Returns the QgsProject singleton instance.
void crsChanged(const QgsCoordinateReferenceSystem &crs)
Emitted when the selected CRS is changed.
QgsProviderSourceWidget * createWidget(QgsMapLayer *layer, QWidget *parent=nullptr)
Creates a new widget to configure the source of the specified layer.
virtual QString groupTitle() const
Returns an optional group title for the source settings, for use in layer properties dialogs.
void validChanged(bool isValid)
Emitted whenever the validation status of the widget changes.
virtual QString sourceUri() const =0
Returns the source URI as currently defined by the widget.
virtual void setMapCanvas(QgsMapCanvas *mapCanvas)
Sets a map canvas associated with the widget.
virtual void setSourceUri(const QString &uri)=0
Sets the source uri to show in the widget.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
bool contains(const QString &key, QgsSettings::Section section=QgsSettings::NoSection) const
Returns true if there exists a setting called key; returns false otherwise.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
Q_DECL_DEPRECATED void saveDefaultStyle() SIP_DEPRECATED
Saves the default style when appropriate button is pressed.
Q_DECL_DEPRECATED void saveStyleAs() SIP_DEPRECATED
Saves a style when appriate button is pressed.
void loadStyle()
Loads a saved style when appropriate button is pressed.
QgsVectorTileLayerProperties(QgsVectorTileLayer *lyr, QgsMapCanvas *canvas, QgsMessageBar *messageBar, QWidget *parent=nullptr, Qt::WindowFlags=QgsGuiUtils::ModalDialogFlags)
Constructor.
Implements a map layer that is dedicated to rendering of vector tiles.
void setRenderer(QgsVectorTileRenderer *r)
Sets renderer for the map layer.
void setLabeling(QgsVectorTileLabeling *labeling)
Sets labeling for the map layer.
QString htmlMetadata() const override
Obtain a formatted HTML string containing assorted metadata for this layer.
static void loadSprites(const QVariantMap &styleDefinition, QgsMapBoxGlStyleConversionContext &context, const QString &styleUrl=QString())
Downloads the sprite image and sets it to the conversion context.
const QgsCoordinateReferenceSystem & crs
Setting options for creating vector data providers.