class web2qgisDialog(QtWidgets.QDialog, FORM_CLASS): def __init__(self, iface, parent=None): """Constructor.""" super(web2qgisDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.iface = iface self.button_box.button(QDialogButtonBox.Save).setEnabled(False) self.loadButton.clicked.connect(self.loadMap) self.button_box.accepted.connect(self.getMap) tplPath = "file:///C:/Users/tchadwin/Desktop/%C3%A9/" singleSymbol = "%sqgis2web_2018_05_17-15_08_53_455820/index.html" % tplPath categorized = "%sqgis2web_2018_05_18-16_25_05_270745/index.html" % tplPath graduated = "%sqgis2web_2018_05_19-09_36_13_550344/index.html" % tplPath self.urlInput.setText( "file:///C:/Users/tchadwin/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/web2qgis/HTMLrefs/leaflet_point.html" ) def loadMap(self): self.webview = QWebView() self.webview.loadFinished.connect(self.mapLoaded) self.webview.load(QUrl(self.urlInput.text())) def mapLoaded(self): webpage = self.webview.page() self.mainframe = webpage.mainFrame() self.detectMap(self.mainframe) for frame in self.mainframe.childFrames(): self.detectMap(frame) def detectMap(self, frame): leaflet = detectLeaflet(frame) openlayers = detectOpenlayers(frame) if leaflet: self.feedbackLabel.setText("Leaflet map detected") self.button_box.button(QDialogButtonBox.Save).setEnabled(True) elif openlayers: self.feedbackLabel.setText("OpenLayers map detected") self.button_box.button(QDialogButtonBox.Save).setEnabled(True) else: self.feedbackLabel.setText("No map detected") self.button_box.button(QDialogButtonBox.Save).setEnabled(False) def getMap(self): webpage = self.webview.page() self.mainframe = webpage.mainFrame() if self.feedbackLabel.text() == "Leaflet map detected": getLeafletMap(self.mainframe, self.iface) for frame in self.mainframe.childFrames(): getLeafletMap(frame, self.iface) elif self.feedbackLabel.text() == "OpenLayers map detected": getOpenlayersMap(self.mainframe, self.iface) for frame in self.mainframe.childFrames(): getOpenlayersMap(frame, self.iface) self.feedbackLabel.clear()
def addDocumentationTab(self, dlgProcessTab, abstract): # Check for URL try: textBox = QWebView(dlgProcessTab) textBox.load(QUrl(abstract)) textBox.show() except: textBox = QTextBrowser(dlgProcessTab) textBox.setText(pystring(abstract)) dlgProcessTab.addTab(textBox, "Documentation")
class WebDialog(QDialog): def __init__(self, parent=None, title='WebDialog'): super().__init__(parent=parent) self.setWindowTitle(title) self.html_file = None layout = QVBoxLayout() layout.setMargin(0) layout.setSpacing(6) self.WebV = QWebView() layout.addWidget(self.WebV) self.setLayout(layout) def setHTML(self, file_path): self.html_file = file_path self.WebV.load(QUrl.fromLocalFile(self.html_file))
class Geo360Dialog(QDockWidget, Ui_orbitalDialog): """Geo360 Dialog Class""" def __init__(self, iface, parent=None, featuresId=None, layer=None): QDockWidget.__init__(self) self.setupUi(self) self.DEFAULT_URL = ("http://" + config.IP + ":" + str(config.PORT) + "/viewer.html") self.DEFAULT_EMPTY = ("http://" + config.IP + ":" + str(config.PORT) + "/none.html") self.DEFAULT_BLANK = ("http://" + config.IP + ":" + str(config.PORT) + "/blank.html") # Create Viewer self.CreateViewer() self.plugin_path = os.path.dirname(os.path.realpath(__file__)) self.iface = iface self.canvas = self.iface.mapCanvas() self.parent = parent # Orientation from image self.yaw = math.pi self.bearing = None self.layer = layer self.featuresId = featuresId self.actualPointDx = None self.actualPointSx = None self.actualPointOrientation = None self.selected_features = qgsutils.getToFeature(self.layer, self.featuresId) # Get image path self.current_image = self.GetImage() # Check if image exist if os.path.exists(self.current_image) is False: qgsutils.showUserAndLogMessage(u"Information: ", u"There is no associated image.") self.resetQgsRubberBand() self.ChangeUrlViewer(self.DEFAULT_EMPTY) return # Copy file to local server self.CopyFile(self.current_image) # Set RubberBand self.resetQgsRubberBand() self.setOrientation() self.setPosition() """Update data from Marzipano Viewer""" def onNewData(self, data): try: newYaw = float(data[0]) self.UpdateOrientation(yaw=newYaw) except: None def CreateViewer(self): """Create Viewer""" qgsutils.showUserAndLogMessage(u"Information: ", u"Create viewer", onlyLog=True) self.cef_widget = QWebView() self.cef_widget.setContextMenuPolicy(Qt.NoContextMenu) self.cef_widget.settings().setAttribute(QWebSettings.JavascriptEnabled, True) pano_view_settings = self.cef_widget.settings() pano_view_settings.setAttribute(QWebSettings.WebGLEnabled, True) # pano_view_settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) pano_view_settings.setAttribute( QWebSettings.Accelerated2dCanvasEnabled, True) pano_view_settings.setAttribute(QWebSettings.JavascriptEnabled, True) self.page = _ViewerPage() self.page.newData.connect(self.onNewData) self.cef_widget.setPage(self.page) self.cef_widget.load(QUrl(self.DEFAULT_URL)) self.ViewerLayout.addWidget(self.cef_widget, 1, 0) # def SetInitialYaw(self): # """Set Initial Viewer Yaw""" # self.bearing = self.selected_features.attribute(config.column_yaw) # # self.view.browser.GetMainFrame().ExecuteFunction("InitialYaw", # # self.bearing) # return def RemoveImage(self): """Remove Image""" try: os.remove(self.plugin_path + "/viewer/image.jpg") except OSError: pass def CopyFile(self, src): """Copy Image File in Local Server""" qgsutils.showUserAndLogMessage(u"Information: ", u"Copying image", onlyLog=True) src_dir = src dst_dir = self.plugin_path + "/viewer" # Copy image in local folder img = Image.open(src_dir) rgb_im = img.convert("RGB") dst_dir = dst_dir + "/image.jpg" try: os.remove(dst_dir) except OSError: pass rgb_im.save(dst_dir) def GetImage(self): """Get Selected Image""" try: path = qgsutils.getAttributeFromFeature(self.selected_features, config.column_name) if not os.path.isabs(path): # Relative Path to Project path_project = QgsProject.instance().readPath("./") path = os.path.normpath(os.path.join(path_project, path)) except Exception: qgsutils.showUserAndLogMessage(u"Information: ", u"Column not found.") return qgsutils.showUserAndLogMessage(u"Information: ", str(path), onlyLog=True) return path def ChangeUrlViewer(self, new_url): """Change Url Viewer""" self.cef_widget.load(QUrl(new_url)) def ReloadView(self, newId): """Reaload Image viewer""" self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) # this will activate the window self.activateWindow() self.selected_features = qgsutils.getToFeature(self.layer, newId) self.current_image = self.GetImage() # Check if image exist if os.path.exists(self.current_image) is False: qgsutils.showUserAndLogMessage(u"Information: ", u"There is no associated image.") self.ChangeUrlViewer(self.DEFAULT_EMPTY) self.resetQgsRubberBand() return # Set RubberBand self.resetQgsRubberBand() self.setOrientation() self.setPosition() # Copy file to local server self.CopyFile(self.current_image) self.ChangeUrlViewer(self.DEFAULT_URL) def GetBackNextImage(self): """Get to Back Image""" sender = QObject.sender(self) lys = self.canvas.layers() # Check if mapa foto is loaded if len(lys) == 0: qgsutils.showUserAndLogMessage(u"Information: ", u"You need load the photo layer.") return for layer in lys: if layer.name() == config.layer_name: self.encontrado = True self.iface.setActiveLayer(layer) f = self.selected_features ac_lordem = f.attribute(config.column_order) if sender.objectName() == "btn_back": new_lordem = int(ac_lordem) - 1 else: new_lordem = int(ac_lordem) + 1 # Filter mapa foto layer ids = [ feat.id() for feat in layer.getFeatures(QgsFeatureRequest( ).setFilterExpression(config.column_order + " ='" + str(new_lordem) + "'")) ] if len(ids) == 0: qgsutils.showUserAndLogMessage( u"Information: ", u"There is no superiority that follows.") # Filter mapa foto layer ids = [ feat.id() for feat in layer.getFeatures(QgsFeatureRequest( ).setFilterExpression(config.column_order + " ='" + str(ac_lordem) + "'")) ] # Update selected feature self.ReloadView(ids[0]) if self.encontrado is False: qgsutils.showUserAndLogMessage( u"Information: ", u"You need a layer with images and set the name in the config.py file.", ) return def FullScreen(self, value): """FullScreen action button""" qgsutils.showUserAndLogMessage(u"Information: ", u"Fullscreen.", onlyLog=True) if value: self.showFullScreen() else: self.showNormal() def UpdateOrientation(self, yaw=None): """Update Orientation""" self.bearing = self.selected_features.attribute(config.column_yaw) try: self.actualPointOrientation.reset() except Exception: pass self.actualPointOrientation = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.LineGeometry) self.actualPointOrientation.setColor(Qt.blue) self.actualPointOrientation.setWidth(5) self.actualPointOrientation.addPoint(self.actualPointDx) # End Point CS = self.canvas.mapUnitsPerPixel() * 25 A1x = self.actualPointDx.x() - CS * math.cos(math.pi / 2) A1y = self.actualPointDx.y() + CS * math.sin(math.pi / 2) self.actualPointOrientation.addPoint(QgsPointXY( float(A1x), float(A1y))) # Vision Angle if yaw is not None: angle = float(self.bearing + yaw) * math.pi / -180 else: angle = float(self.bearing) * math.pi / -180 tmpGeom = self.actualPointOrientation.asGeometry() rotatePoint = self.rotateTool.rotate(tmpGeom, self.actualPointDx, angle) self.actualPointOrientation.setToGeometry(rotatePoint, self.dumLayer) # Set Azimut value tmpGeom = rotatePoint.asPolyline() azim = tmpGeom[0].azimuth(tmpGeom[1]) if azim < 0: azim += 360 self.yawLbl.setText("Yaw : " + str(round(yaw, 2)) + " Azimut : " + str(round(azim, 2))) def setOrientation(self, yaw=None): """Set Orientation in the firt time""" self.bearing = self.selected_features.attribute(config.column_yaw) originalPoint = self.selected_features.geometry().asPoint() self.actualPointDx = qgsutils.convertProjection( originalPoint.x(), originalPoint.y(), self.layer.crs().authid(), self.canvas.mapSettings().destinationCrs().authid(), ) self.actualPointOrientation = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.LineGeometry) self.actualPointOrientation.setColor(Qt.blue) self.actualPointOrientation.setWidth(5) self.actualPointOrientation.addPoint(self.actualPointDx) # End Point CS = self.canvas.mapUnitsPerPixel() * 25 A1x = self.actualPointDx.x() - CS * math.cos(math.pi / 2) A1y = self.actualPointDx.y() + CS * math.sin(math.pi / 2) self.actualPointOrientation.addPoint(QgsPointXY( float(A1x), float(A1y))) # Vision Angle if yaw is not None: angle = float(self.bearing + yaw) * math.pi / -180 else: angle = float(self.bearing) * math.pi / -180 tmpGeom = self.actualPointOrientation.asGeometry() self.rotateTool = transformGeometry() epsg = self.canvas.mapSettings().destinationCrs().authid() self.dumLayer = QgsVectorLayer("Point?crs=" + epsg, "temporary_points", "memory") self.actualPointOrientation.setToGeometry( self.rotateTool.rotate(tmpGeom, self.actualPointDx, angle), self.dumLayer) def setPosition(self): """Set RubberBand Position""" # Transform Point originalPoint = self.selected_features.geometry().asPoint() self.actualPointDx = qgsutils.convertProjection( originalPoint.x(), originalPoint.y(), "EPSG:4326", self.canvas.mapSettings().destinationCrs().authid(), ) self.positionDx = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.PointGeometry) self.positionDx.setWidth(6) self.positionDx.setIcon(QgsRubberBand.ICON_CIRCLE) self.positionDx.setIconSize(6) self.positionDx.setColor(Qt.black) self.positionSx = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.PointGeometry) self.positionSx.setWidth(5) self.positionSx.setIcon(QgsRubberBand.ICON_CIRCLE) self.positionSx.setIconSize(4) self.positionSx.setColor(Qt.blue) self.positionInt = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.PointGeometry) self.positionInt.setWidth(5) self.positionInt.setIcon(QgsRubberBand.ICON_CIRCLE) self.positionInt.setIconSize(3) self.positionInt.setColor(Qt.white) self.positionDx.addPoint(self.actualPointDx) self.positionSx.addPoint(self.actualPointDx) self.positionInt.addPoint(self.actualPointDx) def closeEvent(self, _): """Close dialog""" self.resetQgsRubberBand() self.canvas.refresh() self.iface.actionPan().trigger() self.parent.orbitalViewer = None self.RemoveImage() def resetQgsRubberBand(self): """Remove RubbeBand""" try: self.yawLbl.setText("") self.positionSx.reset() self.positionInt.reset() self.positionDx.reset() self.actualPointOrientation.reset() except Exception: None
import requests from qgis.PyQt.QtCore import QUrl from qgis.PyQt.QtWebKitWidgets import QWebView from qgis.utils import iface parameters = { 'client_id': '<REPLACE WITH YOUR CLIENT_ID>', 'closeto': '{},{}'.format([%$x%],[%$y%]), 'per_page': 1, 'radius': 1000 } response = requests.get( 'https://a.mapillary.com/v3/images', params=parameters) if response.status_code == 200: data = response.json() if data['features']: key = data['features'][0]['properties']['key'] url = 'https://images.mapillary.com/{}/thumb-640.jpg'.format(key) myWV = QWebView(None) myWV.load(QUrl(url)) myWV.show() else: iface.messageBar().pushMessage('No images found')
class QgepPlotSVGWidget(QWidget): webView = None webPage = None frame = None profile = None verticalExaggeration = 10 jsTranslator = QgepJsTranslator() # Signals emitted triggered by javascript actions reachClicked = pyqtSignal([str], name='reachClicked') reachMouseOver = pyqtSignal([str], name='reachMouseOver') reachMouseOut = pyqtSignal([str], name='reachMouseOut') reachPointClicked = pyqtSignal([str, str], name='reachPointClicked') reachPointMouseOver = pyqtSignal([str, str], name='reachPointMouseOver') reachPointMouseOut = pyqtSignal([str, str], name='reachPointMouseOut') specialStructureClicked = pyqtSignal([str], name='specialStructureClicked') specialStructureMouseOver = pyqtSignal([str], name='specialStructureMouseOver') specialStructureMouseOut = pyqtSignal([str], name='specialStructureMouseOut') # Signals emitted for javascript profileChanged = pyqtSignal([str], name='profileChanged') verticalExaggerationChanged = pyqtSignal( [int], name='verticalExaggerationChanged') def __init__(self, parent, network_analyzer: QgepGraphManager, url: str = None): QWidget.__init__(self, parent) self.webView = QWebView() self.webView.setPage(QgepWebPage(self.webView)) self.networkAnalyzer = network_analyzer settings = QSettings() layout = QVBoxLayout(self) if url is None: # Starting with QGIS 3.4, QWebView requires paths with / even on windows. default_url = plugin_root_path().replace( '\\', '/') + '/svgprofile/index.html' url = settings.value("/QGEP/SvgProfilePath", default_url) url = 'file:///' + url developer_mode = settings.value("/QGEP/DeveloperMode", False, type=bool) if developer_mode is True: self.webView.page().settings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) else: self.webView.setContextMenuPolicy(Qt.NoContextMenu) self.webView.load(QUrl(url)) self.frame = self.webView.page().mainFrame() self.frame.javaScriptWindowObjectCleared.connect(self.initJs) layout.addWidget(self.webView) def setProfile(self, profile): self.profile = profile # Forward to javascript self.profileChanged.emit(profile.asJson()) def initJs(self): self.frame.addToJavaScriptWindowObject("profileProxy", self) self.frame.addToJavaScriptWindowObject("i18n", self.jsTranslator) def changeVerticalExaggeration(self, val): self.verticalExaggeration = val self.verticalExaggerationChanged.emit(val) def printProfile(self): printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printpreviewdlg = QPrintPreviewDialog() printpreviewdlg.paintRequested.connect(self.printRequested) printpreviewdlg.exec_() @pyqtSlot(QPrinter) def printRequested(self, printer): self.webView.print_(printer) @pyqtSlot(str) def onReachClicked(self, obj_id): self.reachClicked.emit(obj_id) @pyqtSlot(str) def onReachMouseOver(self, obj_id): self.reachMouseOver.emit(obj_id) @pyqtSlot(str) def onReachMouseOut(self, obj_id): self.reachMouseOut.emit(obj_id) @pyqtSlot(str, str) def onReachPointClicked(self, obj_id, reach_obj_id): self.reachPointClicked.emit(obj_id, reach_obj_id) @pyqtSlot(str, str) def onReachPointMouseOver(self, obj_id, reach_obj_id): self.reachPointMouseOver.emit(obj_id, reach_obj_id) @pyqtSlot(str, str) def onReachPointMouseOut(self, obj_id, reach_obj_id): self.reachPointMouseOut.emit(obj_id, reach_obj_id) @pyqtSlot(str) def onSpecialStructureClicked(self, obj_id): self.specialStructureClicked.emit(obj_id) @pyqtSlot(str) def onSpecialStructureMouseOver(self, obj_id): self.specialStructureMouseOver.emit(obj_id) @pyqtSlot(str) def onSpecialStructureMouseOut(self, obj_id): self.specialStructureMouseOut.emit(obj_id) # Is called from the webView when it's been reloaded and wants to have the # profile information resent @pyqtSlot() def updateProfile(self): if self.profile: self.profileChanged.emit(self.profile.asJson()) self.verticalExaggerationChanged.emit(self.verticalExaggeration)
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel( [alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % ( alg.algorithm.getOutputFromName( value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 0) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance( param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = param.default if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint)): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip( ) != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 1) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = param.default if isinstance(param, ( ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint )): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
class HuntRegister: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None # This plugin depends on alkisplugin self.alkisplugin = None # Members self.alkisToolBar = None # the toolbar instance where the alkisplugin and huntplugin QAction symbols are placed self.alkisSelectAreaLayer = None # QgsVectorLayer selected parcels of alkisplugin self.huntSelectAreaLayer = None # QgsVectorLayer selected parcels of huntplugin # help web view self.helpiew = None # webview containing manuals # All actions are assigned to alter self.huntSelectAreaLayer self.hswapAction = None # single QAction copy selected parcels from alkisplugin to huntplugin self.hAddMarkAction = None # checkable QAction select and unselect parcels self.hlistAction = None # single QAction select parcels by parcel attributes self.hclearAction = None # single QAction unselect all selected parcels self.hownerAction = None # single QAction get parcel certificates for all selected parcels self.hhuntAction = None # single QAction create a hunt register self.hinfoAction = None # single QAction get a basic summary of all selected parcels self.helpAction = None # single QAction open help files webview browser window # self.testAction = None # single QAction used for testing program fragments self.hAddMarkTool = None # click recognizing map tool for self.hAddMarkAction self.core = None # function core for this plugin self.initTimer = QTimer( self.iface ) # timer used to init self.huntSelectAreaLayer dynamically when alkis layers are added self.initTimer.setInterval(1000) # 1 sec interval self.initTimer.timeout.connect(self.initLayers) self.init() # init main instances def init(self): """init main instances""" if (alkisAvailable): try: self.alkisplugin = Alkis.alkisplugin.alkisplugin( self.iface) # create alkisplugin object self.alkisplugin.queryOwnerAction = QAction( None ) # this is used in akisplugin "opendb" and must therefore be set to prevent runtime errors except AttributeError: QMessageBox.critical( None, "Fehler", "norGIS ALKIS-Einbindung zuerst aktivieren und \"JagdKataster\" erneut aktivieren" ) raise AttributeError("alkisplugin not active") else: QMessageBox.critical( None, "Fehler", "norGIS ALKIS-Einbindung installieren und zuerst aktivieren. Dann \"JagdKataster\" erneut aktivieren" ) raise AttributeError("alkisplugin not installed") self.core = HuntCore(self) # function core for this plugin def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" # will be set False in run() self.first_start = True self.helpview = QWebView() self.helpview.resize(1280, 850) self.helpview.setWindowTitle("JagdKataster Anleitungen") help_dir = os.path.join(self.plugin_dir, "help", "build", "html", "index.html") self.helpview.load(QUrl.fromLocalFile(help_dir)) # the toolbar entries of this plugin should be placed alongside the alkisplugin entries # therefore the alkisplugin toolbar is derived tBars = self.iface.mainWindow().findChildren( QToolBar) # get all toolbars from main window self.alkisToolBar = next( (n for n in tBars if n.objectName() == "norGIS_ALKIS_Toolbar"), None ) # find the instance of alkisplugin toolbar by its static name if self.alkisToolBar is None: # in case the toolbar is not yet loaded create the instance with its static name # create alkis toolbar in case it is not yet loaded self.alkisToolBar = self.iface.addToolBar(u"norGIS: ALKIS") self.alkisToolBar.setObjectName("norGIS_ALKIS_Toolbar") #create toolbar items self.hswapAction = QAction(QIcon("hunt:mark_transfer.svg"), "Flächenmarkierung übertragen", self.iface.mainWindow()) self.hswapAction.setWhatsThis( "Flächenmarkierung (gelb) nach Jagd-Flächenmarkierung (blau) übertragen" ) self.hswapAction.setStatusTip( "Flächenmarkierung (gelb) nach Jagd-Flächenmarkierung (blau) übertragen" ) self.hswapAction.triggered.connect(lambda: self.core.swapAlkisToHunt()) self.alkisToolBar.addAction(self.hswapAction) self.hAddMarkAction = QAction(QIcon("hunt:mark_add.svg"), u"Flurstück (de)selektieren", self.iface.mainWindow()) self.hAddMarkAction.setWhatsThis( "Flurstück in Jagd-Flächenmarkierung selektieren oder deselektieren" ) self.hAddMarkAction.setStatusTip( "Flurstück in Jagd-Flächenmarkierung selektieren oder deselektieren" ) self.hAddMarkAction.setCheckable(True) self.hAddMarkAction.triggered.connect( lambda: self.iface.mapCanvas().setMapTool(self.hAddMarkTool)) self.alkisToolBar.addAction(self.hAddMarkAction) self.hAddMarkTool = HAdd(self) self.hAddMarkTool.setAction(self.hAddMarkAction) self.hlistAction = QAction(QIcon("hunt:mark_list.svg"), "Selektieren nach Flurstückseigenschaft", self.iface.mainWindow()) self.hlistAction.setWhatsThis( "Selektierung der Flurstücke in Jagd-Flächenmarkierung anhand Flurstückseigenschaften" ) self.hlistAction.setStatusTip( "Selektierung der Flurstücke in Jagd-Flächenmarkierung anhand Flurstückseigenschaften" ) self.hlistAction.triggered.connect( lambda: self.core.showListSelection()) self.alkisToolBar.addAction(self.hlistAction) self.hclearAction = QAction(QIcon("hunt:mark_clear.svg"), "Alle deselektieren", self.iface.mainWindow()) self.hclearAction.setWhatsThis( "Alle Flurstücke in Jagd-Flächenmarkierung deselektieren") self.hclearAction.setStatusTip( "Alle Flurstücke in Jagd-Flächenmarkierung deselektieren") self.hclearAction.triggered.connect(lambda: self.core.clearHighlight()) self.alkisToolBar.addAction(self.hclearAction) self.hownerAction = QAction(QIcon("hunt:mark_own.svg"), "Flurstücksnachweise anzeigen", self.iface.mainWindow()) self.hownerAction.setWhatsThis( "Flurstücksnachweise für selektierte Flurstücke in Jagd-Flächenmarkierung anzeigen" ) self.hownerAction.setStatusTip( "Flurstücksnachweise für selektierte Flurstücke in Jagd-Flächenmarkierung anzeigen" ) self.hownerAction.triggered.connect( lambda: self.core.showParcelCerts()) self.alkisToolBar.addAction(self.hownerAction) self.hhuntAction = QAction(QIcon("hunt:mark_hunt.svg"), "Jagdkataster erstellen", self.iface.mainWindow()) self.hhuntAction.setWhatsThis( "Jagdkataster für selektierte Flurstücke in Jagd-Flächenmarkierung erstellen" ) self.hhuntAction.setStatusTip( "Jagdkataster für selektierte Flurstücke in Jagd-Flächenmarkierung erstellen" ) self.hhuntAction.triggered.connect(lambda: self.core.showHuntReg()) self.alkisToolBar.addAction(self.hhuntAction) self.hinfoAction = QAction(QIcon("hunt:mark_info.svg"), "Flurstückszusammenfassung anzeigen", self.iface.mainWindow()) self.hinfoAction.setWhatsThis( "Flurstückszusammenfassung für selektierte Flurstücke in Jagd-Flächenmarkierung anzeigen" ) self.hinfoAction.setStatusTip( "Flurstückszusammenfassung für selektierte Flurstücke in Jagd-Flächenmarkierung anzeigen" ) self.hinfoAction.triggered.connect( lambda: self.core.showSummaryDialog()) self.alkisToolBar.addAction(self.hinfoAction) self.helpAction = QAction(QIcon("hunt:logo.svg"), "Anleitungen", self.iface.mainWindow()) self.helpAction.setWhatsThis("JagdKataster-Anleitungen") self.helpAction.setStatusTip("JagdKataster-Anleitungen") self.helpAction.triggered.connect(lambda: self.helpview.show()) # self.testAction = QAction(QIcon("hunt:test.svg"), "Test", self.iface.mainWindow()) # self.testAction.setWhatsThis("Test action") # self.testAction.setStatusTip("Test action") # self.testAction.triggered.connect(lambda: self.core.test(self.huntSelectAreaLayer)) # self.alkisToolBar.addAction(self.testAction) self.iface.addPluginToDatabaseMenu("&ALKIS", self.helpAction) QgsProject.instance().layersAdded.connect( self.initTimer.start ) # react to changes in the layer tree. Maybe the alkis layers were added QgsProject.instance().layersWillBeRemoved.connect( self.layersRemoved ) # remove entries in case this plugin layers are to be removed def initLayers(self): """init self.huntSelectAreaLayer in case the alkis layers from alkisplugin are loaded""" self.initTimer.stop( ) # this methode may be called by a timer started when layers are added => stop the timer after first timeout event if self.alkisSelectAreaLayer is None: # are alkisplugin layers loaded ad readable from entry? (layerId, res) = QgsProject.instance().readEntry("alkis", "/areaMarkerLayer") if res and layerId: self.alkisSelectAreaLayer = QgsProject.instance().mapLayer( layerId) if self.huntSelectAreaLayer is None: # is the huntplugin layer already loaded? (layerId, res) = QgsProject.instance().readEntry("hunt", "/areaMarkerLayer") if res and layerId: self.huntSelectAreaLayer = QgsProject.instance().mapLayer( layerId) if self.huntSelectAreaLayer is None and self.alkisSelectAreaLayer is not None: # alkisplugin layers are loaded but huntplugin layer is not self.createLayer() # create huntplugin layer def layersRemoved(self, layersIds): """remove entries and references in case this plugin layers are to be removed""" if self.alkisSelectAreaLayer is not None and self.alkisSelectAreaLayer.id( ) in layersIds: self.alkisSelectAreaLayer = None if self.huntSelectAreaLayer is not None and self.huntSelectAreaLayer.id( ) in layersIds: QgsProject.instance().removeEntry("hunt", "/areaMarkerLayer") self.core.hlayer = None self.huntSelectAreaLayer = None def createLayer(self): """create and add huntplugin layer to the layer tree""" if (self.alkisSelectAreaLayer is not None): parent = QgsProject.instance().layerTreeRoot().findLayer( self.alkisSelectAreaLayer).parent() layeropts = QgsVectorLayer.LayerOptions(False, False) self.init( ) # reinit main instances because alkis instance conninfo might have changed (db, conninfo) = self.core.openDB() if db is None: return self.huntSelectAreaLayer = QgsVectorLayer( u"%s estimatedmetadata=true checkPrimaryKeyUnicity=0 key='ogc_fid' type=MULTIPOLYGON srid=%d table=%s.po_polygons (polygon) sql=false" % (conninfo, self.alkisplugin.epsg, self.alkisplugin.quotedschema()), u"Jagd-Flächenmarkierung", "postgres", layeropts) sym = QgsSymbol.defaultSymbol(QgsWkbTypes.PolygonGeometry) sym.setColor(Qt.blue) sym.setOpacity(0.3) self.huntSelectAreaLayer.setRenderer(QgsSingleSymbolRenderer(sym)) QgsProject.instance().addMapLayer(self.huntSelectAreaLayer, False) parent.insertLayer(0, self.huntSelectAreaLayer) self.core.hlayer = None QgsProject.instance().writeEntry("hunt", "/areaMarkerLayer", self.huntSelectAreaLayer.id()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" if self.hswapAction: self.hswapAction.deleteLater() self.hswapAction = None if self.hAddMarkAction: self.hAddMarkAction.deleteLater() self.hAddMarkAction = None if self.hlistAction: self.hlistAction.deleteLater() self.hlistAction = None if self.hclearAction: self.hclearAction.deleteLater() self.hclearAction = None if self.hownerAction: self.hownerAction.deleteLater() self.hownerAction = None if self.hhuntAction: self.hhuntAction.deleteLater() self.hhuntAction = None if self.hinfoAction: self.hinfoAction.deleteLater() self.hinfoAction = None if self.helpAction: self.helpAction.deleteLater() self.helpAction = None # if self.testAction: # self.testAction.deleteLater() # self.testAction = None QgsProject.instance().layersAdded.disconnect(self.initTimer.start) QgsProject.instance().layersWillBeRemoved.disconnect( self.layersRemoved) def run(self): """Run method""" if self.first_start: self.first_start = False