Skip to content

Commit

Permalink
Force refresh layers, fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustry committed Aug 28, 2024
1 parent 7648dd1 commit 13beb88
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 53 deletions.
66 changes: 34 additions & 32 deletions dynamic_layers/core/dynamic_layers_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
QgsRectangle,
QgsVectorLayer,
)
from qgis.PyQt.QtCore import NULL
from qgis.utils import iface

from dynamic_layers.core.layer_datasource_modifier import (
Expand Down Expand Up @@ -97,11 +98,13 @@ def update_dynamic_layers_datasource(self):
if layer.renderer() and layer.renderer().type() == 'graduatedSymbol':
layer.triggerRepaint()

layer.updateExtents(True)

if not self.iface:
return

self.iface.actionDraw().trigger()
self.iface.mapCanvas().refresh()
# self.iface.actionDraw().trigger()
# self.iface.mapCanvas().refresh()

def update_dynamic_project_properties(self):
"""
Expand Down Expand Up @@ -142,52 +145,51 @@ def set_project_property(self, project_property: Annotated[str, WmsProjectProper
layer=self.layer,
feature=self.feature,
)
if val is None:
if val is None or val == NULL:
log_message(
f'The expression evaluation "{val}" for the project property "{project_property}" was None, '
f'The expression evaluation "{val}" for the project property "{project_property}" was None/NULL, '
f'it has been set to an empty string.',
Qgis.Warning,
self.feedback,
)
val = ""
self.project.writeEntry(project_property, '', val)

def update_project_extent(self) -> QgsRectangle:
def update_project_extent(self):
"""
Sets the project extent
and corresponding XML property
"""
log_message(tr("Update project extant"), Qgis.Info, self.feedback)
# Get extent from extent layer (if given)
p_extent = None
if self.extent_layer:
self.extent_layer.updateExtents()
self.extent_layer.updateExtents(True)
p_extent = self.extent_layer.extent()
else:
if self.iface:
p_extent = self.iface.mapCanvas().extent()
log_message(tr("Extent from layer : {}").format(self.extent_layer.name()), Qgis.Info, self.feedback)

if p_extent and p_extent.width() <= 0 and self.iface:
log_message(tr("Extent from iface"), Qgis.Info, self.feedback)
p_extent = self.iface.mapCanvas().extent()

# Add a margin
if p_extent:
if self.extent_margin:
margin_x = p_extent.width() * self.extent_margin / 100
margin_y = p_extent.height() * self.extent_margin / 100
margin = max(margin_x, margin_y)
p_extent = p_extent.buffered(margin)

# Modify OWS WMS extent
p_wms_extent = [
p_extent.xMinimum(),
p_extent.yMinimum(),
p_extent.xMaximum(),
p_extent.yMaximum(),
]
p_wms_extent = [str(i) for i in p_wms_extent]
self.project.writeEntry(WmsProjectProperty.Extent, '', p_wms_extent)

# Zoom canvas to extent
if self.iface:
iface.mapCanvas().setExtent(p_extent)

return p_extent
if not p_extent:
return

if self.extent_margin:
margin_x = p_extent.width() * self.extent_margin / 100
margin_y = p_extent.height() * self.extent_margin / 100
margin = max(margin_x, margin_y)
p_extent = p_extent.buffered(margin)
log_message(tr("with a margin of {}").format(margin), Qgis.Info, self.feedback)

# Modify WMS extent
p_wms_extent = [p_extent.xMinimum(), p_extent.yMinimum(), p_extent.xMaximum(), p_extent.yMaximum()]
p_wms_extent = [str(i) for i in p_wms_extent]
self.project.writeEntry(WmsProjectProperty.Extent, '', p_wms_extent)
log_message(tr("Writing the new extent to {}").format(WmsProjectProperty.Extent ), Qgis.Info, self.feedback)

# Zoom canvas to extent
if self.iface:
log_message(tr("Refresh map canvas"), Qgis.Info, self.feedback)
self.iface.mapCanvas().setExtent(p_extent)
self.iface.mapCanvas().refresh()
19 changes: 18 additions & 1 deletion dynamic_layers/core/generate_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,31 @@ def process(self) -> bool:

log_message(tr('Starting the loop over features'), Qgis.Info, self.feedback)

total = 100.0 / self.coverage.featureCount() if self.coverage.featureCount() else 0

request = QgsFeatureRequest()
# noinspection PyUnresolvedReferences
request.setFlags(QgsFeatureRequest.NoGeometry)
for feature in self.coverage.getFeatures(request):
for i, feature in enumerate(self.coverage.getFeatures(request)):

if self.feedback.isCanceled():
break

engine.set_layer_and_feature(self.coverage, feature)

if self.feedback:
self.feedback.pushDebugInfo(tr('Feature : {}').format(feature.id()))

engine.update_dynamic_layers_datasource()

if self.feedback.isCanceled():
break

for layer in self.project.mapLayers().values():
# Force refresh layer extents
if hasattr(layer, 'updateExtents'):
layer.updateExtents(True)

engine.update_dynamic_project_properties()

# Output file name
Expand All @@ -87,4 +102,6 @@ def process(self) -> bool:
for a_file in files:
copyfile(a_file, str(new_path) + a_file.suffix)

self.feedback.setProgress(int(i * total))

return True
4 changes: 2 additions & 2 deletions dynamic_layers/core/layer_datasource_modifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def set_data_source(self, new_source_uri: str):
log_message(
tr(
"Error, layer '{name}' is not valid, error : {error}"
).format(self.layer.name(), self.layer.error()),
).format(name=self.layer.name(), error=self.layer.error()),
Qgis.Critical,
self.feedback,
)
Expand All @@ -96,7 +96,7 @@ def set_data_source(self, new_source_uri: str):
self.layer.renderer().updateClasses(self.layer, self.layer.renderer().mode(), len(ranges))

# Reload layer
self.layer.reload()
# self.layer.reload()
# self.layer.triggerRepaint()

@staticmethod
Expand Down
50 changes: 32 additions & 18 deletions dynamic_layers/dynamic_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@
)
from dynamic_layers.dynamic_layers_dialog import DynamicLayersDialog
from dynamic_layers.processing_provider.provider import Provider
from dynamic_layers.tools import plugin_path, resources_path, tr
from dynamic_layers.tools import (
format_expression,
log_message,
plugin_path,
resources_path,
tr,
)


class DynamicLayers:
Expand Down Expand Up @@ -521,10 +527,10 @@ def on_copy_from_layer(self):
return

# Get the layer datasource
uri = self.selectedLayer.dataProvider().dataSourceUri().split('|')[0]
abstract = self.selectedLayer.abstract()
title = self.selectedLayer.title()
name = self.selectedLayer.name()
uri = format_expression(self.selectedLayer.dataProvider().dataSourceUri().split('|')[0], self.is_expression)
abstract = format_expression(self.selectedLayer.abstract(), self.is_expression)
title = format_expression(self.selectedLayer.title(), self.is_expression)
name = format_expression(self.selectedLayer.name(), self.is_expression)

# Previous values
previous_uri = self.dlg.dynamicDatasourceContent.toPlainText()
Expand Down Expand Up @@ -555,15 +561,10 @@ def on_copy_from_layer(self):
if result == QMessageBox.No:
return

# Set the dynamic datasource content input
self.dlg.dynamicDatasourceContent.setPlainText(f"'{uri}'" if self.is_expression else uri)

# Set templates for title and abstract
self.dlg.abstractTemplate.setPlainText(f"'{abstract}'" if self.is_expression else abstract)

self.dlg.titleTemplate.setText(f"'{title}'" if self.is_expression else title)

self.dlg.dynamic_name_content.setText(f"'{name}'" if self.is_expression else name)
self.dlg.dynamicDatasourceContent.setPlainText(uri)
self.dlg.abstractTemplate.setPlainText(abstract)
self.dlg.titleTemplate.setText(title)
self.dlg.dynamic_name_content.setText(name)

##
# Variables tab
Expand Down Expand Up @@ -720,20 +721,26 @@ def on_copy_from_project_clicked(self):
if not p_title and self.project.readEntry(WmsProjectProperty.Title, "/"):
p_title = self.project.readEntry(WmsProjectProperty.Title, "/")[0]

p_title = format_expression(p_title, self.is_expression)

# Shortname
p_shortname = ''
if self.project.readEntry(PluginProjectProperty.ShortName, PLUGIN_SCOPE_KEY):
p_shortname = self.project.readEntry(PluginProjectProperty.ShortName, PLUGIN_SCOPE_KEY)[0]
if not p_shortname and self.project.readEntry(WmsProjectProperty.ShortName, "/"):
p_shortname = self.project.readEntry(WmsProjectProperty.ShortName, "/")[0]

p_shortname = format_expression(p_shortname, self.is_expression)

# Abstract
p_abstract = ''
if self.project.readEntry(PluginProjectProperty.Abstract, PLUGIN_SCOPE_KEY):
p_abstract = self.project.readEntry(PluginProjectProperty.Abstract, PLUGIN_SCOPE_KEY)[0]
if not p_abstract and self.project.readEntry(WmsProjectProperty.Abstract, "/"):
p_abstract = self.project.readEntry(WmsProjectProperty.Abstract, "/")[0]

p_abstract = format_expression(p_abstract, self.is_expression)

ask = False
previous_title = self.dlg.inProjectTitle.text()
if previous_title != '' and previous_title != p_title:
Expand Down Expand Up @@ -764,8 +771,9 @@ def on_copy_from_project_clicked(self):
if not self.project.readEntry(WmsProjectProperty.Capabilities, "/")[1]:
self.project.writeEntry(WmsProjectProperty.Capabilities, "/", True)

self.dlg.inProjectTitle.setText(f"'{p_title}'" if self.is_expression else p_title)
self.dlg.inProjectAbstract.setPlainText(f"'{p_abstract}'" if self.is_expression else p_abstract)
self.dlg.inProjectTitle.setText(p_title)
self.dlg.inProjectAbstract.setPlainText(p_abstract)
self.dlg.inProjectShortName.setText(p_shortname)

def on_project_property_changed(self, prop: str) -> Optional[str]:
"""
Expand All @@ -776,12 +784,11 @@ def on_project_property_changed(self, prop: str) -> Optional[str]:
return None

widget = self.projectPropertiesInputs[prop]['widget']
if prop in ('title', 'variableSourceLayerExpression'):
if prop in ('title', 'variableSourceLayerExpression', 'shortname'):
val = widget.text()
elif prop == 'abstract':
val = widget.toPlainText()
elif prop in ('extentLayer', 'variableSourceLayer'):
# var = None
layer = widget.currentLayer()
if layer:
val = layer.id()
Expand All @@ -790,6 +797,7 @@ def on_project_property_changed(self, prop: str) -> Optional[str]:
elif prop == 'extentMargin':
val = widget.value()
else:
log_message(f'Unknown widget {prop}, please ask the developer', Qgis.Critical, None)
return None

# Store value into the project
Expand Down Expand Up @@ -861,9 +869,15 @@ def on_apply_variables_clicked(self):
# Set extent margin
engine.extent_margin = self.dlg.inExtentMargin.value()

for layer in self.project.mapLayers().values():
# Force refresh layer extents
if hasattr(layer, 'updateExtents'):
layer.updateExtents(True)

# Set new extent
engine.update_project_extent()
except QgsProcessingException as e:
log_message(str(e), Qgis.Critical, None)
self.dlg.message_bar.pushCritical(tr("Parsing expression error"), str(e))
return

Expand Down

0 comments on commit 13beb88

Please sign in to comment.