Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- /***************************************************************************
- RimoPrinting
- A QGIS plugin
- RimoPrinting
- -------------------
- begin : 2016-03-31
- git sha : $Format:%H$
- copyright : (C) 2016 by Bernd Loigge
- email : bernd.loigge@spl-tele.com
- ***************************************************************************/
- /***************************************************************************
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 2 of the License, or *
- * (at your option) any later version. *
- * *
- ***************************************************************************/
- """
- from qgis.core import *
- from PyQt4.QtCore import Qt, QSettings, QTranslator, qVersion, QCoreApplication, QFileInfo, QVariant, QFile, QSizeF, QPyNullVariant, QUrl
- from PyQt4.QtGui import QAction, QIcon, QFileDialog, QPrinter, QPainter, QFont, QProgressBar
- from PyQt4.QtXml import QDomDocument
- from PyQt4.QtNetwork import QNetworkRequest
- from qgis.gui import QgsMessageBar, QgsMapCanvas, QgsLayerTreeMapCanvasBridge
- # Initialize Qt resources from file resources.py
- import resources
- import re
- # Import the code for the dialog
- from RimoPrinting_dialog import RimoPrintingDialog
- import os.path
- import sys
- sys.path.append('./requests')
- import requests
- import json
- import yaml
- import processing
- import time
- import inspect
- import csv
- import math
- import urllib
- import datetime
- import codecs
- #csv.register_dialect('RimoPrinting', delimiter=';')
- project = QgsProject.instance()
- class RimoPrinting:
- """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__).replace("\\", "/")
- # initialize locale
- locale = QSettings().value('locale/userLocale')[0:2]
- locale_path = os.path.join(
- self.plugin_dir,
- 'i18n',
- 'RimoPrinting_{}.qm'.format(locale))
- if os.path.exists(locale_path):
- self.translator = QTranslator()
- self.translator.load(locale_path)
- if qVersion() > '4.3.3':
- QCoreApplication.installTranslator(self.translator)
- # Create the dialog (after translation) and keep reference
- self.dlg = RimoPrintingDialog()
- # Plugin Variables
- self.loginStatus = False
- # Declare instance attributes
- self.actions = []
- self.menu = self.tr(u'&RimoPrinting')
- # TODO: We are going to let the user set this up in a future iteration
- self.toolbar = self.iface.addToolBar(u'RimoPrinting')
- self.toolbar.setObjectName(u'RimoPrinting')
- # noinspection PyMethodMayBeStatic
- def tr(self, message):
- """Get the translation for a string using Qt translation API.
- We implement this ourselves since we do not inherit QObject.
- :param message: String for translation.
- :type message: str, QString
- :returns: Translated version of message.
- :rtype: QString
- """
- # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
- return QCoreApplication.translate('RimoPrinting', message)
- def add_action(
- self,
- icon_path,
- text,
- callback,
- enabled_flag=True,
- add_to_menu=True,
- add_to_toolbar=True,
- status_tip=None,
- whats_this=None,
- parent=None):
- """Add a toolbar icon to the toolbar.
- :param icon_path: Path to the icon for this action. Can be a resource
- path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
- :type icon_path: str
- :param text: Text that should be shown in menu items for this action.
- :type text: str
- :param callback: Function to be called when the action is triggered.
- :type callback: function
- :param enabled_flag: A flag indicating if the action should be enabled
- by default. Defaults to True.
- :type enabled_flag: bool
- :param add_to_menu: Flag indicating whether the action should also
- be added to the menu. Defaults to True.
- :type add_to_menu: bool
- :param add_to_toolbar: Flag indicating whether the action should also
- be added to the toolbar. Defaults to True.
- :type add_to_toolbar: bool
- :param status_tip: Optional text to show in a popup when mouse pointer
- hovers over the action.
- :type status_tip: str
- :param parent: Parent widget for the new action. Defaults None.
- :type parent: QWidget
- :param whats_this: Optional text to show in the status bar when the
- mouse pointer hovers over the action.
- :returns: The action that was created. Note that the action is also
- added to self.actions list.
- :rtype: QAction
- """
- icon = QIcon(icon_path)
- action = QAction(icon, text, parent)
- action.triggered.connect(callback)
- action.setEnabled(enabled_flag)
- if status_tip is not None:
- action.setStatusTip(status_tip)
- if whats_this is not None:
- action.setWhatsThis(whats_this)
- if add_to_toolbar:
- self.toolbar.addAction(action)
- if add_to_menu:
- self.iface.addPluginToVectorMenu(
- self.menu,
- action)
- self.actions.append(action)
- return action
- def initGui(self):
- global project
- """Create the menu entries and toolbar icons inside the QGIS GUI."""
- icon_path = self.plugin_dir + '/icon.png'
- self.add_action(
- icon_path,
- text=self.tr(u'RimoPrinting'),
- callback=self.run,
- parent=self.iface.mainWindow())
- #Disable Gui Elements for Login
- if self.loginStatus == False:
- self.disableLoginAndTenantGui(False)
- self.dlg.pushButton_2.setEnabled(False)
- self.dlg.pushButton_2.setEnabled(False)
- self.dlg.comboBox_4.setEnabled(False)
- # Set Global Variables (For tasks without Login)
- self.setGlobalVariables()
- # Set Plugin Variables
- self.dlgIsActive = False
- self.dataStore = {"regionData": None, "clusterData": None, "siteClusterData": None}
- self.layerTree = QgsProject.instance().layerTreeRoot()
- # Populate Style List Changer
- self.updateStyleListComboBox()
- # Login (Listener)
- self.dlg.pushButton.clicked.connect(lambda: self.login(self.dlg.comboBox_8.currentText(), self.dlg.lineEdit.text(), self.dlg.lineEdit_2.text()))
- # Select a Tenant (Listener)
- self.dlg.pushButton_2.clicked.connect(lambda: self.selectTenant(self.tenants[self.dlg.comboBox_4.currentIndex()]["tenant"]["asOop"], self.tenants[self.dlg.comboBox_4.currentIndex()]["tenant"]["id"]))
- # Create a Composer (Listener)
- self.dlg.pushButton_3.clicked.connect(lambda: self.createPrintComposer())
- # Refresh All Data layerTree (Listener)
- self.dlg.pushButton_4.clicked.connect(lambda: self.refreshAllRimoDataConnections())
- # Load Backbone Region Data
- self.dlg.pushButton_5.clicked.connect(lambda: self.loadBackboneRegionData())
- # Change Layer Styles
- self.dlg.pushButton_6.clicked.connect(lambda: self.changeLayerStyles())
- # Update Layer Style Folder
- self.dlg.pushButton_7.clicked.connect(lambda: self.updateStyleListComboBox())
- # Read and Set Plugin Version
- self.pluginVersion = self.get_num(self.readFileAndFindString(self.plugin_dir + '/metadata.txt', 'version='))
- def unload(self):
- """Removes the plugin menu item and icon from QGIS GUI."""
- for action in self.actions:
- self.iface.removePluginMenu(
- self.tr(u'&RimoPrinting'),
- action)
- self.iface.removeToolBarIcon(action)
- # remove the toolbar
- del self.toolbar
- #############
- # Run Method:
- #############
- def run(self):
- # Set Global Variables (For tasks without Login)
- self.setGlobalVariables()
- """Run method that performs all the real work"""
- # show the dialog
- #if self.dlgIsActive == True:
- # self.dlg.show()
- # return
- self.dlg.show()
- self.dlgIsActive = True
- # Run the dialog event loop
- result = self.dlg.exec_()
- #Run if Cancel is pressed
- if result == 0:
- return
- # See if OK was pressed
- if result:
- self.iface.messageBar().clearWidgets()
- self.iface.messageBar().pushInfo("RimoPrinting:", "Preparing Data Structure...")
- if self.checkIfEmptyProject() == True:
- if self.createDataDir() == True:
- if self.createRevisionCSV() == True:
- self.iface.messageBar().clearWidgets()
- self.iface.messageBar().pushInfo("RimoPrinting:", "Loading Rimo Data...")
- if self.loadData() == True:
- self.iface.messageBar().clearWidgets()
- self.iface.messageBar().pushInfo("RimoPrinting:", "Loading Revision CSV...")
- if self.loadRevisionCSV() == True:
- if self.setCRSToEPSG31256() == True:
- self.iface.messageBar().clearWidgets()
- self.iface.messageBar().pushInfo("RimoPrinting:", "Data has been successfully loaded!")
- self.saveCurrentProject()
- return
- ##############
- # Gui Methods:
- ##############
- # Login
- def login(self, rimoUrl, user, password):
- global project
- # Rimo Url
- if rimoUrl == 'Production':
- self.rimoUrl = "https://rimo-saas.com/"
- project.writeEntry("rP", "rimoUrl", "https://rimo-saas.com/")
- else:
- self.rimoUrl = "https://rimo-dev.rimo-saas.com/"
- project.writeEntry("rP", "rimoUrl", "https://rimo-dev.rimo-saas.com/")
- # # Check for Proxy
- # s = QSettings()
- # proxyEnabled = s.value("proxy/proxyEnabled", "")
- # print(proxyEnabled)
- # if proxyEnabled == "true":
- # proxyType = str(s.value("proxy/proxyType", "" ))
- # proxyHost = str(s.value("proxy/proxyHost", "" ))
- # proxyPort = str(s.value("proxy/proxyPort", "" ))
- # proxyUser = str(s.value("proxy/proxyUser", "" ))
- # proxyPassword = str(s.value("proxy/proxyPassword", "" ))
- # proxyPrefix = str(proxyHost.split(':')[0])
- # proxyUrl = str(proxyHost.split(':')[1][2:])
- # userAndPass = ""
- # if proxyPassword:
- # userAndPass = proxyUser + ":" + proxyPassword + "@"
- #
- # proxyNewUrl = proxyPrefix + "://" + userAndPass + proxyUrl + ":" + proxyPort
- # self.proxieSettings = {proxyPrefix: proxyNewUrl}
- #
- #
- # else:
- # self.proxieSettings = {"http": self.rimoUrl}
- # Login Request
- r = requests.post(self.rimoUrl + "api/MIT/SDMeteorQGISController/", data=json.dumps({"method": "verifyUser", "user": user, "password": password}))
- data = json.loads(r.text)
- if "_error" in data:
- self.renderWarning("Wrong Username or Password")
- return False
- if "asOop" in data:
- # Tenant Stuff
- tenants = data["userProfile"]
- self.loginStatus = True
- self.dlg.label_10.setText("Logged In.")
- self.dlg.pushButton.setEnabled(False)
- self.dlg.lineEdit.setEnabled(False)
- self.dlg.lineEdit_2.setEnabled(False)
- self.dlg.comboBox_8.setEnabled(False)
- self.dlg.pushButton_2.setEnabled(True)
- self.dlg.comboBox_4.setEnabled(True)
- self.tenants = tenants
- tenantList = []
- for t in self.tenants:
- tenantList.append(t["tenant"]["id"])
- self.dlg.comboBox_4.addItems(tenantList)
- # Select Tenant
- def selectTenant(self, tenantOop, tenantId):
- global project
- self.dlg.pushButton_2.setEnabled(False)
- self.dlg.comboBox_4.setEnabled(False)
- #Global TenantOop
- self.tenantOop = tenantOop
- project.writeEntry("rP", "tenantOop", str(tenantOop))
- #Global TenantID
- self.tenantId = str(tenantId)
- project.writeEntry("rP", "tenantId", str(tenantId))
- #Global UserOop
- self.userOop = [x for x in self.tenants if x["tenant"]["asOop"] == self.tenantOop][0]["asOop"]
- project.writeEntry("rP", "userOop", str(self.userOop))
- #Disable loginButton
- self.dlg.pushButton.setEnabled(False)
- self.disableLoginAndTenantGui(True)
- #Populate ComboBoxen
- #Regions ComboBox
- self.regionData()
- #Cluster ComboBox
- self.clusterData()
- #SiteCluster ComboBox
- self.siteClusterData()
- return True
- ####################
- # Gui Helper Methods
- ####################
- # Disable Login And Tenant Gui Fields
- def disableLoginAndTenantGui(self, status):
- elements = [
- self.dlg.comboBox,
- self.dlg.comboBox_2,
- self.dlg.comboBox_3,
- self.dlg.button_box
- ]
- for e in elements:
- e.setEnabled(status)
- # Load Region Data
- def regionData(self):
- try:
- self.getRimoData(self.rimoUrl + "api/MIT/SDMeteorQGISController", "getRegionsFromTenant", self.tenantOop, "nameToDisplay", self.dlg.comboBox, "regionData")
- except:
- pass
- self.dlg.comboBox.activated.connect(lambda: self.comboBoxChange())
- # Load Cluster Data
- def clusterData(self):
- try:
- self.getRimoData(self.rimoUrl + "api/MIT/SDMeteorQGISController", "getClustersFromRegion", self.dataStore["regionData"][self.dlg.comboBox.currentIndex()]['asOop'], "nameToDisplay", self.dlg.comboBox_2, "clusterData")
- except:
- pass
- self.dlg.comboBox_2.activated.connect(lambda: self.comboBox_2Change())
- # Load Site Cluster Data
- def siteClusterData(self):
- try:
- self.getRimoData(self.rimoUrl + "api/MIT/SDMeteorQGISController", "getSiteClustersFromClusters", self.dataStore["clusterData"][self.dlg.comboBox_2.currentIndex()]['asOop'], "nameToDisplay", self.dlg.comboBox_3, "siteClusterData")
- except:
- pass
- self.dlg.comboBox_3.activated.connect(lambda: self.comboBox_3Change())
- # Access Rimo Data (Used By SiteCluster, Cluster and Region Methods)
- def getRimoData(self, url, method, Oop, comboParameter, comboBox, store):
- #Clear ComboBox
- comboBox.clear()
- #Load and Parse Data
- r = requests.post(url, data =json.dumps({'method': method, 'Oop': Oop, 'version': self.pluginVersion, 'userOop': self.userOop}))
- data = json.loads(r.text)
- #Create Content
- myList = []
- if store == "siteClusterData":
- myList.append("Whole Cluster")
- if len(data) > 0:
- for e in data:
- myList.append(e[comboParameter])
- #setNewDataStorage
- dataStorage = data
- else:
- self.dataStorage = []
- #Return List
- comboBox.addItems(myList)
- #Data
- self.dataStore[store] = data
- # Events fired when comboBox Changes (RegionData)
- def comboBoxChange(self):
- self.dlg.comboBox_3.clear()
- self.dlg.comboBox_3.activated.disconnect()
- self.dlg.comboBox_2.clear()
- self.dlg.comboBox_2.activated.disconnect()
- #Reload Content
- self.clusterData()
- self.siteClusterData()
- # Events fired when comboBox_2 Changes (ClusterData)
- def comboBox_2Change(self):
- self.dlg.comboBox_3.clear()
- self.dlg.comboBox_3.activated.disconnect()
- #Reload Content
- self.siteClusterData()
- # Events fired when comboBox_3 Changes (SiteClusterData)
- def comboBox_3Change(self):
- return
- ######################
- # Data loading Methods
- ######################
- # Check Cluster Has Data
- def checkIfClusterHasData(self, selection):
- if selection == "" or selection == "No Data available":
- return False
- return True
- # Check If Layer Group Exists
- def checkIfLayerGroupExists(self, layerGroupName):
- for child in self.layerTree.children():
- if isinstance(child, QgsLayerTreeGroup):
- if child.name() == layerGroupName:
- return True
- return False
- # Check If Layer Exists
- def checkIfLayerExists(self, layerMetaData):
- layers = self.iface.legendInterface().layers()
- for layer in layers:
- if layer.keywordList() != "":
- layerName = json.loads(layer.keywordList())["name"]
- if layerName == layerMetaData["name"]:
- return True
- return False
- # Get Rimo Layer Properties
- def getRimoLayerProperties(self):
- rimoLayerProps = [
- {"path": "exportBuildingsToGeoJson", "name": "Buildings", "selected": True},
- {"path": "exportFCPsToGeoJson", "name": "FCPs", "selected": True},
- {"path": "exportAccessNodesToGeoJson", "name": "Access Nodes", "selected": True},
- {"path": "exportRouteLocationsToGeoJson", "name": "Route Locations", "selected": True},
- {"path": "exportDirectionLinesToGeoJson", "name": "Direction Lines", "selected": True},
- {"path": "exportShaftLocationsToGeoJson", "name": "Shaft Locations", "selected": True},
- {"path": "exportTrenchesToGeoJson", "name": "Trenches", "selected": True},
- {"path": "exportPipesToGeoJson", "name": "Pipes", "selected": False},
- {"path": "exportCladdingPipesToGeoJson", "name": "Cladding Pipes", "selected": False},
- {"path": "exportInfoLocationsToGeoJson", "name": "Info Locations", "selected": True},
- {"path": "exportFCPPolygonsToGeoJson", "name": "FCP Polygons", "selected": True},
- {"path": "exportSiteClusterPolygonsToGeoJson", "name": "SiteCluster Polygons", "selected": True},
- {"path": "exportClusterPolygonsToGeoJson", "name": "Cluster Polygons", "selected": False}
- ]
- return rimoLayerProps
- # Get Backbone Layer Properties
- def getBackboneRegionLayerProperties(self):
- backboneRegionLayerProps = [
- {"path": "exportClusterPolygonsToGeoJson", "name": "Backbone Cluster Polygons", "selected": False},
- {"path": "exportSiteClusterToGeoJson", "name": "Backbone Site Cluster ", "selected": False},
- {"path": "exportAccessNodesToGeoJson", "name": "Backbone POP", "selected": False},
- {"path": "exportBackboneConnectionsToGeoJson", "name": "Backbone Connection", "selected": False},
- {"path": "exportTrenchesToGeoJson", "name": "Backbone Trenches", "selected": False},
- {"path": "exportCablesToGeoJson", "name": "Backbone Cables", "selected": False},
- {"path": "exportPipesToGeoJson", "name": "Backbone Pipes", "selected": False}
- ]
- return backboneRegionLayerProps
- # Get WMS Layer Properties
- def getWmsLayerProperties(self):
- wmsLayerProps = [
- {"path": "contextualWMSLegend=0&crs=EPSG:3857&dpiMode=7&featureCount=10&format=image/png&layers=basemap_grau_layer&styles=&url=http://tileserver.rimo-saas.com:8081/service?", "name": "Geoland Basemap Grau", "selected": True},
- {"path": "contextualWMSLegend=0&crs=EPSG:3857&dpiMode=7&featureCount=10&format=image/png&layers=basemap_layer&styles=&url=http://tileserver.rimo-saas.com:8081/service?", "name": "Geoland Basemap", "selected": False},
- {"path": "contextualWMSLegend=0&crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers=INSPIRE.KA_GRUNDSTUECK&styles=&url=http://tileserver.rimo-saas.com:8081/service?", "name": "DKM", "selected": True}
- ]
- return wmsLayerProps
- # Add Layer To Iface
- def addLayer(self, layerType, Oop, layerProps, currentGroup):
- if layerType == "Rimo":
- layer = QgsVectorLayer(self.rimoUrl + "geo/" + self.tenantId + "/" + str(Oop) + "/" + layerProps["path"], layerProps["name"], "ogr")
- layer.setKeywordList('{"type": "RimoLayer", "name": "' + layerProps['name'] + '"}')
- elif layerType == "Wms":
- layer = QgsRasterLayer(layerProps["path"], layerProps["name"], "wms")
- layer.setKeywordList('{"type": "WmsLayer", "name": "' + layerProps['name'] + '"}')
- # Set Style from style Sheet
- self.setStyle(layer, layerProps["name"])
- # Add the layer to the registry, False indicates not to add to the layer tree
- QgsMapLayerRegistry.instance().addMapLayer(layer, False)
- # Append layer to the root group node
- currentGroup.addLayer(layer)
- # Set Layer Visible / not Visible
- self.iface.legendInterface().setLayerVisible(layer, layerProps["selected"])
- # Set Layer Styling
- def setStyle(self, layer, qmlName):
- layer.loadNamedStyle(self.plugin_dir + '/styles/default/' + qmlName + '.qml')
- # Set Styling of Folder
- def setStylingForLayerOfMatchingQMLFiles(self, fileName, path):
- layer = self.getLayerByName(fileName)
- if layer != False:
- layer.loadNamedStyle(path)
- ##################
- # Methods when Run
- ##################
- # Check If Project Is Empty
- def checkIfEmptyProject(self):
- if self.checkIfProjectHasDataLayer() == True or self.checkIfProjectHasPrintComposer() == True:
- self.renderWarning("There is already Data or at least one print composer in this Project - Please use an empty QGis-Project for Data loading!")
- return False
- return True
- # Create Data Dir
- def createDataDir(self):
- global project
- if self.isDev():
- folderP = "Development_" + self.tenantId + "_" + unicode(self.dlg.comboBox.currentText()) + "_" + unicode(self.dlg.comboBox_2.currentText()) + "_" + unicode(self.dlg.comboBox_3.currentText()) + "_" + str(time.time())[:-3]
- else:
- folderP = self.tenantId + "_" + unicode(self.dlg.comboBox.currentText()) + "_" + unicode(self.dlg.comboBox_2.currentText()) + "_" + unicode(self.dlg.comboBox_3.currentText()) + "_" + str(time.time())[:-3]
- dataDirectory = self.plugin_dir + "/Data/" + folderP
- self.dataDirectory = dataDirectory
- project.writeEntry("rP", "dataDirectory", self.dataDirectory)
- self.folderPathURLEncoded = urllib.quote(folderP.encode('utf8'))
- project.writeEntry("rP", "folderPathURLEncoded", urllib.quote(folderP.encode('utf8')))
- if not os.path.exists(self.dataDirectory):
- os.makedirs(self.dataDirectory)
- return True
- return False
- # Create A Revision CSV (Important for Composer)
- def createRevisionCSV(self):
- try:
- csvFile = self.dataDirectory + "/revision.csv"
- with open(csvFile, 'w') as csvfile:
- fieldnames = ['Revision:', 'Bearbeiter:', 'Kommentar:']
- writer = csv.writer(csvfile, delimiter=';', lineterminator='\n', quotechar='"', quoting=csv.QUOTE_MINIMAL)
- writer.writerow(fieldnames)
- row1 = ['1', '', '']
- writer.writerow(row1)
- return True
- except:
- return False
- # Load WMS and Rimo Data
- def loadData(self):
- global project
- selection = self.dlg.comboBox_3.currentText()
- if self.checkIfClusterHasData(selection) == False:
- self.renderWarning("No Data for this Cluster available")
- return
- # Get Oop for Rest Call / Set Grid Layer
- if selection == "Whole Cluster":
- Oop = self.dataStore["clusterData"][self.dlg.comboBox_2.currentIndex()]['asOop']
- else:
- Oop = self.dataStore["siteClusterData"][self.dlg.comboBox_3.currentIndex() - 1]['asOop']
- # Set Global Variab+les
- self.clusterOop = str(Oop)
- project.writeEntry("rP", "clusterOop", str(Oop))
- self.regionName = self.dlg.comboBox.currentText()
- project.writeEntry("rP", "regionName", unicode(self.regionName))
- self.clusterName = self.dlg.comboBox_2.currentText()
- project.writeEntry("rP", "clusterName", unicode(self.clusterName))
- self.siteClusterName = self.dlg.comboBox_3.currentText()
- project.writeEntry("rP", "siteClusterName", unicode(self.siteClusterName))
- # Load RimoLayer & Wms Layer Settings
- rimoLayerProps = self.getRimoLayerProperties()
- wmsLayerProps = self.getWmsLayerProperties()
- # Create Layer Group For Rimo Layer in Iface
- self.currentGroup = self.layerTree.addGroup(self.tenantId + ", " + unicode(self.dlg.comboBox.currentText()) + ", " + unicode(self.dlg.comboBox_2.currentText()) + ", " + unicode(self.dlg.comboBox_3.currentText()))
- # Load RimoLayer
- for l in rimoLayerProps:
- try:
- self.addLayer("Rimo", Oop, l, self.currentGroup)
- except:
- self.renderWarning("No Data for Layer: " + l["name"])
- # Create LayerGroup for Overlaymaps / Basemaps if it does not exist
- if self.checkIfLayerGroupExists("Overlaymaps / Basemaps") == False:
- self.layerTree.addGroup(unicode("Overlaymaps / Basemaps"))
- # Add Layer to Overlaymaps / Basemaps - LayerGroup
- for l in wmsLayerProps:
- if self.checkIfLayerExists(l) == False:
- self.addLayer("Wms", None, l, self.layerTree.findGroup(unicode("Overlaymaps / Basemaps")))
- # Set Grid Layer
- if selection == "" or selection == "No Data available":
- return
- elif selection == "Whole Cluster":
- for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
- if lyr.name() == "Cluster Polygons":
- layername = lyr.name()
- else:
- for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
- if lyr.name() == "SiteCluster Polygons":
- layername = lyr.name()
- # Set Global Variable
- self.gridLayerName = layername
- project.writeEntry("rP", "gridLayerName", layername)
- # Add GridGroup to Legend
- self.gridGroup = self.currentGroup.addGroup("Grids")
- # Add BackboneGroup to Legend
- self.backboneRegionGroup = self.layerTree.addGroup("Backbone Data")
- # Check if 'Backbone Region Data' is selected and load backbone data if so
- if self.dlg.checkBox.checkState() != 0:
- self.loadBackboneRegionData()
- return True
- # Load Revision CSV
- def loadRevisionCSV(self):
- csvUri = "file:///" + self.plugin_dir + "/Data/" + self.folderPathURLEncoded + "/revision.csv" + "?delimiter=;&encoding=WINSAMI2"
- csvLayer = QgsVectorLayer(csvUri, "Revision", "delimitedtext")
- csvLayer.setKeywordList('{"type": "RimoLayer", "name": "revision"}')
- QgsMapLayerRegistry.instance().addMapLayer(csvLayer, False)
- self.currentGroup.addLayer(csvLayer)
- self.iface.legendInterface().setLayerVisible(csvLayer, True)
- return True
- # Set CRS
- def setCRSToEPSG31256(self):
- if self.iface.mapCanvas().mapRenderer().hasCrsTransformEnabled():
- my_crs = QgsCoordinateReferenceSystem(31256, QgsCoordinateReferenceSystem.EpsgCrsId)
- self.iface.mapCanvas().mapRenderer().setDestinationCrs(my_crs)
- self.iface.mapCanvas().setMapUnits(0)
- self.iface.mapCanvas().refresh()
- return True
- # Load BackboneRegion Data
- def loadBackboneRegionData(self):
- global project
- # Load BackboneRegionLayer Settings
- backboneLayerProps = self.getBackboneRegionLayerProperties()
- # Get BackboneLayerGroup
- self.backboneGroup = self.getBackboneGroup()
- if self.backboneGroup == False:
- self.backboneGroup = self.layerTree.addGroup("Backbone Data")
- # Check if there is already Data in Group
- if self.getAmountOfChildrenInGroup(self.backboneGroup) > 0:
- self.renderWarning("Data has already been loaded in Backbone Data Group - Use Update Rimo Layer instead")
- return False
- # Get Backbone Region Oop
- self.backboneRegionOop = self.getBackboneRegionOop(self.clusterOop)
- print self.clusterOop
- if self.backboneRegionOop == False:
- self.renderWarning("There are problems loading Backbone Data - Please contact the admin!")
- return False
- # Load BackboneRegionLayer
- for l in backboneLayerProps:
- try:
- self.addLayer("Rimo", self.backboneRegionOop, l, self.backboneGroup)
- except:
- self.renderWarning("No Data for Layer: " + l["name"])
- return True
- # Change Layer Styles
- def changeLayerStyles(self):
- styling = self.dlg.comboBox_9.currentText()
- path = self.plugin_dir + "/styles/" + styling
- for myFile in (os.listdir(path)):
- self.setStylingForLayerOfMatchingQMLFiles(os.path.splitext(myFile)[0], path + "/" + myFile)
- self.iface.mapCanvas().refresh()
- self.iface.mapCanvas().refreshAllLayers()
- return
- ###############################
- # Print Composer Helper Methods
- ###############################
- # Get Grid Layer values
- def getGridLayerValues(self, cFormat, cScale):
- if cFormat == "A0" and cScale == "500":
- M = [{"value": 350, "selected": False, "format": "A0", "scale": "500"}]
- if cFormat == "A0" and cScale == "1000":
- M = [{"value": 700, "selected": False, "format": "A0", "scale": "1000"}]
- if cFormat == "A1" and cScale == "500":
- M = [{"value": 250, "selected": False, "format": "A1", "scale": "500"}]
- if cFormat == "A1" and cScale == "1000":
- M = [{"value": 500, "selected": False, "format": "A1", "scale": "1000"}]
- if cFormat == "A2" and cScale == "500":
- M = [{"value": 180, "selected": False, "format": "A2", "scale": "500"}]
- if cFormat == "A2" and cScale == "1000":
- M = [{"value": 370, "selected": False, "format": "A2", "scale": "1000"}]
- if cFormat == "A3" and cScale == "500":
- M = [{"value": 130, "selected": False, "format": "A3", "scale": "500"}]
- if cFormat == "A3" and cScale == "1000":
- M = [{"value": 250, "selected": True, "format": "A3", "scale": "1000"}]
- if cFormat == "A4" and cScale == "500":
- M = [{"value": 100, "selected": False, "format": "A4", "scale": "500"}]
- if cFormat == "A4" and cScale == "1000":
- M = [{"value": 100, "selected": False, "format": "A4", "scale": "1000"}]
- return M
- # Creates Atlas Grids
- def createAtlasGrid(self, inputLayer, currentGroup, M):
- global project
- # Calculate Layer in MGI
- inputLayerMGI = processing.getObject(processing.runalg("qgis:reprojectlayer", inputLayer, "EPSG:31256", None)['OUTPUT'])
- # Calculate Center Point
- centroidLayer = processing.getObject(processing.runalg("qgis:polygoncentroids", inputLayerMGI, None)['OUTPUT_LAYER'])
- for feat in centroidLayer.getFeatures():
- x = feat.geometry().asPoint()
- # Calculate Boundings
- boundingPolygon = processing.getObject(processing.runalg("qgis:polygonfromlayerextent", inputLayerMGI, False, None)['OUTPUT'])
- for feat in boundingPolygon.getFeatures():
- XMIN = feat.attributes()[0]
- YMIN = feat.attributes()[1]
- XMAX = feat.attributes()[2]
- YMAX = feat.attributes()[3]
- for m in M:
- # Recalculate XMAX - XMIN
- if((XMAX - XMIN) < m["value"]):
- add = (m["value"] - (XMAX - XMIN)) / 2
- XMAX = XMAX + add
- XMIN = XMIN - add
- if((YMAX - YMIN) < m["value"]):
- add = (m["value"] - (YMAX - YMIN)) / 2
- YMAX = YMAX + add
- YMIN = YMIN - add
- # Calculate Distance & New Boundings
- EW = XMAX - XMIN
- NS = YMAX - YMIN
- aEW = (EW % 10) / 2
- aNS = (NS % 10) / 2
- nXMIN = XMIN - aEW
- nYMIN = YMIN - aNS
- nXMAX = XMAX + aEW
- nYMAX = YMAX + aNS
- fieldAmountEW = int((nXMAX - nXMIN) / m["value"])
- fieldAmountNS = int((nYMAX - nYMIN) / m["value"])
- extent = str(nXMIN) + ", " + str(nXMAX) + ", " + str(nYMIN) + ", " + str(nYMAX)
- # Create Grid
- grid = processing.getObject(processing.runalg("qgis:creategrid", 1, extent, m["value"], m["value"], "EPSG:31256", None)['OUTPUT'])
- gridWGS = processing.getObject(processing.runalg("qgis:reprojectlayer", grid, "EPSG:4326", None)['OUTPUT'])
- # Check if Polygon is in Feature Grid + Add Attribute
- finalGrid = processing.getObject(processing.runalg("qgis:joinattributesbylocation", gridWGS, self.getLayerByTagName("Trenches"),u'intersects',0,1,"mean",1,None)['OUTPUT'])
- finalGrid = processing.getObject(processing.runalg("qgis:joinattributesbylocation", finalGrid, self.getLayerByTagName("Buildings"),u'intersects',0,1,"mean",1,None)['OUTPUT'])
- gridName = str(m["format"]) + "_" + str(m["scale"]) + '_Grid_' + str(m["value"]) + 'm'
- if self.getLayerByTagName(gridName) != False:
- return gridName
- finalGrid.setLayerName(gridName)
- # Add Column for Intersection
- finalGrid.dataProvider().addAttributes([QgsField("data_in_g", QVariant.Int)])
- finalGrid.updateFields()
- # Calculate Value
- data_in_gIdx = finalGrid.fieldNameIndex('data_in_g')
- countIdx = finalGrid.fieldNameIndex('count')
- count_1Idx = finalGrid.fieldNameIndex('count_1')
- attrFeatMap = {}
- for feature in finalGrid.getFeatures():
- #Fill data_in_g Column
- if feature.attributes()[countIdx] or feature.attributes()[count_1Idx]:
- attrFeatMap[ feature.id() ] = { data_in_gIdx : 1 }
- else:
- attrFeatMap[ feature.id() ] = { data_in_gIdx : 0 }
- finalGrid.dataProvider().changeAttributeValues(attrFeatMap)
- #Create FieldNames
- #Create Numbers for Atlas
- #Add ID Column
- finalGrid.dataProvider().addAttributes([QgsField("ID", QVariant.Int)])
- finalGrid.dataProvider().addAttributes([QgsField("Page", QVariant.String)])
- finalGrid.updateFields()
- idIDX = finalGrid.fieldNameIndex("ID")
- pageIDX = finalGrid.fieldNameIndex("Page")
- #Calculate IDs
- count = 0
- finalGrid.startEditing()
- for feature in finalGrid.getFeatures():
- finalGrid.changeAttributeValue(feature.id(), idIDX, count)
- count = count + 1
- #Sort IDs
- featureList = []
- for feature in finalGrid.getFeatures():
- myValue = feature.attributes()
- appendValue = [0 if isinstance(v, QPyNullVariant) else v for v in myValue]
- featureList.append(appendValue)
- featureList.sort(key=lambda x: x[1], reverse=True)
- #Fill ID Column
- count = 0
- row = 0
- column = 0
- fieldAmountEW = fieldAmountEW + 1
- for feature in featureList:
- finalGrid.changeAttributeValue(feature[idIDX], idIDX, count)
- if count > 1:
- if count % fieldAmountEW == 0:
- row = row + 1
- column = 0
- pageName = str(row) + '--' + str(column)
- finalGrid.changeAttributeValue(feature[idIDX], pageIDX, pageName)
- count = count + 1
- column = column + 1
- finalGrid.commitChanges()
- # Create /Remove Shapefile
- shpPath = self.dataDirectory + "/" + gridName
- # Remove Shapefile if Exists
- self.removeShapefileIfExists(gridName)
- # Create Shapefile and add it to canvas
- QgsVectorFileWriter.writeAsVectorFormat(finalGrid, shpPath, "utf-8", None, "ESRI Shapefile")
- layer = QgsVectorLayer(shpPath + ".shp", gridName, "ogr")
- layer.setKeywordList('{"type": "GridLayer", "name": "' + gridName + '"}')
- QgsMapLayerRegistry.instance().addMapLayer(layer, False)
- # Set Style
- self.setStyle(layer, layer.name())
- # Set Layer Visible / not Visible
- self.iface.legendInterface().setLayerVisible(layer, m["selected"])
- # Add Layer to Root Group
- currentGroup.addLayer(layer)
- return gridName
- # Check if there has been Rimo Data added at least once
- def checkIfThereIsRimoData(self):
- if self.gridLayerName == "nothing":
- return False
- return True
- # Get Filepath of Composer Template File
- def getPrintComposerTemplateFile(self, filename):
- myFile = os.path.dirname(os.path.dirname(os.path.dirname(self.plugin_dir))) + "/composer_templates/" + filename + ".qpt"
- if self.checkIfPathExists(myFile):
- return myFile
- else:
- return False
- # Get Rimo Composer Data
- def getRimoComposerData(self, tenantId, clusterOop):
- global project
- url = self.rimoUrl + "geo/" + self.tenantId + "/" + self.clusterOop + "/exportMetaInfo"
- r = requests.get(url)
- return json.loads(r.text)
- # Create New Composer File
- def createNewRimoComposer(self, cScale, cFormat, atlasGrid, createAtlas):
- global project
- # Create CRS Transformation for Grids
- transform = self.crsTransformation(4326, 31256)
- # Get Map Canvas
- canvas = QgsMapCanvas()
- if createAtlas == "Atlas":
- # Set Composer Name
- cN = "Atlas" + "_" + str(cFormat) + "_" + str(cScale)
- if createAtlas == "Individual":
- # Set Composer Name
- cN = "Individual" + "_" + str(cFormat) + "_" + str(cScale)
- if createAtlas == "Atlas_StaticLegend":
- # Set Composer Name
- cN = "Atlas_StaticLegend" + "_" + str(cFormat) + "_" + str(cScale)
- # Load Composer File
- myFile = self.getPrintComposerTemplateFile(cN)
- if myFile == False:
- self.renderWarning("No print composer template for the chosen scale / format found.")
- return
- myTemplateFile = file(myFile, 'rt')
- myTemplateContent = myTemplateFile.read()
- myTemplateFile.close()
- # Create Document from File
- myDocument = QDomDocument()
- myDocument.setContent(myTemplateContent, False)
- # Create Composer in Iface
- self.composer = self.iface.createNewComposer(cN)
- self.composer.composition().loadFromTemplate(myDocument)
- self.composition = QgsComposition(self.iface.mapCanvas().mapSettings())
- self.composition.refreshItems()
- self.myComposition = self.composer.composition()
- # Get Data From Template
- # Get Maps
- mainMap = self.myComposition.getComposerItemById('mainMap')
- mainMap.setMapCanvas(canvas)
- overviewMap = self.myComposition.getComposerItemById('overviewMap')
- overviewMap.setMapCanvas(canvas)
- # Get Frames
- planartFrame = self.myComposition.getComposerItemById('planartFrame')
- regionFrame = self.myComposition.getComposerItemById('regionFrame')
- parentFrame = self.myComposition.getComposerItemById('parentFrame')
- bauabschnittFrame = self.myComposition.getComposerItemById('bauabschnittFrame')
- bereichsbezeichnungFrame = self.myComposition.getComposerItemById('bereichsbezeichnungFrame')
- # Get Frame-Text
- planartFrameText = self.myComposition.getComposerItemById('planartFrameText')
- regionFrameText = self.myComposition.getComposerItemById('regionFrameText')
- parentFrameText = self.myComposition.getComposerItemById('parentFrameText')
- bauabschnittFrameText = self.myComposition.getComposerItemById('bauabschnittFrameText')
- bereichsbezeichnungFrameText = self.myComposition.getComposerItemById('bereichsbezeichnungFrameText')
- datumFrameText = self.myComposition.getComposerItemById('datumFrameText')
- # Get Impressum
- impressum = self.myComposition.getComposerItemById('Anschrift')
- # Get Tables
- revisionTable = self.myComposition.getComposerItemById('revisionTable').multiFrame()
- # Get Logos
- companyLogo = self.myComposition.getComposerItemById('companyLogo')
- # Get Legend
- legendFrame = self.myComposition.getComposerItemById('legendFrame')
- legend = self.myComposition.getComposerItemById('legend')
- # Get NorthArrow
- northArrow = self.myComposition.getComposerItemById('NorthArrow')
- # Set Data In Template
- # Set Table Content
- revisionLayer = self.getLayerByTagName("revision")
- revisionTable.setVectorLayer(revisionLayer)
- # Set Logos
- companyLogo.setPictureFile(self.plugin_dir + '/Logos/CompanyLogo.png')
- # Set Legend
- legend.setPictureFile(self.plugin_dir + '/Logos/Legende.jpg')
- # Set Impressum
- impressumTextFile = open(self.plugin_dir + '/Sonstiges/Anschrift.txt', 'r')
- impressumText = impressumTextFile.read()
- impressumTextFile.close()
- impressum.setText(unicode(impressumText, "utf-8" ))
- # Set Frames
- frameData = self.getRimoComposerData(self.tenantId, self.clusterOop)
- regionFrameText.setText(frameData["cluster"] )
- parentFrameText.setText(frameData["region"])
- bauabschnittFrameText.setText(frameData["siteCluster"])
- # Set Main Map
- mainMap.setNewScale(int(cScale), True)
- mainMapLayerSet = [
- self.getLayerByTagName("Direction Lines").id(),
- self.getLayerByTagName("Buildings").id(),
- self.getLayerByTagName("FCPs").id(),
- self.getLayerByTagName("Access Nodes").id(),
- self.getLayerByTagName("Trenches").id(),
- self.getLayerByTagName("Route Locations").id(),
- self.getLayerByTagName("DKM").id(),
- self.getLayerByTagName("Geoland Basemap Grau").id(),
- atlasGrid.id()
- ]
- mainMap.setLayerSet(mainMapLayerSet)
- mainMap.setKeepLayerSet(True)
- mainMap.setUpdatesEnabled(True)
- # Set NorthArrow
- northArrow.setPictureFile(self.plugin_dir + '/Logos/NorthArrow_04.svg')
- # Set Overview Map
- overviewMap.zoomToExtent(transform.transformBoundingBox(atlasGrid.extent()))
- overviewMapLayerSet = [
- self.getLayerByTagName("Trenches").id(),
- atlasGrid.id()
- ]
- overviewMap.setLayerSet(overviewMapLayerSet)
- overviewMap.setKeepLayerSet(True)
- overviewMap.setUpdatesEnabled(False)
- if (createAtlas == "Atlas") or (createAtlas == "Atlas_StaticLegend"):
- # Create Atlas
- myAtlas = self.myComposition.atlasComposition()
- myAtlas.setEnabled(True)
- # Set OverviewMap in Overview
- overviewMap.overview().setFrameMap(0)
- # Atlas Settings
- myAtlas.setCoverageLayer(atlasGrid)
- myAtlas.beginRender()
- myAtlas.setFeatureFilter('"data_in_g" = 1')
- myAtlas.setFilterFeatures(True)
- myAtlas.setPageNameExpression('Page')
- myAtlas.setSortKeyAttributeName('ID')
- myAtlas.setSortFeatures(True)
- myAtlas.setEnabled(False)
- myAtlas.setEnabled(True)
- myAtlas.setFilenamePattern("'" + self.regionName + "_" + self.clusterName + "_" + self.siteClusterName + "_'||\"Page\"")
- mainMap.setAtlasDriven(True)
- self.myComposition.setAtlasMode(QgsComposition.PreviewAtlas)
- mainMap.setNewScale(int(cScale), True)
- self.myComposition.setAtlasMode(QgsComposition.ExportAtlas)
- if createAtlas != "Atlas":
- # Set OverviewMap in Overview
- overviewMap.overview().setFrameMap(0)
- currentExtent = self.iface.mapCanvas().extent()
- mainMap.zoomToExtent(currentExtent)
- mainMap.setNewScale(int(cScale), True)
- # Create Watermark if Development
- if self.isDev():
- watermark = QgsComposerLabel(self.myComposition)
- watermark.setText("Attention - Development")
- watermark.setItemPosition(20, 20)
- fontsize = self.myComposition.paperHeight() / 6
- watermark.setFont(QFont("Cambria", fontsize , QFont.Bold))
- watermark.adjustSizeToText()
- self.myComposition.addComposerLabel(watermark)
- # Refresh Items
- self.myComposition.refreshItems()
- ########################
- # Print Composer Methods
- ########################
- # Create Composer
- def createPrintComposer(self):
- global project
- if self.checkIfThereIsRimoData == False:
- self.renderWarning("Please load RiMo-Data at least once into this Project!")
- return
- # Get Selections
- cType = self.dlg.comboBox_5.currentText()
- cFormat = self.dlg.comboBox_6.currentText()
- cScale = self.dlg.comboBox_7.currentText()
- # Access GridGroup
- if self.getGridGroup() == False:
- self.renderWarning("Grid Group is missing. Can't create Composer")
- return
- # Create Grid Layer
- gridLayer = self.getLayerByTagName(self.gridLayerName)
- gridLayerGroup = self.getGridGroup()
- gridLayerValues = self.getGridLayerValues(cFormat, cScale)
- atlasGridName = self.createAtlasGrid(gridLayer, gridLayerGroup, gridLayerValues)
- atlasGrid = self.getLayerByTagName(atlasGridName)
- if cType == "Individual Print":
- self.createNewRimoComposer(cScale, cFormat, atlasGrid, "Individual")
- self.saveCurrentProject()
- elif cType == "Atlas":
- self.createNewRimoComposer(cScale, cFormat, atlasGrid, "Atlas")
- self.saveCurrentProject()
- elif cType == "Atlas_StaticLegend":
- self.createNewRimoComposer(cScale, cFormat, atlasGrid, "Atlas_StaticLegend")
- self.saveCurrentProject()
- else:
- self.renderWarning("Not supported at the moment!")
- ########################
- # Overall Helper Methods
- ########################
- # CRS Transformation
- def crsTransformation(self, inputCRS, outputCRS):
- source_crs = QgsCoordinateReferenceSystem(inputCRS)
- dest_crs = QgsCoordinateReferenceSystem(outputCRS)
- transform = QgsCoordinateTransform(source_crs, dest_crs)
- return transform
- # Render Warning (message as input)
- def renderWarning(self, message):
- self.iface.messageBar().clearWidgets()
- self.iface.messageBar().pushMessage(message, "", level=QgsMessageBar.WARNING)
- # Check If Dev
- def isDev(self):
- if self.rimoUrl == "https://rimo-dev.rimo-saas.com/":
- return True
- else:
- return False
- # Check if Project has Layer
- def checkIfProjectHasDataLayer(self):
- layers = self.iface.legendInterface().layers()
- count = 0
- for layer in layers:
- count = count + 1
- if count == 0:
- return False
- else:
- return True
- # Check if Project has Print Composers
- def checkIfProjectHasPrintComposer(self):
- if len(self.iface.activeComposers()) == 0:
- return False
- else:
- return True
- # Save Current Project
- def saveCurrentProject(self):
- global project
- p = project
- if self.isDev():
- filePath = self.dataDirectory + "/Development_" + unicode(self.tenantId) + "_" + unicode(self.regionName) + "_" + unicode(self.clusterName) + "_" + unicode(self.siteClusterName) + ".qgs"
- else:
- filePath = self.dataDirectory + "/" + unicode(self.tenantId) + "_" + unicode(self.regionName) + "_" + unicode(self.clusterName) + "_" + unicode(self.siteClusterName) + ".qgs"
- p.setFileName(filePath)
- p.write()
- # Check If Path / File Exists
- def checkIfPathExists(self, path):
- if os.path.exists(path):
- return True
- else:
- return False
- # Access Layer by Tag Name
- def getLayerByTagName(self, myLayer):
- layers = self.iface.legendInterface().layers()
- for layer in layers:
- keys = layer.keywordList()
- if len(keys) > 0:
- layerName = json.loads(layer.keywordList())
- if layerName["name"] == myLayer:
- return layer
- #self.renderWarning("Error - Layer " + myLayer + " not found. Please contact support!")
- return False
- # Removes a Shapefile if Exists (Including all other files)
- def removeShapefileIfExists(self, gridName):
- layers = self.iface.legendInterface().layers()
- for layer in layers:
- if layer.name() == gridName:
- layer = self.getLayerByTagName(gridName)
- shpPath = os.path.dirname(layer.source())
- shpId = layer.id()
- shpName = layer.name()
- QgsMapLayerRegistry.instance().removeMapLayer(shpId)
- for filename in os.listdir(shpPath):
- if filename.startswith(shpName):
- os.remove(shpPath + "/" + filename)
- return
- # Access GridGroup
- def getGridGroup(self):
- global project
- root = project.instance().layerTreeRoot()
- for child in root.children():
- for innerChild in child.children():
- if isinstance(innerChild, QgsLayerTreeGroup) and innerChild.name() == "Grids":
- return innerChild
- return False
- # Access BackboneGroup
- def getBackboneGroup(self):
- global project
- root = project.instance().layerTreeRoot()
- for child in root.children():
- if child.name() == "Backbone Data":
- return child
- return False
- # Count Children in Group
- def getAmountOfChildrenInGroup(self, treeRoot):
- count = 0
- for child in treeRoot.children():
- count += 1
- return count
- # Set global Variables
- def setGlobalVariables(self):
- # Set Global Variables (For tasks without Login)
- if project.readEntry("rP", "tenantOop", "nothing")[0] != "nothing":
- self.rimoUrl = project.readEntry("rP", "rimoUrl", "nothing")[0]
- self.tenantOop = project.readEntry("rP", "tenantOop", "nothing")[0]
- self.tenantId = project.readEntry("rP", "tenantId", "nothing")[0]
- self.userOop = project.readEntry("rP", "userOop", "nothing")[0]
- self.dataDirectory = project.readEntry("rP", "dataDirectory", 'nothing')[0]
- self.folderPathURLEncoded = project.readEntry("rP", "folderPathURLEncoded", "nothing")[0]
- self.clusterOop = project.readEntry("rP", "clusterOop", "0")[0]
- self.regionName = project.readEntry("rP", "regionName", "nothing")[0]
- self.clusterName = project.readEntry("rP", "clusterName", "nothing")[0]
- self.siteClusterName = project.readEntry("rP", "siteClusterName", "nothing")[0]
- self.gridLayerName = project.readEntry("rP", "gridLayerName", "nothing")[0]
- return True
- # Refresh All Layer
- def refreshAllRimoDataConnections(self):
- layers = self.iface.legendInterface().layers()
- for layer in layers:
- keys = layer.keywordList()
- if len(keys) > 0:
- layerName = json.loads(layer.keywordList())
- if layerName["type"] == "RimoLayer":
- layer.dataProvider().forceReload()
- layer.triggerRepaint()
- # Get BackboneRegionOop
- def getBackboneRegionOop(self, clusterOop):
- global project
- r = requests.post(self.rimoUrl + "api/MIT/SDMeteorQGISController", data=json.dumps({"method": "getBackboneRegion", "Oop": clusterOop}))
- data = json.loads(r.text)
- if "_error" in data:
- return False
- if "asOop" in data:
- return data["asOop"]
- # Update Style List ComboBox
- def updateStyleListComboBox(self):
- global project
- comboBox = self.dlg.comboBox_9
- #Clear ComboBox
- comboBox.clear()
- #Return List
- comboBox.addItems(os.listdir(self.plugin_dir + "/styles"))
- # Get layer by Project Layer Name
- def getLayerByName(self, name):
- global project
- myLegendLayers = self.iface.legendInterface().layers()
- for myLayer in myLegendLayers:
- if name == myLayer.name():
- return myLayer
- return False
- # Read file and find String
- def readFileAndFindString(self, filePath, string):
- with open (filePath, 'rt') as in_file:
- for line in in_file:
- if string in line:
- return line
- # Get Number from String
- def get_num(self, x):
- return float(re.findall("\d+\.\d+", x)[0])
- # Load Config Yaml
- def loadConfigYaml(self, path):
- with open(path, 'r') as stream:
- try:
- return yaml.load(stream)
- except yaml.YAMLError as exc:
- self.renderWarning("Config file corrupt")
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement