|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from importlib import resources |
| 4 | +from typing import TYPE_CHECKING |
| 5 | + |
| 6 | +from qgis.core import ( |
| 7 | + QgsFeature, |
| 8 | + QgsFeatureIterator, |
| 9 | + QgsFeatureRequest, |
| 10 | + QgsFieldProxyModel, |
| 11 | + QgsVectorLayer, |
| 12 | +) |
| 13 | +from qgis.PyQt import uic |
| 14 | +from qgis.PyQt.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, QProgressBar |
| 15 | + |
| 16 | +from arho_feature_template.core.models import PlanFeature, RegulationGroupLibrary |
| 17 | +from arho_feature_template.project.layers.code_layers import UndergroundTypeLayer, code_layers |
| 18 | +from arho_feature_template.project.layers.plan_layers import ( |
| 19 | + FEATURE_LAYER_NAME_TO_CLASS_MAP, |
| 20 | + RegulationGroupAssociationLayer, |
| 21 | + plan_feature_layers, |
| 22 | + plan_layers, |
| 23 | +) |
| 24 | +from arho_feature_template.utils.misc_utils import iface, use_wait_cursor |
| 25 | + |
| 26 | +if TYPE_CHECKING: |
| 27 | + from qgis.gui import QgsCheckableComboBox, QgsFieldComboBox, QgsFieldExpressionWidget, QgsMapLayerComboBox |
| 28 | + |
| 29 | + from arho_feature_template.gui.components.code_combobox import CodeComboBox |
| 30 | + |
| 31 | + |
| 32 | +ui_path = resources.files(__package__) / "import_features_form.ui" |
| 33 | +FormClass, _ = uic.loadUiType(ui_path) |
| 34 | + |
| 35 | + |
| 36 | +class ImportFeaturesForm(QDialog, FormClass): |
| 37 | + def __init__(self, active_plan_regulation_groups_library: RegulationGroupLibrary): |
| 38 | + super().__init__() |
| 39 | + self.setupUi(self) |
| 40 | + |
| 41 | + # TYPES |
| 42 | + self.source_layer_selection: QgsMapLayerComboBox |
| 43 | + self.filter_expression: QgsFieldExpressionWidget |
| 44 | + self.selected_features_only: QCheckBox |
| 45 | + |
| 46 | + self.name_selection: QgsFieldComboBox |
| 47 | + self.description_selection: QgsFieldComboBox |
| 48 | + self.feature_type_of_underground_selection: CodeComboBox |
| 49 | + self.regulation_groups_selection: QgsCheckableComboBox |
| 50 | + |
| 51 | + self.target_layer_selection: QgsMapLayerComboBox |
| 52 | + |
| 53 | + self.progress_bar: QProgressBar |
| 54 | + self.process_button_box: QDialogButtonBox |
| 55 | + |
| 56 | + # INIT |
| 57 | + self.process_button_box.button(QDialogButtonBox.Ok).setText("Import") |
| 58 | + self.process_button_box.accepted.connect(self.import_features) |
| 59 | + self.process_button_box.rejected.connect(self.reject) |
| 60 | + |
| 61 | + # Source layer initialization |
| 62 | + # Exclude all project layers from valid source layers |
| 63 | + # NOTE: Some project layers are not included in either `plan_layers` or `code_layers`? |
| 64 | + self.source_layer_selection.setLayer(iface.activeLayer()) |
| 65 | + excluded_layers = [layer.get_from_project() for layer in plan_layers + code_layers] |
| 66 | + self.source_layer_selection.setExceptedLayerList(excluded_layers) |
| 67 | + self.source_layer_selection.layerChanged.connect(self._on_layer_selections_changed) |
| 68 | + |
| 69 | + # Target layer initialization |
| 70 | + # Set only plan feature layers as valid target layers |
| 71 | + self.target_layer_selection.clear() |
| 72 | + self.target_layer_selection.setAdditionalLayers(layer.get_from_project() for layer in plan_feature_layers) |
| 73 | + self.target_layer_selection.setCurrentIndex(0) |
| 74 | + self.target_layer_selection.layerChanged.connect(self._on_layer_selections_changed) |
| 75 | + |
| 76 | + # Name field initialization |
| 77 | + self.name_selection.setAllowEmptyFieldName(True) |
| 78 | + self.name_selection.setFilters(QgsFieldProxyModel.Filter.String) |
| 79 | + self.name_selection.setField("") |
| 80 | + |
| 81 | + # Description field initialization |
| 82 | + self.description_selection.setAllowEmptyFieldName(True) |
| 83 | + self.description_selection.setFilters(QgsFieldProxyModel.Filter.String) |
| 84 | + self.description_selection.setField("") |
| 85 | + |
| 86 | + # Underground type initialization |
| 87 | + # Remove NULL from the selections and set Maanpäällinen as default |
| 88 | + self.feature_type_of_underground_selection.populate_from_code_layer(UndergroundTypeLayer) |
| 89 | + self.feature_type_of_underground_selection.remove_item_by_text("NULL") |
| 90 | + self.feature_type_of_underground_selection.setCurrentIndex(1) # Set default to Maanpäällinen (index 1) |
| 91 | + |
| 92 | + # Regulation groups initialization |
| 93 | + # Only regulation group already in DB are shown and they are not categorized right now |
| 94 | + # NOTE: This means groups that are "Aluevaraus" groups can be given to "Osa-alue" for example |
| 95 | + i = 0 |
| 96 | + for category in active_plan_regulation_groups_library.regulation_group_categories: |
| 97 | + for group in category.regulation_groups: |
| 98 | + self.regulation_groups_selection.addItem(str(group)) |
| 99 | + self.regulation_groups_selection.setItemData(i, group.id_) |
| 100 | + i += 1 |
| 101 | + |
| 102 | + self._on_layer_selections_changed(self.source_layer_selection.currentLayer()) |
| 103 | + |
| 104 | + def _on_layer_selections_changed(self, _: QgsVectorLayer): |
| 105 | + self.source_layer: QgsVectorLayer = self.source_layer_selection.currentLayer() |
| 106 | + self.source_layer_name: str = self.source_layer.name() |
| 107 | + self.target_layer: QgsVectorLayer = self.target_layer_selection.currentLayer() |
| 108 | + self.target_layer_name: str = self.target_layer.name() |
| 109 | + |
| 110 | + self.filter_expression.setLayer(self.source_layer) |
| 111 | + self.name_selection.setLayer(self.source_layer) |
| 112 | + self.description_selection.setLayer(self.source_layer) |
| 113 | + |
| 114 | + if self.source_and_target_layer_types_match(): |
| 115 | + self.process_button_box.button(QDialogButtonBox.Ok).setEnabled(True) |
| 116 | + else: |
| 117 | + self.process_button_box.button(QDialogButtonBox.Ok).setEnabled(False) |
| 118 | + |
| 119 | + def source_and_target_layer_types_match(self) -> bool: |
| 120 | + if not self.source_layer or not self.target_layer: |
| 121 | + return False |
| 122 | + return self.source_layer.wkbType() is self.target_layer.wkbType() |
| 123 | + |
| 124 | + @use_wait_cursor |
| 125 | + def import_features(self): |
| 126 | + if not self.source_layer or not self.target_layer: |
| 127 | + return |
| 128 | + |
| 129 | + self.progress_bar.setValue(0) |
| 130 | + source_features = list(self.get_source_features(self.source_layer)) |
| 131 | + if not source_features: |
| 132 | + iface.messageBar().pushInfo("", "Yhtään kohdetta ei tuotu.") |
| 133 | + return |
| 134 | + |
| 135 | + # Create and add new plan features |
| 136 | + plan_features = self.create_plan_features(source_features) |
| 137 | + total_count = len(plan_features) |
| 138 | + failed_count = 0 |
| 139 | + success_count = 0 |
| 140 | + for i, feat in enumerate(plan_features): |
| 141 | + self.progress_bar.setValue(int((i + 1) / total_count * 100)) |
| 142 | + if self._save_feature(feat, self.target_layer, None, "Kaavakohteen lisääminen"): |
| 143 | + success_count += 1 |
| 144 | + else: |
| 145 | + failed_count += 1 |
| 146 | + |
| 147 | + # If regulation groups are defined, associate them with the plan features |
| 148 | + if len(self.regulation_groups_selection.checkedItems()) > 0: |
| 149 | + associations = self.create_regulation_group_associations(plan_features) |
| 150 | + associations_layer = RegulationGroupAssociationLayer.get_from_project() |
| 151 | + for association in associations: |
| 152 | + self._save_feature(association, associations_layer, None, "Kaavamääräysryhmän assosiaation lisääminen") |
| 153 | + |
| 154 | + if failed_count == 0: |
| 155 | + iface.messageBar().pushSuccess("", "Kaavakohteet tuotiin onnistuneesti.") |
| 156 | + else: |
| 157 | + iface.messageBar().pushInfo("", f"Osa kaavakohteista tuotiin epäonnistuneesti ({failed_count}).") |
| 158 | + |
| 159 | + self.progress_bar.setValue(100) |
| 160 | + |
| 161 | + def get_source_features(self, source_layer: QgsVectorLayer) -> QgsFeatureIterator | list[QgsFeature]: |
| 162 | + expression_text = self.filter_expression.currentText() |
| 163 | + |
| 164 | + # Case 1: Both selection and expression |
| 165 | + if self.selected_features_only.isChecked() and expression_text: |
| 166 | + selected_features = source_layer.selectedFeatures() |
| 167 | + request = QgsFeatureRequest().setFilterExpression(expression_text) |
| 168 | + source_features = [feat for feat in source_layer.getFeatures(request) if feat in selected_features] |
| 169 | + |
| 170 | + # Case 2: Only selection |
| 171 | + elif self.selected_features_only.isChecked(): |
| 172 | + source_features = source_layer.selectedFeatures() |
| 173 | + |
| 174 | + # Case 3: Only expression |
| 175 | + elif expression_text: |
| 176 | + request = QgsFeatureRequest().setFilterExpression(expression_text) |
| 177 | + source_features = source_layer.getFeatures(request) |
| 178 | + |
| 179 | + # Case 4: No expression or selection |
| 180 | + else: |
| 181 | + source_features = source_layer.getFeatures() |
| 182 | + |
| 183 | + return source_features |
| 184 | + |
| 185 | + def create_plan_features(self, source_features: QgsFeatureIterator | list[QgsFeature]) -> list[QgsFeature]: |
| 186 | + type_of_underground_id = self.feature_type_of_underground_selection.value() |
| 187 | + source_layer_name_field = self.name_selection.currentField() |
| 188 | + source_layer_description_field = self.description_selection.currentField() |
| 189 | + layer_class = FEATURE_LAYER_NAME_TO_CLASS_MAP.get(self.target_layer_name) |
| 190 | + if not layer_class: |
| 191 | + msg = f"Could not find plan feature layer class for layer name {self.target_layer_name}" |
| 192 | + raise ValueError(msg) |
| 193 | + |
| 194 | + return [ |
| 195 | + layer_class.feature_from_model( |
| 196 | + PlanFeature( |
| 197 | + geom=feature.geometry(), |
| 198 | + type_of_underground_id=type_of_underground_id, |
| 199 | + layer_name=self.target_layer_name, |
| 200 | + name=feature[source_layer_name_field] if source_layer_name_field else None, |
| 201 | + description=feature[source_layer_description_field] if source_layer_description_field else None, |
| 202 | + ) |
| 203 | + ) |
| 204 | + for feature in source_features |
| 205 | + ] |
| 206 | + |
| 207 | + def create_regulation_group_associations(self, plan_features: list[QgsFeature]) -> list[QgsFeature]: |
| 208 | + return [ |
| 209 | + RegulationGroupAssociationLayer.feature_from( |
| 210 | + regulation_group_id, self.target_layer_name, plan_feature["id"] |
| 211 | + ) |
| 212 | + for regulation_group_id in self.regulation_groups_selection.checkedItemsData() |
| 213 | + for plan_feature in plan_features |
| 214 | + ] |
| 215 | + |
| 216 | + @staticmethod |
| 217 | + def _save_feature(feature: QgsFeature, layer: QgsVectorLayer, id_: str | None, edit_text: str = "") -> bool: |
| 218 | + if not layer.isEditable(): |
| 219 | + layer.startEditing() |
| 220 | + layer.beginEditCommand(edit_text) |
| 221 | + |
| 222 | + if id_ is None: |
| 223 | + layer.addFeature(feature) |
| 224 | + else: |
| 225 | + layer.updateFeature(feature) |
| 226 | + |
| 227 | + layer.endEditCommand() |
| 228 | + return layer.commitChanges(stopEditing=False) |
0 commit comments