Пример #1
0
class MapSwipePlugin:

  def __init__(self, iface):
    
    def translate():
      #
      # For create file 'qm'
      # 1) Define that files need for translation: mapswipetool.pro
      # 2) Create 'ts': pylupdate4 -verbose mapswipetool.pro
      # 3) Edit your translation: QtLinquist
      # 4) Create 'qm': lrelease *.ts 
      #
      dirname = os.path.dirname( os.path.abspath(__file__) )
      locale = QSettings().value("locale/userLocale")
      localePath = os.path.join( dirname, "i18n", "%s_%s.qm" % ( name_src, locale ) )
      if os.path.exists(localePath):
        self.translator = QTranslator()
        self.translator.load(localePath)
        if qVersion() > '4.3.3':
          QCoreApplication.installTranslator(self.translator)      

    self.iface = iface
    self.canvas = iface.mapCanvas() 
    self.action = None # Define by initGui
    self.tool = MapSwipeTool( self.iface )
    self.prevTool = None # Define by run

    name_src = "mapswipetool"
    translate()

  def initGui(self):
    title = "Map swipe tool"
    icon = QIcon( os.path.join( os.path.dirname(__file__), 'mapswipetool.png' ) )
    self.action = QAction( icon, title, self.iface.mainWindow() )
    self.action.setObjectName( "MapSwipeTool" )
    self.action.setWhatsThis( title )
    self.action.setStatusTip( title )
    self.action.triggered.connect( self.run )
    self.menu = "&Map swipe tool"

    # Maptool
    self.action.setCheckable( True )
    self.tool.setAction( self.action )

    self.iface.addToolBarIcon( self.action )
    self.iface.addPluginToMenu( self.menu, self.action )

  def unload(self):
    self.canvas.unsetMapTool( self.tool )
    self.iface.removeToolBarIcon( self.action )
    self.iface.removePluginMenu( self.menu, self.action )
    del self.action

  @pyqtSlot()
  def run(self):
    if self.canvas.mapTool() != self.tool:
      self.prevTool = self.canvas.mapTool()
      self.canvas.setMapTool( self.tool )
    else:
      self.canvas.setMapTool( self.prevTool )
Пример #2
0
def setup_locale(application, name, language=None, format="%s.%s"):
    """
    Load the translation for the current user locale.
    The name argument is the file name without the suffix (eg. ".fr.qm").
    So use the name "ufwi_rpcd" to load "ufwi_rpcd.fr.qm".
    """
    # Add language as suffix
    if not language:
        language = get_language()
        if not language:
            # No locale: do nothing
            return True
    filename = format % (name, language)

    translator = QTranslator(application)
    if filename.startswith(":"):
        ret = translator.load(filename)
        if ret:
            application.installTranslator(translator)
            debug("Load locale from resources: %s" % filename)
            return True
    else:
        for directory in ('.', '/usr/share/ufwi_rpcd/i18n'):
            ret = translator.load(filename, directory)
            if not ret:
                continue
            debug("Load locale file: %s" % path_join(directory, filename))
            application.installTranslator(translator)
            return True
    error("Unable to load translation file: %s" % filename)
    return False
Пример #3
0
    class __Translator:
        def __init__(self):
            self.dff = QTranslator()

            self.generic = QTranslator()
            self.Conf = Conf()
            self.loadLanguage()

        def loadLanguage(self):
            """ Load DFF translation + a Qt translation file

            FIXME need to check if qt4 directory exists in /usr/share or /usr/local/share
            """

            l1 = self.generic.load("/usr/share/qt4/translations/qt_" + str(self.Conf.getLanguage()).lower()[:2])
            l2 = self.dff.load(
                sys.modules["ui.gui"].__path__[0] + "/i18n/Dff_" + str(self.Conf.getLanguage()).lower()[:2]
            )

            return l1 and l2

        def getDFF(self):
            return self.dff

        def getGeneric(self):
            return self.generic
 def __init__(self, hintInfo, parent = None):
     super(InfoHintDialog,self).__init__(parent)
     
     self.setFixedSize(480, 290)
     
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
     
     self.okBtn = QPushButton(self.tr("OK"), self)
     self.okBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
     
     self.setTitle(self.tr("Tip Information"))
     
     self.hintInfo = hintInfo
     
     self.okBtn.move((self.width() - self.okBtn.width())/2, self.height() - self.okBtn.height() - 10)
     
     self.connect(self.okBtn, SIGNAL("clicked()"),self.slotOk)
Пример #5
0
    def __init__(self,parent = None):
        super(MainFrame,self).__init__(parent)
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
            StoreInfoParser.instance().setLanguage("chinese")
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        #初始化子控件
        self.initSubWidget()

        #绑定信号和槽
        self.bandSignalSlot()
        
        self.setMinimumSize(800,600)
        self.showFullScreen()
        
        self.updateWidgetInfo()
        self.setPosition()
def main():
    app = QApplication([i.encode('utf-8') for i in sys.argv])
    app.setOrganizationName(ffmc.__name__)
    app.setOrganizationDomain(ffmc.__url__)
    app.setApplicationName('FF Muli Converter')
    app.setWindowIcon(QIcon(':/ffmulticonverter.png'))

    locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load('qt_' + locale, ':/'):
        app.installTranslator(qtTranslator)
    appTranslator = QTranslator()
    if appTranslator.load('ffmulticonverter_' + locale, ':/'):
        app.installTranslator(appTranslator)

    if not os.path.exists(config.log_dir):
        os.makedirs(config.log_dir)

    logging.basicConfig(
            filename=config.log_file,
            level=logging.DEBUG,
            format=config.log_format,
            datefmt=config.log_dateformat
            )

    converter = MainWindow()
    converter.show()
    app.exec_()
Пример #7
0
class Translate:
    def __init__(self):
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = os.path.join(self.plugin_dir, "i18n", "PluginMapotempo_{}.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)

    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("PluginMapotempo", message)
Пример #8
0
class qWat():
    def __init__(self, iface):
        self.iface = iface
        self.settings = MySettings()
        self.mainDialog = MainDialog()

         # Initialise the translation environment.
        userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/qwat"
        systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/qwat"
        locale = QSettings().value("locale/userLocale")
        myLocale = locale[0:2]
        if QFileInfo(userPluginPath).exists():
            pluginPath = userPluginPath+"/i18n/qwat_"+myLocale+".qm"
        elif QFileInfo(systemPluginPath).exists():
            pluginPath = systemPluginPath+"/i18n/qwat_"+myLocale+".qm"
        self.localePath = pluginPath
        if QFileInfo(self.localePath).exists():
            self.translator = QTranslator()
            self.translator.load(self.localePath)
            QCoreApplication.installTranslator(self.translator)


    def initGui(self):
        self.uiAction = QAction(QIcon(":/plugins/qWat/icons/qwat.svg"), "settings", self.iface.mainWindow())
        self.uiAction.triggered.connect(self.showDialog)
        self.iface.addPluginToMenu("&qWat", self.uiAction)
        self.iface.addToolBarIcon(self.uiAction)


    def unload(self):
        self.iface.removePluginMenu("&qWat", self.uiAction)
        self.iface.removeToolBarIcon(self.uiAction)

    def showDialog(self):
        self.mainDialog.show()
Пример #9
0
class QtTranslator(GetTextTranslator):

    """This deals with translating Qt itself. The rest of the strings are
    still translated using the gettext mechanism, as we've modified pyuic4
    to use gettext too.

    """

    def __init__(self, component_manager):
        GetTextTranslator.__init__(self, component_manager)
        self.qt_translator = QTranslator(QCoreApplication.instance())
        try:
            self.qt_dir = os.environ["QTDIR"]
        except:
            if sys.platform == "win32":
                self.qt_dir = os.path.join(sys.exec_prefix, "share", "qt4")
            else:
                self.qt_dir = os.path.join("/usr", "share", "qt4")
        # Avoid stuff like Thai numerals if the language is not explicitly
        # set to Thai.
        QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))

    def translate_ui(self, language):
        app = QCoreApplication.instance()
        # We always need to remove a translator, to make sure we generate a
        # LanguageChange event even if their is no Qt translation for that
        # language installed.
        app.removeTranslator(self.qt_translator)
        self.qt_translator.load(os.path.join(self.qt_dir, "translations",
            "qt_" + language + ".qm"))
        app.installTranslator(self.qt_translator)
        # The title can also contain the database name.
        self.controller().update_title()
Пример #10
0
 def Translate(self, lang):
     translator = QTranslator(qApp)
     translator.load(":Translations/dc_" + lang + ".qm")
     qApp.installTranslator(translator)
     self.basename = self.tr("Data Centers GUI")
     self.demandGraphEditor.basename = self.demandGraphEditor.tr("Request Graph Editor")
     self.resourcesGraphEditor.basename = self.resourcesGraphEditor.tr("Resources Graph Editor")
     self.ui.retranslateUi(self)
     self.settingsDialog.ui.retranslateUi(self.settingsDialog)
     self.demandGraphEditor.ui.retranslateUi(self.demandGraphEditor)
     self.resourcesGraphEditor.ui.retranslateUi(self.resourcesGraphEditor)
     self.randomDialog.ui.retranslateUi(self.randomDialog)
     self.Vis.ui.retranslateUi(self.Vis)
     self.graphvis.ui.retranslateUi(self.graphvis)
     self.showStats()
     for k in self.demands.keys():
         cb = QComboBox()
         cb.addItems([self.tr("No"),self.tr("Yes")])
         cb.setCurrentIndex(0 if self.demands[k].critical else 1)
         QObject.connect(cb, SIGNAL("currentIndexChanged(int)"), k.emitDataChanged)
         self.ui.demands.setItemWidget(k,3,cb)
         if self.demands[k].assigned:
             k.setText(4, self.tr("Yes"))
         else:
             k.setText(4, self.tr("No"))
Пример #11
0
    def init(self, logo, title):
        from qgis.core import QgsApplication
        from PyQt4.QtGui import QApplication, QFont, QIcon
        from PyQt4.QtCore import QLocale, QTranslator
        try:
            import PyQt4.QtSql
        except ImportError:
            pass

        self.app = QgsApplication(self.sysargv, True)
        import roam.roam_style
        self.app.setStyleSheet(roam.roam_style.appstyle)
        QgsApplication.setPrefixPath(self.prefixpath, True)
        QgsApplication.initQgis()

        locale = QLocale.system().name()
        self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale))
        translator = QTranslator()
        translator.load(self.translationFile, "i18n")
        self.app.installTranslator(translator)

        QApplication.setStyle("Plastique")
        QApplication.setFont(QFont('Segoe UI'))
        QApplication.setWindowIcon(QIcon(logo))
        QApplication.setApplicationName(title)

        import roam.editorwidgets.core
        roam.editorwidgets.core.registerallwidgets()
        return self
Пример #12
0
class GenericTool():
	
	def __init__(self, iface):
		self.toolLabel = ''
		self.toolName = self.__class__.__name__
		
		self.iface = iface
		
		
		self.plugin_dir = os.path.dirname(__file__)
		self.icon_path = ":/plugins/LAPIGTools/icons/" + self.toolName + ".png"
		
		locale = QSettings().value('locale/userLocale')[0:2]
		locale_path = os.path.join(
			self.plugin_dir,
			'i18n',
			'CalculateRegion_{}.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)

	def initGui(self):
		self.obtainAction = QAction(QIcon(self.icon_path),QCoreApplication.translate(self.toolLabel,"&"+self.labelName), self.iface.mainWindow())
		QObject.connect(self.obtainAction, SIGNAL("triggered()"), self.run)
		return self.obtainAction,self.labelName
		
	def unload(self):
		#self.iface.removePluginMenu(self.toolLabel, self.obtainAction)
		self.iface.removeToolBarIcon(self.obtainAction)
 def slotCheckPassWord(self):
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
         
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
         
     passwd = self.passwordLineEdit.text()
     if passwd.isNull() or passwd.isEmpty():
         self.showHintInfo(self.tr("Please input the password first!"))
         return
 
     #读取/etc/shadow文件,获取以root开头的行
     crypasswd = self.getSystemAdministratorPassword()
     if not crypasswd:
         self.showHintInfo(self.tr("The password is not in shadow, can not check!"))
         return
 
     if not self.checkPasswd(passwd,crypasswd):
         self.showHintInfo(self.tr("The password is wrong, input again!"))
         return
 
     self.accept()
Пример #14
0
def correr_interfaz(app):
    ESettings().cargar()
    import src.ui.inicio  # lint:ok
    # Traductor
    local = QLocale.system().name()
    qtraductor = QTranslator()
    qtraductor.load("qt_" + local, QLibraryInfo.location(
                    QLibraryInfo.TranslationsPath))

    edis = EDIS()
    app.setWindowIcon(QIcon(paths.ICONOS['icon']))
    # Aplicar estilo
    with open(os.path.join(paths.PATH,
              "extras", "temas", "default.qss")) as tema:
        estilo = tema.read()
    app.setStyleSheet(estilo)
    # Archivos de última sesión
    archivos = ESettings.get('general/archivos')
    # Archivos recientes
    recents_files = ESettings.get('general/recientes')
    if recents_files is None:
        recents_files = []
    edis.cargar_archivos(archivos, recents_files)
    edis.show()
    sys.exit(app.exec_())
 def slotShowRestartNetworkInfo(self, status):
     """显示重启网络的状态信息"""
         
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
     """显示重启网络的状态信息"""
     
     if status == "Start":
         self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
     elif status == "Success":
         self.waitingDlg.setHintInfo(self.tr("network start success!"))
         vmtype = StoreInfoParser.instance().getVmType()
         if vmtype == "offline":
             pass 
     elif status == "Failed":
         self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
     else:
         return
     
     if self.waitingDlg.isHidden():
         self.waitingDlg.exec_()
    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
            
        if not self.checkInputValid():
            return

        if self.autoGetIpCheckbox.isChecked():
            netconf = self.setDynamicNetwork()
        elif self.staticIpGroupbox.isChecked():
            netconf = self.setStaticNetwork()

        #重新启动网络
        self.restartNetworkTD.setNetConf(netconf)
        self.restartNetworkTD.start()

        return
 def slotSave(self):
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
         
     """改变当前的分辨率"""
     screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString()
     if not screenName.isEmpty() and not screenName.isNull():
         self.curResolutionValue = self.getCurrentScreenResolution(str(screenName))
         if self.curResolutionValue:
             reScreen = self.resolutionCombox.currentText()
             if reScreen == "800x600":
                pass 
             else:
                pass
             #弹出提示框,默认为取消
             rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_()
             if rb == QDialog.Accepted:
                self.jytcapi.jysetdispconf(str(reScreen))
             elif rb == QDialog.Rejected:
                pass
Пример #18
0
 def slotShowRestartNetworkInfo(self, status):
     """显示重启网络的状态信息"""
     
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
     
     if status == "Start":
         #InfoHintDialog(self.tr("restarting network, please wait ...")).exec_()
         self.waitingDlg.setHintInfo(self.tr("restarting network, please wait ..."))
     elif status == "Success":
         #InfoHintDialog(self.tr("network setting success")).exec_()
         self.waitingDlg.setHintInfo(self.tr("network setting success"))
     elif status == "Failed":
         #InfoHintDialog(self.tr("network restart failed")).exec_()
         self.waitingDlg.setHintInfo(self.tr("network restart failed"))
     else:
         return
     
     if self.waitingDlg.isHidden():
         desktop = QApplication.desktop()
         self.waitingDlg.move((desktop.width() - self.waitingDlg.width())/2, (desktop.height() - self.waitingDlg.height())/2)
         self.waitingDlg.exec_()
Пример #19
0
def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename,"w")
                print ('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print "Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work."
        else:
            print "Log file is not set. Pleaase set it in settings."

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
Пример #20
0
def main():
    global app, aboutData

    import setproctitle
    setproctitle.setproctitle("iosshy")

    from PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QSettings
    from PyQt4.QtGui import QApplication, QSystemTrayIcon, QImage

    from tunneldialog import TunnelDialog

    try:
        from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs
        from PyKDE4.kdeui import KApplication, KIcon

        aboutData = KAboutData(
            name, #appName
            name, #catalogName
            ki18n(name), #programName
            version,
            ki18n(description), #shortDescription
            KAboutData.License_BSD, #licenseKey
            ki18n("© 2010 Massimiliano Torromeo"), #copyrightStatement
            ki18n(""), #text
            url #homePageAddress
        )
        aboutData.setBugAddress("http://github.com/mtorromeo/iosshy/issues")
        aboutData.addAuthor(
            ki18n("Massimiliano Torromeo"), #name
            ki18n("Main developer"), #task
            "*****@*****.**" #email
        )
        aboutData.setProgramLogo(QImage(":icons/network-server.png"))

        KCmdLineArgs.init(sys.argv, aboutData)

        app = KApplication()
        app.setWindowIcon(KIcon("network-server"))

        if app.isSessionRestored():
            sys.exit(0)
    except ImportError:
        app = QApplication(sys.argv)
        app.setOrganizationName("MTSoft")
        app.setApplicationName(name)


    if QSystemTrayIcon.isSystemTrayAvailable():
        translator = QTranslator()
        qmFile = "tunneller_%s.qm" % QLocale.system().name()
        if os.path.isfile(qmFile):
            translator.load(qmFile)
        app.installTranslator(translator)

        dialog = TunnelDialog()
        sys.exit(app.exec_())
    else:
        print "System tray not available. Exiting."
        sys.exit(1)
Пример #21
0
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     self._print_signal.connect(self._print)
Пример #22
0
class BigSearch ():
    def __init__(self, iface):
        self.iface = iface

        self.process = SearchProcess()

        # Initialise the translation environment.
        userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/bigsearch"
        systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/bigsearch"
        locale = QSettings().value("locale/userLocale")
        myLocale = locale[0:2]
        if QFileInfo(userPluginPath).exists():
            pluginPath = userPluginPath+"/i18n/bigsearch_"+myLocale+".qm"
        elif QFileInfo(systemPluginPath).exists():
            pluginPath = systemPluginPath+"/i18n/bigsearch_"+myLocale+".qm"
        self.localePath = pluginPath
        if QFileInfo(self.localePath).exists():
            self.translator = QTranslator()
            self.translator.load(self.localePath)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        # # dock
        # self.dockAction = QAction(QIcon(":/plugins/bigsearch/icons/bigsearch.svg"), "Big Search",
        #                           self.iface.mainWindow())
        # self.dockAction.setCheckable(True)
        # self.dockAction.triggered.connect(self.dock.setVisible)
        # self.iface.addPluginToMenu("&Big Search", self.dockAction)
        # self.iface.addToolBarIcon(self.dockAction)
        # self.dock.visibilityChanged.connect(self.dockAction.setChecked)

        # settings
        self.settingsAction = QAction(QIcon(":/plugins/bigsearch/icons/settings.svg"), "Configuration",
                                      self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)
        self.iface.addPluginToMenu("&Big Search", self.settingsAction)
        # help
        self.helpAction = QAction(QIcon(":/plugins/bigsearch/icons/help.svg"), "Help", self.iface.mainWindow())
        self.helpAction.triggered.connect(lambda: QDesktopServices().openUrl(QUrl("http://io.github.com/3nids/bigsearch/")))
        self.iface.addPluginToMenu("&Big Search", self.helpAction)

        self.searchEdit = QLineEdit()
        self.searchEdit.textChanged.connect(self.doSearch)
        self.searchEditAction = self.iface.addToolBarWidget(self.searchEdit)

    def unload(self):
        # Remove the plugin menu item and icon
        # self.iface.removePluginMenu("&Big Search", self.dockAction)
        self.iface.removePluginMenu("&Big Search", self.helpAction)
        self.iface.removePluginMenu("&Big Search", self.settingsAction)
        # self.iface.removeToolBarIcon(self.dockAction)
        self.iface.removeToolBarIcon(self.searchEditAction)

    def doSearch(self, searchText):
        self.process.newSearch(searchText)

    def showSettings(self):
        ConfigurationDialog(self.iface).exec_()
Пример #23
0
class RuGeocoderPlugin:
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.__converter_dlg = ConverterDialog()
        self.__geocoder_dlg = BatchGeocodingDialog()

        # i18n support
        override_locale = QSettings().value('locale/overrideFlag', False, type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale', '', type=unicode)

        self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path, locale_full_name[0:2])
        if QFileInfo(self.locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        # Setup signals
        self.action_convert = QAction(QIcon(':/plugins/rugeocoderplugin/convert.png'),
                                      QCoreApplication.translate('RuGeocoder', 'Convert CSV to SHP'),
                                      self.iface.mainWindow())
        QObject.connect(self.action_convert, SIGNAL("triggered()"), self.run_convert)

        self.action_batch_geocoding = QAction(QIcon(':/plugins/rugeocoderplugin/icon.png'),
                                              QCoreApplication.translate('RuGeocoder', 'Batch geocoding'),
                                              self.iface.mainWindow())
        QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action_convert)
        self.iface.addPluginToMenu('&RuGeocoder', self.action_convert)

        self.iface.addToolBarIcon(self.action_batch_geocoding)
        self.iface.addPluginToMenu('&RuGeocoder', self.action_batch_geocoding)

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu('&RuGeocoder', self.action_convert)
        self.iface.removeToolBarIcon(self.action_convert)

        self.iface.removePluginMenu('&RuGeocoder', self.action_batch_geocoding)
        self.iface.removeToolBarIcon(self.action_batch_geocoding)

    def run_convert(self):
        if not self.__converter_dlg.isVisible():
            self.__converter_dlg = ConverterDialog()
            self.__converter_dlg.show()
            self.__converter_dlg.exec_()

    def run_batch(self):
        if not self.__geocoder_dlg.isVisible():
            self.__geocoder_dlg = BatchGeocodingDialog()
            self.__geocoder_dlg.show()
            self.__geocoder_dlg.exec_()
Пример #24
0
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     if param.style_Qt:
         self.setStyle(param.style_Qt)
Пример #25
0
 def loadPluginsTranslators(self):
     reload(gayeogi.plugins)
     app = QtGui.QApplication.instance()
     for plugin in gayeogi.plugins.__all__:
         translator = QTranslator()
         if translator.load(plugin + u'_' + locale,
                 os.path.join(lnPath, u'plugins', u'langs')):
             self.translators.append(translator)
             app.installTranslator(translator)
Пример #26
0
def run():
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName(u'gayeogi')
    translator = QTranslator()
    if translator.load(u'main_' + locale, os.path.join(lnPath, u'langs')):
        app.installTranslator(translator)
    main = Main()
    main.show()
    sys.exit(app.exec_())
class FieldPyculatorPlugin:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # i18n support
        override_locale = QSettings().value('locale/overrideFlag', False, type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale', '', type=unicode)

        self.locale_path = currentPath + '/i18n/field_pyculator_' + locale_full_name[0:2] + '.qm'
        if path.exists(self.locale_path):
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

    def tr(self, text):
        return QCoreApplication.translate('FieldPyculatorPlugin', text)

    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(':/plugins/fieldpyculatorplugin/icon.png'),
                              self.tr('FieldPyculator'), self.iface.mainWindow())
        # connect the action to the run method
        QObject.connect(self.action, SIGNAL('triggered()'), self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(self.tr('&FieldPyculator'), self.action)

        # track layer changing
        QObject.connect(self.iface, SIGNAL('currentLayerChanged( QgsMapLayer* )'), self.layer_changed)

        # check already selected layers
        self.layer_changed()

    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(self.tr('&FieldPyculator'), self.action)
        self.iface.removeToolBarIcon(self.action)
        # Remove layer changing tracking
        QObject.disconnect(self.iface, SIGNAL('currentLayerChanged( QgsMapLayer* )'), self.layer_changed)

    def layer_changed(self):
        layer = self.iface.activeLayer()
        if (layer is None) or (layer.type() != QgsMapLayer.VectorLayer):
            self.action.setEnabled(False)
        else:
            self.action.setEnabled(True)

    def run(self):
        # create and show the dialog
        self.dlg = FieldPyculatorDialog(self.iface)
        # show the dialog
        self.dlg.show()
Пример #28
0
class kuw_filter:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.outdir = ''
        self.ilayers = QgsMapLayerRegistry.instance()
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/kuw_filter"
        # initialize locale
        localePath = ""
        locale = QSettings().value("locale/userLocale")[0:5]
        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/kuw_filter_" + locale + ".qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = kuw_filterDialog()
    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/kuw_filter/icon.png"), \
            QCoreApplication.translate("kuw_filter", "Kuwahara Filter", None, QApplication.UnicodeUTF8), self.iface.mainWindow())
        # connect the action to the run method
        QObject.connect(self.action, SIGNAL("triggered()"), self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(QCoreApplication.translate("kuw_filter","&Kuwahara Filter", None, QApplication.UnicodeUTF8), self.action)
    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(QCoreApplication.translate("kuw_filter","&Kuwahara Filter", None, QApplication.UnicodeUTF8), self.action)
        self.iface.removeToolBarIcon(self.action)
    # run method that performs all the real work
    def run(self):
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        # See if OK was pressed
        if True:
            # do something useful (delete the line containing pass and
            # substitute with your code)
            self.dlg.output.setText('')
            self.dlg.progressBar.setValue(0)
            self.dlg.refb.setText('1')
            self.dlg.mem.setText('100')
            self.dlg.inputbox.clear()
            for (key, layer) in self.ilayers.mapLayers().iteritems():
                if layer.type() == 1:
                    self.dlg.inputbox.addItem(unicode(layer.name()), key)
            pass
Пример #29
0
 def test_UI_raw_text_and_translations(self):
     gui = self.window.getGui()
     settingsText = gui.dock.pushButtonOptions.text()
     self.assertEqual(settingsText, "Settings")
     for lang, expected_translation in zip(["de", "pl"], ["Einrichten", "Ustawienia"]):
         path = os.path.join("i18n", "timemanager_{}.qm".format(lang))
         translator = QTranslator()
         result = translator.load(path)
         translation = translator.translate(gui.dock.objectName(), settingsText)
         self.assertEqual(translation, expected_translation)
Пример #30
0
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     self._print_signal.connect(self._print)
     # Pour Mac OS X
     self.setAttribute(Qt.AA_DontUseNativeMenuBar)
Пример #31
0
class quickFinder(QObject):

    name = u"&Quick Finder"
    actions = None
    toolbar = None
    finders = {}

    loadingIcon = None

    def __init__(self, iface):
        QObject.__init__(self)
        self.iface = iface
        self.actions = {}
        self.finders = {}
        self.settings = MySettings()

        self._initFinders()

        self.iface.projectRead.connect(self._reloadFinders)
        self.iface.newProjectCreated.connect(self._reloadFinders)

        # translation environment
        self.plugin_dir = os.path.dirname(__file__)
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n',
                                  'quickfinder_{0}.qm'.format(locale))
        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)
            QCoreApplication.installTranslator(self.translator)

    def initGui(self):
        self.actions['showSettings'] = QAction(
            QIcon(":/plugins/quickfinder/icons/settings.svg"),
            self.tr(u"&Settings"), self.iface.mainWindow())
        self.actions['showSettings'].triggered.connect(self.showSettings)
        self.iface.addPluginToMenu(self.name, self.actions['showSettings'])
        self.actions['help'] = QAction(
            QIcon(":/plugins/quickfinder/icons/help.svg"), self.tr("Help"),
            self.iface.mainWindow())
        self.actions['help'].triggered.connect(lambda: QDesktopServices(
        ).openUrl(QUrl("http://3nids.github.io/quickfinder")))
        self.iface.addPluginToMenu(self.name, self.actions['help'])
        self._initToolbar()
        self.rubber = QgsRubberBand(self.iface.mapCanvas())
        self.rubber.setColor(QColor(255, 255, 50, 200))
        self.rubber.setIcon(self.rubber.ICON_CIRCLE)
        self.rubber.setIconSize(15)
        self.rubber.setWidth(4)
        self.rubber.setBrushStyle(Qt.NoBrush)

    def unload(self):
        """ Unload plugin """
        for key in self.finders.keys():
            self.finders[key].close()
        for action in self.actions.itervalues():
            self.iface.removePluginMenu(self.name, action)
        if self.toolbar:
            del self.toolbar
        if self.rubber:
            self.iface.mapCanvas().scene().removeItem(self.rubber)
            del self.rubber

    def _initToolbar(self):
        """setup the plugin toolbar."""
        self.toolbar = self.iface.addToolBar(self.name)
        self.toolbar.setObjectName('mQuickFinderToolBar')
        self.searchAction = QAction(
            QIcon(":/plugins/quickfinder/icons/magnifier13.svg"),
            self.tr("Search"), self.toolbar)
        self.stopAction = QAction(
            QIcon(":/plugins/quickfinder/icons/wrong2.svg"), self.tr("Cancel"),
            self.toolbar)
        self.finderBox = FinderBox(self.finders, self.iface, self.toolbar)
        self.finderBox.searchStarted.connect(self.searchStarted)
        self.finderBox.searchFinished.connect(self.searchFinished)
        self.finderBoxAction = self.toolbar.addWidget(self.finderBox)
        self.finderBoxAction.setVisible(True)
        self.searchAction.triggered.connect(self.finderBox.search)
        self.toolbar.addAction(self.searchAction)
        self.stopAction.setVisible(False)
        self.stopAction.triggered.connect(self.finderBox.stop)
        self.toolbar.addAction(self.stopAction)
        self.toolbar.setVisible(True)

    def _initFinders(self):
        self.finders['geomapfish'] = GeomapfishFinder(self)
        self.finders['osm'] = OsmFinder(self)
        self.finders['project'] = ProjectFinder(self)
        for key in self.finders.keys():
            self.finders[key].message.connect(self.displayMessage)
        self.refreshProject()

    def _reloadFinders(self):
        for key in self.finders.keys():
            self.finders[key].close()
            self.finders[key].reload()
        self.refreshProject()

    @pyqtSlot(str, QgsMessageBar.MessageLevel)
    def displayMessage(self, message, level):
        self.iface.messageBar().pushMessage("QuickFinder", message, level)

    def showSettings(self):
        if ConfigurationDialog().exec_():
            self._reloadFinders()

    def searchStarted(self):
        self.searchAction.setVisible(False)
        self.stopAction.setVisible(True)

    def searchFinished(self):
        self.searchAction.setVisible(True)
        self.stopAction.setVisible(False)

    def refreshProject(self):
        if not self.finders['project'].activated:
            return
        if not self.settings.value("refreshAuto"):
            return
        nDays = self.settings.value("refreshDelay")
        # do not ask more ofen than 3 days
        askLimit = min(3, nDays)
        recentlyAsked = self.settings.value(
            "refreshLastAsked") >= nDaysAgoIsoDate(askLimit)
        if recentlyAsked:
            return
        threshDate = nDaysAgoIsoDate(nDays)
        uptodate = True
        for search in self.finders['project'].searches.values():
            if search.dateEvaluated <= threshDate:
                uptodate = False
                break
        if uptodate:
            return
        self.settings.setValue("refreshLastAsked", nDaysAgoIsoDate(0))
        ret = QMessageBox(
            QMessageBox.Warning, "Quick Finder",
            QCoreApplication.translate(
                "Auto Refresh",
                "Some searches are outdated. Do you want to refresh them ?"),
            QMessageBox.Cancel | QMessageBox.Yes).exec_()
        if ret == QMessageBox.Yes:
            RefreshDialog(self.finders['project']).exec_()
Пример #32
0
class ParcelChecker:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ParcelChecker_{}.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)
        self.dlg = ParcelCheckerDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&1 Parcel Checker')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'ParcelChecker')
        self.toolbar.setObjectName(u'ParcelChecker')
        self.dlg.lineEdit.clear()
        self.dlg.pushButton.clicked.connect(self.select_input_file)

    # 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('ParcelChecker', 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
        """

        # Create the dialog (after translation) and keep reference
        #self.dlg = ParcelCheckerDialog()

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/ParcelChecker/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Check the parcels V0.1'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&1 Parcel Checker'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def select_input_file(self):
        filename = QFileDialog.getOpenFileName(self.dlg, "Select input file",
                                               "", '*.dxf')
        self.dlg.lineEdit.setText(filename)

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            #-----clear
            cLayer = iface.mapCanvas().currentLayer()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)
            cLayer = iface.mapCanvas().currentLayer()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)

            line_Dxf = self.dlg.lineEdit.text()
            db = os.path.expanduser(
                '~\\.qgis2\\python\\plugins\\ParcelChecker\\qgis.dbf')
            outputs_QGISEXPLODELINES_1 = processing.runalg(
                'qgis:explodelines', line_Dxf, None)
            outputs_GRASS7VCLEAN_1 = processing.runalg(
                'grass7:v.clean', outputs_QGISEXPLODELINES_1['OUTPUT'], 1,
                0.001, ('0,2000,0,2000'), -1.0, 0.0001, None, None)
            outputs_GRASS7VCLEAN_2 = processing.runalg(
                'grass7:v.clean', outputs_GRASS7VCLEAN_1['output'], 0, 0.001,
                ('0,2000,0,2000'), -1.0, 0.0001, None, None)
            outputs_QGISFIELDCALCULATOR_1 = processing.runalg(
                'qgis:fieldcalculator', outputs_GRASS7VCLEAN_2['output'], 'ex',
                0, 10.0, 4.0, True, '$length', None)
            outputs_QGISJOINATTRIBUTESTABLE_1 = processing.runandload(
                'qgis:joinattributestable',
                outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'], db, 'layer',
                'layer', None)

            #---- ---------------iface activity--------------------------------------
            cLayer = iface.mapCanvas().currentLayer()
            expr = QgsExpression("ex=0")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            cLayer.startEditing()
            for fid in ids:
                cLayer.deleteFeature(fid)
            cLayer.commitChanges()

            #---- ---------------iface activity 02--------------------------------------

            cLayer = iface.mapCanvas().currentLayer()
            expr = QgsExpression(" \"layer_2\" is NULL")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            cLayer.startEditing()
            for fid in ids:
                cLayer.deleteFeature(fid)
            cLayer.commitChanges()
            #------------------
            cLayer = iface.mapCanvas().currentLayer()
            layer = self.iface.activeLayer()
            myfilepath = iface.activeLayer().dataProvider().dataSourceUri()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)
            layer = QgsVectorLayer(myfilepath, os.path.basename(line_Dxf[:-4]),
                                   'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(layer)
            cLayer = iface.mapCanvas().currentLayer()
            outputs_QGISPOLYGONIZE_1 = processing.runalg(
                'qgis:polygonize', cLayer, False, True, None)
            outputs_QGISPOINTONSURFACE_1 = processing.runandload(
                'qgis:pointonsurface', line_Dxf, None)
            cLayer = iface.mapCanvas().currentLayer()
            expr = QgsExpression(" \"Layer\" is not 'LOTNO'")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            cLayer.startEditing()
            for fid in ids:
                cLayer.deleteFeature(fid)
            cLayer.commitChanges()
            outputs_QGISJOINATTRIBUTESBYLOCATION_1 = processing.runandload(
                'qgis:joinattributesbylocation',
                outputs_QGISPOLYGONIZE_1['OUTPUT'], cLayer, ['contains'], 0.0,
                0, 'sum,mean,min,max,median', 1, None)
            b = r"" + line_Dxf[:-4] + "Report01.txt"
            file = open(b, 'w')
            cLayer = iface.mapCanvas().currentLayer()

            #------------------------------------------------------------------------
            cLayer = iface.mapCanvas().currentLayer()
            layer = self.iface.activeLayer()
            myfilepath = iface.activeLayer().dataProvider().dataSourceUri()

            outputs_QGISDISSOLVE_2 = processing.runandload(
                'qgis:dissolve', cLayer, False, 'Text', None)
            layer = self.iface.activeLayer()
            myfilepath2 = iface.activeLayer().dataProvider().dataSourceUri()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)

            outputs_QGISDISSOLVE_3 = processing.runandload(
                'qgis:dissolve', myfilepath, False, 'Text', None)

            #---- ---------------iface activity 03--------------------------------------

            cLayer = iface.mapCanvas().currentLayer()
            expr = QgsExpression(" \"Layer\" is NULL")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            cLayer.startEditing()
            for fid in ids:
                cLayer.deleteFeature(fid)
            cLayer.commitChanges()

            feats_count = cLayer.featureCount()
            file.write('----------Processed result of the plan--------"\n')
            file.write('\nNo of Lots              ')
            file.write(str(feats_count))
            #-----------------------------------------------------------------------------------------
            cLayer = iface.mapCanvas().currentLayer()
            layer = self.iface.activeLayer()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)
            cLayer = iface.mapCanvas().currentLayer()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)
            cLayer = iface.mapCanvas().currentLayer()
            QgsMapLayerRegistry.instance().removeMapLayer(cLayer)
            layer = QgsVectorLayer(myfilepath, os.path.basename(line_Dxf[:-4]),
                                   'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(layer)

            #---- ---------------iface activity 05--------------------------------------
            cLayer = iface.mapCanvas().currentLayer()
            expr = QgsExpression(" \"area\" is 0")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            cLayer.startEditing()
            for fid in ids:
                cLayer.deleteFeature(fid)
            cLayer.commitChanges()

            count1 = cLayer.featureCount()
            file.write('\nNo of Polygons          ')
            file.write(str(count1))
            expr = QgsExpression(" \"Text\" is NULL")
            it = cLayer.getFeatures(QgsFeatureRequest(expr))
            ids = [i.id() for i in it]
            cLayer.setSelectedFeatures(ids)
            count2 = len(ids)
            file.write('\nNo of Polygons unloted  ')
            file.write(str(count2))

            if str(count1 < count2):
                file.write(
                    '\nplease numbered the unloted lots and re do the processed '
                )
            now = datetime.datetime.now()
            date = str(now)
            a1 = str(now.strftime("%Y-%m-%d"))
            file.write("\nDate : " + a1 + "\n")

            file.write(
                '\n------------------------- R&D @ SGO ------------------------'
            )

            file.close()
            layer = iface.activeLayer()
            layer.setCustomProperty("labeling", "pal")
            layer.setCustomProperty("labeling/enabled", "true")
            layer.setCustomProperty("labeling/fontFamily", "Arial")
            layer.setCustomProperty("labeling/fontSize", "10")
            layer.setCustomProperty("labeling/fieldName", "Text")
            layer.setCustomProperty("labeling/placement", "4")
            iface.mapCanvas().refresh()
            from PyQt4.QtGui import *
            window = iface.mainWindow()
            QMessageBox.information(
                window, "Info",
                "Process complete....!\n \n (if unloted polygon exist, dont goto the next step)"
            )

            pass
Пример #33
0
    def __init__(self, config):
        super(FreeseerApp, self).__init__()
        self.config = config
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")),
                            QIcon.Normal, QIcon.Off)
        self.setWindowIcon(self.icon)

        self.aboutDialog = AboutDialog()
        self.aboutDialog.setModal(True)

        self.logDialog = LogDialog()

        #
        # Translator
        #
        self.app = QApplication.instance()
        self.current_language = None
        self.uiTranslator = QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")
        self.app.installTranslator(self.uiTranslator)
        self.langActionGroup = QActionGroup(self)
        self.langActionGroup.setExclusive(True)
        QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8'))
        self.connect(self.langActionGroup, SIGNAL('triggered(QAction *)'),
                     self.translate)
        # --- Translator

        #
        # Setup Menubar
        #
        self.menubar = self.menuBar()

        self.menubar.setGeometry(self.qrect_with_dpi(0, 0, 500, 50))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        self.menuLanguage = QMenu(self.menubar)
        self.menuLanguage.setObjectName(_fromUtf8("menuLanguage"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))

        exitIcon = QIcon.fromTheme("application-exit")
        self.actionExit = QAction(self)
        self.actionExit.setShortcut("Ctrl+Q")
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setIcon(exitIcon)

        helpIcon = QIcon.fromTheme("help-contents")
        self.actionOnlineHelp = QAction(self)
        self.actionOnlineHelp.setObjectName(_fromUtf8("actionOnlineHelp"))
        self.actionOnlineHelp.setIcon(helpIcon)

        self.actionAbout = QAction(self)
        self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
        self.actionAbout.setIcon(self.icon)

        self.actionLog = QAction(self)
        self.actionLog.setObjectName(_fromUtf8("actionLog"))
        self.actionLog.setShortcut("Ctrl+L")

        # Actions
        self.menuFile.addAction(self.actionExit)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addAction(self.actionLog)
        self.menuHelp.addAction(self.actionOnlineHelp)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuLanguage.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.setupLanguageMenu()
        # --- End Menubar

        self.connect(self.actionExit, SIGNAL('triggered()'), self.close)
        self.connect(self.actionAbout, SIGNAL('triggered()'),
                     self.aboutDialog.show)
        self.connect(self.actionLog, SIGNAL('triggered()'),
                     self.logDialog.show)
        self.connect(self.actionOnlineHelp, SIGNAL('triggered()'),
                     self.openOnlineHelp)

        self.retranslateFreeseerApp()
        self.aboutDialog.aboutWidget.retranslate("en_US")
class FFTConvolution:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'FFTConvolution_{}.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 = FFTConvolutionDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&FFT COnvolution Filters')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'FFTConvolution')
        self.toolbar.setObjectName(u'FFTConvolution')

        self.dlg.output_file.clear()
        self.dlg.output_file_button.clicked.connect(self.select_output_file)

    # 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('FFTConvolution', 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.addPluginToRasterMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/FFTConvolution/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'FFT Convolution filters'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginRasterMenu(
                self.tr(u'&FFT COnvolution Filters'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def select_output_file(self):
        filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ",
                                               "", '*.tif')
        self.dlg.output_file.setText(filename)

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            if self.dlg.smoothing.isChecked():
                edge = False
            else:
                edge = True
            #call the function linking to real work
            #the input is translated from the GUI input to correct format here
            self.fft_convolution(in_layer=self.dlg.input_layer.currentLayer(),
                                 out_path=self.dlg.output_file.text(),
                                 size=self.dlg.size.text(),
                                 edge=edge,
                                 new_crs=self.dlg.crs.crs(),
                                 tiled=self.dlg.window.isChecked(),
                                 tilerows=self.dlg.window_rows.text(),
                                 tilecols=self.dlg.window_cols.text(),
                                 add_layer=self.dlg.check_add.isChecked())

    #this function parses the arguments, calls the appropriate functions and displays the new layer if needed
    def fft_convolution(self,
                        in_layer,
                        out_path,
                        size=10,
                        edge=False,
                        new_crs=None,
                        tiled=False,
                        tilerows=0,
                        tilecols=0,
                        add_layer=True):
        #if the file has no extension, add '.tif'
        ext = os.path.splitext(out_path)[-1].lower()
        if ext == '':
            out_path = out_path + '.tif'
        #if the file already exists, ask the user
        if os.path.isfile(out_path):
            reply = QMessageBox.question(None, 'File exists!',
                                         'File exists - overwite it?',
                                         QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.No:
                return False
        #we need the CRS as EPSG code, or None if invalid
        if new_crs.isValid():
            new_crs = new_crs.authid()
        else:
            new_crs = None
        #preprocessing the input layer's path
        in_path = in_layer.dataProvider().dataSourceUri()
        #QMessageBox.information(None, "DEBUG:", str(in_path))
        if in_path.find('=') > -1:
            QMessageBox.information(None, "Sorry!",
                                    "WMS support wasn't implemented yet!")
            return False
        #the main computation
        layer = self.gaussian_filter(in_path=in_path,
                                     out_path=out_path,
                                     size=int(re.sub(r"\D", "", size)),
                                     edge=edge,
                                     tiled=tiled,
                                     tilerows=tilerows,
                                     tilecols=tilecols,
                                     new_crs=new_crs)
        if add_layer:
            QgsMapLayerRegistry.instance().addMapLayers([layer])
            qgis.utils.iface.mapCanvas().refresh()

    #returns number of array dimensions
    def __array_rank(self, arr):
        return len(arr.shape)

    #loads the newly created layer
    def __load_layer(self, path):
        fileName = path
        fileInfo = QFileInfo(fileName)
        baseName = fileInfo.baseName()
        rlayer = QgsRasterLayer(fileName, baseName)
        if not rlayer.isValid():
            raise Exception(
                "Computation finished, but layer failed to load. Inspect the path zou specified for the output layer."
            )
        return rlayer

    #pads the window to process its original extend accurately
    def __extend_window(self, window, size, height, width):
        minrow = max(window[0][0] - size, 0)
        maxrow = min(window[0][1] + size, height)
        mincol = max(window[1][0] - size, 0)
        maxcol = min(window[1][1] + size, width)
        return ((minrow, maxrow), (mincol, maxcol))

    #creates a window generator, in the same format as it is returned by block_windows method
    def __generate_windows(self, height, width, tilerows, tilecols):
        rownum = int(math.ceil(float(height) / tilerows))
        colnum = int(math.ceil(float(width) / tilecols))
        for i in range(rownum):
            #last row's and column's dimensions are computed by modulo - they are smaller than regular tiles
            if i == rownum - 1:
                rowsize = height % tilerows
            else:
                rowsize = tilerows
            for j in range(colnum):
                if j == colnum - 1:
                    colsize = width % tilecols
                else:
                    colsize = tilecols
                cell = ((i, j), ((i * tilerows, i * tilerows + rowsize),
                                 (j * tilecols, j * tilecols + colsize)))
                yield cell

    #like __generate_windows(), but returns an array
    def __generate_window_array(self, height, width, tilerows, tilecols):
        rownum = int(math.ceil(float(height) / tilerows))
        colnum = int(math.ceil(float(width) / tilecols))
        windows = np.asarray(np.zeros((height, width), dtype=object))
        for i in range(rownum):
            #last row's and column's dimensions are computed by modulo - they are smaller than regular tiles
            if i == rownum - 1:
                rowsize = height % tilerows
            else:
                rowsize = tilerows
            for j in range(colnum):
                if j == colnum - 1:
                    colsize = width % tilecols
                else:
                    colsize = tilecols
                windows[i][j] = ((i * tilerows, i * tilerows + rowsize),
                                 (j * tilecols, j * tilecols + colsize))
        return windows

    #processes the window parameters
    #returns the windows as a generator or an array (specified in the generator parameter)
    def __compute_windows(self,
                          in_raster,
                          height,
                          width,
                          size,
                          tilerows=0,
                          tilecols=0,
                          generator=True):
        #input validation
        size = int(size)
        try:
            tilerows = int(tilerows)
        except ValueError:
            tilerows = 0
        try:
            tilecols = int(tilecols)
        except ValueError:
            tilecols = 0
        #when raster's dimensions are modified due to reprojection, we must adjust the windows as well
        #this algorithm is quick'n'dirty - we just sompute one ratio and make all tiles larger/smaller
        #reprojecting each tile node would be better - perhaps in some future version
        if height != in_raster.height or width != in_raster.width:
            hratio = float(height) / in_raster.height
            wratio = float(width) / in_raster.width
        else:
            hratio = 1
            wratio = 1

        windows = []
        #if only one of tile's dimension was set, we assume a square
        if tilecols == 0 and tilerows > 0:
            tilecols = tilerows
        elif tilerows == 0 and tilecols > 0:
            tilerows = tilecols
        #if tiles are too small (including default 0 length), we make them automatically
        #"2*size" is the total padding length and also an arbitrarily chosen minimum
        #"size" would be a minimum to get accurate tiles, but this way only 1/9 of the tile would be useful => inefficient
        #"2*size" means at least 50% efficiency
        if min(tilerows, tilecols) <= 2 * size:
            #if the raster has blocks and they are big enough, we use them
            blocks = in_raster.block_shapes
            block = blocks[0]
            if min(block[0], block[1]) > 2 * size:
                #if we compute the original raster, use the block as-is
                #otherwise use the dimensions and continue
                if hratio == 1 and wratio == 1:
                    return in_raster.block_windows(1)
                else:
                    tilerows = block[0]
                    tilecols = block[1]
            else:
                #"2*size + 100" is an arbitrary constant
                #it's quite efficient on smaller rasters and shouldn't make any memory issues
                #really small rasters shouldn't be computed by tiles anyway
                tilerows = 2 * size + 100
                tilecols = 2 * size + 100
        #we transform the dimensions if needed
        tilerows = int(hratio * tilerows)
        tilecols = int(wratio * tilecols)
        #if the tiles are too big (more than half of any dimension of the raster),
        #we switch to the untiled algorithm
        if 2 * tilerows >= height or 2 * tilecols >= width:
            return False
        #if windows are not read from the raster, we must make them
        if generator:
            windows = self.__generate_windows(height, width, tilerows,
                                              tilecols)
        else:
            windows = self.__generate_window_array(height, width, tilerows,
                                                   tilecols)
        return windows

    #computes the affine transformation, raster dimensions and metadata for the new raster
    def __compute_transform(self, in_raster, new_crs):
        affine, width, height = calculate_default_transform(
            in_raster.crs, new_crs, in_raster.width, in_raster.height,
            *in_raster.bounds)
        kwargs = in_raster.meta.copy()
        kwargs.update({
            'driver': 'GTiff',
            'crs': new_crs,
            'transform': affine,
            'affine': affine,
            'width': width,
            'height': height
        })
        return affine, height, width, kwargs

    #calls reproject() function for every band
    def __reproject(self, in_raster, out_raster, affine, new_crs):
        for k in range(1, in_raster.count + 1):
            reproject(source=rasterio.band(in_raster, k),
                      destination=rasterio.band(out_raster, k),
                      src_transform=affine,
                      src_crs=in_raster.crs,
                      dst_transform=affine,
                      dst_crs=new_crs,
                      resampling=RESAMPLING.nearest)
        return out_raster

    #the original MikeT's function from http://gis.stackexchange.com/a/10467
    #my addition is the conversion of the padded array to float to avoid errors with integer rasters
    #the intended input is a single band raster array
    def __gaussian_blur1d(self, in_array, size):
        #check validity
        try:
            if 0 in in_array.shape:
                raise Exception("Null array can't be processed!")
        except TypeError:
            raise Exception("Null array can't be processed!")
        # expand in_array to fit edge of kernel
        padded_array = np.pad(in_array, size, 'symmetric').astype(float)
        # build kernel
        x, y = np.mgrid[-size:size + 1, -size:size + 1]
        g = np.exp(-(x**2 / float(size) + y**2 / float(size)))
        g = (g / g.sum()).astype(float)
        # do the Gaussian blur
        out_array = fftconvolve(padded_array, g, mode='valid')
        return out_array.astype(in_array.dtype)

    #the intended input is an array with various number of bands
    #returns a numpy array
    def __gaussian_blur(self, in_array, size):
        #make sure the input is a numpy array
        in_array = np.asarray(in_array)
        #find number of dimensions - 2 for single-band or 3 for multiband rasters
        rank = self.__array_rank(in_array)
        if rank == 2:
            return self.__gaussian_blur1d(in_array,
                                          size).astype(in_array.dtype)
        elif rank > 3 or rank == 1:
            raise TypeError("Invalid number of dimensions!")
        #continue to multiband
        count = in_array.shape[0]
        out = []
        for i in range(count):
            band = in_array[i]
            out_band = self.__gaussian_blur1d(band,
                                              size)  #.astype(in_array.dtype)
            #if out_band != False:
            out.append(out_band)
        return np.asarray(out)

    #the real work is done here
    #filters a raster specified by the file's path (in_path) and writes it to another file (out_path)
    def gaussian_filter(self,
                        in_path,
                        out_path,
                        size,
                        edge=False,
                        tiled=False,
                        tilerows=0,
                        tilecols=0,
                        new_crs=None):
        with rasterio.drivers():
            with rasterio.open(in_path, 'r') as in_raster:
                if new_crs == None:
                    new_crs = in_raster.crs
                affine, height, width, kwargs = self.__compute_transform(
                    in_raster, new_crs)
                if tiled:
                    #we make two sets of tiles, for the old and the new raster
                    #this is important in case of reprojection
                    old_windows = self.__compute_windows(
                        in_raster=in_raster,
                        height=in_raster.height,
                        width=in_raster.width,
                        size=size,
                        tilerows=tilerows,
                        tilecols=tilecols)
                    #windows for the new raster are made in two steps: generator and array
                    new_windows = self.__compute_windows(in_raster=in_raster,
                                                         height=height,
                                                         width=width,
                                                         size=size,
                                                         tilerows=tilerows,
                                                         tilecols=tilecols,
                                                         generator=False)
                    #if windows are too big or invalid, we process the raster without them
                    try:
                        iter(old_windows)
                        iter(new_windows)
                    except TypeError:
                        tiled = False
                with rasterio.open(out_path, 'w', **kwargs) as out_raster:
                    out_raster = self.__reproject(in_raster, out_raster,
                                                  affine, new_crs)
                    if tiled:
                        for index, window in old_windows:
                            oldbigwindow = self.__extend_window(
                                window, size, in_raster.height,
                                in_raster.width)
                            in_array = in_raster.read(window=oldbigwindow)
                            out_array = self.__gaussian_blur(in_array, size)
                            #for edge detection we subtract the output array from the original
                            #this may produce some artifacts when the raster is reprojected
                            #or extensive and with degree coordinates
                            if edge:
                                out_array = np.subtract(in_array, out_array)
                            #now compute the window for writing into the new raster
                            nwindow = new_windows[index[0]][index[1]]
                            newbigwindow = self.__extend_window(
                                nwindow, size, height, width)
                            out_raster.write(out_array, window=newbigwindow)
                    else:
                        in_array = in_raster.read()
                        out_array = self.__gaussian_blur(in_array, size)
                        if edge:
                            out_array = out_array = np.subtract(
                                in_array, out_array)
                        out_raster.write(out_array)
        return self.__load_layer(out_path)
Пример #35
0
class CalculateHeight:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'CalculateHeight_{}.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)


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Calculate height')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'CalculateHeight')
        self.toolbar.setObjectName(u'CalculateHeight')

    # 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('CalculateHeight', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = CalculateHeightDialog(self.iface.mainWindow())

        self.dlg.buttonCalculate.clicked.connect(self.calculateHeights)

        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.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/CalculateHeight/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Calculate Heights'),
            callback=self.run,
            parent=self.iface.mainWindow())


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Calculate height'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar


    def run(self):
        """Run method that performs all the real work"""



        self.dem_layers_list = []
        self.vector_layers_list = []
        layers = self.iface.legendInterface().layers()

        for layer in layers:
            if(layer.type() == layer.RasterLayer):
                self.dem_layers_list.append(layer)
            elif (layer.type() == layer.VectorLayer):
                self.vector_layers_list.append(layer)
        
        self.dlg.cbDEMLayers.clear()
        self.dlg.cbDEMLayers.addItems(list(map(lambda l:l.name(),self.dem_layers_list)))
        self.dlg.cbVectorLayers.clear()
        self.dlg.cbVectorLayers.addItems(list(map(lambda l:l.name(),self.vector_layers_list)))


        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

    def calculateHeights(self):
        target_layer = self.vector_layers_list[self.dlg.cbVectorLayers.currentIndex()]
        dem_layer = self.dem_layers_list[self.dlg.cbDEMLayers.currentIndex()]        
        transform_util = QgsCoordinateTransform(target_layer.crs(), dem_layer.crs()) #, QgsProject.instance())

        for feature in target_layer.getFeatures():
            print feature.id()
            
            geom = feature.geometry()

            coords = geom.asPolygon()

            def updateZValue(coords):
                result = []

                def calculate(coord):
                    res = QgsPointV2(coord)
                    projected_point = transform_util.transform(coord);
                    sample = dem_layer.dataProvider().identify(projected_point, QgsRaster.IdentifyFormatValue).results()
                    res.addZValue(sample[1])
                    return res

                for coord in coords:
                    new_coord = calculate(coord)
                    result.append(new_coord)

                return result
            
            new_coords = map(updateZValue, coords)
            for list_ in new_coords:
                for c in list_:
                    print c.x()
                    print c.y()
                    print c.z()
                    print c.asJSON()
            
            new_geom = QgsGeometry.fromPolygon(new_coords)
            
            feature.setGeometry(new_geom)
Пример #36
0
class raster_tracer:
    """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__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'raster_tracer_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&raster_tracer')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'raster_tracer')
        self.toolbar.setObjectName(u'raster_tracer')

        #print "** INITIALIZING raster_tracer"

        self.pluginIsActive = False
        self.dockwidget = None

    # 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('raster_tracer', 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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/raster_tracer/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Raster tracer'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    #--------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING raster_tracer"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        #print "** UNLOAD raster_tracer"

        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&raster_tracer'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #--------------------------------------------------------------------------
    def raster_selected(self):
        layer_index = self.dockwidget.comboBox.currentIndex()
        self.map_canvas = self.iface.mapCanvas()
        self.tool_identify2 = PointTool(self.map_canvas,
                                        self.layers_list[layer_index],
                                        self.iface, self.dockwidget)
        self.map_canvas.setMapTool(self.tool_identify2)
        print "ya!"

    def line_type_selected(self):
        indx = self.dockwidget.comboBoxLinePoly.currentIndex()
        self.linetype = self.line_types[indx]
        self.tool_identify2.linetype = self.linetype
        print "line type selected: %s" % self.linetype

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING raster_tracer"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = raster_tracerDockWidget()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            self.dockwidget.comboBox.currentIndexChanged.connect(
                self.raster_selected)
            self.dockwidget.comboBoxLinePoly.currentIndexChanged.connect(
                self.line_type_selected)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.TopDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

        layers = self.iface.legendInterface().layers()
        self.layer_list = []
        self.layers_list = []
        for layer in layers:
            if not layer.type() == QgsMapLayer.RasterLayer: continue
            self.layer_list.append(layer.name())
            self.layers_list.append(layer)
        self.dockwidget.comboBox.addItems(self.layer_list)
        self.line_types = ["Line", "Polygon"]
        self.dockwidget.comboBoxLinePoly.addItems(self.line_types)
Пример #37
0
class Formiga:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'Formiga_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Formiga2local')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'Formiga')
        self.toolbar.setObjectName(u'Formiga')

    # 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('Formiga', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = FormigaDialog()

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/Formiga/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'transform insects into ants'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Formiga2local'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Пример #38
0
# so that the inasafe library functions gettext will work
# .. see:: :py:func:`common.utilities`
os.environ['LANG'] = str(locale_name)

# LOGGER.debug('%s %s %s %s' % (
#     preferred_locale,
#     override_flag,
#     QLocale.system().name(),
#     os.environ['LANG']))

root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
translation_path = os.path.join(root, 'safe_qgis', 'i18n',
                                'inasafe_' + str(locale_name) + '.qm')

if os.path.exists(translation_path):
    translator = QTranslator()
    result = translator.load(translation_path)
    if not result:
        message = 'Failed to load translation for %s' % locale_name
        raise TranslationLoadError(message)
    # noinspection PyTypeChecker,PyCallByClass
    QCoreApplication.installTranslator(translator)

# MONKEYPATCHING safe.defaults.get_defaults to use get_defaults
# see safe_qgis.utilities.defaults for more details
try:
    import safe.defaults
    from safe_qgis.utilities.defaults import get_defaults

    safe.defaults.get_defaults = lambda the_default=None: get_defaults(
        the_default)
class KharifModel:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'KharifModel_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Kharif Model - all crop - all year - zone only')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'KharifModelMulticrop')
        self.toolbar.setObjectName(u'KharifModelMulticrop')

    # 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('KharifModelMulticrop', 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
		"""

        # Create the dialog (after translation) and keep reference
        self.dlg = KharifModelDialog(crops=dict_crop.keys())

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/KharifModelMulticrop/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Kharif Model - all crop - all year - zone only'),
            callback=self.run,
            parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Kharif Model - all crop - all year - zone only'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""

        start_time = time.time()

        if PLUGIN_MODE == 'DEBUG':
            if not os.path.exists(DEBUG_BASE_FOLDER_PATH):
                raise Exception(
                    'Set DEBUG_BASE_FOLDER_PATH for the debug dataset')
            paths = [DEBUG_BASE_FOLDER_PATH]
        elif PLUGIN_MODE == 'REAL':
            paths = ['']
        else:
            if not os.path.exists(TEST_SUITE_BASE_FOLDER_PATH):
                raise Exception(
                    'Set TEST_SUITE_BASE_FOLDER_PATH for the debug dataset')
            paths = [
                os.path.join(TEST_SUITE_BASE_FOLDER_PATH, base_path)
                for base_path in os.listdir(TEST_SUITE_BASE_FOLDER_PATH)
            ]
            filter(lambda p: os.path.isdir(p), paths)
        path_num = 0
        for path in paths:
            path_num += 1
            # if os.path.basename(path) == '503_ptp-1_03': continue
            if not os.path.exists(os.path.join(path, 'Zones.shp')): continue
            if self.fetch_inputs(path) is False: return
            # return
            print 'cluster', os.path.basename(path)
            # print self.rain['2013'].keys();	return
            year_num = 0
            print 'years', self.rain.keys()
            for year in self.rain:
                # if year_num > 0: break
                year_num += 1
                print 'checking whether already processed for year', year
                if os.path.exists(
                        os.path.join(path, year + '_' +
                                     ZONEWISE_BUDGET_CSV_FILENAME)):
                    continue
                print 'initializing calculations'
                self.modelCalculator = KharifModelCalculator(
                    self.path, self.et0, **self.input_layers)
                rain_input_dict = {
                    circle: {
                        'daily_rain': self.rain[year][circle]
                    }
                    for circle in self.rain[year]
                }
                rain_sum_input_dict = {
                    circle: {
                        'year': year,
                        'sum': self.rain_sum_monsoon[year][circle]
                    }
                    for circle in self.rain_sum_monsoon[year]
                }
                self.modelCalculator.calculate(
                    rain_input_dict,
                    self.crop_names,
                    self.sowing_threshold,
                    monsoon_end_date_index=self.monsoon_end_date_index,
                    cluster=str(path_num) + '/' + str(len(paths) - 1),
                    year=str(year_num) + '/' + str(len(self.rain.keys())))

                pointwise_output_csv_filepath = os.path.join(
                    self.base_path, year + '_' + POINTWISE_OUTPUT_CSV_FILENAME)

                op = KharifModelOutputProcessor()
                # Removed for urgent case of zone-level outputs only
                # op.output_point_results_to_csv	(
                #   self.modelCalculator.output_grid_points,
                # 	pointwise_output_csv_filepath,
                # 	crops=[crop.name for crop in self.modelCalculator.crops]
                # )
                zonewise_budgets = op.compute_zonewise_budget(
                    self.modelCalculator.zone_points_dict,
                    self.modelCalculator.
                    zone_points_dict_ag_missing,  #removed for urgent village charts (17-11-2018)
                    self.modelCalculator.zone_points_dict_current_fallow,
                    self.modelCalculator.zone_points_dict_non_ag_missing_LU,
                    self.modelCalculator.zones_layer)
                print self.circle_avg_year_dict
                village_avg_year_dict = {
                    feature['VIL_NAME']:
                    self.circle_avg_year_dict[feature['Circle'].lower()]
                    for feature in
                    self.modelCalculator.zones_layer.feature_dict.values()
                }
                print village_avg_year_dict
                op.output_zonewise_budget_to_csv(
                    zonewise_budgets, self.modelCalculator.crops,
                    self.rabi_crop_names, self.modelCalculator.currnet_fallow,
                    self.modelCalculator.LULC_pseudo_crops.values(),
                    os.path.join(self.base_path,
                                 year + '_' + ZONEWISE_BUDGET_CSV_FILENAME),
                    rain_sum_input_dict, year, village_avg_year_dict)

                # Removed for urgent case of zone-level outputs only
                # op.compute_and_output_cadastral_vulnerability_to_csv(
                # 	self.crop_names,
                # 	self.modelCalculator.output_cadastral_points,
                # 	os.path.join(self.base_path, year + '_' + CADESTRAL_VULNERABILITY_CSV_FILENAME)
                # )

                # kharif_model_crop_end_output_layer = \
                # 	op.render_and_save_pointwise_output_layer(
                # 		pointwise_output_csv_filepath,
                # 		'Kharif Model Crop End Output',
                # 		'Crop duration PET-AET',
                # 		self.output_configuration['graduated_rendering_interval_points'],
                # 		shapefile_path=os.path.join(self.base_path, 'kharif_crop_duration_et_deficit.shp')
                # 	)
                # if(crop in long_kharif_crops):
                # 	kharif_model_monsoon_end_output_layer = \
                # 		op.render_and_save_pointwise_output_layer(
                # 			pointwise_output_csv_filepath,
                # 			'Kharif Model Monsoon End Output',
                # 			'Monsoon PET-AET',
                # 			self.output_configuration['graduated_rendering_interval_points'],
                # 			shapefile_path=os.path.join(self.base_path, 'kharif_monsoon_et_deficit.shp')
                # 		)

                # Removed for urgent case of zone-level outputs only
                # for i in range(len(self.crop_names)):
                # 	op.compute_and_display_cadastral_vulnerability(
                # 		self.modelCalculator.cadastral_layer,
                # 		self.modelCalculator.output_grid_points,
                # 		self.modelCalculator.output_cadastral_points,
                # 		i,
                # 		self.crop_names[i],
                # 		self.path
                # 	)

            QgsMapLayerRegistry.instance().removeMapLayers([
                self.input_layers['zones_layer'].id(),
                self.input_layers['soil_layer'].id(),
                self.input_layers['lulc_layer'].id(),
                self.input_layers['slope_layer'].id(),
                # self.input_layers['cadastral_layer'].id()
            ])
        print("KM--- %s seconds ---" % (time.time() - start_time))
        print self.plugin_dir

    # self.iface.actionHideAllLayers().trigger()
    # 	self.iface.legendInterface().setLayerVisible(self.input_layers['zones_layer'], True)
    # 	if 'drainage_layer' in locals():	self.iface.legendInterface().setLayerVisible(self.input_layers['drainage_layer'], True)
    # 	if (crop in long_kharif_crops):		self.iface.legendInterface().setLayerVisible(kharif_model_monsoon_end_output_layer, True)
    # 	self.iface.legendInterface().setLayerVisible(kharif_model_crop_end_output_layer, True)
    # 	self.iface.mapCanvas().setExtent(self.input_layers['zones_layer'].extent())
    # 	self.iface.mapCanvas().mapRenderer().setDestinationCrs(self.input_layers['zones_layer'].crs())

    #~ if self.dlg.save_image_group_box.isChecked():
    #~ QTimer.singleShot(1000, lambda :	self.iface.mapCanvas().saveAsImage(self.dlg.save_image_filename.text()))

    def fetch_inputs(self, path):
        def set_et0_from_et0_file_data(et0_file_data):
            et0 = []
            for i in range(0, len(et0_file_data)):
                if (i in [0, 3, 5, 10]): et0.extend([et0_file_data[i]] * 30)
                elif i == 8: et0.extend([et0_file_data[i]] * 28)
                else: et0.extend([et0_file_data[i]] * 31)
            return et0

        self.rain = OrderedDict()
        if path != '':
            self.base_path = self.path = path
            self.input_layers = {}
            self.input_layers['zones_layer'] = self.iface.addVectorLayer(
                os.path.join(path, 'Zones.shp'), 'Zones', 'ogr')
            self.input_layers['soil_layer'] = self.iface.addVectorLayer(
                os.path.join(path, 'Soil.shp'), 'Soil Cover', 'ogr')
            self.input_layers['lulc_layer'] = self.iface.addVectorLayer(
                os.path.join(path, 'LULC.shp'), 'Land-Use-Land-Cover', 'ogr')
            # self.input_layers['cadastral_layer'] = self.iface.addVectorLayer(os.path.join(path, 'Cadastral.shp'), 'Cadastral Map', 'ogr')
            self.input_layers['slope_layer'] = self.iface.addRasterLayer(
                os.path.join(path, 'Slope.tif'), 'Slope')
            #~ self.input_layers['drainage_layer'] = self.iface.addRasterLayer(os.path.join(path, 'Drainage.shp'), 'Drainage', 'ogr')
            data_dir = os.path.join(self.plugin_dir, 'Data')
            # self.input_layers['soil_layer'] = self.iface.addVectorLayer(os.path.join(data_dir, 'soil utm.shp'), 'Soil Cover', 'ogr')
            # self.input_layers['lulc_layer'] = self.iface.addVectorLayer(os.path.join(data_dir, 'lulc utm.shp'), 'Land-Use-Land-Cover', 'ogr')

            # csvreader=csv.reader(open(os.path.join(path, RAINFALL_CSV_FILENAME)))
            with open(os.path.join(path, 'Rainfall.csv')) as f:
                csvreader_for_avg_year = csv.DictReader(f)
                self.circle_avg_year_dict = {
                    row['Circle'].lower(): row['Year']
                    for row in csvreader_for_avg_year
                }
                print self.circle_avg_year_dict
            csvreader = csv.reader(
                open(
                    os.path.join(TEST_SUITE_BASE_FOLDER_PATH,
                                 'Rainfall_all.csv'))
            )  # FOR urgent village charts (17-11-2018)
            next(csvreader)
            # self.rain = OrderedDict((row[0].lower(),{'year': row[1],'daily_rain':[float(val) for val in row[2:]]}) for row in csvreader)
            # self.rain['0'] = self.rain[next(iter(self.rain.keys()))]
            ###For multiple rainfall years use the following###
            self.rain = {}
            years = []
            dist_taluka_year_tuples = set([])
            for row in csvreader:
                # print row
                if row[3] not in self.rain:
                    years += [row[3]]
                    self.rain[row[3]] = {}
                # self.rain[row[1]][row[0].lower()] = [float(val) for val in row[2:]]
                self.rain[row[3]][(row[0].lower(), row[1].lower(),
                                   row[2].lower())] = [
                                       float(val) for val in row[4:]
                                   ]
                dist_taluka_year_tuples.add(
                    (row[0].lower(), row[1].lower(), row[3]))

            for dty in dist_taluka_year_tuples:
                for k in self.rain[dty[2]]:
                    if (k[0], k[1]) == (dty[0], dty[1]):
                        # print zc[3], zc[0], zc[1]
                        self.rain[dty[2]][(dty[0], dty[1],
                                           '0')] = self.rain[dty[2]][(k[0],
                                                                      k[1],
                                                                      k[2])]
                        break

            # return

            et0_file_data = [
                float(row["ET0"]) for row in csv.DictReader(
                    open(os.path.join(path, ET0_CSV_FILENAME)))
            ]
            self.et0 = set_et0_from_et0_file_data(et0_file_data)
            self.sowing_threshold = DEFAULT_SOWING_THRESHOLD
            self.monsoon_end_date_index = MONSOON_END_DATE_INDEX
            self.rain_sum_monsoon = {
                year: {
                    circle:
                    sum(self.rain[year][circle]
                        [START_DATE_INDEX:self.monsoon_end_date_index + 1])
                    for circle in self.rain[year].keys()
                }
                for year in self.rain.keys()
            }
            # self.rain_sum_monsoon={key:{'year':self.rain[key]['year'],'sum':sum(self.rain[key]['daily_rain'][START_DATE_INDEX : self.monsoon_end_date_index+1])} for key in self.rain.keys()}

            # if not OVERRIDE_FILECROPS_BY_DEBUG_OR_TEST_CROPS and os.path.exists(os.path.join(path, CROPS_FILENAME)):
            # 	self.crop_names = open(os.path.join(path, CROPS_FILENAME), 'r').read().split(',')
            # 	print (self.crop_names)
            # 	if len(self.crop_names) == 0 :	raise Exception('No crop selected')
            # else:
            # 	self.crop_names = DEBUG_OR_TEST_CROPS
            # self.rabi_crop_names = DEBUG_OR_TEST_RABI_CROPS
            self.crop_names = dict_crop
            self.rabi_crop_names = dict_rabi_crop
            self.output_configuration = {}
            # self.output_configuration['graduated_rendering_interval_points'] = DEBUG_OR_TEST_GRADUATED_RENDERING_INTERVAL_POINTS

        else:
            self.dlg.show()
            if self.dlg.exec_() == QFileDialog.Rejected: return False

            path = self.path = self.base_path = self.dlg.folder_path.text()
            self.input_layers = {}
            self.input_layers['zones_layer'] = self.iface.addVectorLayer(
                self.dlg.zones_layer_filename.text(), 'Zones', 'ogr')
            self.input_layers['soil_layer'] = self.iface.addVectorLayer(
                self.dlg.soil_layer_filename.text(), 'Soil Cover', 'ogr')
            self.input_layers['lulc_layer'] = self.iface.addVectorLayer(
                self.dlg.lulc_layer_filename.text(), 'Land-Use-Land-Cover',
                'ogr')
            self.input_layers['cadastral_layer'] = self.iface.addVectorLayer(
                self.dlg.cadastral_layer_filename.text(), 'Cadastral Map',
                'ogr')
            self.input_layers['slope_layer'] = self.iface.addRasterLayer(
                self.dlg.slope_layer_filename.text(), 'Slope')
            if self.dlg.drainage_layer_filename.text() != '':
                self.drainage_layer = self.iface.addVectorLayer(
                    self.dlg.drainage_layer_filename.text(), 'Drainage', 'ogr')

            csvreader = csv.reader(
                open(str(self.dlg.rainfall_csv_filename.text())))
            next(csvreader)
            # self.rain = OrderedDict((row[0].lower(),{'year': row[1],'daily_rain':[float(val) for val in row[2:]]}) for row in csvreader)
            # self.rain['0'] = self.rain[next(iter(self.rain.keys()))]
            ###For multiple rainfall years use the following###
            self.rain = {}
            years = []
            for row in csvreader:
                if row[1] not in self.rain:
                    years += row[1]
                    self.rain[row[1]] = {}
                self.rain[row[1]][row[0].lower()] = [
                    float(val) for val in row[2:]
                ]
            for y in years:
                self.rain[y]['0'] = self.rain[y][next(iter(
                    self.rain[y].keys()))]
            # self.rain = OrderedDict(
            # 	(row[1].lower(), {row[0].lower(): [float(val) for val in row[2:]]}) for row in csvreader
            # )
            # print 'circles', self.rain['2013'].keys()
            # self.rain['0'] = self.rain[next(iter(self.rain.keys()))]

            et0_file_data = [
                float(row["ET0"]) for row in csv.DictReader(
                    open(os.path.join(path, ET0_CSV_FILENAME)))
            ]
            self.et0 = set_et0_from_et0_file_data(et0_file_data)
            self.sowing_threshold = self.dlg.sowing_threshold.value()
            self.monsoon_end_date_index = self.dlg.monsoon_end.value() + 122
            self.rain_sum_monsoon = {
                year: {
                    circle:
                    sum(self.rain[year][circle]
                        [START_DATE_INDEX:self.monsoon_end_date_index + 1])
                    for circle in self.rain[year].keys()
                }
                for year in self.rain.keys()
            }
            # 'year':self.rain[key]['year'],'sum':sum(self.rain[key]['daily_rain'][START_DATE_INDEX : self.monsoon_end_date_index+1])} for circle in self.rain.keys()}

            # self.crop_names = self.dlg.crops
            # self.rabi_crop_names = self.dlg.rabi_crops
            # for urgent requirement of all crops
            self.crop_names = dict_crop
            self.rabi_crop_names = dict_rabi_crop
            if len(self.crop_names) == 0: raise Exception('No crop selected')
            self.output_configuration = {}
Пример #40
0
class redLayer(QgsMapTool):
    """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
        self.canvas = iface.mapCanvas()
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'redLayer_{}.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 = redLayerDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Red Layer')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'redLayer')
        self.toolbar.setObjectName(u'redLayer')
        QgsMapTool.__init__(self, self.canvas)

    # 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('redLayer', 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)
        if callback:
            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.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.sketchButton = self.add_action(
            ':/plugins/redLayer/icons/sketch.svg',
            text=self.tr(u'Sketch on map'),
            callback=self.sketchAction,
            parent=self.iface.mainWindow())
        self.penButton = self.add_action(
            ':/plugins/redLayer/icons/pen.svg',
            text=self.tr(u'Draw line on map'),
            callback=self.penAction,
            parent=self.iface.mainWindow())
        self.canvasButton = self.add_action(
            ':/plugins/redLayer/icons/canvas.svg',
            text=self.tr(u'Color and width canvas'),
            callback=None,
            parent=self.iface.mainWindow())
        self.eraseButton = self.add_action(
            ':/plugins/redLayer/icons/erase.svg',
            text=self.tr(u'Erase sketches'),
            callback=self.eraseAction,
            parent=self.iface.mainWindow())
        self.removeButton = self.add_action(
            ':/plugins/redLayer/icons/remove.svg',
            text=self.tr(u'Remove all sketches'),
            callback=self.removeSketchesAction,
            parent=self.iface.mainWindow())
        self.noteButton = self.add_action(
            ':/plugins/redLayer/icons/note.svg',
            text=self.tr(u'Add text annotations to sketches'),
            callback=None,
            parent=self.iface.mainWindow())
        self.convertButton = self.add_action(
            ':/plugins/redLayer/icons/toLayer.svg',
            text=self.tr(u'Convert annotations to Memory Layer'),
            callback=self.toMemoryLayerAction,
            parent=self.iface.mainWindow())
        self.canvasButton.setMenu(self.canvasMenu())
        self.noteButton.setCheckable (True)
        self.penButton.setCheckable (True)
        self.sketchButton.setCheckable (True)
        self.eraseButton.setCheckable (True)
        self.geoSketches = []
        self.dumLayer = QgsVectorLayer("Point?crs=EPSG:4326", "temporary_points", "memory")
        self.pressed=None
        self.previousPoint = None
        self.previousMoved = None
        self.points = 0
        self.currentColor = QColor("#aa0000")
        self.currentWidth = 5
        self.annotation = sketchNoteDialog(self.iface)
        self.annotatatedSketch = None
        self.sketchEnabled(None)
        self.iface.projectRead.connect(self.projectReadAction)
        self.iface.newProjectCreated.connect(self.newProjectCreatedAction)
        QgsMapLayerRegistry.instance().legendLayersAdded.connect(self.notSavedProjectAction)

    def canvasMenu(self):
        contextMenu = QMenu()
        self.colorPaletteAction = contextMenu.addAction(QIcon(os.path.join(self.plugin_dir,"icons","colorPalette.png")),"")
        self.colorPaletteAction.triggered.connect(self.colorPaletteFunc)
        self.width2Action = contextMenu.addAction(QIcon(os.path.join(self.plugin_dir,"icons","width2.png")),"")
        self.width2Action.triggered.connect(self.width2Func)
        self.width4Action = contextMenu.addAction(QIcon(os.path.join(self.plugin_dir,"icons","width4.png")),"")
        self.width4Action.triggered.connect(self.width4Func)
        self.width8Action = contextMenu.addAction(QIcon(os.path.join(self.plugin_dir,"icons","width8.png")),"")
        self.width8Action.triggered.connect(self.width8Func)
        self.width16Action = contextMenu.addAction(QIcon(os.path.join(self.plugin_dir,"icons","width16.png")),"")
        self.width16Action.triggered.connect(self.width16Func)
        return contextMenu



    def sketchEnabled(self,enabled):
        self.enabled = enabled
        if enabled:
            self.sketchButton.setEnabled(True)
            self.penButton.setEnabled(True)
            self.canvasButton.setEnabled(True)
            self.eraseButton.setEnabled(True)
            self.removeButton.setEnabled(True)
            self.noteButton.setEnabled(True)
            self.convertButton.setEnabled(True)
        else:
            self.sketchButton.setDisabled(True)
            self.penButton.setDisabled(True)
            self.canvasButton.setDisabled(True)
            self.eraseButton.setDisabled(True)
            self.removeButton.setDisabled(True)
            self.noteButton.setDisabled(True)
            self.convertButton.setDisabled(True)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        self.removeSketchesAction()
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Red Layer'),
                action)
            self.iface.removeToolBarIcon(action)
        del self.toolbar


    def sketchAction(self):
        """Run method that performs all the real work"""
        gsvMessage="Click on map to draw geo sketches"
        self.iface.mainWindow().statusBar().showMessage(gsvMessage)
        self.dumLayer.setCrs(self.iface.mapCanvas().mapRenderer().destinationCrs())
        self.canvas.setMapTool(self)
        self.canvasAction = "sketch"

    def penAction(self):
        gsvMessage="Click on map and drag to draw a line"
        self.iface.mainWindow().statusBar().showMessage(gsvMessage)
        self.dumLayer.setCrs(self.iface.mapCanvas().mapRenderer().destinationCrs())
        self.canvas.setMapTool(self)
        self.canvasAction = "pen"

    def canvasAction(self):
        pass
        
    def colorPaletteFunc(self):
        self.currentColor = QgsColorDialogV2.getColor(self.currentColor,None)
        
    def width2Func(self):
        self.currentWidth = 2

    def width4Func(self):
        self.currentWidth = 4

    def width8Func(self):
        self.currentWidth = 8

    def width16Func(self):
        self.currentWidth = 16

    def eraseAction(self):
        gsvMessage="Click on map to erase geo sketches"
        self.iface.mainWindow().statusBar().showMessage(gsvMessage)
        self.dumLayer.setCrs(self.iface.mapCanvas().mapRenderer().destinationCrs())
        self.canvas.setMapTool(self)
        self.canvasAction = "erase"

    def exportAction(self):
        pass

    def removeSketchesAction(self):
        self.removeAllAnnotations()
        for sketch in self.geoSketches:
            sketch[2].reset()
        self.geoSketches = []
        self.gestures = 0
        self.annotatatedSketch = None

    def ex_activate(self):
        if self.canvasAction == "sketch":
            self.sketchButton.setChecked(True)
        if self.canvasAction == "pen":
            self.penButton.setChecked(True)

    def deactivate(self):
        if self.canvasAction == "sketch":
            self.sketchButton.setChecked(False)
            self.points = 0
        if self.canvasAction == "pen":
            self.penButton.setChecked(False)
            self.previousPoint = None
            self.previousMoved = None
            self.gestures += 1
            self.points = 0
        if self.canvasAction == "erase":
            self.eraseButton.setChecked(False)

    def canvasPressEvent(self, event):
        # Press event handler inherited from QgsMapTool used to store the given location in WGS84 long/lat
        if event.button() == Qt.RightButton:
            print "rightbutton"
            if self.noteButton.isChecked():
                midIdx = -int(self.points/2)
                if midIdx == 0:
                    midIdx = -1
                annotation = sketchNoteDialog.newPoint(self.iface,self.geoSketches[midIdx][2].asGeometry())
                if annotation:
                    self.geoSketches[-1][3] = annotation
                    self.geoSketches[-1][4] = annotation.document().toPlainText()
                self.annotatatedSketch = True
            self.gestures += 1
            self.points = 0
            self.penAction()
            self.previousPoint = None
            self.previousMoved = None
            self.movedPoint = None
            self.pressed = None
            self.dragged = None
        else:
            self.pressed=True
            self.dragged = None
            self.movedPoint = None
            self.px = event.pos().x()
            self.py = event.pos().y()
            self.pressedPoint = self.canvas.getCoordinateTransform().toMapCoordinates(self.px, self.py)
            if self.canvasAction == "sketch":
                self.points = 0
            if self.canvasAction == "pen":
                self.snapSys = self.iface.mapCanvas().snappingUtils()
                snappedPoint = self.snapSys.snapToMap(self.pressedPoint)
                if snappedPoint.isValid():
                    self.pressedPoint = snappedPoint.point()
                self.sketch=QgsRubberBand(self.iface.mapCanvas(),QGis.Line )
                self.sketch.setWidth(self.currentWidth)
                self.sketch.setColor(self.currentColor)
                self.sketch.addPoint(self.pressedPoint)

    def canvasMoveEvent(self, event):
        # Moved event handler inherited from QgsMapTool needed to highlight the direction that is giving by the user
        if self.pressed:
            x = event.pos().x()
            y = event.pos().y()
            self.movedPoint = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)
            if self.canvasAction == "sketch":
                if abs(x-self.px)>3 or abs(y-self.py)>3:
                    sketch=QgsRubberBand(self.iface.mapCanvas(),QGis.Line )
                    sketch.setWidth(self.currentWidth)
                    sketch.setColor(self.currentColor)
                    sketch.addPoint(self.pressedPoint)
                    sketch.addPoint(self.movedPoint)
                    self.pressedPoint = self.movedPoint
                    self.points += 1
                    self.geoSketches.append([self.currentColor.name(),str(self.currentWidth),sketch,None,"",self.gestures])
                    self.px = x; self.py = y
                    
            if self.canvasAction == "pen":
                if not QgsGeometry.fromPoint(self.movedPoint).equals(QgsGeometry.fromPoint(self.pressedPoint)):
                    self.dragged = True
                    self.snapSys = self.iface.mapCanvas().snappingUtils()
                    snappedPoint = self.snapSys.snapToMap(self.movedPoint)
                    if snappedPoint.isValid():
                        self.movedPoint = snappedPoint.point()
                    self.sketch.reset()
                    if self.previousPoint:
                        self.sketch.addPoint(self.previousPoint)
                    else:
                        self.sketch.addPoint(self.pressedPoint)
                    self.sketch.addPoint(self.movedPoint)
                    self.iface.mainWindow().statusBar().showMessage("Sketch lenght: %s" % math.sqrt(self.pressedPoint.sqrDist(self.movedPoint)))
                else:
                    self.dragged = None
                    
            if self.canvasAction == "erase":
                cursor = QgsRectangle (self.canvas.getCoordinateTransform().toMapCoordinates(x-7,y-7),self.canvas.getCoordinateTransform().toMapCoordinates(x+7,y+7))
                for sketch in self.geoSketches:
                    if sketch[2].asGeometry() and sketch[2].asGeometry().boundingBox().intersects(cursor):
                        sketch[2].reset()
                        if sketch[3]:
                            try:
                                self.iface.mapCanvas().scene().removeItem( sketch[3] )
                            except:
                                pass


    def canvasReleaseEvent(self, event):
        if event.button() == Qt.RightButton:
            return
        self.pressed=None
        QgsProject.instance().setDirty(True)
        if self.canvasAction == "pen":
            if not self.dragged:
                if self.previousPoint:
                    self.sketch.addPoint(self.previousPoint)
                    self.sketch.addPoint(self.pressedPoint)
                    self.previousPoint = self.pressedPoint
                else:
                    self.previousPoint = self.pressedPoint
                    return
            elif self.previousMoved:
                self.previousMoved = None
                self.sketch.addPoint(self.previousPoint)
                self.sketch.addPoint(self.movedPoint)
                self.previousPoint = self.movedPoint
                
            else:
                self.previousPoint = self.movedPoint
                self.previousMoved = True
            self.geoSketches.append([self.currentColor.name(),str(self.currentWidth),self.sketch,None,"",self.gestures])
            self.points += 1 

        if self.canvasAction == "sketch" and self.noteButton.isChecked():
            if self.points > 0:
                midIdx = -int(self.points/2)
                annotation = sketchNoteDialog.newPoint(self.iface,self.geoSketches[midIdx][2].asGeometry())
                if annotation:
                    self.geoSketches[midIdx][3] = annotation
                    self.geoSketches[midIdx][4] = annotation.document().toPlainText()
                self.annotatatedSketch = True
                self.gestures += 1

    def notSavedProjectAction(self):
        print "layer loaded!"
        self.sketchEnabled(True)
        try:
            QgsMapLayerRegistry.instance().legendLayersAdded.disconnect(self.notSavedProjectAction)
        except:
            pass
        
    def newProjectCreatedAction(self):
        #remove current sketches
        try:
            QgsMapLayerRegistry.instance().legendLayersAdded.connect(self.notSavedProjectAction)
        except:
            pass
        self.removeSketchesAction()
        self.sketchEnabled(None)

    def projectReadAction(self):
        #remove current sketches
        try:
            QgsMapLayerRegistry.instance().layerLoaded.disconnect(self.notSavedProjectAction)
        except:
            pass
        try:
            self.removeSketchesAction()
            #connect to signal to save sketches along with project file
            QgsProject.instance().projectSaved.connect(self.afterSaveProjectAction)
            QgsProject.instance().writeProject.connect(self.beforeSaveProjectAction)
            self.projectFileInfo = QFileInfo(QgsProject.instance().fileName())
            self.sketchFileInfo = QFileInfo(os.path.join(self.projectFileInfo.path(),self.projectFileInfo.baseName()+'.sketch'))
            #load project.sketch if file exists
            self.loadSketches()
            self.sketchEnabled(True)
        except:
            print "no project error"
            pass

    def beforeSaveProjectAction(self,domDoc):
    #method to expunge redlayer annotation from annotation ready to to save
        if self.annotatatedSketch:
            annotationStrings = []
            for sketch in self.geoSketches:
                if sketch[4] != "":
                    annotationStrings.append(sketch[4])
            nodes = domDoc.elementsByTagName("TextAnnotationItem")
            for i in range(0,nodes.count()):
                node = nodes.at(i)
                annotationDocumentNode = node.attributes().namedItem("document")
                annotationDocument = QTextDocument()
                annotationDocument.setHtml(annotationDocumentNode.nodeValue())
                if annotationDocument.toPlainText() in annotationStrings: # erase only redlayer annotations
                    parent = node.parentNode()
                    parent.removeChild(node)
        self.saveSketches()

    def afterSaveProjectAction(self):
        pass
        #print "AFTER SAVE"
        #self.recoverAllAnnotations()
        
    def saveSketches(self):
        if self.geoSketches != []:
            print "SAVING SKETCHES"
            outfile = open(self.sketchFileInfo.absoluteFilePath(), 'w')
            for sketch in self.geoSketches:
                if sketch[2].asGeometry():
                    try:
                        note = sketch[3].document().toPlainText().replace("\n","%%N%%")
                    except:
                        note = ""
                    outfile.write(sketch[0]+'|'+sketch[1]+'|'+sketch[2].asGeometry().exportToWkt()+"|"+note+"|"+str(sketch[5])+'\n')
            outfile.close()
        else:
            if self.sketchFileInfo.exists():
                sketchFile = QFile(self.sketchFileInfo.absoluteFilePath())
                if sketchFile:
                    sketchFile.remove()

    def removeAllAnnotations(self):
        #erase all annotation to prevent saving them along with project file
        for item in self.iface.mapCanvas().scene().items():
            try:
                if item.mapPosition():
                    self.iface.mapCanvas().scene().removeItem(item)
                    del item
            except:
                pass

    def recoverAllAnnotations(self):
        for sketch in self.geoSketches:
            if sketch[4] != "":
                sketch[3] = sketchNoteDialog.newPoint(self.iface,sketch[2].asGeometry(),txt = sketch[4])

    def loadSketches(self):
        self.geoSketches = []
        self.annotatatedSketch = None
        if self.sketchFileInfo.exists():
            infile = open(self.sketchFileInfo.filePath(), 'r')
            canvas = self.iface.mapCanvas()
            mapRenderer = canvas.mapRenderer()
            srs=mapRenderer.destinationCrs()
            dumLayer = QgsVectorLayer("Line?crs="+str(srs.authid()), "temporary_lines", "memory")
            self.geoSketches = []
            for line in infile:
                inline = line.split("|")
                sketch=QgsRubberBand(self.iface.mapCanvas(),QGis.Line )
                sketch.setWidth( int(inline[1]) )
                sketch.setColor(QColor(inline[0]))
                sketch.setToGeometry(QgsGeometry.fromWkt(inline[2]),dumLayer)
                if inline[3] != "":
                    annotationText = inline[3].replace("%%N%%","\n")
                    annotationObject = sketchNoteDialog.newPoint(self.iface,QgsGeometry.fromWkt(inline[2]),txt = annotationText)
                    self.annotatatedSketch = True
                else:
                    annotationObject = None
                    annotationText = ""
                self.geoSketches.append([inline[0],inline[1],sketch,annotationObject,annotationText,int(inline[4])])
            self.gestures = int(inline[4])+1
            infile.close()

    def toMemoryLayerAction(self):
        polyGestures = {}
        lastPoint = None
        gestureId = 0
        #cycle to classify elementary sketches in gestures
        for sketch in self.geoSketches:
            if sketch[2].asGeometry():
                if not lastPoint or sketch[2].asGeometry().vertexAt(0) == lastPoint:
                    try:
                        polyGestures[gestureId].append(sketch[:-1])
                    except:
                        polyGestures[gestureId] =[sketch[:-1]]
                    lastPoint = sketch[2].asGeometry().vertexAt(1)
                else:
                    lastPoint = None
                    gestureId +=1
        #print "POLYGESTURES\n",polyGestures
        #print gestureId, polyGestures.keys()
        sketchLayer = QgsVectorLayer("LineString", "Sketch Layer", "memory")
        sketchLayer.setCrs(self.iface.mapCanvas().mapRenderer().destinationCrs())
        sketchLayer.startEditing()
        sketchLayer.addAttribute(QgsField("note",QVariant.String))
        sketchLayer.addAttribute(QgsField("color",QVariant.String))
        sketchLayer.addAttribute(QgsField("width",QVariant.Double))
        for gestureId,gestureLine in polyGestures.iteritems():
            geometryList = []
            note = ""
            polygon = []
            for segment in gestureLine:
                vertex = segment[2].asGeometry().vertexAt(0)
                polygon.append(QgsPoint(vertex.x(),vertex.y()))
                if segment[4] != "":
                    note = segment[4]
            polygon.append(segment[2].asGeometry().vertexAt(1))
            polyline = QgsGeometry.fromPolyline(polygon)
            newFeat = QgsFeature()
            newFeat.setGeometry(polyline)
            newFeat.setAttributes([note,QColor(segment[0]).name(),float(segment[1])/3.5])
            sketchLayer.addFeatures([newFeat])
        sketchLayer.commitChanges()
        sketchLayer.loadNamedStyle(os.path.join(self.plugin_dir,"sketchLayerStyle.qml"))
        QgsMapLayerRegistry.instance().addMapLayer(sketchLayer)
        sketchLayer.setSelectedFeatures ([])
        self.removeSketchesAction()
Пример #41
0
class MenuBuilder:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   '{}.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)

        # Declare instance attributes
        self.plugin_name = self.tr('&Menu Builder')
        # reference to plugin actions
        self.actions = []
        # used to store active menus
        self.menus = []

        # Create the dialog (after translation) and keep reference
        self.dlg = MenuBuilderDialog(self)

    # 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('MenuBuilder', message)

    def initGui(self):
        """Create the plugin entries inside the QGIS GUI."""
        # create the configure entry
        icon = QIcon(':/plugins/MenuBuilder/resources/settings.svg')
        configure = QAction(icon, self.tr('&Configure Menus'),
                            self.iface.mainWindow())
        configure.triggered.connect(self.run_configure)
        configure.setEnabled(True)
        configure.setStatusTip(
            self.tr("Configure menus with drag&drop from qgisbrowser"))
        configure.setWhatsThis(
            self.tr("Configure menus with drag&drop from qgisbrowser"))
        self.iface.addPluginToMenu(self.plugin_name, configure)
        self.actions.append(configure)

        # restore previous session if exists
        try:
            self.dlg.restore_session()
        except Exception as exc:
            QMessageBox(QMessageBox.Warning,
                        "Restoring MenuBuilder last session",
                        exc.message.decode(self.dlg.pgencoding),
                        QMessageBox.Ok, self.dlg).exec_()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.plugin_name, action)
        for menu in self.menus:
            menu.deleteLater()
        self.iface.removeDockWidget(self.dlg.dock_widget)

    def run_configure(self):
        # show the configure dialog
        self.dlg.show()
        self.dlg.update_database_list()
        # Run the dialog event loop
        self.dlg.exec_()
Пример #42
0
class CalidadCAR:
    """Implementación del plugin."""
    def __init__(self, iface):
        """Constructor.

        :param iface: Una instancia de la interfaz que será pasada a esta clase,
            la cual proveé una ligadura con la cual se podrá manipular la aplicación
            de QGIS en tiempo de ejecución.
        :type iface: QgsInterface
        """
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'CalidadCAR_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Calidad CAR')
        self.toolbar = self.iface.addToolBar(u'CalidadCAR')
        self.toolbar.setObjectName(u'CalidadCAR')

        self.layers = []
        self.dlg = CalidadCARDialog()
        # self.csvDialog = CSVDialog()

    # 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('CalidadCAR', 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):
        """Agrega una acción la la barra de herramientas, y al menú del plugin.

        :param icon_path: Ruta del icono. Puede ser la ruta de un recurso recurso
            (ejemplo: ':/plugins/foo/bar.png') o una ruta normal del sistema de archivos
        :type icon_path: str

        :param text: Texto que será mostrado en el menu de opciones de plugin para esta accion.
        :type text: str

        :param callback: Función que será llamada cuando se hace click sobre la acción.
        :type callback: function

        :param enabled_flag: Una bandera que indica si la acción debería ser activada
            por defecto. Por defecto este valor esta en True.
        :type enabled_flag: bool

        :param add_to_menu: Una bandera indicando si la acción debería ser agregada
            al menú de opciones del plugin. Por defecto esta en True
        :type add_to_menu: bool

        :param add_to_toolbar: Una bandera indicando si la acción debería ser agregada
            a la barra de herramientas del plugin. Por defecto esta en True
        :type add_to_toolbar: bool

        :param status_tip: Texto opcional que aparecerá cuando el puntero del mouse
            se pocisione sobre la acción.
        :type status_tip: str

        :param parent: Widget padre de la nueva acción. Por defecto será None
        :type parent: QWidget

        :param whats_this: Texto opcional para mostrar en la barra de estatus,
            cuando el puntero del mouse se pocisione sobre la acción.

        :returns: La acción que fue creada. Notar que la acción también es
            agregada a 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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Crea las entradas del menu, y las acciones de la barra de herramientas
            dentro de la interfaz de QGIS"""

        icon_path = ':/plugins/CalidadCAR/icons/layers-icon.png'
        self.addLayersAction = self.add_action(icon_path,
                                               text=self.tr(u'Cargar fondos'),
                                               callback=self.cargarCapas,
                                               parent=self.iface.mainWindow())

        icon_path = ':/plugins/CalidadCAR/icons/csv-join-icon-add.png'
        self.addCsvAction = self.add_action(icon_path,
                                            text=self.tr(u'Unir CSV'),
                                            callback=self.addCsv,
                                            parent=self.iface.mainWindow())

        icon_path = ':/plugins/CalidadCAR/icons/add-section-icon.png'
        self.addSectionAction = self.add_action(
            icon_path,
            text=self.tr(u'Agregar sección'),
            callback=self.addSection,
            parent=self.iface.mainWindow())

        icon_path = ':/plugins/CalidadCAR/icons/start-icon.png'
        self.intersctionAction = self.add_action(
            icon_path,
            text=self.tr(u'Calcular'),
            callback=self.intersection,
            parent=self.iface.mainWindow())

        icon_path = ':/plugins/CalidadCAR/icons/refresh-icon.png'
        self.intersctionAction = self.add_action(
            icon_path,
            text=self.tr(u'Limpiar'),
            callback=self.clean,
            parent=self.iface.mainWindow())

        # self.intersctionAction.setEnabled(False)
        # self.addSectionAction.setEnabled(False)
        # self.addCsvAction.setEnabled(False)

    def clean(self):
        """Recarga el plugin, limpiando todas las capas cargadas, excepto, las
           capas de salida de información."""
        for layer in self.layers:
            QgsMapLayerRegistry.instance().removeMapLayer(layer)

        csv_layers = QgsMapLayerRegistry.instance().mapLayersByName("csv")
        for layer in csv_layers:
            QgsMapLayerRegistry.instance().removeMapLayer(layer)

        tempLayer = QgsMapLayerRegistry.instance().mapLayersByName("temp")
        for layer in tempLayer:
            layer.commitChanges()
            QgsMapLayerRegistry.instance().removeMapLayer(layer)

        self.layers = []

    def addSection(self):
        """Utiliza una capa llamada temp, para insertar las nuevas secciones,
           esta operación solo podrá ser realizada si existe la capa de secciones.

           En caso de que no exista la capa temp, se creara una nueva, con el crs
           de la capa de secciones.
        """
        tempLayer = None
        try:
            seccionesLayer = QgsMapLayerRegistry.instance().mapLayersByName(
                "secciones")[0]
        except IndexError:
            self.errorDialog(
                u'No se encontró la capa de secciones.',
                u'Asegurate de agregarla con la opción de cargar fondos.')
            return

        try:
            tempLayer = QgsMapLayerRegistry.instance().mapLayersByName(
                "temp")[0]
        except IndexError:
            crs = seccionesLayer.crs().authid()

            tempLayer = QgsVectorLayer('LineString?crs=' + crs, 'temp',
                                       'memory')

            pr = tempLayer.dataProvider()
            fields = seccionesLayer.pendingFields()
            pr.addAttributes(fields)

            QgsMapLayerRegistry.instance().addMapLayer(tempLayer)

        self.iface.setActiveLayer(tempLayer)
        tempLayer.startEditing()

    def check(self, segments, point):
        """Verifica si un punto se encuentra entre dos segmentos

        :param segments: Lista de segmentos entre los que se puede encontrar el punto.
        :type segments: Lista de QgsSegments

        :param point: punto sobre el cual se va a hacer la verificación
        :type point: QgsPoint

        :returns: Un booleano que indica si la condición se cumple o no.
        :rtype: Boolean
        """
        if len(segments) == 1: return False
        polygon = geometry.buildConvexPolygon(segments)
        # layer =  QgsVectorLayer('Polygon?crs=epsg:3116', 'poly' , "memory")
        # pr = layer.dataProvider()
        # poly = QgsFeature()
        # poly.setGeometry(polygon)
        # pr.addFeatures([poly])
        # layer.updateExtents()
        # QgsMapLayerRegistry.instance().addMapLayers([layer])
        return polygon.contains(point)

    def place(self, segments, p):
        """Ubica un punto entre los dos segmentos consecutivos a los que pertenece.

        :param segments: Lista de segmentos
        :type segments: Lista de QgsSegments

        :param p: punto que se va a ubicar en la lista de segmentos
        :type point: QgsPoint

        """
        low, hi = 0, len(segments)
        mid, cont = 0, 0

        while (low <= hi):
            mid = low + ((hi - low) / 2)
            if self.check(segments[low:mid + 1], p):
                hi = mid
            else:
                low = mid
            cont += 1
            #Sacurity trigger
            if cont == 20: break

        return low

    # def place(self, segments, p):
    #     for i in xrange(len(segments) - 1):
    #         if self.check([segments[i], segments[i + 1]], p):
    #             return i
    #     return None

    def addFeature(self, layerA, feature=None, idx=-1):
        """Inserta una característica (feature) en una capa en un orden establecido

        :param layerA: Capa en la que se va a insertar la característica (feature)
        :type layerA: QgsVectorLayer

        :param feature: Característica (feature) que se va a insertar en la capa.
        :type feature: QgsFeature

        :param idx: Indice de la nueva característica (feature) que se va a insertar.
        :type idx: Integer

        :returns: Una nueva capa con la característica insertada en el pocisión idx.
        :rtype: QgsVectorLayer
        """
        crs = layerA.crs().authid()
        tempLayer = QgsVectorLayer('LineString?crs=' + crs, 'output', 'memory')
        pr = tempLayer.dataProvider()
        fields = layerA.pendingFields()

        for f in fields:
            pr.addAttributes([f])

        features = list(layerA.getFeatures())
        if idx != -1:
            features.insert(idx + 1, feature)

        tempLayer.updateFields()

        for feature in features:
            pr.addFeatures([feature])

        tempLayer.updateExtents()
        return tempLayer

    def intersection(self):
        """Este método se encarga de recopilar toda la información, para posteriormente
           aplicarle la lógica del plugin.

           Para que el usuario pueda realizar esta operación, necesariamente, tienen
           que estar cargadas la capa de ejes, y la capa de secciones transversales.
        """
        try:
            secciones = QgsMapLayerRegistry.instance().mapLayersByName(
                "secciones")[0]
            eje = QgsMapLayerRegistry.instance().mapLayersByName("ejes")[0]
        except IndexError:
            self.errorDialog(
                u'No se encontraron algunas de las capas necesarias para realizar esta operación.',
                u'Asegurate de agregar la capa de secciones, y la capa del eje con la opción Configurar Fondo.'
            )
            return

        work_layer = self.addFeature(secciones)

        try:
            """En caso de que existan secciones temporales, se combinaran con la
               capa de secciones, para crear la capa work_layer"""
            temp = QgsMapLayerRegistry.instance().mapLayersByName("temp")[0]

            for new_feature in temp.getFeatures():
                segements = geometry.getSegments(work_layer)
                point = geometry.intersectionLayerGeometry(
                    eje, new_feature.geometry())
                if point is None: continue
                idx = self.place(segements, point)
                # print 'IDX: ', idx
                work_layer = self.addFeature(work_layer, new_feature, idx)

        except IndexError:
            pass

        #Mostrar la capa de trabajo work_layer
        QgsMapLayerRegistry.instance().addMapLayer(work_layer)

        #Crar un DataFrame de pandas con la tabla de atributos de la capa de trabajo
        table = [row.attributes() for row in work_layer.getFeatures()]
        field_names = [field.name() for field in work_layer.pendingFields()]
        pd_frame = pandas.DataFrame(table, columns=field_names)
        print pd_frame

        #Crear un DataFrame de pandas con las distancias de la sucesión de secciones
        points = geometry.intersectionPoints(eje, work_layer)

        distances = [0]
        for i in xrange(len(points) - 1):
            distances.append(geometry.distance(points[i], points[i + 1]))
        # print distances

        pd_dataframe = pandas.DataFrame(distances, columns=['Distancia'])
        print pd_dataframe

    def addCsv(self):
        """Crea una capa a partir de un archivo CSV, y une la información que
           contiene esta, con la tabla de atributos de la capa de secciones,
           la cual tendrá que existir, para que se pueda realizar esta operación.
        """
        try:
            shp = QgsMapLayerRegistry.instance().mapLayersByName(
                "secciones")[0]
        except IndexError:
            self.errorDialog(
                u'No se encontró la capa de secciones.',
                u'Asegurate de agregarla con la opción de Cargar fondos.')
            return

        sheet = None
        field_names = [field.name() for field in shp.pendingFields()]
        csvDialog = CSVDialog(field_names)
        result = csvDialog.exec_()
        if result and csvDialog.getLayer():
            # print csvDialog.getSelectedColumns()

            sheet = csvDialog.getLayer()
            QgsMapLayerRegistry.instance().addMapLayer(sheet)

            #Columnas del archivo CSV
            columns = csvDialog.getSelectedColumns()
            #Filtra las columnas existentes, para evitar información duplicada
            field_names = [field.name() for field in shp.pendingFields()]

            columns = [
                col for col in columns if 'csv' + col not in field_names
            ]

            if columns == []:
                #No hay columnas nuevas para unir
                return

            shpField = csvDialog.getJoinFieldTarget()
            csvField = csvDialog.getJoinField()
            joinObject = QgsVectorJoinInfo()
            joinObject.joinLayerId = sheet.id()
            joinObject.joinFieldName = csvField
            joinObject.targetFieldName = shpField

            joinObject.setJoinFieldNamesSubset(columns)
            joinObject.memoryCache = True
            shp.addJoin(joinObject)

            # self.addSectionAction.setEnabled(True)
            # self.intersctionAction.setEnabled(True)

    def unload(self):
        """Remueve el menú del plugin, y las acciones de la barra de herramientas
           de la interfaz de QGIS."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Calidad CAR'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def addLayers(self):
        """Carga las capas que el usuario ingreso en el dialog de cargar fondos,
           los fondos se volverán a cargar cada vez que se llame este método, en
           caso de que el usuario quiera recargar un fondo."""

        #Eliminar los fondos cargados
        for layer in self.layers:
            QgsMapLayerRegistry.instance().removeMapLayer(layer)

        self.layers = []
        files = self.dlg.getFilePaths()

        #Cargar los fondos que se encuentrán en el dialogo de cargar fondos.
        for layer in files:
            path, name = layer
            layerInfo = QFileInfo(path)

            if layerInfo.suffix() == 'tif':
                self.addRasterLayer(path, name)
            elif layerInfo.suffix() == 'shp':
                self.addVectorLayer(path, name)

        for layer in self.layers:
            QgsMapLayerRegistry.instance().addMapLayer(layer)

    def addVectorLayer(self, path, name):
        """Agrega una capa vectorizada a self.layers

        :param path: Ruta de la capa que se va a cargar.
        :type path: str

        :param name: Nombre de la capa que se va a cargar, este nombre será el
            identificador de la capa.
        :type name: str
        """
        layer = QgsVectorLayer(path, name, 'ogr')
        if not layer.isValid():
            return

        # Cambiar el color del layer
        symbol_layer = layer.rendererV2().symbols()[0].symbolLayer(0)
        if name == 'ejes' or name == 'secciones':
            symbol_layer.setColor(QColor(0, 0, 0))
        else:
            symbol_layer.setColor(QColor(randint(0, 50), randint(0, 255), 163))

        self.layers.append(layer)

    def addRasterLayer(self, path, name):
        """Agrega una capa rasterizada a self.layers

        :param path: Ruta de la capa que se va a cargar.
        :type path: str

        :param name: Nombre de la capa que se va a cargar, este nombre será el
            identificador de la capa.
        :type name: str
        """
        rlayer = QgsRasterLayer(path, name)
        if not rlayer.isValid(): return
        self.layers.append(rlayer)

    def cargarCapas(self):
        """Run method that performs all the real work"""
        self.dlg.show()
        result = self.dlg.exec_()
        if result:
            self.addLayers()
            # self.addCsvAction.setEnabled(True)

    def errorDialog(selg, text, detail):
        """Dialogo de error que se lanzará cuando el usuario intente hacer una
           operación que no esta permitida.

        :param text: Identificador principal del error.
        :type text: str

        :param name: Información detallada del error.
        :type name: str
        """
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setText(text)
        msg.setInformativeText(detail)
        msg.setWindowTitle("Error")
        msg.exec_()
Пример #43
0
    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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'SuewsSimple_{}.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 = SuewsSimpleDialog()
        self.dlg.pushButtonIMPcalcBuild.clicked.connect(self.IMCP)
        self.dlg.pushButtonIMPcalcVeg.clicked.connect(self.IMCP)
        self.dlg.pushButtonLCFPcalc.clicked.connect(self.LCFP)
        self.dlg.pushButtonImport_IMPB.clicked.connect(self.import_file_IMPB)
        self.dlg.pushButtonImport_IMPV.clicked.connect(self.import_file_IMPV)
        self.dlg.pushButtonImport_LCFP.clicked.connect(self.import_file_LCFP)
        self.dlg.defaultButton.clicked.connect(self.set_default_settings)
        self.dlg.helpButton.clicked.connect(self.help)
        self.dlg.runButton.clicked.connect(self.start_progress)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.dlg.pushButtonImport.clicked.connect(self.met_file)
        self.dlg.pushButtonImportInitial.clicked.connect(self.import_initial)
        self.dlg.pushButtonExportInitial.clicked.connect(self.export_initial)

        self.fileDialog = QFileDialog()
        self.fileDialog.setNameFilter("(*Point_isotropic.txt)")

        self.fileDialogInit = QFileDialog()
        self.fileDialogInit.setNameFilter("(*.nml)")

        self.fileDialogMet = QFileDialog()
        self.fileDialogMet.setNameFilter("(*.txt)")

        self.fileDialogOut = QFileDialog()
        self.fileDialogOut.setFileMode(4)
        self.fileDialogOut.setAcceptMode(1)
        self.folderPathOut = None
        self.folderPath = None

        self.ret = 0

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Suews Simple')
        # TODO: We are going to let the user set this up in a future iteration
        # self.toolbar = self.iface.addToolBar(u'SuewsSimple')
        # self.toolbar.setObjectName(u'SuewsSimple')

        self.model_dir = os.path.normpath(self.plugin_dir + os.sep +
                                          os.pardir + os.sep + 'suewsmodel')
Пример #44
0
class SuewsSimple:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'SuewsSimple_{}.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 = SuewsSimpleDialog()
        self.dlg.pushButtonIMPcalcBuild.clicked.connect(self.IMCP)
        self.dlg.pushButtonIMPcalcVeg.clicked.connect(self.IMCP)
        self.dlg.pushButtonLCFPcalc.clicked.connect(self.LCFP)
        self.dlg.pushButtonImport_IMPB.clicked.connect(self.import_file_IMPB)
        self.dlg.pushButtonImport_IMPV.clicked.connect(self.import_file_IMPV)
        self.dlg.pushButtonImport_LCFP.clicked.connect(self.import_file_LCFP)
        self.dlg.defaultButton.clicked.connect(self.set_default_settings)
        self.dlg.helpButton.clicked.connect(self.help)
        self.dlg.runButton.clicked.connect(self.start_progress)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.dlg.pushButtonImport.clicked.connect(self.met_file)
        self.dlg.pushButtonImportInitial.clicked.connect(self.import_initial)
        self.dlg.pushButtonExportInitial.clicked.connect(self.export_initial)

        self.fileDialog = QFileDialog()
        self.fileDialog.setNameFilter("(*Point_isotropic.txt)")

        self.fileDialogInit = QFileDialog()
        self.fileDialogInit.setNameFilter("(*.nml)")

        self.fileDialogMet = QFileDialog()
        self.fileDialogMet.setNameFilter("(*.txt)")

        self.fileDialogOut = QFileDialog()
        self.fileDialogOut.setFileMode(4)
        self.fileDialogOut.setAcceptMode(1)
        self.folderPathOut = None
        self.folderPath = None

        self.ret = 0

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Suews Simple')
        # TODO: We are going to let the user set this up in a future iteration
        # self.toolbar = self.iface.addToolBar(u'SuewsSimple')
        # self.toolbar.setObjectName(u'SuewsSimple')

        self.model_dir = os.path.normpath(self.plugin_dir + os.sep +
                                          os.pardir + os.sep + 'suewsmodel')
        # sys.path.append(self.model_dir)

    # 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('SuewsSimple', 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):

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = ':/plugins/SuewsSimple/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'SUEWS (simple)'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Suews Simple'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        if not (os.path.isfile(self.model_dir + os.sep + 'SUEWS_V2018a') or
                os.path.isfile(self.model_dir + os.sep + 'SUEWS_V2018a.exe')):
            if QMessageBox.question(
                    self.iface.mainWindow(), "OS specific binaries missing",
                    "Before you start to use this plugin for the very first time, the OS specific suews\r\n"
                    "program (4Mb) must be be download from the UMEP repository and stored\r\n"
                    "in your plugin directory: "
                    "(" + self.model_dir + ").\r\n"
                    "\r\n"
                    "Join the email-list for updates and other information:\r\n"
                    "http://www.lists.rdg.ac.uk/mailman/listinfo/met-umep.\r\n"
                    "\r\n"
                    "UMEP on the web:\r\n"
                    "http://www.urban-climate.net/umep/\r\n"
                    "\r\n"
                    "\r\n"
                    "Do you want to contiune with the download?",
                    QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok:
                if sys.platform == 'win32':
                    urllib.urlretrieve(
                        'https://gvc.gu.se/digitalAssets/1695/1695894_suews_v2018a.exe',
                        self.model_dir + os.sep + 'SUEWS_V2018a.exe')
                if sys.platform == 'linux2':
                    urllib.urlretrieve(
                        'https://gvc.gu.se/digitalAssets/1695/1695887_suews_v2018a',
                        self.model_dir + os.sep + 'SUEWS_V2018a')
                if sys.platform == 'darwin':
                    urllib.urlretrieve(
                        'https://gvc.gu.se/digitalAssets/1695/1695886_suews_v2018a',
                        self.model_dir + os.sep + 'SUEWS_V2018a')
            else:
                QMessageBox.critical(
                    self.iface.mainWindow(), "Binaries not downloaded",
                    "This plugin will not be able to start before binaries are downloaded"
                )
                return

        self.dlg.show()
        self.dlg.exec_()

    def IMCP(self):
        sg = ImageMorphParmsPoint(self.iface)
        self.dlg.setEnabled(False)
        sg.run()
        self.dlg.setEnabled(True)

    def LCFP(self):
        sg = LandCoverFractionPoint(self.iface)
        self.dlg.setEnabled(False)
        sg.run()
        self.dlg.setEnabled(True)

    def folder_path(self):
        self.fileDialogOut.open()
        result = self.fileDialogOut.exec_()
        if result == 1:
            self.folderPathOut = self.fileDialogOut.selectedFiles()
            self.dlg.textOutput.setText(self.folderPathOut[0] + '/')

        self.dlg.runButton.setEnabled(True)

    def met_file(self):
        self.fileDialogMet.open()
        result = self.fileDialogMet.exec_()
        if result == 1:
            self.folderPathMet = self.fileDialogMet.selectedFiles()
            self.dlg.textInputMetdata.setText(self.folderPathMet[0])

        self.dlg.runButton.setEnabled(True)

    def import_file_IMPB(self):
        self.fileDialog.open()
        result = self.fileDialog.exec_()
        if result == 1:
            self.folderPath = self.fileDialog.selectedFiles()
            headernum = 1
            delim = ' '
            try:
                data = np.loadtxt(self.folderPath[0],
                                  skiprows=headernum,
                                  delimiter=delim)
            except:
                QMessageBox.critical(
                    None, "Import Error",
                    "The file does not have the correct format")
                return
            self.dlg.lineEdit_zHBuild.setText(str(data[2]))
            self.dlg.lineEdit_faiBuild.setText(str(data[1]))
            self.dlg.lineEdit_paiBuild.setText(str(data[0]))
            if self.dlg.pai_build.text():
                if np.abs(float(self.dlg.pai_build.text()) - data[0]) > 0.01:
                    self.iface.messageBar().pushMessage(
                        "Non-consistency warning",
                        "A relatively large difference in "
                        "building fraction between the DSM and the landcover grid was found: "
                        + str(float(self.dlg.pai_build.text()) - data[0]),
                        level=QgsMessageBar.WARNING)

    def import_file_IMPV(self):
        self.fileDialog.open()
        result = self.fileDialog.exec_()
        if result == 1:
            self.folderPath = self.fileDialog.selectedFiles()
            headernum = 1
            delim = ' '
            try:
                data = np.loadtxt(self.folderPath[0],
                                  skiprows=headernum,
                                  delimiter=delim)
            except:
                QMessageBox.critical(
                    None, "Import Error",
                    "The file does not have the correct format")
                return
            self.dlg.lineEdit_zHveg.setText(str(data[2]))
            self.dlg.lineEdit_faiveg.setText(str(data[1]))
            self.dlg.lineEdit_paiveg.setText(str(data[0]))
            if self.dlg.pai_evergreen.text() or self.dlg.pai_decid.text():
                if np.abs(
                        float(self.dlg.pai_decid.text()) +
                        float(self.dlg.pai_evergreen.text()) - data[0]) > 0.01:
                    self.iface.messageBar().pushMessage(
                        "Non-consistency warning",
                        "A relatively large difference in "
                        "vegetation fraction between the canopy DSM and the landcover grid was found: "
                        + str(
                            float(self.dlg.pai_decid.text()) +
                            float(self.dlg.pai_evergreen.text()) - data[0]),
                        level=QgsMessageBar.WARNING)

    def import_file_LCFP(self):
        self.fileDialog.open()
        result = self.fileDialog.exec_()
        if result == 1:
            self.folderPath = self.fileDialog.selectedFiles()
            headernum = 1
            delim = ' '
            try:
                data = np.loadtxt(self.folderPath[0],
                                  skiprows=headernum,
                                  delimiter=delim)
            except:
                QMessageBox.critical(
                    self.iface.mainWindow(), "Import Error",
                    "The file does not have the correct format")
                return
            self.dlg.pai_paved.setText(str(data[0]))
            self.dlg.pai_build.setText(str(data[1]))
            self.dlg.pai_evergreen.setText(str(data[2]))
            self.dlg.pai_decid.setText(str(data[3]))
            self.dlg.pai_grass.setText(str(data[4]))
            self.dlg.pai_baresoil.setText(str(data[5]))
            self.dlg.pai_water.setText(str(data[6]))
            if self.dlg.lineEdit_paiBuild.text():
                if np.abs(float(self.dlg.lineEdit_paiBuild.text()) -
                          data[1]) > 0.01:
                    self.iface.messageBar().pushMessage(
                        "Non-consistency warning",
                        "A relatively large difference in "
                        "building fraction between the DSM and the landcover grid was found: "
                        + str(
                            float(self.dlg.lineEdit_paiBuild.text()) -
                            data[1]),
                        level=QgsMessageBar.WARNING)
            if self.dlg.lineEdit_paiveg.text():
                if np.abs(
                        float(self.dlg.lineEdit_paiveg.text()) - data[2] -
                        data[3]) > 0.01:
                    self.iface.messageBar().pushMessage(
                        "Non-consistency warning",
                        "A relatively large difference in "
                        "vegetation fraction between the canopy DSM and the landcover grid was found: "
                        + str(
                            float(self.dlg.lineEdit_paiveg.text()) - data[2] -
                            data[3]),
                        level=QgsMessageBar.WARNING)

    def import_initial(self):
        self.fileDialogInit.open()
        result = self.fileDialogInit.exec_()
        if result == 1:
            self.folderPathInit = self.fileDialogInit.selectedFiles()
            nml = f90nml.read(self.folderPathInit[0])
            # dayssincerain = nml['initialconditions']['dayssincerain']
            # dailymeantemperature = nml['initialconditions']['temp_c0']
            # self.dlg.DaysSinceRain.setText(str(dayssincerain))
            # self.dlg.DailyMeanT.setText(str(dailymeantemperature))
            self.dlg.comboBoxLeafCycle.setCurrentIndex(1)

    def export_initial(self):
        outputfile = self.fileDialog.getSaveFileName(None, "Save As:", None,
                                                     "Namelist (*.nml)")
        # self.fileDialogInit.open()
        # result = self.fileDialogInit.exec_()
        if outputfile:
            self.folderPathInit = outputfile
            self.write_to_init(
                self.model_dir + '/BaseFiles/InitialConditionsKc_2012.nml',
                self.folderPathInit)

            # # DaysSinceRain = self.dlg.DaysSinceRain.text()
            # # DailyMeanT = self.dlg.DailyMeanT.text()
            # LeafCycle = self.dlg.comboBoxLeafCycle.currentIndex() - 1.
            # SoilMoisture = self.dlg.spinBoxSoilMoisture.value()
            # moist = int(SoilMoisture * 1.5)
            #
            # nml = f90nml.read(self.model_dir + '/BaseFiles/InitialConditionsKc_2012.nml')
            # # nml['initialconditions']['dayssincerain'] = int(DaysSinceRain)
            # # nml['initialconditions']['temp_c0'] = float(DailyMeanT)
            # nml['initialconditions']['soilstorepavedstate'] = moist
            # nml['initialconditions']['soilstorebldgsstate'] = moist
            # nml['initialconditions']['soilstoreevetrstate'] = moist
            # nml['initialconditions']['soilstoredectrstate'] = moist
            # nml['initialconditions']['soilstoregrassstate'] = moist
            # nml['initialconditions']['soilstorebsoilstate'] = moist
            #
            # if LeafCycle == 0:  # Winter
            #     nml['initialconditions']['gdd_1_0'] = 0
            #     nml['initialconditions']['gdd_2_0'] = -450
            #     nml['initialconditions']['laiinitialevetr'] = 4
            #     nml['initialconditions']['laiinitialdectr'] = 1
            #     nml['initialconditions']['laiinitialgrass'] = 1.6
            # elif LeafCycle == 1:
            #     nml['initialconditions']['gdd_1_0'] = 50
            #     nml['initialconditions']['gdd_2_0'] = -400
            #     nml['initialconditions']['laiinitialevetr'] = 4.2
            #     nml['initialconditions']['laiinitialdectr'] = 2.0
            #     nml['initialconditions']['laiinitialgrass'] = 2.6
            # elif LeafCycle == 2:
            #     nml['initialconditions']['gdd_1_0'] = 150
            #     nml['initialconditions']['gdd_2_0'] = -300
            #     nml['initialconditions']['laiinitialevetr'] = 4.6
            #     nml['initialconditions']['laiinitialdectr'] = 3.0
            #     nml['initialconditions']['laiinitialgrass'] = 3.6
            # elif LeafCycle == 3:
            #     nml['initialconditions']['gdd_1_0'] = 225
            #     nml['initialconditions']['gdd_2_0'] = -150
            #     nml['initialconditions']['laiinitialevetr'] = 4.9
            #     nml['initialconditions']['laiinitialdectr'] = 4.5
            #     nml['initialconditions']['laiinitialgrass'] = 4.6
            # elif LeafCycle == 4: # Summer
            #     nml['initialconditions']['gdd_1_0'] = 300
            #     nml['initialconditions']['gdd_2_0'] = 0
            #     nml['initialconditions']['laiinitialevetr'] = 5.1
            #     nml['initialconditions']['laiinitialdectr'] = 5.5
            #     nml['initialconditions']['laiinitialgrass'] = 5.9
            # elif LeafCycle == 5:
            #     nml['initialconditions']['gdd_1_0'] = 225
            #     nml['initialconditions']['gdd_2_0'] = -150
            #     nml['initialconditions']['laiinitialevetr'] = 4.9
            #     nml['initialconditions']['laiinitialdectr'] = 4,5
            #     nml['initialconditions']['laiinitialgrass'] = 4.6
            # elif LeafCycle == 6:
            #     nml['initialconditions']['gdd_1_0'] = 150
            #     nml['initialconditions']['gdd_2_0'] = -300
            #     nml['initialconditions']['laiinitialevetr'] = 4.6
            #     nml['initialconditions']['laiinitialdectr'] = 3.0
            #     nml['initialconditions']['laiinitialgrass'] = 3.6
            # elif LeafCycle == 7:
            #     nml['initialconditions']['gdd_1_0'] = 50
            #     nml['initialconditions']['gdd_2_0'] = -400
            #     nml['initialconditions']['laiinitialevetr'] = 4.2
            #     nml['initialconditions']['laiinitialdectr'] = 2.0
            #     nml['initialconditions']['laiinitialgrass'] = 2.6
            # nml.write(self.folderPathInit, force=True)

    def set_default_settings(self):
        f = open(self.model_dir + '/BaseFiles/SUEWS_SiteSelect.txt')
        lin = f.readlines()
        index = 2
        lines = lin[index].split()
        self.dlg.lineEdit_YYYY.setText(lines[1])
        self.dlg.pai_paved.setText(lines[13])
        self.dlg.pai_build.setText(lines[14])
        self.dlg.pai_evergreen.setText(lines[15])
        self.dlg.pai_decid.setText(lines[16])
        self.dlg.pai_grass.setText(lines[17])
        self.dlg.pai_baresoil.setText(lines[18])
        self.dlg.pai_water.setText(lines[19])
        self.dlg.lineEdit_zHBuild.setText(lines[23])
        self.dlg.lineEdit_faiBuild.setText(lines[28])
        self.dlg.lineEdit_paiBuild.setText(lines[14])
        self.dlg.lineEdit_zHveg.setText(
            str((float(lines[24]) + float(lines[25])) / 2))
        self.dlg.lineEdit_faiveg.setText(
            str((float(lines[29]) + float(lines[30])) / 2))
        self.dlg.lineEdit_paiveg.setText(
            str(float(lines[15]) + float(lines[16])))
        self.dlg.Latitude.setText(lines[4])
        self.dlg.Longitude.setText(lines[5])
        self.dlg.PopDensNight.setText(lines[32])
        self.dlg.Height.setText(lines[9])

        # nml = f90nml.read(self.model_dir + '/BaseFiles/InitialConditionsKc_2012.nml')
        # dayssincerain = nml['initialconditions']['dayssincerain']
        # dailymeantemperature = nml['initialconditions']['temp_c0']
        # self.dlg.DaysSinceRain.setText(str(dayssincerain))
        # self.dlg.DailyMeanT.setText(str(dailymeantemperature))
        self.dlg.comboBoxLeafCycle.setCurrentIndex(1)

        nml = f90nml.read(self.model_dir + '/BaseFiles/RunControl.nml')

        self.dlg.FileCode.setText(str(nml['runcontrol']['FileCode']))

        self.dlg.UTC.setText('0')

        self.dlg.textInputMetdata.setText(self.model_dir +
                                          '/BaseFiles/Kc_2012_data_60.txt')
        self.dlg.textOutput.setText(self.model_dir + '/Output/')
        self.dlg.spinBoxSoilMoisture.setValue(100)

        self.dlg.runButton.setEnabled(True)

    def write_site_select(self, numoflines, newdata):
        f = open(self.model_dir + '/BaseFiles/SUEWS_SiteSelect.txt', 'r')
        lin = f.readlines()
        f2 = open(self.model_dir + '/Input/SUEWS_SiteSelect.txt', 'w')

        # write to file
        f2.write(lin[0])
        f2.write(lin[1])
        for l in range(0, numoflines):
            for i in range(0, newdata.__len__()):
                f2.write(str(newdata[i]))
                f2.write('\t')
            f2.write('\n')
        f2.write(lin[2 + numoflines])
        f2.write(lin[3 + numoflines])
        f.close()
        f2.close()

    def start_progress(self):

        try:
            import matplotlib.pyplot
        except ImportError:
            pass
            self.iface.messageBar().pushMessage(
                "Unable to import Matplotlib module. Plots will not be produced",
                "Visit UMEP webpage for installation instructions.",
                level=QgsMessageBar.WARNING)

        # Checking consistency between fractions
        if np.abs(
                float(self.dlg.pai_build.text()) -
                float(self.dlg.lineEdit_paiBuild.text())) > 0.05:
            QMessageBox.critical(
                self.iface.mainWindow(), "Non-consistency Error",
                "A relatively large difference in "
                "building fraction between the DSM and the landcover grid was found: "
                + str(
                    float(self.dlg.pai_build.text()) -
                    float(self.dlg.lineEdit_paiBuild.text())))
            return
        if np.abs(
                float(self.dlg.pai_decid.text()) +
                float(self.dlg.pai_evergreen.text()) -
                float(self.dlg.lineEdit_paiveg.text())) > 0.05:
            QMessageBox.critical(
                self.iface.mainWindow(), "Non-consistency Error",
                "A relatively large difference in "
                "building fraction between the Vegetation DSM and the landcover grid was found: "
                + str(
                    float(self.dlg.pai_decid.text()) +
                    float(self.dlg.pai_evergreen.text()) -
                    float(self.dlg.lineEdit_paiveg.text())))
            return

        # Getting values from GUI
        YYYY = self.dlg.lineEdit_YYYY.text()
        pai_paved = self.dlg.pai_paved.text()
        pai_build = self.dlg.pai_build.text()
        pai_evergreen = self.dlg.pai_evergreen.text()
        pai_decid = self.dlg.pai_decid.text()
        pai_grass = self.dlg.pai_grass.text()
        pai_baresoil = self.dlg.pai_baresoil.text()
        pai_water = self.dlg.pai_water.text()
        zHBuild = self.dlg.lineEdit_zHBuild.text()
        faiBuild = float(self.dlg.lineEdit_faiBuild.text())
        paiBuild = self.dlg.lineEdit_paiBuild.text()
        zHveg = self.dlg.lineEdit_zHveg.text()
        faiveg = float(self.dlg.lineEdit_faiveg.text())
        paiveg = self.dlg.lineEdit_paiveg.text()
        lat = self.dlg.Latitude.text()
        lon = self.dlg.Longitude.text()
        popdens = float(self.dlg.PopDensNight.text())
        filecode = self.dlg.FileCode.text()
        utc = self.dlg.UTC.text()
        z = self.dlg.Height.text()

        # Checking LC fractions = 1
        LCtest = float(pai_paved) + float(pai_build) + float(
            pai_evergreen) + float(pai_decid) + float(pai_grass) + float(
                pai_baresoil) + float(pai_water)
        if not LCtest == 1.:
            QMessageBox.critical(
                self.iface.mainWindow(), "Non-consistency Error",
                "Sum of Land cover fraction is not"
                " equal to 1 (" + str(LCtest) + ")")
            return

        # Create new SiteSelect
        f = open(self.model_dir + '/BaseFiles/SUEWS_SiteSelect.txt', 'r')
        lin = f.readlines()
        index = 2
        lines = np.array(lin[index].split())
        newdata = lines
        # gridcode = newdata[0]
        newdata[1] = YYYY
        newdata[4] = lat
        newdata[5] = lon
        newdata[6] = int(utc)
        newdata[9] = float(z)
        newdata[13] = pai_paved
        newdata[14] = pai_build
        newdata[15] = pai_evergreen
        newdata[16] = pai_decid
        newdata[17] = pai_grass
        newdata[18] = pai_baresoil
        newdata[19] = pai_water
        newdata[23] = zHBuild
        newdata[24] = zHveg
        newdata[25] = zHveg
        newdata[28] = faiBuild
        newdata[29] = faiveg
        newdata[30] = faiveg
        newdata[32] = popdens
        self.write_site_select(1, newdata)
        f.close()

        # Plots or not
        if self.dlg.checkBoxPlots.isChecked():
            plot = 1
        else:
            plot = 0
        plotnml = f90nml.read(self.model_dir + '/plot.nml')
        plotnml['plot']['plotbasic'] = plot
        plotnml['plot']['plotmonthlystat'] = plot
        plotnml.write(self.model_dir + '/plot.nml', force=True)

        # Create new RunControl
        inmetfile = self.dlg.textInputMetdata.text()
        outfolder = self.dlg.textOutput.text() + '/'
        nml = f90nml.read(self.model_dir + '/BaseFiles/RunControl.nml')
        if not (faiBuild == -999.0 or faiveg == -999.0):
            nml['runcontrol']['RoughLenMomMethod'] = 3

        resolutionfilesin = nml['runcontrol']['resolutionfilesin']
        runmetfile = self.model_dir + '/Input/' + str(
            filecode) + '_' + self.dlg.lineEdit_YYYY.text() + '_data_' + str(
                int(int(resolutionfilesin) / 60.)) + '.txt'
        try:
            shutil.copy(inmetfile, runmetfile)
        except:
            os.remove(inmetfile)
            shutil.copy(inmetfile, runmetfile)

        nml['runcontrol']['fileCode'] = str(filecode)
        nml['runcontrol']['fileoutputpath'] = str(outfolder)
        nml['runcontrol']['fileinputpath'] = self.model_dir + '/Input/'
        nml.write(self.model_dir + '/RunControl.nml', force=True)

        initfilein = self.model_dir + '/BaseFiles/InitialConditionsKc_2012.nml'
        initfileout = self.model_dir + '/Input/InitialConditions' + str(
            filecode) + '_' + str(YYYY) + '.nml'
        self.write_to_init(initfilein, initfileout)

        # TODO: Put suews in a worker
        # self.startWorker(self.iface, self.model_dir, self.dlg)

        QMessageBox.information(
            self.dlg, "Model information",
            "Model run will now start. QGIS might freeze during calcualtion."
            "This will be fixed in future versions")
        # Suews_wrapper_v2018a.wrapper(self.model_dir)
        try:
            Suews_wrapper_v2018a.wrapper(self.model_dir)
            time.sleep(1)
            self.iface.messageBar().pushMessage(
                "Model run finished",
                "Check problems.txt in " + self.model_dir + " for "
                "additional information about the run",
                level=QgsMessageBar.INFO)
        except Exception as e:
            time.sleep(1)
            QMessageBox.critical(
                self.dlg, "An error occurred",
                str(e) + "\r\n\r\n"
                "Also check problems.txt in " + self.model_dir + "\r\n\r\n"
                "Please report any errors to https://bitbucket.org/fredrik_ucg/umep/issues"
            )
            return

        shutil.copy(self.model_dir + '/RunControl.nml',
                    outfolder + '/RunControl.nml')

    def write_to_init(self, initfilein, initfileout):
        LeafCycle = self.dlg.comboBoxLeafCycle.currentIndex()
        SoilMoisture = self.dlg.spinBoxSoilMoisture.value()
        moist = int(SoilMoisture * 1.5)

        nml = f90nml.read(initfilein)

        nml['initialconditions']['soilstorepavedstate'] = moist
        nml['initialconditions']['soilstorebldgsstate'] = moist
        nml['initialconditions']['soilstoreevetrstate'] = moist
        nml['initialconditions']['soilstoredectrstate'] = moist
        nml['initialconditions']['soilstoregrassstate'] = moist
        nml['initialconditions']['soilstorebsoilstate'] = moist

        if not (LeafCycle == 1 or LeafCycle == 5):
            self.iface.messageBar().pushMessage(
                "Warning",
                "A transition period between Winter and Summer has been "
                "choosen. Preferably start the model run during Winter or "
                "Summer.",
                level=QgsMessageBar.WARNING)

        # Based on London data
        if LeafCycle == 1:  # Winter
            nml['initialconditions']['gdd_1_0'] = 0
            nml['initialconditions']['gdd_2_0'] = -450
            nml['initialconditions']['laiinitialevetr'] = 4
            nml['initialconditions']['laiinitialdectr'] = 1
            nml['initialconditions']['laiinitialgrass'] = 1.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.3
            nml['initialconditions']['porosity0'] = 0.2
        elif LeafCycle == 2:
            nml['initialconditions']['gdd_1_0'] = 50
            nml['initialconditions']['gdd_2_0'] = -400
            nml['initialconditions']['laiinitialevetr'] = 4.2
            nml['initialconditions']['laiinitialdectr'] = 2.0
            nml['initialconditions']['laiinitialgrass'] = 2.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.4
            nml['initialconditions']['porosity0'] = 0.3
        elif LeafCycle == 3:
            nml['initialconditions']['gdd_1_0'] = 150
            nml['initialconditions']['gdd_2_0'] = -300
            nml['initialconditions']['laiinitialevetr'] = 4.6
            nml['initialconditions']['laiinitialdectr'] = 3.0
            nml['initialconditions']['laiinitialgrass'] = 3.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.6
            nml['initialconditions']['porosity0'] = 0.5
        elif LeafCycle == 4:
            nml['initialconditions']['gdd_1_0'] = 225
            nml['initialconditions']['gdd_2_0'] = -150
            nml['initialconditions']['laiinitialevetr'] = 4.9
            nml['initialconditions']['laiinitialdectr'] = 4.5
            nml['initialconditions']['laiinitialgrass'] = 4.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.8
            nml['initialconditions']['porosity0'] = 0.6
        elif LeafCycle == 5:  # Summer
            nml['initialconditions']['gdd_1_0'] = 300
            nml['initialconditions']['gdd_2_0'] = 0
            nml['initialconditions']['laiinitialevetr'] = 5.1
            nml['initialconditions']['laiinitialdectr'] = 5.5
            nml['initialconditions']['laiinitialgrass'] = 5.9
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.8
            nml['initialconditions']['porosity0'] = 0.6
        elif LeafCycle == 6:
            nml['initialconditions']['gdd_1_0'] = 225
            nml['initialconditions']['gdd_2_0'] = -150
            nml['initialconditions']['laiinitialevetr'] = 4.9
            nml['initialconditions']['laiinitialdectr'] = 4, 5
            nml['initialconditions']['laiinitialgrass'] = 4.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.8
            nml['initialconditions']['porosity0'] = 0.5
        elif LeafCycle == 7:
            nml['initialconditions']['gdd_1_0'] = 150
            nml['initialconditions']['gdd_2_0'] = -300
            nml['initialconditions']['laiinitialevetr'] = 4.6
            nml['initialconditions']['laiinitialdectr'] = 3.0
            nml['initialconditions']['laiinitialgrass'] = 3.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.5
            nml['initialconditions']['porosity0'] = 0.4
        elif LeafCycle == 8:  # Late Autumn
            nml['initialconditions']['gdd_1_0'] = 50
            nml['initialconditions']['gdd_2_0'] = -400
            nml['initialconditions']['laiinitialevetr'] = 4.2
            nml['initialconditions']['laiinitialdectr'] = 2.0
            nml['initialconditions']['laiinitialgrass'] = 2.6
            nml['initialconditions']['albEveTr0'] = 0.10
            nml['initialconditions']['albDecTr0'] = 0.12
            nml['initialconditions']['albGrass0'] = 0.18
            nml['initialconditions']['decidCap0'] = 0.4
            nml['initialconditions']['porosity0'] = 0.2

        nml.write(initfileout, force=True)

    def help(self):
        url = 'http://umep-docs.readthedocs.io/en/latest/processor/Urban%20Energy%20Balance%20Urban%20Energy%20' \
              'Balance%20(SUEWS,%20simple).html'
        webbrowser.open_new_tab(url)
Пример #45
0
        def __init__(self):
            self.dff = QTranslator()

            self.generic = QTranslator()
            self.Conf = Conf()
            self.loadLanguage()
Пример #46
0
class yieldMain:
    """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
        self.canvas = self.iface.mapCanvas()
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'yield_{}.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.mw = yieldMainWindow(self.iface)


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Where is the yield?')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'yield')
        self.toolbar.setObjectName(u'yield')

    # 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('yieldProject', 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):
        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.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)
        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/yield_project/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'prototype for jam'),
            callback=self.run,
            parent=self.iface.mainWindow())


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Jam Resampler'),
                action)
        self.iface.removeToolBarIcon(action)
    
    def take_a_shape(self):
        table = ("rectangle", "diamond", "pentagon", "triangle","equilateral_triangle",\
                  "regular_star", "arrow", "circle", "cross")
        index = int(round(random.random()*(len(table)-1)))
        shape = table[index]
        return shape

    def run(self):
        #sudo apt-get install libqt4-sql-psql
        
        db = QSqlDatabase.addDatabase("QPSQL","first2");
        self.initUi = iniDbDialog()
        self.initUi.show()
        self.initUi.ui.tHostName.setText("localhost");
        self.initUi.ui.tDbName.setText("yield_db");
        self.initUi.ui.tUserName.setText("postgres");
        self.initUi.ui.tPassword.setText("postgres");
        self.initUi.ui.tPort.setText('5432')
        res = self.initUi.exec_()

        """db.setHostName("sige-demo");
        db.setDatabaseName("sige");
        db.setUserName("sige");
        db.setPassword("sige");"""
        

            
        if res:
            db.setHostName(self.initUi.ui.tHostName.text());
            db.setDatabaseName(self.initUi.ui.tDbName.text());
            db.setUserName(self.initUi.ui.tUserName.text());
            db.setPassword(self.initUi.ui.tPassword.text());
            db.setPort(int(self.initUi.ui.tPort.text()))
            self.initUi = None
            
            ok = db.open();
            if ok:
                QMessageBox.information(QDialog(), "Database status", "Database is connected")        
                self.mw.db = db
                #print db.lastError().databaseText()
                #print db.lastError().driverText()
        
                self.mw.show()
                
                ## Run the dialog event loop
                
            else:
                QMessageBox.critical(QDialog(), "Database status", "Connection failed")   
Пример #47
0
class mesh2DView:
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'meshBuilder_{}.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)

        self.dlg = mesh2DViewDiag()

        pixMap = QtGui.QPixmap(os.path.join(self.plugin_dir,
                                            'Georeference.svg'))
        geoIcon = QtGui.QIcon(pixMap)
        self.dlg.geoReferenceBtn.setIcon(geoIcon)
        self.dlg.geoReferenceBtn.setIconSize(0.7*pixMap.rect().size())
        self.dlg.geoReferenceBtn.setToolTip(u'設定參考座標系')

        caption1 = u'請選擇一個 mesh2D 檔案(.2dm)'
        self.dlg.mshFileSelectBtn.pressed.connect(
            lambda: fileBrowser(self.dlg, caption1, '', self.dlg.meshFileEdit,
                                '(*.2dm)'))
        self.dlg.mshFileSelectBtn.setToolTip(caption1)
        caption2 = u'請選擇建立 shp 檔案的資料夾'
        self.dlg.folderSelectBtn.pressed.connect(
            lambda: folderBrowser(self.dlg, caption2, '',
                                  self.dlg.folderLineEdit))
        self.dlg.folderSelectBtn.setToolTip(caption2)
        self.dlg.geoReferenceBtn.clicked.connect(self.selectCrs)

    def run(self):
        result = self.dlg.exec_()
        if result:
            self.read2dm()
            return result

    def selectCrs(self):
        crsDiag = QgsGenericProjectionSelector()
        crsDiag.exec_()
        crsId = crsDiag.selectedCrsId()
        crsType = QgsCoordinateReferenceSystem.InternalCrsId
        self.crs = QgsCoordinateReferenceSystem(crsId, crsType)

    def read2dm(self):
        try:
            crs = self.crs
        except(AttributeError):
            crs = QgsCoordinateReferenceSystem(
                3826, QgsCoordinateReferenceSystem.EpsgCrsId)
        meshFile = self.dlg.meshFileEdit.text()
        f = open(meshFile, 'r')
        nodeFields = QgsFields()
        nodeFields.append(QgsField("id", QVariant.Int))
        nodeFields.append(QgsField("z", QVariant.Double))
        nodePath = os.path.join(self.dlg.folderLineEdit.text(), 'Nodes.shp')
        nodeWriter = QgsVectorFileWriter(nodePath, 'UTF-8', nodeFields,
                                         QGis.WKBPoint, crs, 'ESRI Shapefile')

        data = f.readlines()
        NodeDict = dict()
        Regions = list()
        NodeStrings = list()
        oneString = list()
        for line in data:
            line = line.split()
            if line[0] == 'ND':
                NodeDict.update(
                    {int(line[1]): (float(line[2]), float(line[3]),
                                    float(line[4]))})
                geoString = ('POINT (' + line[2] + ' ' + line[3] + ')')
                feature = QgsFeature()
                feature.setGeometry(QgsGeometry.fromWkt(geoString))
                feature.setAttributes([int(line[1]), float(line[4])])
                nodeWriter.addFeature(feature)
            elif line[0] in meshType.keys():
                Regions.append(int(line[-1]))
            elif line[0] == 'NS':
                for i in range(1, len(line)):
                    oneString.append(fabs(int(line[i])))
                if int(line[-1]) < 0:
                    NodeStrings.append(oneString)
                    oneString = list()

        del nodeWriter
        Regions = list(set(Regions))
        Regions.sort()

        group = QgsProject.instance().layerTreeRoot().addGroup(
            os.path.basename(meshFile))

        regionWriters = list()
        fields = QgsFields()
        fields.append(QgsField("id", QVariant.Int))
        layerList = list()
        layerList.append(nodePath)
        for i in range(0, len(Regions)):
            layerName = 'Material' + str(Regions[i])
            path = os.path.join(self.dlg.folderLineEdit.text(),
                                layerName + '.shp')
            self.iface.messageBar().pushMessage(path)
            regionWriters.append(
                QgsVectorFileWriter(path, 'UTF-8', fields, QGis.WKBPolygon, crs,
                                    'ESRI Shapefile'))
            layerList.append(path)
        for line in data:
            line = line.split()
            if line[0] in meshType.keys():
                n = meshType[line[0]]
                geoString = 'POLYGON (('
                for k in range(2, 2+n):
                    Coor = NodeDict[int(line[k])]
                    geoString += (str(Coor[0]) + ' ' + str(Coor[1]) + ', ')
                Coor = NodeDict[int(line[2])]
                geoString += (str(Coor[0]) + ' ' + str(Coor[1]))
                geoString += '))'
                writer = regionWriters[int(line[-1])-1]

                feature = QgsFeature()
                feature.setGeometry(QgsGeometry().fromWkt(geoString))
                feature.setAttributes([int(line[1])])
                writer.addFeature(feature)

                if writer.hasError() != QgsVectorFileWriter.NoError:
                    self.iface.messageBar().pushMessage(
                        "Error when creating shapefile: ",
                        writer.errorMessage())

        for writer in regionWriters:
            del writer

        counter = 1
        for lineString in NodeStrings:
            path = os.path.join(self.dlg.folderLineEdit.text(),
                                'NodeString' + str(counter) + '.shp')
            writer = QgsVectorFileWriter(path, 'UTF-8', fields,
                                         QGis.WKBLineString, crs,
                                         'ESRI Shapefile')
            layerList.append(path)
            geoString = 'LINESTRING ('
            for i in range(0, len(lineString)):
                nodeCoor = NodeDict[lineString[i]]
                geoString += (str(nodeCoor[0]) + " " + str(nodeCoor[1]) + ", ")
            geoString = geoString[:-2] + ')'

            feature = QgsFeature()
            feature.setGeometry(QgsGeometry().fromWkt(geoString))
            feature.setAttributes([counter])
            writer.addFeature(feature)
            del writer
            counter += 1

        for i in range(0, len(layerList)):
            layer = QgsVectorLayer(
                layerList[i], QFileInfo(layerList[i]).baseName(), 'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            group.addLayer(layer)
            layer.reload()
Пример #48
0
class ExportToHE:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ExportToHE_{}.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 = ExportToHEDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Export to HE')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'ExportToHE')
        self.toolbar.setObjectName(u'ExportToHE')

        # Anfang Eigene Funktionen -------------------------------------------------
        # (jh, 08.02.2017)

        logger.info('\n\nQKan_ExportHE initialisiert...')

        # --------------------------------------------------------------------------
        # Pfad zum Arbeitsverzeichnis sicherstellen
        wordir = os.path.join(site.getuserbase(), 'qkan')

        if not os.path.isdir(wordir):
            os.makedirs(wordir)

        # --------------------------------------------------------------------------
        # Konfigurationsdatei qkan.json lesen
        #

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with codecs.open(self.configfil, 'r', 'utf-8') as fileconfig:
                self.config = json.loads(fileconfig.read().replace('\\', '/'))
        else:
            self.config['database_HE'] = ''
            # Vorlagedatenbank nur für den Fall, dass der Anwender keine eigene Vorlage erstellen will
            self.config['dbtemplate_HE'] = os.path.join(
                os.path.dirname(__file__), "templates", "itwh.idbf")
            self.config['database_QKan'] = ''
            with codecs.open(self.configfil, 'w', 'utf-8') as fileconfig:
                fileconfig.write(json.dumps(self.config))

        # Standard für Suchverzeichnis festlegen
        project = QgsProject.instance()
        self.default_dir = os.path.dirname(project.fileName())

        if 'database_QKan' in self.config:
            database_QKan = self.config['database_QKan']
        else:
            database_QKan = ''
        self.dlg.tf_QKanDB.setText(database_QKan)
        self.dlg.pb_selectQKanDB.clicked.connect(self.selectFile_QKanDB)

        if 'database_HE' in self.config:
            database_HE = self.config['database_HE']
        else:
            database_HE = ''
        self.dlg.tf_heDB_dest.setText(database_HE)
        self.dlg.pb_selectHeDB_dest.clicked.connect(self.selectFile_HeDB_dest)

        if 'dbtemplate_HE' in self.config:
            dbtemplate_HE = self.config['dbtemplate_HE']
        else:
            dbtemplate_HE = ''
        self.dlg.tf_heDB_template.setText(dbtemplate_HE)
        self.dlg.pb_selectHeDB_template.clicked.connect(
            self.selectFile_HeDB_template)

        if 'datenbanktyp' in self.config:
            datenbanktyp = self.config['datenbanktyp']
        else:
            datenbanktyp = 'spatialite'
            pass  # Es gibt noch keine Wahlmöglichkeit

        self.dlg.pb_exportall.clicked.connect(self.exportall)
        self.dlg.pb_modifyall.clicked.connect(self.modifyall)
        self.dlg.pb_initall.clicked.connect(self.initall)
        self.dlg.pb_exportnone.clicked.connect(self.exportnone)
        self.dlg.pb_modifynone.clicked.connect(self.modifynone)
        self.dlg.pb_initnone.clicked.connect(self.initnone)

        # Auswahl der zu exportierenden Tabellen ----------------------------------------------

        # Eigene Funktion für die zahlreichen Checkboxen

        def cb_set(name, cbox, default):
            if name in self.config:
                checked = self.config[name]
            else:
                checked = default
            cbox.setChecked(checked)
            return checked

        export_schaechte = cb_set('export_schaechte',
                                  self.dlg.cb_export_schaechte, True)
        export_auslaesse = cb_set('export_auslaesse',
                                  self.dlg.cb_export_auslaesse, True)
        export_speicher = cb_set('export_speicher',
                                 self.dlg.cb_export_speicher, True)
        export_haltungen = cb_set('export_haltungen',
                                  self.dlg.cb_export_haltungen, True)
        export_pumpen = cb_set('export_pumpen', self.dlg.cb_export_pumpen,
                               False)
        export_wehre = cb_set('export_wehre', self.dlg.cb_export_wehre, False)
        export_flaechenrw = cb_set('export_flaechenrw',
                                   self.dlg.cb_export_flaechenrw, True)
        export_flaechensw = cb_set('export_flaechensw',
                                   self.dlg.cb_export_flaechensw, True)
        export_abflussparameter = cb_set('export_abflussparameter',
                                         self.dlg.cb_export_abflussparameter,
                                         True)
        export_regenschreiber = cb_set('export_regenschreiber',
                                       self.dlg.cb_export_regenschreiber,
                                       False)
        export_rohrprofile = cb_set('export_rohrprofile',
                                    self.dlg.cb_export_rohrprofile, False)
        export_speicherkennlinien = cb_set(
            'export_speicherkennlinien', self.dlg.cb_export_speicherkennlinien,
            False)
        export_bodenklassen = cb_set('export_bodenklassen',
                                     self.dlg.cb_export_bodenklassen, False)

        modify_schaechte = cb_set('modify_schaechte',
                                  self.dlg.cb_modify_schaechte, False)
        modify_auslaesse = cb_set('modify_auslaesse',
                                  self.dlg.cb_modify_auslaesse, False)
        modify_speicher = cb_set('modify_speicher',
                                 self.dlg.cb_modify_speicher, False)
        modify_haltungen = cb_set('modify_haltungen',
                                  self.dlg.cb_modify_haltungen, False)
        modify_pumpen = cb_set('modify_pumpen', self.dlg.cb_modify_pumpen,
                               False)
        modify_wehre = cb_set('modify_wehre', self.dlg.cb_modify_wehre, False)
        modify_flaechenrw = cb_set('modify_flaechenrw',
                                   self.dlg.cb_modify_flaechenrw, False)
        modify_flaechensw = cb_set('modify_flaechensw',
                                   self.dlg.cb_modify_flaechensw, False)
        modify_abflussparameter = cb_set('modify_abflussparameter',
                                         self.dlg.cb_modify_abflussparameter,
                                         False)
        modify_regenschreiber = cb_set('modify_regenschreiber',
                                       self.dlg.cb_modify_regenschreiber,
                                       False)
        modify_rohrprofile = cb_set('modify_rohrprofile',
                                    self.dlg.cb_modify_rohrprofile, False)
        modify_speicherkennlinien = cb_set(
            'modify_speicherkennlinien', self.dlg.cb_modify_speicherkennlinien,
            False)
        modify_bodenklassen = cb_set('modify_bodenklassen',
                                     self.dlg.cb_modify_bodenklassen, False)

        init_schaechte = cb_set('init_schaechte', self.dlg.cb_init_schaechte,
                                False)
        init_auslaesse = cb_set('init_auslaesse', self.dlg.cb_init_auslaesse,
                                False)
        init_speicher = cb_set('init_speicher', self.dlg.cb_init_speicher,
                               False)
        init_haltungen = cb_set('init_haltungen', self.dlg.cb_init_haltungen,
                                False)
        init_pumpen = cb_set('init_pumpen', self.dlg.cb_init_pumpen, False)
        init_wehre = cb_set('init_wehre', self.dlg.cb_init_wehre, False)
        init_flaechenrw = cb_set('init_flaechenrw',
                                 self.dlg.cb_init_flaechenrw, False)
        init_flaechensw = cb_set('init_flaechensw',
                                 self.dlg.cb_init_flaechensw, False)
        init_abflussparameter = cb_set('init_abflussparameter',
                                       self.dlg.cb_init_abflussparameter,
                                       False)
        init_regenschreiber = cb_set('init_regenschreiber',
                                     self.dlg.cb_init_regenschreiber, False)
        init_rohrprofile = cb_set('init_rohrprofile',
                                  self.dlg.cb_init_rohrprofile, False)
        init_speicherkennlinien = cb_set('init_speicherkennlinien',
                                         self.dlg.cb_init_speicherkennlinien,
                                         False)
        init_bodenklassen = cb_set('init_bodenklassen',
                                   self.dlg.cb_init_bodenklassen, False)

        export_difftezg = cb_set('export_difftezg',
                                 self.dlg.cb_export_difftezg, True)
        export_verschneidung = cb_set('export_verschneidung',
                                      self.dlg.cb_export_verschneidung, True)

        # Ende Eigene Funktionen ---------------------------------------------------

    # 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('ExportToHE', 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):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/QKan_ExportHE/icon_qk2he.png'
        self.add_action(icon_path,
                        text=self.tr(u'Export to Hystem-Extran'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.tr(u'&Export to HE'),
                                              action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    # Anfang Eigene Funktionen -------------------------------------------------
    # (jh, 08.02.2017)

    def selectFile_HeDB_dest(self):
        """Datenbankverbindung zur HE-Datenbank (Firebird) auswaehlen und gegebenenfalls die Zieldatenbank
           erstellen, aber noch nicht verbinden."""

        filename = QFileDialog.getSaveFileName(
            self.dlg, "Dateinamen der Ziel-HE-Datenbank eingeben",
            self.default_dir, "*.idbf")
        # if os.path.dirname(filename) != '':
        # os.chdir(os.path.dirname(filename))
        self.dlg.tf_heDB_dest.setText(filename)

    def selectFile_HeDB_template(self):
        """Vorlage-HE-Datenbank (Firebird) auswaehlen."""

        filename = QFileDialog.getOpenFileName(
            self.dlg, u"Dateinamen der Vorlage-HE-Datenbank eingeben",
            self.default_dir, "*.idbf")
        # if os.path.dirname(filename) != '':
        # os.chdir(os.path.dirname(filename))
        self.dlg.tf_heDB_template.setText(filename)

    def selectFile_QKanDB(self):
        """Datenbankverbindung zur QKan-Datenbank (SpatiLite) auswaehlen."""

        filename = QFileDialog.getOpenFileName(self.dlg,
                                               u"QKan-Datenbank auswählen",
                                               self.default_dir, "*.sqlite")
        # if os.path.dirname(filename) != '':
        # os.chdir(os.path.dirname(filename))
        self.dlg.tf_QKanDB.setText(filename)

    def exportall(self):
        """Aktiviert alle Checkboxen zm Export"""

        self.dlg.cb_export_schaechte.setChecked(True)
        self.dlg.cb_export_auslaesse.setChecked(True)
        self.dlg.cb_export_speicher.setChecked(True)
        self.dlg.cb_export_haltungen.setChecked(True)
        self.dlg.cb_export_pumpen.setChecked(True)
        self.dlg.cb_export_wehre.setChecked(True)
        self.dlg.cb_export_flaechenrw.setChecked(True)
        self.dlg.cb_export_flaechensw.setChecked(True)
        self.dlg.cb_export_abflussparameter.setChecked(True)
        self.dlg.cb_export_regenschreiber.setChecked(True)
        self.dlg.cb_export_rohrprofile.setChecked(True)
        self.dlg.cb_export_speicherkennlinien.setChecked(True)
        self.dlg.cb_export_bodenklassen.setChecked(True)

    def modifyall(self):
        """Aktiviert alle Checkboxen zm Ändern"""

        self.dlg.cb_modify_schaechte.setChecked(True)
        self.dlg.cb_modify_auslaesse.setChecked(True)
        self.dlg.cb_modify_speicher.setChecked(True)
        self.dlg.cb_modify_haltungen.setChecked(True)
        self.dlg.cb_modify_pumpen.setChecked(True)
        self.dlg.cb_modify_wehre.setChecked(True)
        self.dlg.cb_modify_flaechenrw.setChecked(True)
        self.dlg.cb_modify_flaechensw.setChecked(True)
        self.dlg.cb_modify_abflussparameter.setChecked(True)
        self.dlg.cb_modify_regenschreiber.setChecked(True)
        self.dlg.cb_modify_rohrprofile.setChecked(True)
        self.dlg.cb_modify_speicherkennlinien.setChecked(True)
        self.dlg.cb_modify_bodenklassen.setChecked(True)

    def initall(self):
        """Aktiviert alle Checkboxen zm Initialisieren"""

        self.dlg.cb_init_schaechte.setChecked(True)
        self.dlg.cb_init_auslaesse.setChecked(True)
        self.dlg.cb_init_speicher.setChecked(True)
        self.dlg.cb_init_haltungen.setChecked(True)
        self.dlg.cb_init_pumpen.setChecked(True)
        self.dlg.cb_init_wehre.setChecked(True)
        self.dlg.cb_init_flaechenrw.setChecked(True)
        self.dlg.cb_init_flaechensw.setChecked(True)
        self.dlg.cb_init_abflussparameter.setChecked(True)
        self.dlg.cb_init_regenschreiber.setChecked(True)
        self.dlg.cb_init_rohrprofile.setChecked(True)
        self.dlg.cb_init_speicherkennlinien.setChecked(True)
        self.dlg.cb_init_bodenklassen.setChecked(True)

    def exportnone(self):
        """Deaktiviert alle Checkboxen zm Export"""

        self.dlg.cb_export_schaechte.setChecked(False)
        self.dlg.cb_export_auslaesse.setChecked(False)
        self.dlg.cb_export_speicher.setChecked(False)
        self.dlg.cb_export_haltungen.setChecked(False)
        self.dlg.cb_export_pumpen.setChecked(False)
        self.dlg.cb_export_wehre.setChecked(False)
        self.dlg.cb_export_flaechenrw.setChecked(False)
        self.dlg.cb_export_flaechensw.setChecked(False)
        self.dlg.cb_export_abflussparameter.setChecked(False)
        self.dlg.cb_export_regenschreiber.setChecked(False)
        self.dlg.cb_export_rohrprofile.setChecked(False)
        self.dlg.cb_export_speicherkennlinien.setChecked(False)
        self.dlg.cb_export_bodenklassen.setChecked(False)

    def modifynone(self):
        """Deaktiviert alle Checkboxen zm Ändern"""

        self.dlg.cb_modify_schaechte.setChecked(False)
        self.dlg.cb_modify_auslaesse.setChecked(False)
        self.dlg.cb_modify_speicher.setChecked(False)
        self.dlg.cb_modify_haltungen.setChecked(False)
        self.dlg.cb_modify_pumpen.setChecked(False)
        self.dlg.cb_modify_wehre.setChecked(False)
        self.dlg.cb_modify_flaechenrw.setChecked(False)
        self.dlg.cb_modify_flaechensw.setChecked(False)
        self.dlg.cb_modify_abflussparameter.setChecked(False)
        self.dlg.cb_modify_regenschreiber.setChecked(False)
        self.dlg.cb_modify_rohrprofile.setChecked(False)
        self.dlg.cb_modify_speicherkennlinien.setChecked(False)
        self.dlg.cb_modify_bodenklassen.setChecked(False)

    def initnone(self):
        """Deaktiviert alle Checkboxen zm Initialisieren"""

        self.dlg.cb_init_schaechte.setChecked(False)
        self.dlg.cb_init_auslaesse.setChecked(False)
        self.dlg.cb_init_speicher.setChecked(False)
        self.dlg.cb_init_haltungen.setChecked(False)
        self.dlg.cb_init_pumpen.setChecked(False)
        self.dlg.cb_init_wehre.setChecked(False)
        self.dlg.cb_init_flaechenrw.setChecked(False)
        self.dlg.cb_init_flaechensw.setChecked(False)
        self.dlg.cb_init_abflussparameter.setChecked(False)
        self.dlg.cb_init_regenschreiber.setChecked(False)
        self.dlg.cb_init_rohrprofile.setChecked(False)
        self.dlg.cb_init_speicherkennlinien.setChecked(False)
        self.dlg.cb_init_bodenklassen.setChecked(False)

    # -------------------------------------------------------------------------
    # Formularfunktionen

    def countselection(self):
        """Zählt nach Änderung der Auswahlen in den Listen im Formular die Anzahl
        der betroffenen Flächen und Haltungen"""
        liste_teilgebiete = self.listselecteditems(self.dlg.lw_teilgebiete)

        # Zu berücksichtigende Flächen zählen
        auswahl = ''
        if len(liste_teilgebiete) != 0:
            auswahl = " WHERE flaechen.teilgebiet in ('{}')".format(
                "', '".join(liste_teilgebiete))

        sql = u"""SELECT count(*) AS anzahl FROM flaechen{auswahl}""".format(
            auswahl=auswahl)

        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (1) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False
        daten = self.dbQK.fetchone()
        if not (daten is None):
            self.dlg.lf_anzahl_flaechen.setText(str(daten[0]))
        else:
            self.dlg.lf_anzahl_flaechen.setText('0')

        # Zu berücksichtigende Schächte zählen
        auswahl = ''
        if len(liste_teilgebiete) != 0:
            auswahl = " WHERE schaechte.teilgebiet in ('{}')".format(
                "', '".join(liste_teilgebiete))

        sql = """SELECT count(*) AS anzahl FROM schaechte{auswahl}""".format(
            auswahl=auswahl)
        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (2) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False
        daten = self.dbQK.fetchone()
        if not (daten is None):
            self.dlg.lf_anzahl_schaechte.setText(str(daten[0]))
        else:
            self.dlg.lf_anzahl_schaechte.setText('0')

        # Zu berücksichtigende Haltungen zählen
        auswahl = ''
        if len(liste_teilgebiete) != 0:
            auswahl = " WHERE haltungen.teilgebiet in ('{}')".format(
                "', '".join(liste_teilgebiete))

        sql = """SELECT count(*) AS anzahl FROM haltungen{auswahl}""".format(
            auswahl=auswahl)
        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (2) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False
        daten = self.dbQK.fetchone()
        if not (daten is None):
            self.dlg.lf_anzahl_haltungen.setText(str(daten[0]))
        else:
            self.dlg.lf_anzahl_haltungen.setText('0')

    # -------------------------------------------------------------------------
    # Funktion zur Zusammenstellung einer Auswahlliste für eine SQL-Abfrage

    def listselecteditems(self, listWidget):
        """Erstellt eine Liste aus den in einem Auswahllisten-Widget angeklickten Objektnamen

        :param listWidget: String for translation.
        :type listWidget: QListWidgetItem

        :returns: Tuple containing selected teilgebiete
        :rtype: tuple
        """
        items = listWidget.selectedItems()
        liste = []
        for elem in items:
            liste.append(elem.text())
        return liste

    # Ende Eigene Funktionen ---------------------------------------------------

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog

        # Check, ob die relevanten Layer nicht editable sind.
        if len({'flaechen', 'haltungen', 'linkfl', 'tezg', 'schaechte'}
               & get_editable_layers()) > 0:
            iface.messageBar().pushMessage(
                u"Bedienerfehler: ",
                u'Die zu verarbeitenden Layer dürfen nicht im Status "bearbeitbar" sein. Abbruch!',
                level=QgsMessageBar.CRITICAL)
            return False

        # Übernahme der Quelldatenbank:
        # Wenn ein Projekt geladen ist, wird die Quelldatenbank daraus übernommen.
        # Wenn dies nicht der Fall ist, wird die Quelldatenbank aus der
        # json-Datei übernommen.

        database_QKan = ''

        database_QKan, epsg = get_database_QKan()
        if not database_QKan:
            fehlermeldung(
                u"Fehler in k_link",
                u"database_QKan konnte nicht aus den Layern ermittelt werden. Abbruch!"
            )
            logger.error(
                "k_link: database_QKan konnte nicht aus den Layern ermittelt werden. Abbruch!"
            )
            return False

        if database_QKan != '':
            self.dlg.tf_QKanDB.setText(database_QKan)

        # Datenbankverbindung für Abfragen
        self.dbQK = DBConnection(
            dbname=database_QKan
        )  # Datenbankobjekt der QKan-Datenbank zum Lesen
        if self.dbQK is None:
            fehlermeldung(
                "Fehler in QKan_CreateUnbefFl",
                u'QKan-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format(
                    database_QKan))
            iface.messageBar().pushMessage("Fehler in QKan_Import_from_HE", u'QKan-Datenbank {:s} wurde nicht gefunden!\nAbbruch!'.format( \
                database_QKan), level=QgsMessageBar.CRITICAL)
            return None

        # Check, ob alle Teilgebiete in Flächen, Schächten und Haltungen auch in Tabelle "teilgebiete" enthalten

        sql = """INSERT INTO teilgebiete (tgnam)
                SELECT teilgebiet FROM flaechen 
                WHERE teilgebiet IS NOT NULL and
                teilgebiet NOT IN (SELECT tgnam FROM teilgebiete)
                GROUP BY teilgebiet"""
        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (3) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False

        sql = """INSERT INTO teilgebiete (tgnam)
                SELECT teilgebiet FROM haltungen 
                WHERE teilgebiet IS NOT NULL and
                teilgebiet NOT IN (SELECT tgnam FROM teilgebiete)
                GROUP BY teilgebiet"""
        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (4) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False

        sql = """INSERT INTO teilgebiete (tgnam)
                SELECT teilgebiet FROM schaechte 
                WHERE teilgebiet IS NOT NULL and
                teilgebiet NOT IN (SELECT tgnam FROM teilgebiete)
                GROUP BY teilgebiet"""
        try:
            self.dbQK.sql(sql)
        except:
            fehlermeldung(u"QKan_ExportHE (5) SQL-Fehler in SpatiaLite: \n",
                          sql)
            del self.dbQK
            return False

        self.dbQK.commit()

        # Anlegen der Tabelle zur Auswahl der Teilgebiete

        # Zunächst wird die Liste der beim letzten Mal gewählten Teilgebiete aus config gelesen
        liste_teilgebiete = []
        if 'liste_teilgebiete' in self.config:
            liste_teilgebiete = self.config['liste_teilgebiete']

        # Abfragen der Tabelle teilgebiete nach Teilgebieten
        sql = 'SELECT "tgnam" FROM "teilgebiete" GROUP BY "tgnam"'
        self.dbQK.sql(sql)
        daten = self.dbQK.fetchall()
        self.dlg.lw_teilgebiete.clear()

        for ielem, elem in enumerate(daten):
            self.dlg.lw_teilgebiete.addItem(QListWidgetItem(elem[0]))
            try:
                if elem[0] in liste_teilgebiete:
                    self.dlg.lw_teilgebiete.setCurrentRow(ielem)
            except BaseException as err:
                fehlermeldung(
                    u'QKan_ExportHE (6), Fehler in elem = {}\n'.format(
                        str(elem)), err)
        # if len(daten) == 1:
        # self.dlg.lw_teilgebiete.setCurrentRow(0)

        # Ereignis bei Auswahländerung in Liste Teilgebiete

        self.dlg.lw_teilgebiete.itemClicked.connect(self.countselection)
        self.countselection()

        # Formular anzeigen

        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            # Abrufen der ausgewählten Elemente in beiden Listen
            liste_teilgebiete = self.listselecteditems(self.dlg.lw_teilgebiete)

            # Eingaben aus Formular übernehmen
            database_Qkan = self.dlg.tf_QKanDB.text()
            database_HE = self.dlg.tf_heDB_dest.text()
            dbtemplate_HE = self.dlg.tf_heDB_template.text()
            datenbanktyp = 'spatialite'

            check_export = {}
            check_export[
                'export_schaechte'] = self.dlg.cb_export_schaechte.isChecked()
            check_export[
                'export_auslaesse'] = self.dlg.cb_export_auslaesse.isChecked()
            check_export[
                'export_speicher'] = self.dlg.cb_export_speicher.isChecked()
            check_export[
                'export_haltungen'] = self.dlg.cb_export_haltungen.isChecked()
            check_export[
                'export_pumpen'] = self.dlg.cb_export_pumpen.isChecked()
            check_export['export_wehre'] = self.dlg.cb_export_wehre.isChecked()
            check_export[
                'export_flaechenrw'] = self.dlg.cb_export_flaechenrw.isChecked(
                )
            check_export[
                'export_flaechensw'] = self.dlg.cb_export_flaechensw.isChecked(
                )
            check_export[
                'export_abflussparameter'] = self.dlg.cb_export_abflussparameter.isChecked(
                )
            check_export[
                'export_regenschreiber'] = self.dlg.cb_export_regenschreiber.isChecked(
                )
            check_export[
                'export_rohrprofile'] = self.dlg.cb_export_rohrprofile.isChecked(
                )
            check_export[
                'export_speicherkennlinien'] = self.dlg.cb_export_speicherkennlinien.isChecked(
                )
            check_export[
                'export_bodenklassen'] = self.dlg.cb_export_bodenklassen.isChecked(
                )

            check_export[
                'modify_schaechte'] = self.dlg.cb_modify_schaechte.isChecked()
            check_export[
                'modify_auslaesse'] = self.dlg.cb_modify_auslaesse.isChecked()
            check_export[
                'modify_speicher'] = self.dlg.cb_modify_speicher.isChecked()
            check_export[
                'modify_haltungen'] = self.dlg.cb_modify_haltungen.isChecked()
            check_export[
                'modify_pumpen'] = self.dlg.cb_modify_pumpen.isChecked()
            check_export['modify_wehre'] = self.dlg.cb_modify_wehre.isChecked()
            check_export[
                'modify_flaechenrw'] = self.dlg.cb_modify_flaechenrw.isChecked(
                )
            check_export[
                'modify_flaechensw'] = self.dlg.cb_modify_flaechensw.isChecked(
                )
            check_export[
                'modify_abflussparameter'] = self.dlg.cb_modify_abflussparameter.isChecked(
                )
            check_export[
                'modify_regenschreiber'] = self.dlg.cb_modify_regenschreiber.isChecked(
                )
            check_export[
                'modify_rohrprofile'] = self.dlg.cb_modify_rohrprofile.isChecked(
                )
            check_export[
                'modify_speicherkennlinien'] = self.dlg.cb_modify_speicherkennlinien.isChecked(
                )
            check_export[
                'modify_bodenklassen'] = self.dlg.cb_modify_bodenklassen.isChecked(
                )

            check_export[
                'init_schaechte'] = self.dlg.cb_init_schaechte.isChecked()
            check_export[
                'init_auslaesse'] = self.dlg.cb_init_auslaesse.isChecked()
            check_export[
                'init_speicher'] = self.dlg.cb_init_speicher.isChecked()
            check_export[
                'init_haltungen'] = self.dlg.cb_init_haltungen.isChecked()
            check_export['init_pumpen'] = self.dlg.cb_init_pumpen.isChecked()
            check_export['init_wehre'] = self.dlg.cb_init_wehre.isChecked()
            check_export[
                'init_flaechenrw'] = self.dlg.cb_init_flaechenrw.isChecked()
            check_export[
                'init_flaechensw'] = self.dlg.cb_init_flaechensw.isChecked()
            check_export[
                'init_abflussparameter'] = self.dlg.cb_init_abflussparameter.isChecked(
                )
            check_export[
                'init_regenschreiber'] = self.dlg.cb_init_regenschreiber.isChecked(
                )
            check_export[
                'init_rohrprofile'] = self.dlg.cb_init_rohrprofile.isChecked()
            check_export[
                'init_speicherkennlinien'] = self.dlg.cb_init_speicherkennlinien.isChecked(
                )
            check_export[
                'init_bodenklassen'] = self.dlg.cb_init_bodenklassen.isChecked(
                )

            check_export[
                'export_difftezg'] = self.dlg.cb_export_difftezg.isChecked()
            check_export[
                'export_verschneidung'] = self.dlg.cb_export_verschneidung.isChecked(
                )

            # Konfigurationsdaten schreiben
            self.config['database_HE'] = database_HE
            self.config['dbtemplate_HE'] = dbtemplate_HE
            self.config['database_Qkan'] = database_Qkan
            self.config['datenbanktyp'] = datenbanktyp
            self.config['liste_teilgebiete'] = liste_teilgebiete
            for el in check_export:
                self.config[el] = check_export[el]

            with codecs.open(self.configfil, 'w') as fileconfig:
                # logger.debug(u"Config-Dictionary: {}".format(self.config))
                fileconfig.write(json.dumps(self.config))

            exportKanaldaten(iface, database_HE, dbtemplate_HE, database_Qkan,
                             liste_teilgebiete, 0.1, datenbanktyp,
                             check_export)
Пример #49
0
class Plugin:
    """The QGIS interface implementation for the InaSAFE plugin.

    This class acts as the 'glue' between QGIS and our custom logic.
    It creates a toolbar and menubar entry and launches the InaSAFE user
    interface if these are activated.
    """
    def __init__(self, iface):
        """Class constructor.

        On instantiation, the plugin instance will be assigned a copy
        of the QGIS iface object which will allow this plugin to access and
        manipulate the running QGIS instance that spawned it.

        :param iface:Quantum GIS iface instance. This instance is
            automatically passed to the plugin by QGIS when it loads the
            plugin.
        :type iface: QGisAppInterface
        """

        # Save reference to the QGIS interface
        self.iface = iface
        self.dock_widget = None
        self.action_import_dialog = None
        self.action_save_scenario = None
        self.action_batch_runner = None
        self.action_shake_converter = None
        self.action_minimum_needs = None
        self.key_action = None
        self.action_function_browser = None
        self.action_options = None
        self.action_keywords_dialog = None
        self.translator = None
        self.toolbar = None
        self.actions = []  # list of all QActions we create for InaSAFE
        self.action_dock = None
        #print self.tr('InaSAFE')
        custom_logging.setup_logger()
        # For enable/disable the keyword editor icon
        self.iface.currentLayerChanged.connect(self.layer_changed)

    #noinspection PyArgumentList
    def change_i18n(self, new_locale):
        """Change internationalisation for the plugin.

        Override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        :param new_locale: the new locale i.e. 'id', 'af', etc.
        :type new_locale: str
        :raises: TranslationLoadException
        """

        os.environ['LANG'] = str(new_locale)

        LOGGER.debug('%s %s %s' %
                     (new_locale, QLocale.system().name(), os.environ['LANG']))

        root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        translation_path = os.path.join(root, 'safe_qgis', 'i18n',
                                        'inasafe_' + str(new_locale) + '.qm')

        if os.path.exists(translation_path):
            self.translator = QTranslator()
            result = self.translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % new_locale
                raise TranslationLoadError(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' %
                     (translation_path, os.path.exists(translation_path)))

    # 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('Plugin', message)

    def add_action(self, action, add_to_toolbar=True):
        """Add a toolbar icon to the InaSAFE toolbar.

        :param action: The action that should be added to the toolbar.
        :type action: QAction

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the InaSAFE toolbar. Defaults to True.
        :type add_to_toolbar: bool

        """
        # store in the class list of actions for easy plugin unloading
        self.actions.append(action)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), action)
        if add_to_toolbar:
            self.toolbar.addAction(action)

    # noinspection PyPep8Naming
    def initGui(self):
        """Gui initialisation procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from initGui!

        This method is called by QGIS and should be used to set up
        any graphical user interface elements that should appear in QGIS by
        default (i.e. before the user performs any explicit action with the
        plugin).
        """
        self.toolbar = self.iface.addToolBar('InaSAFE')
        self.toolbar.setObjectName('InaSAFEToolBar')
        # Import dock here as it needs to be imported AFTER i18n is set up
        from safe_qgis.widgets.dock import Dock
        self.dock_widget = None
        #--------------------------------------
        # Create action for plugin dockable window (show/hide)
        #--------------------------------------
        # pylint: disable=W0201
        self.action_dock = QAction(QIcon(':/plugins/inasafe/icon.svg'),
                                   self.tr('Toggle InaSAFE Dock'),
                                   self.iface.mainWindow())
        self.action_dock.setObjectName('InaSAFEDockToggle')
        self.action_dock.setStatusTip(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setCheckable(True)
        self.action_dock.setChecked(True)
        self.action_dock.triggered.connect(self.toggle_dock_visibility)
        self.add_action(self.action_dock)

        #--------------------------------------
        # Create action for keywords editor
        #--------------------------------------
        self.action_keywords_dialog = QAction(
            QIcon(':/plugins/inasafe/show-keyword-editor.svg'),
            self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow())
        self.action_keywords_dialog.setStatusTip(
            self.tr('Open InaSAFE keywords editor'))
        self.action_keywords_dialog.setWhatsThis(
            self.tr('Open InaSAFE keywords editor'))
        self.action_keywords_dialog.setEnabled(False)

        self.action_keywords_dialog.triggered.connect(
            self.show_keywords_editor)

        self.add_action(self.action_keywords_dialog)

        #--------------------------------------
        # Create action for options dialog
        #--------------------------------------
        self.action_options = QAction(
            QIcon(':/plugins/inasafe/configure-inasafe.svg'),
            self.tr('InaSAFE Options'), self.iface.mainWindow())
        self.action_options.setStatusTip(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.setWhatsThis(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.triggered.connect(self.show_options)

        self.add_action(self.action_options)

        #--------------------------------------
        # Create action for impact functions doc dialog
        #--------------------------------------
        self.action_function_browser = QAction(
            QIcon(':/plugins/inasafe/show-impact-functions.svg'),
            self.tr('InaSAFE Impact Functions Browser'),
            self.iface.mainWindow())
        self.action_function_browser.setStatusTip(
            self.tr('Open InaSAFE Impact Functions Browser'))
        self.action_function_browser.setWhatsThis(
            self.tr('Open InaSAFE Impact Functions Browser'))
        self.action_function_browser.triggered.connect(
            self.show_function_browser)

        self.add_action(self.action_function_browser)

        # Short cut for Open Impact Functions Doc
        self.key_action = QAction("Test Plugin", self.iface.mainWindow())
        self.iface.registerMainWindowAction(self.key_action, "F7")
        self.key_action.triggered.connect(self.shortcut_f7)

        #---------------------------------------
        # Create action for minimum needs dialog
        #---------------------------------------
        self.action_minimum_needs = QAction(
            QIcon(':/plugins/inasafe/show-minimum-needs.svg'),
            self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow())
        self.action_minimum_needs.setStatusTip(
            self.tr('Open InaSAFE minimum needs tool'))
        self.action_minimum_needs.setWhatsThis(
            self.tr('Open InaSAFE minimum needs tool'))
        self.action_minimum_needs.triggered.connect(self.show_minimum_needs)

        self.add_action(self.action_minimum_needs)

        #---------------------------------------
        # Create action for converter dialog
        #---------------------------------------
        self.action_shake_converter = QAction(
            QIcon(':/plugins/inasafe/show-converter-tool.svg'),
            self.tr('InaSAFE Converter'), self.iface.mainWindow())
        self.action_shake_converter.setStatusTip(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.setWhatsThis(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.triggered.connect(
            self.show_shakemap_importer)

        self.add_action(self.action_shake_converter)

        #---------------------------------------
        # Create action for batch runner dialog
        #---------------------------------------
        self.action_batch_runner = QAction(
            QIcon(':/plugins/inasafe/show-batch-runner.svg'),
            self.tr('InaSAFE Batch Runner'), self.iface.mainWindow())
        self.action_batch_runner.setStatusTip(
            self.tr('Open InaSAFE Batch Runner'))
        self.action_batch_runner.setWhatsThis(
            self.tr('Open InaSAFE Batch Runner'))
        self.action_batch_runner.triggered.connect(self.show_batch_runner)

        self.add_action(self.action_batch_runner)

        #---------------------------------------
        # Create action for batch runner dialog
        #---------------------------------------
        self.action_save_scenario = QAction(
            QIcon(':/plugins/inasafe/save-as-scenario.svg'),
            self.tr('Save current scenario'), self.iface.mainWindow())

        message = self.tr('Save current scenario to text file')
        self.action_save_scenario.setStatusTip(message)
        self.action_save_scenario.setWhatsThis(message)
        # noinspection PyUnresolvedReferences
        self.action_save_scenario.triggered.connect(self.save_scenario)
        self.add_action(self.action_save_scenario)

        #--------------------------------------
        # Create action for import OSM Dialog
        #--------------------------------------
        self.action_import_dialog = QAction(
            QIcon(':/plugins/inasafe/show-osm-download.svg'),
            self.tr('InaSAFE OpenStreetMap Downloader'),
            self.iface.mainWindow())
        self.action_import_dialog.setStatusTip(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        self.action_import_dialog.setWhatsThis(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        self.action_import_dialog.triggered.connect(self.show_osm_downloader)

        self.add_action(self.action_import_dialog)

        #--------------------------------------
        # Create action for impact layer merge Dialog
        #--------------------------------------
        self.action_impact_merge_dlg = QAction(
            QIcon(':/plugins/inasafe/show-impact-merge.svg'),
            self.tr('InaSAFE Impact Layer Merge'), self.iface.mainWindow())
        self.action_impact_merge_dlg.setStatusTip(
            self.tr('InaSAFE Impact Layer Merge'))
        self.action_impact_merge_dlg.setWhatsThis(
            self.tr('InaSAFE Impact Layer Merge'))
        self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge)

        self.add_action(self.action_impact_merge_dlg)

        #--------------------------------------
        # create dockwidget and tabify it with the legend
        #--------------------------------------
        self.dock_widget = Dock(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
        myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend')

        if myLegendTab:
            self.iface.mainWindow().tabifyDockWidget(myLegendTab,
                                                     self.dock_widget)
            self.dock_widget.raise_()

        #
        # Hook up a slot for when the dock is hidden using its close button
        # or  view-panels
        #
        self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action)

        # pylint: disable=W0201

    # noinspection PyMethodMayBeStatic
    def clear_modules(self):
        """Unload inasafe functions and try to return QGIS to before InaSAFE.
        """
        from safe.impact_functions import core

        core.unload_plugins()
        # next lets force remove any inasafe related modules
        modules = []
        for myModule in sys.modules:
            if 'inasafe' in myModule:
                # Check if it is really one of our modules i.e. exists in the
                #  plugin directory
                tokens = myModule.split('.')
                path = ''
                for myToken in tokens:
                    path += os.path.sep + myToken
                parent = os.path.abspath(
                    os.path.join(__file__, os.path.pardir, os.path.pardir))
                full_path = os.path.join(parent, path + '.py')
                if os.path.exists(os.path.abspath(full_path)):
                    LOGGER.debug('Removing: %s' % myModule)
                    modules.append(myModule)
        for myModule in modules:
            del (sys.modules[myModule])
        for myModule in sys.modules:
            if 'inasafe' in myModule:
                print myModule

        # Lets also clean up all the path additions that were made
        package_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        LOGGER.debug('Path to remove: %s' % package_path)
        # We use a list comprehension to ensure duplicate entries are removed
        LOGGER.debug(sys.path)
        sys.path = [y for y in sys.path if package_path not in y]
        LOGGER.debug(sys.path)

    def unload(self):
        """GUI breakdown procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from unload!

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.
        """
        # Remove the plugin menu item and icon
        for myAction in self.actions:
            self.iface.removePluginMenu(self.tr('InaSAFE'), myAction)
            self.iface.removeToolBarIcon(myAction)
        self.iface.mainWindow().removeDockWidget(self.dock_widget)
        self.iface.mainWindow().removeToolBar(self.toolbar)
        self.dock_widget.setVisible(False)
        self.dock_widget.destroy()
        self.iface.currentLayerChanged.disconnect(self.layer_changed)

        self.clear_modules()

    def toggle_inasafe_action(self, checked):
        """Check or uncheck the toggle inaSAFE toolbar button.

        This slot is called when the user hides the inaSAFE panel using its
        close button or using view->panels.

        :param checked: True if the dock should be shown, otherwise False.
        :type checked: bool
        """

        self.action_dock.setChecked(checked)

    # Run method that performs all the real work
    def toggle_dock_visibility(self):
        """Show or hide the dock widget."""
        if self.dock_widget.isVisible():
            self.dock_widget.setVisible(False)
        else:
            self.dock_widget.setVisible(True)
            self.dock_widget.raise_()

    def show_minimum_needs(self):
        """Show the minimum needs dialog."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.minimum_needs import MinimumNeeds

        dialog = MinimumNeeds(self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_impact_merge(self):
        """Show the impact layer merge dialog."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.impact_merge_dialog import ImpactMergeDialog

        dialog = ImpactMergeDialog(self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_options(self):
        """Show the options dialog."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.options_dialog import OptionsDialog

        dialog = OptionsDialog(self.iface, self.dock_widget,
                               self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_keywords_editor(self):
        """Show the keywords editor."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.keywords_dialog import KeywordsDialog

        # Next block is a fix for #776
        if self.iface.activeLayer() is None:
            return

        try:
            keyword_io = KeywordIO()
            keyword_io.read_keywords(self.iface.activeLayer())
        except UnsupportedProviderError:
            # noinspection PyUnresolvedReferences,PyCallByClass
            QMessageBox.warning(
                None, self.tr('Unsupported layer type'),
                self.tr('The layer you have selected cannot be used for '
                        'analysis because its data type is unsupported.'))
            return
        # End of fix for #776
        # Fix for #793
        except NoKeywordsFoundError:
            # we will create them from scratch in the dialog
            pass
        # End of fix for #793

        dialog = KeywordsDialog(self.iface.mainWindow(), self.iface,
                                self.dock_widget)
        dialog.exec_()  # modal

    def show_function_browser(self):
        """Show the impact function browser tool."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.function_browser import FunctionBrowser

        dialog = FunctionBrowser(self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_shakemap_importer(self):
        """Show the converter dialog."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.shakemap_importer import ShakemapImporter

        dialog = ShakemapImporter(self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_osm_downloader(self):
        """Show the OSM buildings downloader dialog."""
        from safe_qgis.tools.osm_downloader import OsmDownloader

        dialog = OsmDownloader(self.iface.mainWindow(), self.iface)
        dialog.exec_()  # modal

    def show_batch_runner(self):
        """Show the batch runner dialog."""
        from safe_qgis.batch.batch_dialog import BatchDialog

        dialog = BatchDialog(parent=self.iface.mainWindow(),
                             iface=self.iface,
                             dock=self.dock_widget)
        dialog.exec_()  # modal

    def save_scenario(self):
        """Save current scenario to text file,"""
        self.dock_widget.save_current_scenario()

    def layer_changed(self, layer):
        """Enable or disable keywords editor icon when active layer changes.
        :param layer: The layer that is now active.
        :type layer: QgsMapLayer
        """
        if layer is None:
            self.action_keywords_dialog.setEnabled(False)
        else:
            self.action_keywords_dialog.setEnabled(True)

    def shortcut_f7(self):
        """Executed when user press F7 - will show the shakemap importer."""
        self.show_shakemap_importer()
Пример #50
0
    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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ExportToHE_{}.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 = ExportToHEDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Export to HE')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'ExportToHE')
        self.toolbar.setObjectName(u'ExportToHE')

        # Anfang Eigene Funktionen -------------------------------------------------
        # (jh, 08.02.2017)

        logger.info('\n\nQKan_ExportHE initialisiert...')

        # --------------------------------------------------------------------------
        # Pfad zum Arbeitsverzeichnis sicherstellen
        wordir = os.path.join(site.getuserbase(), 'qkan')

        if not os.path.isdir(wordir):
            os.makedirs(wordir)

        # --------------------------------------------------------------------------
        # Konfigurationsdatei qkan.json lesen
        #

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with codecs.open(self.configfil, 'r', 'utf-8') as fileconfig:
                self.config = json.loads(fileconfig.read().replace('\\', '/'))
        else:
            self.config['database_HE'] = ''
            # Vorlagedatenbank nur für den Fall, dass der Anwender keine eigene Vorlage erstellen will
            self.config['dbtemplate_HE'] = os.path.join(
                os.path.dirname(__file__), "templates", "itwh.idbf")
            self.config['database_QKan'] = ''
            with codecs.open(self.configfil, 'w', 'utf-8') as fileconfig:
                fileconfig.write(json.dumps(self.config))

        # Standard für Suchverzeichnis festlegen
        project = QgsProject.instance()
        self.default_dir = os.path.dirname(project.fileName())

        if 'database_QKan' in self.config:
            database_QKan = self.config['database_QKan']
        else:
            database_QKan = ''
        self.dlg.tf_QKanDB.setText(database_QKan)
        self.dlg.pb_selectQKanDB.clicked.connect(self.selectFile_QKanDB)

        if 'database_HE' in self.config:
            database_HE = self.config['database_HE']
        else:
            database_HE = ''
        self.dlg.tf_heDB_dest.setText(database_HE)
        self.dlg.pb_selectHeDB_dest.clicked.connect(self.selectFile_HeDB_dest)

        if 'dbtemplate_HE' in self.config:
            dbtemplate_HE = self.config['dbtemplate_HE']
        else:
            dbtemplate_HE = ''
        self.dlg.tf_heDB_template.setText(dbtemplate_HE)
        self.dlg.pb_selectHeDB_template.clicked.connect(
            self.selectFile_HeDB_template)

        if 'datenbanktyp' in self.config:
            datenbanktyp = self.config['datenbanktyp']
        else:
            datenbanktyp = 'spatialite'
            pass  # Es gibt noch keine Wahlmöglichkeit

        self.dlg.pb_exportall.clicked.connect(self.exportall)
        self.dlg.pb_modifyall.clicked.connect(self.modifyall)
        self.dlg.pb_initall.clicked.connect(self.initall)
        self.dlg.pb_exportnone.clicked.connect(self.exportnone)
        self.dlg.pb_modifynone.clicked.connect(self.modifynone)
        self.dlg.pb_initnone.clicked.connect(self.initnone)

        # Auswahl der zu exportierenden Tabellen ----------------------------------------------

        # Eigene Funktion für die zahlreichen Checkboxen

        def cb_set(name, cbox, default):
            if name in self.config:
                checked = self.config[name]
            else:
                checked = default
            cbox.setChecked(checked)
            return checked

        export_schaechte = cb_set('export_schaechte',
                                  self.dlg.cb_export_schaechte, True)
        export_auslaesse = cb_set('export_auslaesse',
                                  self.dlg.cb_export_auslaesse, True)
        export_speicher = cb_set('export_speicher',
                                 self.dlg.cb_export_speicher, True)
        export_haltungen = cb_set('export_haltungen',
                                  self.dlg.cb_export_haltungen, True)
        export_pumpen = cb_set('export_pumpen', self.dlg.cb_export_pumpen,
                               False)
        export_wehre = cb_set('export_wehre', self.dlg.cb_export_wehre, False)
        export_flaechenrw = cb_set('export_flaechenrw',
                                   self.dlg.cb_export_flaechenrw, True)
        export_flaechensw = cb_set('export_flaechensw',
                                   self.dlg.cb_export_flaechensw, True)
        export_abflussparameter = cb_set('export_abflussparameter',
                                         self.dlg.cb_export_abflussparameter,
                                         True)
        export_regenschreiber = cb_set('export_regenschreiber',
                                       self.dlg.cb_export_regenschreiber,
                                       False)
        export_rohrprofile = cb_set('export_rohrprofile',
                                    self.dlg.cb_export_rohrprofile, False)
        export_speicherkennlinien = cb_set(
            'export_speicherkennlinien', self.dlg.cb_export_speicherkennlinien,
            False)
        export_bodenklassen = cb_set('export_bodenklassen',
                                     self.dlg.cb_export_bodenklassen, False)

        modify_schaechte = cb_set('modify_schaechte',
                                  self.dlg.cb_modify_schaechte, False)
        modify_auslaesse = cb_set('modify_auslaesse',
                                  self.dlg.cb_modify_auslaesse, False)
        modify_speicher = cb_set('modify_speicher',
                                 self.dlg.cb_modify_speicher, False)
        modify_haltungen = cb_set('modify_haltungen',
                                  self.dlg.cb_modify_haltungen, False)
        modify_pumpen = cb_set('modify_pumpen', self.dlg.cb_modify_pumpen,
                               False)
        modify_wehre = cb_set('modify_wehre', self.dlg.cb_modify_wehre, False)
        modify_flaechenrw = cb_set('modify_flaechenrw',
                                   self.dlg.cb_modify_flaechenrw, False)
        modify_flaechensw = cb_set('modify_flaechensw',
                                   self.dlg.cb_modify_flaechensw, False)
        modify_abflussparameter = cb_set('modify_abflussparameter',
                                         self.dlg.cb_modify_abflussparameter,
                                         False)
        modify_regenschreiber = cb_set('modify_regenschreiber',
                                       self.dlg.cb_modify_regenschreiber,
                                       False)
        modify_rohrprofile = cb_set('modify_rohrprofile',
                                    self.dlg.cb_modify_rohrprofile, False)
        modify_speicherkennlinien = cb_set(
            'modify_speicherkennlinien', self.dlg.cb_modify_speicherkennlinien,
            False)
        modify_bodenklassen = cb_set('modify_bodenklassen',
                                     self.dlg.cb_modify_bodenklassen, False)

        init_schaechte = cb_set('init_schaechte', self.dlg.cb_init_schaechte,
                                False)
        init_auslaesse = cb_set('init_auslaesse', self.dlg.cb_init_auslaesse,
                                False)
        init_speicher = cb_set('init_speicher', self.dlg.cb_init_speicher,
                               False)
        init_haltungen = cb_set('init_haltungen', self.dlg.cb_init_haltungen,
                                False)
        init_pumpen = cb_set('init_pumpen', self.dlg.cb_init_pumpen, False)
        init_wehre = cb_set('init_wehre', self.dlg.cb_init_wehre, False)
        init_flaechenrw = cb_set('init_flaechenrw',
                                 self.dlg.cb_init_flaechenrw, False)
        init_flaechensw = cb_set('init_flaechensw',
                                 self.dlg.cb_init_flaechensw, False)
        init_abflussparameter = cb_set('init_abflussparameter',
                                       self.dlg.cb_init_abflussparameter,
                                       False)
        init_regenschreiber = cb_set('init_regenschreiber',
                                     self.dlg.cb_init_regenschreiber, False)
        init_rohrprofile = cb_set('init_rohrprofile',
                                  self.dlg.cb_init_rohrprofile, False)
        init_speicherkennlinien = cb_set('init_speicherkennlinien',
                                         self.dlg.cb_init_speicherkennlinien,
                                         False)
        init_bodenklassen = cb_set('init_bodenklassen',
                                   self.dlg.cb_init_bodenklassen, False)

        export_difftezg = cb_set('export_difftezg',
                                 self.dlg.cb_export_difftezg, True)
        export_verschneidung = cb_set('export_verschneidung',
                                      self.dlg.cb_export_verschneidung, True)
Пример #51
0
class TabRenamer:
    """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__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'TabRenamer_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Tab Renamer')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'TabRenamer')
        self.toolbar.setObjectName(u'TabRenamer')

        #path เริ่มต้น
        self.path = '/'

    # 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('TabRenamer', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = TabRenamerDialog()

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        #เชื่อมปุ่มกับช่องคำสั่งเปิด File browser
        self.dlg.pushButton.clicked.connect(self.select_output_file)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/TabRenamer/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Rename Tab'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Tab Renamer'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #คำสั่งเลือกไฟล์
    def select_output_file(self):
        #เปิดไฟล์ Browse
        #ช่องแรกช่างแม่ง ช่องสองชื่อTitle ช่องสามPathเริ่มต้น(ตอนแรกเป็น '/' สร้างไว้ข้างบน) ช่องสี่เลือกสกุลไฟล์
        #เลือกไฟล์เสร็จเก็บเข้าตัวแปล filenames
        filenames = QFileDialog.getOpenFileNames(self.dlg,
                                                 "Select tab files  ",
                                                 self.path, '*.tab')

        #เช็คว่ามีไฟล์รึเปล่า
        if (len(filenames) > 0):
            #save path ก่อนหน้า
            self.path = QFileInfo(filenames[0]).path()

            #format ชื่อไฟล์ใหม่โดยเอาชื่อไฟล์มาต่อกัน คั่นด้วย ;
            filenames_string = ""
            for filename in filenames:
                filenames_string += filename + ";"
            self.dlg.lineEdit.setText(filenames_string)

    #คำสั่งทำงานตอนเปิดปลั๊กอิน
    def run(self):
        """Run method that performs all the real work"""
        #import ชื่อไฟล์ที่จะเปลี่ยน
        import db_file_names
        #เคลียร์ช่อง path
        self.dlg.lineEdit.clear()
        # เคลียร์combobox
        self.dlg.comboBox.clear()
        # นำชื่อไฟล์ไปใส่ comboBox
        self.dlg.comboBox.addItems(db_file_names.file_name_lists)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # ทำงานเมื่อกด OK
        if result:
            # ไปดึงชื่อไฟล์มา
            filenames = self.dlg.lineEdit.text()

            # เช็คว่าชื่อไหนถูกเลือก
            selectedNameIndex = self.dlg.comboBox.currentIndex()
            new_name = db_file_names.file_name_lists[selectedNameIndex]

            #วน for แต่ละไฟล์ที่แยกด้วย semicolon
            for f in filenames.split(";"):
                #ตัดช่องว่างทิ้ง
                if (f == ""):
                    break

                #เปิดไฟล์
                file = open(f, "r")
                #อ่านไฟล์เก็บใส่ตัวแปร txt
                txt = file.read()
                #แยกบรรทัดเก็บใส่ array
                lines = txt.splitlines()

                #ประกาศชื่อ Column ว่างเปล่าไว้
                name_of_column = None

                #วนหาชื่อ Column
                #index คือจำนวนบรรทัด
                index = 0
                for line in lines:
                    # หาบรรทัดที่มีคำว่า Fields 1
                    if ("Fields 1" in line):
                        # เอาบรรทัดถัดไป
                        line_contain_name = lines[index + 1]

                        #เอาชือมันมาจากคำแรกของบรรทัดมา
                        name_of_column = line_contain_name.split()[0]

                        #เขียนชื่อทับอันเก่า(ยังไม่ใช่เขียนใส่ไฟล์จริง)
                        txt = txt.replace(name_of_column, new_name)
                        break
                    index += 1
                #ปิดการอ่านไฟล์
                file.close()

                if (name_of_column != None):
                    #เปิดไฟล์
                    file = open(f, "w")
                    #ลบไฟล์เก่าทิ้ง
                    file.truncate()
                    #เขียนทับ
                    file.write(txt)
                    #ปิดการเขียนไฟล์
                    file.close()
Пример #52
0
class PolygonsParallelToLineAlgorithm(GeoAlgorithm):

    OUTPUT_LAYER = 'OUTPUT_LAYER'
    LINE_LAYER = 'LINE_LAYER'
    POLYGON_LAYER = 'POLYGON_LAYER'
    SELECTED = 'SELECTED'
    WRITE_SELECTED = 'WRITE_SELECTED'
    LONGEST = 'LONGEST'
    MULTI = 'MULTI'
    DISTANCE = 'DISTANCE'
    ANGLE = 'ANGLE'
    COLUMN_NAME = '_rotated'

    def __init__(self):
        self._translateUi()
        GeoAlgorithm.__init__(self)

    def _translateUi(self):
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(os.path.dirname(__file__), 'i18n',
                                   'pptl_{}.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)

    def getIcon(self):
        path = os.path.join(os.path.dirname(__file__), "icons", "icon.png")
        return QIcon(path)

    def tr(self, message):
        className = self.__class__.__name__
        return QCoreApplication.translate(className, message)

    def defineCharacteristics(self):
        # The name that the user will see in the toolbox
        self.name = self.tr('Polygons parallel to line')

        # The branch of the toolbox under which the algorithm will appear
        self.group = self.tr('Algorithms for vector layers')

        self.addOutput(
            OutputVector(self.OUTPUT_LAYER,
                         'Output layer with rotated polygons'))
        self.addParameter(
            ParameterVector(self.LINE_LAYER, self.tr('Select line layer'),
                            [ParameterVector.VECTOR_TYPE_LINE]))
        self.addParameter(
            ParameterVector(self.POLYGON_LAYER,
                            self.tr('Select polygon layer'),
                            [ParameterVector.VECTOR_TYPE_POLYGON]))
        self.addParameter(
            ParameterBoolean(self.SELECTED,
                             self.tr('Rotate only selected polygons')))
        self.addParameter(
            ParameterBoolean(
                self.WRITE_SELECTED,
                self.tr('Save only selected'),
            ))
        self.addParameter(
            ParameterBoolean(
                self.LONGEST,
                self.tr("Rotate by longest edge if both angles between "
                        "polygon edges and line segment <= 'Angle value'")))
        self.addParameter(
            ParameterBoolean(self.MULTI,
                             self.tr("Do not rotate multipolygons")))
        self.addParameter(
            ParameterNumber(self.DISTANCE, self.tr("Distance from line")))
        self.addParameter(
            ParameterNumber(self.ANGLE, self.tr("Angle value"), maxValue=89.9))

    def processAlgorithm(self, progress):
        self._operationCounter = 0
        self._progress = progress
        self._getInputValues()
        self._lineLayer = dataobjects.getObjectFromUri(self._lineLayerName)
        self._polygonLayer = dataobjects.getObjectFromUri(
            self._polygonLayerName)
        self._createLineSpatialIndex()
        self._validatePolygonLayer()
        self._addAttribute()
        self._linesDict = {x.id(): x for x in self._lineLayer.getFeatures()}
        self._rotateAndWriteSelectedOrAll(self._getWriter())
        self._deleteAttribute()

    def _getInputValues(self):
        self._lineLayerName = self.getParameterValue(self.LINE_LAYER)
        self._polygonLayerName = self.getParameterValue(self.POLYGON_LAYER)
        self._isSelected = self.getParameterValue(self.SELECTED)
        self._isWriteSelected = self.getParameterValue(self.WRITE_SELECTED)
        self._byLongest = self.getParameterValue(self.LONGEST)
        self._multi = self.getParameterValue(self.MULTI)
        self._distance = self.getParameterValue(self.DISTANCE)
        self._angle = self.getParameterValue(self.ANGLE)
        self._outputLayer = self.getOutputValue(self.OUTPUT_LAYER)

    def _createLineSpatialIndex(self):
        self._index = QgsSpatialIndex()
        for line in self._lineLayer.getFeatures():
            self._index.insertFeature(line)

    def _validatePolygonLayer(self):
        self._totalNumber = self._polygonLayer.featureCount()
        if not self._totalNumber:
            raise GeoAlgorithmExecutionException(
                self.tr("Layer does not have any polygons"))
        if self._isWriteSelected and not self._isSelected:
            raise GeoAlgorithmExecutionException(
                self.tr('You have chosen "Save only selected" without '
                        '"Rotate only selected polygons"'))
        if self._isSelected:
            self._totalNumber = self._polygonLayer.selectedFeatureCount()
            if not self._totalNumber:
                raise GeoAlgorithmExecutionException(
                    self.tr('You have chosen "Rotate only selected polygons" '
                            'but there are no selected'))

    def _addAttribute(self):
        for attr in self._polygonLayer.pendingFields():
            if self.COLUMN_NAME == attr.name():
                if attr.isNumeric():
                    break
                else:
                    self._deleteAttribute()
        else:
            self._polygonLayer.dataProvider().addAttributes(
                [QgsField(self.COLUMN_NAME, QVariant.Int)])
            self._polygonLayer.updateFields()

    def _deleteAttribute(self):
        for i, attr in enumerate(self._polygonLayer.pendingFields()):
            if attr.name() == self.COLUMN_NAME:
                self._polygonLayer.dataProvider().deleteAttributes([i])
                self._polygonLayer.updateFields()

    def _getWriter(self):
        settings = QSettings()
        systemEncoding = settings.value('/UI/encoding', 'System')
        provider = self._polygonLayer.dataProvider()
        return QgsVectorFileWriter(self._outputLayer, systemEncoding,
                                   provider.fields(), provider.geometryType(),
                                   provider.crs())

    def _rotateAndWriteSelectedOrAll(self, writer):
        if self._isSelected:
            self._rotateAndWriteSeleced(writer)
        else:
            polygons = self._polygonLayer.getFeatures()
            for polygon in polygons:
                self._rotateAndWritePolygon(polygon, writer)

    def _rotateAndWriteSeleced(self, writer):
        if self._isWriteSelected:
            for polygon in self._polygonLayer.selectedFeatures():
                self._rotateAndWritePolygon(polygon, writer)
        else:
            selectedPolygonsIds = self._polygonLayer.selectedFeaturesIds()
            for p in self._polygonLayer.getFeatures():
                if p.id() in selectedPolygonsIds:
                    self._rotateAndWritePolygon(p, writer)
                else:
                    writer.addFeature(p)

    def _rotateAndWritePolygon(self, polygon, writer):
        self._progressBar()
        self._p = polygon
        self._initiateRotation()
        writer.addFeature(self._p)

    def _progressBar(self):
        self._operationCounter += 1
        currentPercentage = self._operationCounter / self._totalNumber * 100
        self._progress.setPercentage(round(currentPercentage))

    def _initiateRotation(self):
        self._getNearestLine()
        dist = self._nearLine.geometry().distance(self._p.geometry())
        if not self._distance or dist <= self._distance:
            self._simpleOrMultiGeometry()

    def _getNearestLine(self):
        self._center = self._p.geometry().centroid()
        nearId = self._index.nearestNeighbor(self._center.asPoint(), 1)
        self._nearLine = self._linesDict.get(nearId[0])

    def _simpleOrMultiGeometry(self):
        isMulti = self._p.geometry().isMultipart()
        if isMulti and not self._multi:
            dct = {}
            mPolygonVertexes = self._p.geometry().asMultiPolygon()
            for i, part in enumerate(mPolygonVertexes):
                minDistance, vertexIndex = self._getNearestVertex(part[0])
                dct[(i, vertexIndex)] = minDistance
            i, vertexIndex = min(dct, key=dct.get)
            self._nearestEdges(mPolygonVertexes[i][0], vertexIndex)
        elif not isMulti:
            polygonVertexes = self._p.geometry().asPolygon()[0][:-1]
            vertexIndex = self._getNearestVertex(polygonVertexes)[1]
            self._nearestEdges(polygonVertexes, vertexIndex)

    def _getNearestVertex(self, polygonVertexes):
        vertexToSegmentDict = {}
        for vertex in polygonVertexes:
            vertexGeom = QgsGeometry.fromPoint(vertex)
            vertexToSegment = vertexGeom.distance(self._nearLine.geometry())
            vertexToSegmentDict[vertexToSegment] = vertex

        minDistance = min(vertexToSegmentDict.keys())
        self._nearestVertex = vertexToSegmentDict[minDistance]
        vertexIndex = polygonVertexes.index(self._nearestVertex)
        return minDistance, vertexIndex

    def _nearestEdges(self, polygonVertexes, vertexIndex):
        # if vertex is first
        if vertexIndex == 0:
            self._line1 = QgsGeometry.fromPolyline(
                [polygonVertexes[0], polygonVertexes[1]])
            self._line2 = QgsGeometry.fromPolyline(
                [polygonVertexes[0], polygonVertexes[-1]])

        # if vertex is last
        elif vertexIndex == len(polygonVertexes) - 1:
            self._line1 = QgsGeometry.fromPolyline(
                [polygonVertexes[-1], polygonVertexes[0]])
            self._line2 = QgsGeometry.fromPolyline(
                [polygonVertexes[-1], polygonVertexes[-2]])
        else:
            self._line1 = QgsGeometry.fromPolyline([
                polygonVertexes[vertexIndex], polygonVertexes[vertexIndex + 1]
            ])
            self._line2 = QgsGeometry.fromPolyline([
                polygonVertexes[vertexIndex], polygonVertexes[vertexIndex - 1]
            ])

        line1Azimuth = self._line1.asPolyline()[0].azimuth(
            self._line1.asPolyline()[1])
        line2Azimuth = self._line2.asPolyline()[0].azimuth(
            self._line2.asPolyline()[1])
        self._segmentAzimuth(line1Azimuth, line2Azimuth)

    def _segmentAzimuth(self, line1Azimuth, line2Azimuth):
        nearLineGeom = self._nearLine.geometry()
        if nearLineGeom.isMultipart():
            dct = {}
            minDists = []

            for line in nearLineGeom.asMultiPolyline():
                l = QgsGeometry.fromPolyline(line)
                closestSegmContext = l.closestSegmentWithContext(
                    self._nearestVertex)
                minDists.append(closestSegmContext[0])
                dct[closestSegmContext[0]] = [line, closestSegmContext[-1]]

            minDistance = min(minDists)
            closestSegment = dct[minDistance][0]
            indexSegmEnd = dct[minDistance][1]
            segmEnd = closestSegment[indexSegmEnd]
            segmStart = closestSegment[indexSegmEnd - 1]
        else:
            closestSegmContext = nearLineGeom.closestSegmentWithContext(
                self._nearestVertex)
            indexSegmEnd = closestSegmContext[-1]
            segmEnd = nearLineGeom.asPolyline()[indexSegmEnd]
            segmStart = nearLineGeom.asPolyline()[indexSegmEnd - 1]

        segmentAzimuth = segmStart.azimuth(segmEnd)
        self._dltAz1 = self._getDeltaAzimuth(segmentAzimuth, line1Azimuth)
        self._dltAz2 = self._getDeltaAzimuth(segmentAzimuth, line2Azimuth)

        self._azimuth()

    def _getDeltaAzimuth(self, segment, line):
        if (segment >= 0 and line >= 0) or (segment <= 0 and line <= 0):
            delta = segment - line
            if segment > line and abs(delta) > 90:
                delta -= 180
            elif segment < line and abs(delta) > 90:
                delta += 180

        if 90 >= segment >= 0 and line <= 0:
            delta = segment + abs(line)
            if delta > 90:
                delta -= 180
        elif 90 < segment and line <= 0:
            delta = segment - line - 180
            if abs(delta) > 90:
                delta -= 180

        if -90 <= segment <= 0 and line >= 0:
            delta = segment - line
            if abs(delta) > 90:
                delta += 180
        elif -90 > segment and line >= 0:
            delta = segment - line + 180
            if abs(delta) > 90:
                delta += 180

        return delta

    def _azimuth(self):
        delta1 = abs(self._dltAz1)
        delta2 = abs(self._dltAz2)

        if abs(self._dltAz1) > 90:
            delta1 = 180 - delta1
        if abs(self._dltAz2) > 90:
            delta2 = 180 - delta2

        self._rotate(delta1, delta2)

    def _rotate(self, delta1, delta2):
        self._rotationCheck = True
        if delta1 <= self._angle and delta2 <= self._angle:
            if self._byLongest:
                self._rotateByLongest(delta1, delta2)
            else:
                self._rotateNotByLongest(delta1, delta2)
        else:
            self._othersRotations(delta1, delta2)

        self._markAsRotated()

    def _rotateByLongest(self, delta1, delta2):
        if delta1 <= self._angle and delta2 <= self._angle:
            length1 = self._line1.geometry().length()
            length2 = self._line2.geometry().length()

            if length1 >= length2:
                self._p.geometry().rotate(self._dltAz1, self._center.asPoint())
            elif length1 < length2:
                self._p.geometry().rotate(self._dltAz2, self._center.asPoint())
            elif length1 == length2:
                self._rotateNotByLongest(delta1, delta2)
            else:
                self._rotationCheck = False

    def _rotateNotByLongest(self, delta1, delta2):
        if delta1 > delta2:
            self._p.geometry().rotate(self._dltAz2, self._center.asPoint())
        elif delta1 <= delta2:
            self._p.geometry().rotate(self._dltAz1, self._center.asPoint())
        else:
            self._rotationCheck = False

    def _othersRotations(self, delta1, delta2):
        if delta1 <= self._angle:
            self._p.geometry().rotate(self._dltAz1, self._center.asPoint())
        elif delta2 <= self._angle:
            self._p.geometry().rotate(self._dltAz2, self._center.asPoint())
        else:
            self._rotationCheck = False

    def _markAsRotated(self):
        if self._rotationCheck:
            self._p[self.COLUMN_NAME] = 1
Пример #53
0
class NeighborMerger:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'NeighborMerger_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&NeighborMerger')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'NeighborMerger')
        self.toolbar.setObjectName(u'NeighborMerger')

    # 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('NeighborMerger', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = NeighborMergerDialog()

        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):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/NeighborMerger/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Merge neighbors'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.tr(u'&NeighborMerger'),
                                              action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def display_error(self, message):
        self.iface.messageBar().pushMessage("Erreur",
                                            message,
                                            level=QgsMessageBar.CRITICAL)

    def merge_selected_features(self, layer):
        # Récupération de la liste des entités (QgsFeature) sélectionnées :
        selected = layer.selectedFeatures()
        if len(selected) < 2:
            self.display_error(
                u'Le nombre d\'entités sélectionnées est insuffisant.')
            return

        # Déselectionne les entités sélectionnés :
        layer.removeSelection()

        # Récupération des géométries (QgsGeometry)
        # des entités sélectionnées :
        geoms = [ft.geometry() for ft in selected]

        valid, invalidity_msg = all_touches_one_group(geoms)
        if not valid:
            self.display_error(invalidity_msg)
            return

        # Fusion des entités dans la nouvelle géométrie 'merged_geom' :
        merged_geom = QgsGeometry(geoms[0])
        for geom in geoms[1:]:
            merged_geom = merged_geom.combine(geom)

        # Création de la nouvelle entité utilisant cette géométrie
        # (il est nécessaire de lui dire les champs à utiliser
        #  avant l'ouverture du formulaire)
        new_feature = QgsFeature()
        new_feature.setGeometry(merged_geom)
        new_feature.setFields(layer.fields())

        # Entre en mode édition :
        layer.startEditing()

        # Ouverture du formulaire relatif à la nouvelle entité :
        valid = self.iface.openFeatureForm(layer, new_feature, False)
        if not valid:
            # Sortie du mode édition sans valider d'éventuels changements
            # et affichage d'un message d'erreur
            layer.rollBack()
            self.display_error(u'Erreur dans la saisie des attributs.')
            return

        # Ajout de la nouvelle entité :
        valid = layer.dataProvider().addFeatures([new_feature])
        if not valid:
            # Sortie du mode édition sans valider d'éventuels changements
            # et affichage d'un message d'erreur
            layer.rollBack()
            self.display_error(
                u'Erreur lors de l\'ajout de la nouvelle entité.')
            return

        # Suppression des entités dont est issues la fusion :
        for ft in selected:
            layer.deleteFeature(ft.id())

        # Validation des changements :
        layer.commitChanges()

        # Affichage d'un message de validation :
        self.iface.messageBar().pushMessage(
            "OK",
            u"La nouvelle entité a été créée.",
            level=QgsMessageBar.SUCCESS,
        )

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            #
            target_layer = self.dlg.targetLayerComboBox.currentLayer()
            if not target_layer:
                self.display_error(u"Pas de couche séléctionnée.")
                return
            self.merge_selected_features(target_layer)
    def __init__(self):
        self.SetTreeLocationDialog = SetTreeLocationDialogHandler()
        self.InfoDialog = InfoDialogHandler()
        self.RunCaseDialog = RunCaseDialogHandler()
        self.ECSConversionDialog = ECSConversionDialogHandler()
        self.CopyDialog = CopyDialogHandler()
        self.GUIActivationDialog = GUIActivationDialogHandler()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    lang = "en"
    qm = ["en", "fr"]
    if len(sys.argv) == 2:
        lang = sys.argv[1]

    QM_FILE = "CFDSTUDY_msg_" + lang + ".qm"
    fi = QFileInfo(QM_FILE)

    if not fi.exists():
        QMessageBox.warning(None, "File error",
                            "Cannot find translation for language: " + lang)
    else:
        translator = QTranslator()
        translator.load(QM_FILE)
        app.installTranslator(translator)
    w = InfoDialogHandler()

    w.show()
    sys.exit(app.exec_())
Пример #55
0
class DaoController():
    def __init__(self, settings, plugin_name, iface):
        self.settings = settings
        self.plugin_name = plugin_name
        self.iface = iface
        self.translator = None
        self.plugin_dir = None
        self.tree_manage = None
        self.logged = False
        self.postgresql_version = None

    def set_tree_manage(self, tree_manage):
        self.tree_manage = tree_manage

    def set_schema_name(self, schema_name):
        self.schema_name = schema_name

    def tr(self, message, context_name=None):
        if context_name is None:
            context_name = self.plugin_name
        value = QCoreApplication.translate(context_name, message)
        # If not translation has been found, check into 'ui_message' context
        if value == message:
            value = QCoreApplication.translate('ui_message', message)
        return value

    def set_qgis_settings(self, qgis_settings):
        self.qgis_settings = qgis_settings

    def set_plugin_dir(self, plugin_dir):
        self.plugin_dir = plugin_dir

    def set_plugin_name(self, plugin_name):
        self.plugin_name = plugin_name

    def plugin_settings_value(self, key, default_value=""):
        key = self.plugin_name + "/" + key
        value = self.qgis_settings.value(key, default_value)
        return value

    def plugin_settings_set_value(self, key, value):
        self.qgis_settings.setValue(self.plugin_name + "/" + key, value)

    def set_actions(self, actions):
        self.actions = actions

    def check_actions(self, check=True):
        """ Utility to check/uncheck all actions """
        for action_index, action in self.actions.iteritems():  #@UnusedVariable
            action.setChecked(check)

    def check_action(self, check=True, index=1):
        """ Check/Uncheck selected action """
        key = index
        if type(index) is int:
            key = str(index).zfill(2)
        if key in self.actions:
            action = self.actions[key]
            action.setChecked(check)

    def get_schema_name(self):
        self.schema_name = self.plugin_settings_value('schema_name')
        return self.schema_name

    def set_database_connection(self):
        """ Ser database connection """

        # Initialize variables
        self.dao = None
        self.last_error = None
        self.log_codes = {}

        layer_source = self.get_layer_source_from_credentials()
        if layer_source is None:
            return False

        # Connect to database
        self.logged = self.connect_to_database(layer_source['host'],
                                               layer_source['port'],
                                               layer_source['db'],
                                               layer_source['user'],
                                               layer_source['password'])

        return self.logged

    def get_layer_source_from_credentials(self):

        # Get database parameters from layer 'version'
        layer = self.get_layer_by_tablename("version_tm")
        if not layer:
            self.last_error = self.tr("Layer not found") + ": 'version_tm'"
            return None

        layer_source = self.get_layer_source(layer)
        self.schema_name = layer_source['schema']
        conn_info = QgsDataSourceUri(
            layer.dataProvider().dataSourceUri()).connectionInfo()

        attempts = 1
        logged = self.connect_to_database(layer_source['host'],
                                          layer_source['port'],
                                          layer_source['db'],
                                          layer_source['user'],
                                          layer_source['password'])
        while not logged:
            attempts += 1
            if attempts <= 2:
                (success, layer_source['user'],
                 layer_source['password']) = QgsCredentials.instance().get(
                     conn_info, layer_source['user'], layer_source['password'])
                logged = self.connect_to_database(layer_source['host'],
                                                  layer_source['port'],
                                                  layer_source['db'],
                                                  layer_source['user'],
                                                  layer_source['password'])
            else:
                return None

                # Put the credentials back (for yourself and the provider), as QGIS removes it when you "get" it
        QgsCredentials.instance().put(conn_info, layer_source['user'],
                                      layer_source['password'])

        return layer_source

    def connect_to_database(self, host, port, db, user, pwd):
        """ Connect to database with selected parameters """

        # Update current user
        self.user = user

        # We need to create this connections for Table Views
        self.db = QSqlDatabase.addDatabase("QPSQL")
        self.db.setHostName(host)
        self.db.setPort(int(port))
        self.db.setDatabaseName(db)
        self.db.setUserName(user)
        self.db.setPassword(pwd)
        status = self.db.open()
        if not status:
            msg = "Database connection error. Please check connection parameters"
            self.last_error = self.tr(msg)
            return False

        # Connect to Database
        self.dao = PgDao()
        self.dao.set_params(host, port, db, user, pwd)
        status = self.dao.init_db()
        if not status:
            msg = "Database connection error. Please check connection parameters"
            self.last_error = self.tr(msg)
            return False

        return status

    def get_error_message(self, log_code_id):
        """ Get error message from selected error code """

        if self.schema_name is None:
            return

        sql = ("SELECT error_message"
               " FROM " + self.schema_name + ".audit_cat_error"
               " WHERE id = " + str(log_code_id))
        result = self.dao.get_row(sql)
        if result:
            self.log_codes[log_code_id] = result[0]
        else:
            self.log_codes[
                log_code_id] = "Error message not found in the database: " + str(
                    log_code_id)

    def get_postgresql_version(self):
        """ Get PostgreSQL version (integer value) """

        self.postgresql_version = None
        sql = "SELECT current_setting('server_version_num');"
        row = self.dao.get_row(sql)
        if row:
            self.postgresql_version = row[0]

        return self.postgresql_version

    def show_message(self,
                     text,
                     message_level=1,
                     duration=5,
                     context_name=None,
                     parameter=None):
        """ Show message to the user with selected message level
        message_level: {INFO = 0, WARNING = 1, CRITICAL = 2, SUCCESS = 3} """

        msg = None
        if text is not None:
            msg = self.tr(text, context_name)
            if parameter is not None:
                msg += ": " + str(parameter)
        self.iface.messageBar().pushMessage("", msg, message_level, duration)

    def show_info(self, text, duration=5, context_name=None, parameter=None):
        """ Show information message to the user """
        self.show_message(text, 0, duration, context_name, parameter)

    def show_warning(self,
                     text,
                     duration=5,
                     context_name=None,
                     parameter=None):
        """ Show warning message to the user """
        self.show_message(text, 1, duration, context_name, parameter)

    def show_warning_detail(self, text, detail_text, context_name=None):
        """ Show warning message with a button to show more details """

        inf_text = "Press 'Show Me' button to get more details..."
        widget = self.iface.messageBar().createMessage(
            self.tr(text, context_name), self.tr(inf_text))
        button = QPushButton(widget)
        button.setText(self.tr("Show Me"))
        button.pressed.connect(
            partial(self.show_details, detail_text,
                    self.tr('Warning details')))
        widget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(widget, 1)

    def show_details(self, detail_text, title=None, inf_text=None):
        """ Shows a message box with detail information """

        self.iface.messageBar().clearWidgets()
        msg_box = QMessageBox()
        msg_box.setText(detail_text)
        if title is not None:
            msg_box.setWindowTitle(title)
        if inf_text is not None:
            msg_box.setInformativeText(inf_text)
        msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
        msg_box.setStandardButtons(QMessageBox.Ok)
        msg_box.setDefaultButton(QMessageBox.Ok)
        msg_box.exec_()

    def ask_question(self,
                     text,
                     title=None,
                     inf_text=None,
                     context_name=None,
                     parameter=None):
        """ Ask question to the user """

        msg_box = QMessageBox()
        msg = self.tr(text, context_name)
        if parameter is not None:
            msg += ": " + str(parameter)
        msg_box.setText(msg)
        if title is not None:
            msg_box.setWindowTitle(title)
        if inf_text is not None:
            msg_box.setInformativeText(inf_text)
        msg_box.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
        msg_box.setDefaultButton(QMessageBox.Ok)
        msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
        ret = msg_box.exec_()
        if ret == QMessageBox.Ok:
            return True
        elif ret == QMessageBox.Discard:
            return False

    def show_info_box(self,
                      text,
                      title=None,
                      inf_text=None,
                      context_name=None,
                      parameter=None):
        """ Ask question to the user """

        if text is not None:
            msg = self.tr(text, context_name)
            if parameter is not None:
                msg += ": " + str(parameter)

        msg_box = QMessageBox()
        msg_box.setText(msg)
        msg_box.setWindowFlags(Qt.WindowStaysOnTopHint)
        if title is not None:
            msg_box.setWindowTitle(title)
        if inf_text is not None:
            msg_box.setInformativeText(inf_text)
        msg_box.setDefaultButton(QMessageBox.No)
        ret = msg_box.exec_()  #@UnusedVariable

    def get_row(self, sql, log_info=True, log_sql=False, commit=False):
        """ Execute SQL. Check its result in log tables, and show it to the user """

        if log_sql:
            self.log_info(sql)
        row = self.dao.get_row(sql, commit)
        self.last_error = self.dao.last_error
        if not row:
            # Check if any error has been raised
            if self.last_error is not None:
                text = "Undefined error"
                if '-1' in self.log_codes:
                    text = self.log_codes[-1]
                self.show_warning_detail(text, str(self.last_error))
            elif self.last_error is None and log_info:
                self.log_info("Any record found: " + sql)

        return row

    def get_rows(self, sql, log_info=True, log_sql=False, commit=False):
        """ Execute SQL. Check its result in log tables, and show it to the user """

        if log_sql:
            self.log_info(sql)
        rows = self.dao.get_rows(sql, commit=commit)
        self.last_error = self.dao.last_error
        if not rows:
            # Check if any error has been raised
            if self.last_error is not None:
                self.show_warning_detail(self.log_codes[-1],
                                         str(self.last_error))
            elif self.last_error is None and log_info:
                self.log_info("Any record found: " + sql)

        return rows

    def execute_sql(self,
                    sql,
                    search_audit=False,
                    log_sql=False,
                    log_error=False,
                    commit=True):
        """ Execute SQL. Check its result in log tables, and show it to the user """

        if log_sql:
            self.log_info(sql)
        result = self.dao.execute_sql(sql, commit=commit)
        self.last_error = self.dao.last_error
        if not result:
            if log_error:
                self.log_info(sql)
            self.show_warning_detail(self.log_codes[-1],
                                     str(self.dao.last_error))
            return False
        else:
            if search_audit:
                # Get last record from audit tables (searching for a possible error)
                return self.get_error_from_audit(commit=commit)

        return True

    def execute_insert_or_update(self,
                                 tablename,
                                 unique_field,
                                 unique_value,
                                 fields,
                                 values,
                                 commit=True):
        """ Execute INSERT or UPDATE sentence. Used for PostgreSQL database versions <9.5 """

        # Check if we have to perfrom an INSERT or an UPDATE
        if unique_value != 'current_user':
            unique_value = "'" + unique_value + "'"
        sql = "SELECT * FROM " + self.schema_name + "." + tablename
        sql += " WHERE " + str(unique_field) + " = " + unique_value
        row = self.get_row(sql, commit=commit)

        # Get fields
        sql_fields = ""
        for fieldname in fields:
            sql_fields += fieldname + ", "

        # Get values
        sql_values = ""
        for value in values:
            if value != 'current_user':
                sql_values += "'" + value + "', "
            else:
                sql_values += value + ", "

        # Perform an INSERT
        if not row:
            # Set SQL for INSERT
            sql = " INSERT INTO " + self.schema_name + "." + tablename + "(" + unique_field + ", "
            sql += sql_fields[:-2] + ") VALUES ("

            # Manage value 'current_user'
            # if unique_value != 'current_user':
            #     unique_value = "'" + unique_value + "'"
            sql += unique_value + ", " + sql_values[:-2] + ");"

        # Perform an UPDATE
        else:
            # Set SQL for UPDATE
            sql = " UPDATE " + self.schema_name + "." + tablename
            sql += " SET ("
            sql += sql_fields[:-2] + ") = ("
            sql += sql_values[:-2] + ")"
            sql += " WHERE " + unique_field + " = " + unique_value

        # Execute sql
        self.log_info(sql)
        result = self.dao.execute_sql(sql, commit=commit)
        self.last_error = self.dao.last_error
        if not result:
            self.show_warning_detail(self.log_codes[-1],
                                     str(self.dao.last_error))
            return False

        return True

    def execute_upsert(self,
                       tablename,
                       unique_field,
                       unique_value,
                       fields,
                       values,
                       commit=True):
        """ Execute UPSERT sentence """
        # Check PostgreSQL version
        if not self.postgresql_version:
            self.get_postgresql_version()

        if int(self.postgresql_version) < 90500:
            self.execute_insert_or_update(tablename,
                                          unique_field,
                                          unique_value,
                                          fields,
                                          values,
                                          commit=commit)
            return True

        # Set SQL for INSERT
        sql = " INSERT INTO " + self.schema_name + "." + tablename + "(" + unique_field + ", "

        # Iterate over fields
        sql_fields = ""
        for fieldname in fields:
            sql_fields += fieldname + ", "
        sql += sql_fields[:-2] + ") VALUES ("

        # Manage value 'current_user'
        if unique_value != 'current_user':
            unique_value = "'" + unique_value + "'"

        # Iterate over values
        sql_values = ""
        for value in values:
            if value != 'current_user':
                sql_values += "'" + value + "', "
            else:
                sql_values += value + ", "
        sql += unique_value + ", " + sql_values[:-2] + ")"

        # Set SQL for UPDATE
        sql += " ON CONFLICT (" + unique_field + ") DO UPDATE"
        sql += " SET ("
        sql += sql_fields[:-2] + ") = ("
        sql += sql_values[:-2] + ")"
        sql += " WHERE " + tablename + "." + unique_field + " = " + unique_value

        # Execute UPSERT
        self.log_info(sql)
        result = self.dao.execute_sql(sql, commit=commit)
        self.last_error = self.dao.last_error
        if not result:
            self.show_warning_detail(self.log_codes[-1],
                                     str(self.dao.last_error))
            return False

        return True

    def get_error_from_audit(self, commit=True):
        """ Get last error from audit tables that has not been showed to the user """

        if self.schema_name is None:
            return

        sql = (
            "SELECT audit_function_actions.id, error_message, log_level, show_user"
            " FROM " + self.schema_name + ".audit_function_actions"
            " INNER JOIN " + self.schema_name + ".audit_cat_error"
            " ON audit_function_actions.audit_cat_error_id = audit_cat_error.id"
            " WHERE audit_cat_error.id != 0 AND debug_info is null"
            " ORDER BY audit_function_actions.id DESC LIMIT 1")
        result = self.dao.get_row(sql, commit=commit)
        if result is not None:
            if result['log_level'] <= 2:
                sql = "UPDATE " + self.schema_name + ".audit_function_actions"
                sql += " SET debug_info = 'showed'"
                sql += " WHERE id = " + str(result['id'])
                self.dao.execute_sql(sql, commit=commit)
                if result['show_user']:
                    self.show_message(result['error_message'],
                                      result['log_level'])
                return False
            elif result['log_level'] == 3:
                # Debug message
                pass

        return True

    def translate_form(self, dialog, context_name):
        """ Translate widgets of the form to current language """

        # Get objects of type: QLabel
        widget_list = dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translate_widget(context_name, widget)

        # Get objects of type: QCheckBox
        widget_list = dialog.findChildren(QCheckBox)
        for widget in widget_list:
            self.translate_widget(context_name, widget)

        # Get objects of type: QTabWidget
        widget_list = dialog.findChildren(QTabWidget)
        for widget in widget_list:
            self.translate_widget(context_name, widget)

    def translate_widget(self, context_name, widget):
        """ Translate widget text """

        if not widget:
            return

        if type(widget) is QTabWidget:
            num_tabs = widget.count()
            for i in range(0, num_tabs):
                tab_page = widget.widget(i)
                widget_name = tab_page.objectName()
                text = self.tr(widget_name, context_name)
                if text != widget_name:
                    widget.setTabText(i, text)

        else:
            widget_name = widget.objectName()
            text = self.tr(widget_name, context_name)
            if text != widget_name:
                widget.setText(text)

    def start_program(self, program):
        """ Start an external program (hidden) """

        SW_HIDE = 0
        info = subprocess.STARTUPINFO()
        info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = SW_HIDE
        subprocess.Popen(program, startupinfo=info)

    def get_layer_by_layername(self, layername, log_info=False):
        """ Get layer with selected @layername (the one specified in the TOC) """

        layer = QgsMapLayerRegistry.instance().mapLayersByName(layername)
        if layer:
            layer = layer[0]
        elif layer is None and log_info:
            self.log_info("Layer not found", parameter=layername)

        return layer

    def get_layer_by_tablename(self,
                               tablename,
                               show_warning=False,
                               log_info=False):
        """ Iterate over all layers and get the one with selected @tablename """

        # Check if we have any layer loaded
        layers = self.iface.legendInterface().layers()
        if len(layers) == 0:
            return None

        # Iterate over all layers
        layer = None
        for cur_layer in layers:
            uri_table = self.get_layer_source_table_name(cur_layer)
            if uri_table is not None and uri_table == tablename:
                layer = cur_layer
                break

        if layer is None and show_warning:
            self.show_warning("Layer not found", parameter=tablename)

        if layer is None and log_info:
            self.log_info("Layer not found", parameter=tablename)

        return layer

    def get_layer_by_nodetype(self,
                              nodetype_id,
                              show_warning=False,
                              log_info=False):
        """ Get layer related with selected @nodetype_id """

        layer = None
        sql = ("SELECT sys_feature_cat.tablename"
               " FROM " + self.schema_name + ".node_type"
               " INNER JOIN " + self.schema_name + ".sys_feature_cat"
               " ON node_type.type = sys_feature_cat.id"
               " WHERE node_type.id = '" + nodetype_id + "'")
        row = self.get_row(sql, log_sql=True)
        if row:
            tablename = row[0]
            layer = self.get_layer_by_tablename(tablename)

        if layer is None and show_warning:
            self.show_warning("Layer not found", parameter=tablename)

        if layer is None and log_info:
            self.log_info("Layer not found", parameter=tablename)

        return layer

    def get_layer_source(self, layer):
        """ Get database connection paramaters of @layer """

        # Initialize variables
        layer_source = {
            'db': None,
            'schema': None,
            'table': None,
            'host': None,
            'port': None,
            'user': None,
            'password': None
        }

        # Get dbname, host, port, user and password
        uri = layer.dataProvider().dataSourceUri()
        pos_db = uri.find('dbname=')
        pos_host = uri.find(' host=')
        pos_port = uri.find(' port=')
        pos_user = uri.find(' user='******' password='******' sslmode=')
        if pos_db <> -1 and pos_host <> -1:
            uri_db = uri[pos_db + 8:pos_host - 1]
            layer_source['db'] = uri_db
        if pos_host <> -1 and pos_port <> -1:
            uri_host = uri[pos_host + 6:pos_port]
            layer_source['host'] = uri_host
        if pos_port <> -1:
            if pos_user <> -1:
                pos_end = pos_user
            elif pos_sslmode <> -1:
                pos_end = pos_sslmode
            uri_port = uri[pos_port + 6:pos_end]
            layer_source['port'] = uri_port
        if pos_user <> -1 and pos_password <> -1:
            uri_user = uri[pos_user + 7:pos_password - 1]
            layer_source['user'] = uri_user
        if pos_password <> -1 and pos_sslmode <> -1:
            uri_password = uri[pos_password + 11:pos_sslmode - 1]
            layer_source['password'] = uri_password

        # Get schema and table or view name
        pos_table = uri.find('table=')
        pos_end_schema = uri.rfind('.')
        pos_fi = uri.find('" ')
        if pos_table <> -1 and pos_fi <> -1:
            uri_schema = uri[pos_table + 6:pos_end_schema]
            uri_table = uri[pos_end_schema + 2:pos_fi]
            layer_source['schema'] = uri_schema
            layer_source['table'] = uri_table

        return layer_source

    def get_layer_source_table_name(self, layer):
        """ Get table or view name of selected layer """

        if layer is None:
            return None

        uri_table = None
        uri = layer.dataProvider().dataSourceUri().lower()
        pos_ini = uri.find('table=')
        pos_end_schema = uri.rfind('.')
        pos_fi = uri.find('" ')
        if pos_ini <> -1 and pos_fi <> -1:
            uri_table = uri[pos_end_schema + 2:pos_fi]

        return uri_table

    def get_layer_primary_key(self, layer=None):
        """ Get primary key of selected layer """

        uri_pk = None
        if layer is None:
            layer = self.iface.activeLayer()
        if layer is None:
            return uri_pk
        uri = layer.dataProvider().dataSourceUri().lower()
        pos_ini = uri.find('key=')
        pos_end = uri.rfind('srid=')
        if pos_ini <> -1:
            uri_pk = uri[pos_ini + 5:pos_end - 2]

        return uri_pk

    def get_project_user(self):
        """ Set user """
        return self.user

    def log_message(self,
                    text=None,
                    message_level=0,
                    context_name=None,
                    parameter=None):
        """ Write message into QGIS Log Messages Panel with selected message level
            @message_level: {INFO = 0, WARNING = 1, CRITICAL = 2, SUCCESS = 3} 
        """
        msg = None
        if text is not None:
            msg = self.tr(text, context_name)
            if parameter is not None:
                msg += ": " + str(parameter)
        QgsMessageLog.logMessage(msg, self.plugin_name, message_level)

    def log_info(self, text=None, context_name=None, parameter=None):
        """ Write information message into QGIS Log Messages Panel """
        self.log_message(text, 0, context_name, parameter=parameter)

    def log_warning(self, text=None, context_name=None, parameter=None):
        """ Write warning message into QGIS Log Messages Panel """
        self.log_message(text, 1, context_name, parameter=parameter)

    def add_translator(self, locale_path):
        """ Add translation file to the list of translation files to be used for translations """

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
            #self.log_info("Add translator", parameter=locale_path)
        else:
            self.log_info("Locale not found", parameter=locale_path)

    def manage_translation(self, locale_name, dialog=None):
        """ Manage locale and corresponding 'i18n' file """

        # Get locale of QGIS application
        locale = QSettings().value('locale/userLocale').lower()
        if locale == 'es_es':
            locale = 'es'
        elif locale == 'es_ca':
            locale = 'ca'
        elif locale == 'en_us':
            locale = 'en'

        # If user locale file not found, set English one by default
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   locale_name + '_{}.qm'.format(locale))
        if not os.path.exists(locale_path):
            self.log_info("Locale not found", parameter=locale_path)
            locale_default = 'en'
            locale_path = os.path.join(
                self.plugin_dir, 'i18n',
                locale_name + '_{}.qm'.format(locale_default))
            # If English locale file not found, just log it
            if not os.path.exists(locale_path):
                self.log_info("Locale not found", parameter=locale_path)

        # Add translation file
        self.add_translator(locale_path)

        # If dialog is set, then translate form
        if dialog:
            self.translate_form(dialog, locale_name)

    def get_project_type(self):
        """ Get water software from table 'version' """

        project_type = None
        sql = ("SELECT lower(wsoftware)"
               " FROM " + self.schema_name +
               ".version ORDER BY id DESC LIMIT 1")
        row = self.get_row(sql)
        if row:
            project_type = row[0]

        return project_type

    def check_function(self, function_name):
        """ Check if @function_name exists """

        schema_name = self.schema_name.replace('"', '')
        sql = ("SELECT routine_name FROM information_schema.routines"
               " WHERE lower(routine_schema) = '" + schema_name + "'"
               " AND lower(routine_name) = '" + function_name + "'")
        row = self.get_row(sql, log_info=False)
        return row

    def check_table(self, tablename):
        """  Check if selected table exists in selected schema """
        return self.dao.check_table(self.schema_name, tablename)

    def get_group_layers(self, geom_type):
        """ Get layers of the group @geom_type """

        list_items = []
        sql = ("SELECT tablename FROM " + self.schema_name + ".sys_feature_cat"
               " WHERE type = '" + geom_type.upper() + "'")
        rows = self.get_rows(sql, log_sql=True)
        if rows:
            for row in rows:
                layer = self.get_layer_by_tablename(row[0])
                if layer:
                    list_items.append(layer)

        return list_items

    def check_role(self, role_name):
        """ Check if @role_name exists """

        sql = ("SELECT * FROM pg_roles WHERE lower(rolname) = '" + role_name +
               "'")
        row = self.get_row(sql, log_info=False)
        return row

    def check_role_user(self, role_name):
        """ Check if current user belongs to @role_name """

        if not self.check_role(role_name):
            return True

        sql = ("SELECT pg_has_role('" + self.user + "', '" + role_name +
               "', 'MEMBER');")
        row = self.get_row(sql)
        return row[0]

    def check_user_roles(self):
        """ Check roles of this user to show or hide toolbars """

        role_admin = False
        role_master = self.check_role_user("rol_master")
        role_epa = self.check_role_user("rol_epa")
        role_edit = self.check_role_user("rol_edit")
        role_om = self.check_role_user("rol_om")

        if role_admin:
            pass
        elif role_master:
            self.tree_manage.enable_toolbar("master")
            self.tree_manage.enable_toolbar("epa")
            self.tree_manage.enable_toolbar("edit")
            self.tree_manage.enable_toolbar("cad")
            if self.tree_manage.wsoftware == 'ws':
                self.tree_manage.enable_toolbar("om_ws")
            elif self.tree_manage.wsoftware == 'ud':
                self.tree_manage.enable_toolbar("om_ud")
        elif role_epa:
            self.tree_manage.enable_toolbar("epa")
        elif role_edit:
            self.tree_manage.enable_toolbar("edit")
            self.tree_manage.enable_toolbar("cad")
        elif role_om:
            if self.tree_manage.wsoftware == 'ws':
                self.tree_manage.enable_toolbar("om_ws")
            elif self.tree_manage.wsoftware == 'ud':
                self.tree_manage.enable_toolbar("om_ud")

    def get_current_user(self):
        """ Get current user connected to database """

        sql = ("SELECT current_user")
        row = self.get_row(sql)
        cur_user = ""
        if row:
            cur_user = str(row[0])

        return cur_user
Пример #56
0
class RasterDisplayComposer:
    """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__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'RasterDisplayComposer_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&RasterDisplayComposer')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'RasterDisplayComposer')
        self.toolbar.setObjectName(u'RasterDisplayComposer')

        # print "** INITIALIZING RasterDisplayComposer"

        self.pluginIsActive = False
        self.dockwidget = None

        self.loaded_raster_layers = {}
        self.dock_is_hidden = True

        self.isLoaded = False

        #self.preLoad()

    def preLoad(self):
        """
        Preload the plugin interface
        :return:
        """
        """
        :return:
        """
        logger.debug("plugin is active: {}".format(self.pluginIsActive))
        if not self.pluginIsActive:
            self.pluginIsActive = True

            # print "** STARTING RasterDisplayComposer"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = RasterDisplayComposerDockWidget()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            self.initDockWidgetSignals()
            self.loadComboBox()
            self.updateLoadedrasterLayers()
            self.dockwidget.hide()
            self.dock_is_hidden = True

    # 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('RasterDisplayComposer', 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.addPluginToRasterMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        logger.debug("Init GUI")
        icon_path = ':/plugins/RasterDisplayComposer/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Raster Display Composer'),
                        callback=self.run,
                        parent=self.iface.mainWindow())
        # QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL(""), )
        QgsMapLayerRegistry.instance().layersAdded.connect(
            self.updateLoadedrasterLayers)
        QgsMapLayerRegistry.instance().layerWillBeRemoved.connect(
            self.updateLoadedrasterLayers)
        logger.debug("Init GUI ok")

    # --------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        # print "** CLOSING RasterDisplayComposer"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        # print "** UNLOAD RasterDisplayComposer"

        for action in self.actions:
            self.iface.removePluginRasterMenu(
                self.tr(u'&RasterDisplayComposer'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    # --------------------------------------------------------------------------

    def run(self):
        """Run method that loads and starts the plugin"""
        logger.debug("Run")
        logger.debug("self.isLoaded {}".format(self.isLoaded))
        logger.debug("self.dock_is_hidden {}".format(self.dock_is_hidden))
        if not self.isLoaded:
            self.preLoad()
            self.isLoaded = True

        if self.dock_is_hidden:
            self.dockwidget.show()
            self.dock_is_hidden = False
        else:
            self.dockwidget.hide()
            self.dock_is_hidden = True

    def initDockWidgetSignals(self):
        logger.debug("initDockWidgetSignals")
        self.dockwidget.pushButton_load.clicked.connect(self.loadRGBImage)
        self.dockwidget.pushButton_refresh.clicked.connect(
            self.updateLoadedrasterLayers)

    def updateLoadedrasterLayers(self, layers_added=[]):
        """
        Re-write the dictionnary of loaded raster layers with new layers
        :param layers_added:
        :return:
        """
        # print layers_added
        # print "self.iface.mapCanvas().layers()", self.iface.mapCanvas().layers()
        # print "legendInterface().layers()", self.iface.legendInterface().layers()
        # print "updateLoadedRasterlayers"
        if self.isLoaded:
            logger.debug("updateLoadedrasterLayers")
            self.loaded_raster_layers = {}

            try:
                # case of layer added
                load_list = self.iface.mapCanvas().layers() + layers_added
            except TypeError:
                # case of layer deleted
                load_list = self.iface.mapCanvas().layers()

            for layer in load_list:
                if layer.type() == layer.RasterLayer:
                    # print layer
                    # print layer.source()
                    # print layer.name()
                    # print layer.type()
                    self.loaded_raster_layers[layer.name()] = layer.source()
            # print self.loaded_raster_layers
            self.loadComboBox()

    def loadComboBox(self):
        """
        Fill in the combobox with name of the loaded raster layers
        :return:
        """
        logger.debug("loadComboBox")
        for combo_box in [
                self.dockwidget.comboBox_red, self.dockwidget.comboBox_green,
                self.dockwidget.comboBox_blue, self.dockwidget.comboBox_alpha
        ]:
            combo_box.clear()
            combo_box.addItems(self.loaded_raster_layers.keys())

    def loadRGBImage(self):
        """
        Get path of selected images, run gdalbuildvrt and loa the result in qgis
        :return:
        """
        logger.debug("loadRGBImage")
        layers_to_append = []
        for combo_box in [
                self.dockwidget.comboBox_red, self.dockwidget.comboBox_green,
                self.dockwidget.comboBox_blue
        ]:
            layers_to_append.append(
                self.loaded_raster_layers[combo_box.currentText()])
        # print layers_to_append
        if self.dockwidget.checkBox_alpha.isChecked():
            layers_to_append.append(self.loaded_raster_layers[
                self.dockwidget.comboBox_alpha.currentText()])

        no_data_option = ""
        no_data = "a"
        if self.dockwidget.checkBox_noData.isChecked():
            no_data = self.dockwidget.spinBox_noData.value()
            no_data_option = "-srcnodata " + str(no_data)

        # print layers_to_append

        rasterToLoad = "/tmp/RasterDisplayComposer.VRT"
        # command = ["gdalbuildvrt -separate", no_data_option, rasterToLoad] + layers_to_append
        # print " ".join(command)
        # os.system(" ".join(command))
        root_vrt = self.createVRT(layers_to_append, no_data)
        if self.dockwidget.checkBox_save.isChecked():
            rasterToLoad = self.getOutPutVRTFilename()
            if rasterToLoad:
                self.writeVRT(root_vrt, rasterToLoad)
            else:
                rasterToLoad = '\'' + ET.tostring(root_vrt) + '\''
        else:
            rasterToLoad = '\'' + ET.tostring(root_vrt) + '\''

        band_name = self.dockwidget.lineEdit_bandName.text()
        rasterLayer = QgsRasterLayer(rasterToLoad, band_name)

        QgsMapLayerRegistry.instance().addMapLayer(rasterLayer)

    def getInfoFromImage(self, image):
        """
        Get information about image with GDAL python api
        :param image:
        :return: dictionnary with information
        """
        logger.debug("getInfoFromImage")
        dicImage = {"image": image, "noData": "a"}

        dataset = gdal.Open(str(image), GA_ReadOnly)
        if dataset is not None:
            dicImage["size"] = [dataset.RasterXSize, dataset.RasterYSize]
            dicImage["numberOfBands"] = dataset.RasterCount
            dicImage["projection"] = dataset.GetProjection()
            geotransform = dataset.GetGeoTransform()
            if geotransform is not None:
                dicImage["origin"] = [geotransform[0], geotransform[3]]
                dicImage["pixelSize"] = [geotransform[1], geotransform[5]]
                # dicImage["geotransform"] = geotransform
                geoTransformListStr = [str(x) for x in geotransform]
                dicImage["geotransform"] = ", ".join(geoTransformListStr)
            spatialReference = osr.SpatialReference()
            spatialReference.ImportFromWkt(dataset.GetProjectionRef())
            dicImage["intEpsgCode"] = str(
                spatialReference.GetAuthorityCode("PROJCS"))
            # get info from band 1
            band = dataset.GetRasterBand(1)
            dicImage["dataType"] = gdal.GetDataTypeName(band.DataType)
            if not band.GetNoDataValue():
                dicImage["noData"] = "a"
            else:
                dicImage["noData"] = band.GetNoDataValue()

        print dicImage
        return dicImage

    def createVRT(self, listOfImages, no_data="a"):
        """
        Create the xml of the vrt to avoid file creation on disk
        :param listOfImages:
        :return:
        """
        logger.debug("createVRT")
        vrtFilename = None
        infoFromImage = self.getInfoFromImage(listOfImages[0])
        rootNode = ET.Element('VRTDataset')
        totalXSize = infoFromImage["size"][0]
        totalYSize = infoFromImage["size"][1]
        dataType = infoFromImage["dataType"]

        # for each band red green blue
        for index, image in enumerate(listOfImages):
            #  <VRTRasterBand dataType="Byte" band="1">
            bandNode = ET.SubElement(rootNode, "VRTRasterBand", {
                'dataType': str(dataType),
                'band': str(index + 1)
            })

            # <NoDataValue>-100.0</NoDataValue>
            if no_data == "a":
                no_data = infoFromImage["noData"]
            if no_data != "a":
                node = ET.SubElement(bandNode, 'NoDataValue')
                node.text = str(no_data)
            # <SourceFilename relativeToVRT="1">nine_band.dat</SourceFilename>
            sourceNode = ET.SubElement(bandNode, 'SimpleSource')

            node = ET.SubElement(sourceNode, 'SourceFilename',
                                 {'relativeToVRT': '1'})
            node.text = image
            # <SourceBand>1</SourceBand>
            node = ET.SubElement(sourceNode, 'SourceBand')
            node.text = str(1)
            # <SrcRect xOff="0" yOff="0" xSize="1000" ySize="1000"/>
            node = ET.SubElement(
                sourceNode, 'SrcRect', {
                    'xOff': '0',
                    'yOff': '0',
                    'xSize': str(totalXSize),
                    'ySize': str(totalYSize)
                })
            # <DstRect xOff="0" yOff="0" xSize="1000" ySize="1000"/>
            node = ET.SubElement(
                sourceNode, 'DstRect', {
                    'xOff': '0',
                    'yOff': '0',
                    'xSize': str(totalXSize),
                    'ySize': str(totalYSize)
                })
            # bandNode.attrib['dataType'] = str(dataType)

        rootNode.attrib['rasterXSize'] = str(totalXSize)
        rootNode.attrib['rasterYSize'] = str(totalYSize)
        node = ET.SubElement(rootNode, 'SRS')
        node.text = "EPSG:" + str(infoFromImage["intEpsgCode"])  # projection

        geotransformNode = ET.SubElement(rootNode, 'GeoTransform')
        geotransformNode.text = infoFromImage["geotransform"]
        return rootNode

    def getOutPutVRTFilename(self):
        """
        Get name of the output VRT. The folder of the output filename will be saved in settings for next time
        :return: filename of the vrt
        """
        logger.debug("getOutPutVRTFilename")
        settings = QSettings()
        lastFolder = settings.value("rasterDisplayComposer_vrtlastFolder")

        if lastFolder:
            path = lastFolder
        else:
            path = QDir.currentPath()

        fileOpened = QFileDialog.getOpenFileName(None, "Load a raster file",
                                                 path)

        settings.setValue("rasterDisplayComposer_vrtlastFolder",
                          os.path.dirname(fileOpened))
        settings.sync()
        return fileOpened

    def writeVRT(self, vrt_xml, output_filename):
        """
        Write the given xml in the given output_filename
        :param vrt_xml:
        :param output_filename:
        :return:
        """
        logger.debug("writeVRT")
        tree = ET.ElementTree(vrt_xml)
        f = open(output_filename, "w")
        f.write(ET.tostring(tree, pretty_print=True))
        f.close()
Пример #57
0
class AboutWidget(QWidgetWithDpi):
    """ Common About Dialog for the Freeseer Project. This should be used for the
    about dialog when including one in GUIs.

    Layout:
    Logo  |  About Infos
          |  Buttons
    """
    def __init__(self, parent=None):
        super(AboutWidget, self).__init__(parent)

        self.current_language = "en_US"
        self.uiTranslator = QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")

        self.fontSize = self.font().pixelSize()
        self.fontUnit = "px"
        if self.fontSize == -1:  # Font is set as points, not pixels.
            self.fontUnit = "pt"
            self.fontSize = self.font().pointSize()

        icon = QIcon()
        self.logoPixmap = QPixmap(_fromUtf8(":/freeseer/logo.png"))
        icon.addPixmap(self.logoPixmap, QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)

        self.mainLayout = QGridLayout()
        self.setLayout(self.mainLayout)

        # Logo
        self.logo = QLabel("Logo")
        # To offset the logo so that it's to the right of the title
        self.logo.setStyleSheet("QLabel {{ margin-left: {} {} }}".format(
            self.set_width_with_dpi(90) + (self.fontSize * 2.5),
            self.fontUnit))
        self.logo.setPixmap(
            self.logoPixmap.scaledToHeight(self.set_height_with_dpi(80)))
        self.mainLayout.addWidget(self.logo, 0, 0, Qt.AlignTop)

        # Info
        self.aboutInfo = QLabel("About Info", openExternalLinks=True)
        self.aboutInfo.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.aboutInfo.setWordWrap(True)
        self.mainLayout.addWidget(self.aboutInfo, 0, 0)

        # Buttons
        self.buttonsLayout = QHBoxLayout()
        self.issueButton = QPushButton("Report an issue")
        self.docsButton = QPushButton("Freeseer documentation")
        self.contactButton = QPushButton("Contact us")
        self.buttonsLayout.insertWidget(0, self.docsButton)
        self.buttonsLayout.insertWidget(1, self.issueButton)
        self.buttonsLayout.insertWidget(2, self.contactButton)

        self.mainLayout.addLayout(self.buttonsLayout, 2, 0)

        self.connect(self.docsButton, SIGNAL('clicked()'), self.openDocsUrl)
        self.connect(self.issueButton, SIGNAL('clicked()'),
                     self.openNewIssueUrl)
        self.connect(self.contactButton, SIGNAL('clicked()'),
                     self.openContactUrl)

        self.retranslate()

    def retranslate(self, language=None):
        if language is not None:
            self.current_language = language

        self.uiTranslator.load(":/languages/tr_%s.qm" % self.current_language)

        #
        # Main Text
        #
        self.descriptionString = self.uiTranslator.translate(
            "AboutDialog",
            "Freeseer is a video capture utility capable of capturing presentations. It captures "
            "video sources such as usb, firewire, or local desktop along with audio and mixes them "
            "together to produce a video.")
        self.copyrightString = self.uiTranslator.translate(
            "AboutDialog", 'Copyright (C) 2014 The Free and '
            'Open Source Software Learning Centre')
        self.licenseTextString = self.uiTranslator.translate(
            "AboutDialog", "Freeseer is licensed under the GPL "
            "version 3. This software is provided 'as-is',without any express or implied warranty. In "
            "no event will the authors be held liable for any damages arising from the use of this software."
        )

        self.aboutInfoString = u'<h1>' + NAME.capitalize() + u'</h1>' + \
            u'<br><b>' + self.uiTranslator.translate("AboutDialog", "Version") + \
            ": " + __version__ + u'</b>' + \
            u'<p>' + self.descriptionString + u'</p>' + \
            u'<p>' + self.copyrightString + u'</p>' + \
            u'<p><a href="' + URL + u'">' + URL + u'</a></p>' \
            u'<p>' + self.licenseTextString + u'</p>' \
            u'<p>' + self.uiTranslator.translate("AboutDialog", "Record button graphics by") + \
            u': <a href="' + RECORD_BUTTON_LINK + u'">' + RECORD_BUTTON_ARTIST + u'</a></p>' \
            u'<p>' + self.uiTranslator.translate("AboutDialog", "Headphones graphics by") + \
            u': <a href="' + HEADPHONES_LINK + u'">' + HEADPHONES_ARTIST + u'</a></p><br>'

        self.aboutInfo.setText(self.aboutInfoString)
        # --- End Main Text

    def openDocsUrl(self):
        """Opens a link to the Freeseer online documentation"""
        url = QUrl("http://freeseer.readthedocs.org")
        QDesktopServices.openUrl(url)

    def openNewIssueUrl(self):
        """Opens a link to the Freeseer new issue page"""
        url = QUrl("https://github.com/Freeseer/freeseer/issues/new")
        QDesktopServices.openUrl(url)

    def openContactUrl(self):
        """Opens a link to Freeseer's contact information"""
        url = QUrl("http://freeseer.readthedocs.org/en/latest/contact.html")
        QDesktopServices.openUrl(url)
Пример #58
0
class ValorizaSoloUrbano:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ValorizaSoloUrbano_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&_Valoriza Solo Urbano')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'ValorizaSoloUrbano')
        self.toolbar.setObjectName(u'ValorizaSoloUrbano')

    # 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('ValorizaSoloUrbano', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = ValorizaSoloUrbanoDialog()

        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):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/ValorizaSoloUrbano/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Obra Linear'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(
                self.tr(u'&_Valoriza Solo Urbano'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):

        #CARREGA A LISTA DOS NOMES DOS LAYER DA TOC
        layers = self.iface.legendInterface().layers()
        layer_list = []
        i = 0
        iObra = 0
        iLote = 0
        for layer in layers:
            nomeLayer = layer.name()
            layer_list.append(nomeLayer)
            if 'obra' in str(nomeLayer).lower():
                iObra = i
            if 'lote' in str(nomeLayer).lower():
                iLote = i
            i = i + 1

        #SELECIONAR O SHP DA OBRA
        self.dlg.comboBox_obra.clear()
        self.dlg.comboBox_obra.addItems(layer_list)

        #SELECIONAR O SHP DOS LOTES
        self.dlg.comboBox_lote.clear()
        self.dlg.comboBox_lote.addItems(layer_list)

        #SELECIONAR OBRA E LOTE AUTOMATICAMENTE
        self.dlg.comboBox_obra.setCurrentIndex(iObra)
        self.dlg.comboBox_lote.setCurrentIndex(iLote)
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            # pass

            selectedLayerIndex = self.dlg.comboBox_obra.currentIndex()
            selectedLayerObra = layers[selectedLayerIndex]
            selectedLayerIndex = self.dlg.comboBox_lote.currentIndex()
            selectedLayerLote = layers[selectedLayerIndex]

            #LISTA DOS CAMPOS OBTIDA PELO dataProvider
            lotes = selectedLayerLote.dataProvider()

            #CRIACAO DE NOVO CAMPOS EM LOTES
            field_dista1_index = lotes.fields().indexFromName("area")
            if field_dista1_index == -1:
                #CRIAR O CAMPO AREA, POIS ELE NAO EXISTE
                lotes.addAttributes(
                    [QgsField("area", QVariant.Double, 'double', 20, 2)])
                selectedLayerLote.updateFields()

            field_dista1_index = lotes.fields().indexFromName("distobra")
            if field_dista1_index == -1:
                #CRIAR O CAMPO DISTOBRA, POIS ELE NAO EXISTE
                lotes.addAttributes(
                    [QgsField("distobra", QVariant.Double, 'double', 20, 2)])
                selectedLayerLote.updateFields()

            field_valor_index = lotes.fields().indexFromName("valor")
            if field_valor_index == -1:
                #CRIAR O CAMPO VALOR, POIS ELE NAO EXISTE
                lotes.addAttributes(
                    [QgsField("valor", QVariant.Double, 'double', 20, 2)])
                selectedLayerLote.updateFields()

            field_valtot_index = lotes.fields().indexFromName("valtot")
            if field_valtot_index == -1:
                #CRIAR O CAMPO VALTOT, POIS ELE NAO EXISTE
                lotes.addAttributes(
                    [QgsField("valtot", QVariant.Double, 'double', 20, 2)])
                selectedLayerLote.updateFields()

            #DETECTA OS IDs DOS NOVOS CAMPOS CRIADOS
            id_field_area = lotes.fields().indexFromName('area')
            id_field_distObra = lotes.fields().indexFromName('distobra')
            id_field_valor = lotes.fields().indexFromName('valor')
            id_field_valtot = lotes.fields().indexFromName('valtot')

            #PARAMETRO PARA O CALCULO DE VALOR1
            if self.dlg.radioButton_pav.isChecked():
                #radioButton_pavimentacao_via
                localmin1 = 0.00
                localmax1 = 100.00
                valor1 = 10.00
                localmin2 = 100.00
                localmax2 = 200.00
                valor2 = 5.00
                localmin3 = 200.00
                localmax3 = 300.00
                valor3 = 2.50

            #LE AS COORDENADA DA OBRA
            for fObra in selectedLayerObra.getFeatures():
                geomObra = fObra.geometry()

            #INICIO DA EDICAO DOS DADOS
            selectedLayerLote.startEditing()

            #LE AS COORDENADA DOS LOTES
            val_tot_geral = 0.00
            val_tot_area = 0.00
            tot_lotes = 0
            for fLote in selectedLayerLote.getFeatures():
                id = fLote.id()
                geomLote = fLote.geometry()

                #CALCULO DA DISTANCIA ENTRE POLIGONOS E AREA DO LOTE
                distobra = QgsGeometry.distance(geomLote, geomObra)
                val_area = QgsGeometry.area(geomLote)

                valor = 0.0
                if localmin1 <= distobra < localmax1:
                    valor = valor1
                elif localmin2 <= distobra < localmax2:
                    valor = valor2
                elif localmin3 <= distobra < localmax3:
                    valor = valor3

                #TOTALIZA VALOR POR LOTE
                val_tot_lot = val_area * valor

                #TOTALIZA POR LOTE AFETADO
                if valor > 0:
                    val_tot_area = val_tot_area + val_area
                    val_tot_geral = val_tot_geral + val_tot_lot
                    tot_lotes = tot_lotes + 1

                #GRAVA OS VALORES NA CAMADA DE LOTES
                selectedLayerLote.changeAttributeValue(id, id_field_area,
                                                       geomLote.area())
                selectedLayerLote.changeAttributeValue(id, id_field_distObra,
                                                       distobra)
                selectedLayerLote.changeAttributeValue(id, id_field_valor,
                                                       valor)
                selectedLayerLote.changeAttributeValue(id, id_field_valtot,
                                                       val_tot_lot)

            #COMITA AS MUDANCAS
            selectedLayerLote.commitChanges()

            iface.messageBar().pushMessage("BID - VALORIZA SOLO URBANO",
                                           "Calculo realizado com sucesso!",
                                           level=QgsMessageBar.INFO,
                                           duration=5)

            #ABRE A TABELA DE ATRIBUTOS DOS LOTES
            iface.showAttributeTable(selectedLayerLote)

            #FORMATA A MENSAGEM
            tot_tributo_geral = val_tot_geral * 0.02
            tot_valor = round(val_tot_geral, 2)
            tot_area = round(val_tot_area, 2)
            tot_tributo = round(tot_tributo_geral, 2)
            tot_valor_formatado = '{0:,}'.format(tot_valor).replace(',', '.')
            tot_tributo_formatado = '{0:,}'.format(tot_tributo).replace(
                ',', '.')
            tot_area_formatado = '{0:,}'.format(tot_area).replace(',', '.')
            tot_lotes_formatado = '{0:,}'.format(tot_lotes).replace(',', '.')
            txt1 = '%s' % ("VALORIZA SOLO URBANO\n\n\n")
            txt2 = 'Total Lotes......................=  %s\n\n' % (
                tot_lotes_formatado)
            txt3 = 'Total Area (m2)..............=  %s\n\n' % (
                tot_area_formatado)
            txt4 = 'Total Incremento ($).....=  %s\n\n' % (tot_valor_formatado)
            txt5 = 'Total Aliquota a 2 ($).....=  %s\n' % (
                tot_tributo_formatado)
            txt6 = '%s%s%s%s%s' % (txt1, txt2, txt3, txt4, txt5)
            import ctypes
            MessageBox = ctypes.windll.user32.MessageBoxA
            MessageBox(None, txt6, '   B I D  /  A B R A S F', 0)
Пример #59
0
class Plugin:
    """The QGIS interface implementation for the Risk in a box plugin.

    This class acts as the 'glue' between QGIS and our custom logic.
    It creates a toolbar and menubar entry and launches the InaSAFE user
    interface if these are activated.
    """
    def __init__(self, iface):
        """Class constructor.

        On instantiation, the plugin instance will be assigned a copy
        of the QGIS iface object which will allow this plugin to access and
        manipulate the running QGIS instance that spawned it.

        Args:
           iface - a Quantum GIS QGisAppInterface instance. This instance
           is automatically passed to the plugin by QGIS when it loads the
           plugin.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """

        # Save reference to the QGIS interface
        self.iface = iface
        self.translator = None
        self.setupI18n()
        #print self.tr('InaSAFE')

    def setupI18n(self, thePreferredLocale=None):
        """Setup internationalisation for the plugin.

        See if QGIS wants to override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        Args:
           thePreferredLocale - optional parameter which if set
           will override any other way of determining locale..
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        myOverrideFlag = QSettings().value('locale/overrideFlag',
                                           QVariant(False)).toBool()
        myLocaleName = None
        if thePreferredLocale is not None:
            myLocaleName = thePreferredLocale
        elif myOverrideFlag:
            myLocaleName = QSettings().value('locale/userLocale',
                                             QVariant('')).toString()
        else:
            myLocaleName = QLocale.system().name()
        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(myLocaleName)

        myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        myTranslationPath = os.path.join(
            myRoot, 'safe_qgis', 'i18n',
            'inasafe_' + str(myLocaleName) + '.qm')
        if os.path.exists(myTranslationPath):
            self.translator = QTranslator()
            myResult = self.translator.load(myTranslationPath)
            if not myResult:
                myMessage = 'Failed to load translation for %s' % myLocaleName
                raise TranslationLoadException(myMessage)
            QCoreApplication.installTranslator(self.translator)

    def tr(self, theString):
        """We implement this ourself since we do not inherit QObject.

        Args:
           theString - string for translation.
        Returns:
           Translated version of theString.
        Raises:
           no exceptions explicitly raised.
        """
        return QCoreApplication.translate('Plugin', theString)

    def initGui(self):
        """Gui initialisation procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to set up
        any graphical user interface elements that should appear in QGIS by
        default (i.e. before the user performs any explicit action with the
        plugin).

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Import dock here as it needs to be imported AFTER i18n is set up
        from safe_qgis.dock import Dock
        self.dockWidget = None
        #--------------------------------------
        # Create action for plugin dockable window (show/hide)
        #--------------------------------------
        # pylint: disable=W0201
        self.actionDock = QAction(QIcon(':/plugins/inasafe/icon.png'),
                                  self.tr('Toggle InaSAFE Dock'),
                                  self.iface.mainWindow())
        self.actionDock.setStatusTip(self.tr('Show/hide InaSAFE dock widget'))
        self.actionDock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget'))
        self.actionDock.setCheckable(True)
        self.actionDock.setChecked(True)
        QObject.connect(self.actionDock, SIGNAL('triggered()'),
                        self.showHideDockWidget)
        # add to plugin toolbar
        self.iface.addToolBarIcon(self.actionDock)
        # add to plugin menu
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionDock)

        #--------------------------------------
        # Create action for keywords editor
        #--------------------------------------
        self.actionKeywordsDialog = QAction(
            QIcon(':/plugins/inasafe/keywords.png'), self.tr('Keyword Editor'),
            self.iface.mainWindow())
        self.actionKeywordsDialog.setStatusTip(
            self.tr('Open the keywords editor'))
        self.actionKeywordsDialog.setWhatsThis(
            self.tr('Open the keywords editor'))
        QObject.connect(self.actionKeywordsDialog, SIGNAL('triggered()'),
                        self.showKeywordsEditor)

        self.iface.addToolBarIcon(self.actionKeywordsDialog)
        self.iface.addPluginToMenu(self.tr('InaSAFE'),
                                   self.actionKeywordsDialog)
        #--------------------------------------
        # Create action for reset icon
        #--------------------------------------
        self.actionResetDock = QAction(QIcon(':/plugins/inasafe/reload.png'),
                                       self.tr('Reset Dock'),
                                       self.iface.mainWindow())
        self.actionResetDock.setStatusTip(self.tr('Reset the InaSAFE Dock'))
        self.actionResetDock.setWhatsThis(self.tr('Reset the InaSAFE Dock'))
        QObject.connect(self.actionResetDock, SIGNAL('triggered()'),
                        self.resetDock)

        self.iface.addToolBarIcon(self.actionResetDock)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionResetDock)

        #--------------------------------------
        # Create action for options dialog
        #--------------------------------------
        self.actionOptions = QAction(QIcon(':/plugins/inasafe/options.png'),
                                     self.tr('InaSAFE Options'),
                                     self.iface.mainWindow())
        self.actionOptions.setStatusTip(self.tr('Open InaSAFE options dialog'))
        self.actionOptions.setWhatsThis(self.tr('Open InaSAFE options dialog'))
        QObject.connect(self.actionOptions, SIGNAL('triggered()'),
                        self.showOptions)

        self.iface.addToolBarIcon(self.actionOptions)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionOptions)

        #--------------------------------------
        # create dockwidget and tabify it with the legend
        #--------------------------------------
        self.dockWidget = Dock(self.iface)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget)
        myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend')
        if myLegendTab:
            self.iface.mainWindow().tabifyDockWidget(myLegendTab,
                                                     self.dockWidget)
            self.dockWidget.raise_()

        #
        # Hook up a slot for when the current layer is changed
        #
        QObject.connect(self.iface,
                        SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                        self.layerChanged)
        # pylint: disable=W0201

    def unload(self):
        """Gui breakdown procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock)
        self.iface.removeToolBarIcon(self.actionDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'),
                                    self.actionKeywordsDialog)
        self.iface.removeToolBarIcon(self.actionKeywordsDialog)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock)
        self.iface.removeToolBarIcon(self.actionResetDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions)
        self.iface.removeToolBarIcon(self.actionOptions)
        self.iface.mainWindow().removeDockWidget(self.dockWidget)
        self.dockWidget.setVisible(False)
        self.dockWidget.destroy()
        QObject.disconnect(self.iface,
                           SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                           self.layerChanged)

    # Run method that performs all the real work
    def showHideDockWidget(self):
        """Show or hide the dock widget.

        This slot is called when the user clicks the toolbar icon or
        menu item associated with this plugin. It will hide or show
        the dock depending on its current state.

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        if self.dockWidget.isVisible():
            self.dockWidget.setVisible(False)
        else:
            self.dockWidget.setVisible(True)
            self.dockWidget.raise_()

    def showOptions(self):
        """Show the options dialog.

        This slot is called when the user clicks the options toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.options_dialog import OptionsDialog

        myDialog = OptionsDialog(self.iface.mainWindow(), self.iface,
                                 self.dockWidget)
        myDialog.show()

    def showKeywordsEditor(self):
        """Show the keywords editor.

        This slot is called when the user clicks the keyword editor toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.keywords_dialog import KeywordsDialog

        if self.iface.activeLayer() is None:
            return
        myDialog = KeywordsDialog(self.iface.mainWindow(), self.iface,
                                  self.dockWidget)
        myDialog.show()

    def resetDock(self):
        """Reset the dock to its default state.

        This slot is called when the user clicks the reset icon in the toolbar
        or the reset menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        self.dockWidget.getLayers()

    def layerChanged(self, theLayer):
        """Enable or disable the keywords editor icon.

        This slot is called when the user clicks the keyword editor toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        if theLayer is None:
            self.actionKeywordsDialog.setEnabled(False)
        else:
            self.actionKeywordsDialog.setEnabled(True)
        self.dockWidget.layerChanged(theLayer)
Пример #60
0
class GeodynGem:
    """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: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'GeodynGem_{}.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)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Geodyn gemeente')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GeodynGem')
        self.toolbar.setObjectName(u'GeodynGem')

        # iface.messageBar().pushMessage("Error", "I'm sorry Dave, I'm afraid I can't do that",
        #                                level=QgsMessageBar.CRITICAL)

    # 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('GeodynGem', 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
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = GeodynGemDialog()

        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.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        self.dlg.lineEdit.clear()
        self.dlg.pushButton.clicked.connect(self.select_output_folder)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/GeodynGem/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(
                u'geografische afvalwater prognose tool voor gemeenten'),
            callback=self.run,
            parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Geodyn gemeente'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def move_to_front(self, l, txt):
        """searches for txt in layer.name() if match: move to front of list"""
        index = [l.index(i) for i in l if txt.lower() in i.name().lower()]
        if len(index) > 0:
            l.insert(0, l.pop(index[0]))
        if txt in ["VE", "opp"]:
            l.append(QgsVectorLayer(baseName="no data"))
        return l

    def remove_result_layers(self, remove_all=False, delete_source=False):
        layers_to_remove = [
            layer for layer, flag in settings.l_result_layers_to_remove
            if remove_all or flag
        ]
        ins = QgsMapLayerRegistry.instance()
        ##layers = ins.mapLayersByName()
        layers = self.iface.legendInterface().layers()
        for layer in layers:
            source = layer.source()
            if layer.name() in layers_to_remove:
                print_log("remove layer {}".format(layer.name()), "d")
                ins.removeMapLayer(layer.id())
                if delete_source:
                    pass  # not sure if necessary
                    result = QgsVectorFileWriter.deleteShapeFile(source)
                    if not result:
                        print_log(
                            "Tool afgebroken! Kan resultaat ({}) niet verwijderen!"
                            .format(source), "e", self.iface)
                        return

    def select_output_folder(self):
        # filename = QFileDialog.getSaveFileName(self.dlg, "Select output folder ", "", '*.txt')
        # outputFolder = QFileDialog.getExistingDirectory(self.dlg, "Select Output Folder", QDir.currentPath())
        outputFolder = QFileDialog.getExistingDirectory(
            self.dlg, 'Select Output Folder')
        self.dlg.lineEdit.setText(outputFolder)

    def run(self):
        """Run method that performs all the real work"""

        self.remove_result_layers(remove_all=True, delete_source=True)

        layers = self.iface.legendInterface().layers()
        if not layers:
            print_log(
                "Tool afgebroken! Geen layers gevonden. Voeg eerst layers toe",
                "e", self.iface)
            return
        layer_points, layer_lines, layer_polygons = [], [], []
        if b_QgsWKBTypes:
            for i, layer in enumerate(layers):
                if hasattr(layer, "wkbType"):
                    # qgis.core.QgsWKBTypes.displayString(int(vl.wkbType()))
                    if "point" in QgsWKBTypes.displayString(
                            int(layer.wkbType())).lower():  ## QGis.WKBPoint:
                        layer_points.append(layer)
                    elif "line" in QgsWKBTypes.displayString(
                            int(layer.wkbType())).lower(
                            ):  ##QGis.WKBLineString:
                        layer_lines.append(layer)
                    elif "polygon" in QgsWKBTypes.displayString(
                            int(layer.wkbType())).lower():  ##QGis.WKBPolygon:
                        layer_polygons.append(layer)
                    else:
                        pass

        else:
            print_log(
                "ImportError for QgsWKBTypes. Kan geen geometrie herkennen voor layer inputs. \
                        Controleer of juiste layers zijn geselecteerd of upgrade QGIS.",
                "w", self.iface)
            layer_points = layer_lines = layer_polygons = layers

        self.dlg.comboBox_1.clear()
        self.dlg.comboBox_2.clear()
        self.dlg.comboBox_3.clear()
        self.dlg.comboBox_4.clear()
        self.dlg.comboBox_5.clear()
        self.dlg.comboBox_6.clear()
        self.dlg.comboBox_7.clear()
        self.dlg.comboBox_1.addItems([
            i.name() for i in self.move_to_front(layer_points, "punt")
        ])  # knooppunt
        self.dlg.comboBox_2.addItems([
            i.name() for i in self.move_to_front(layer_lines, "lijn")
        ])  # afvoerrelatie
        self.dlg.comboBox_3.addItems([
            i.name() for i in self.move_to_front(layer_points, "BAG")
        ])  # drinkwater BAG
        self.dlg.comboBox_4.addItems(
            [i.name() for i in self.move_to_front(layer_points, "VE")])  # VE's
        self.dlg.comboBox_5.addItems([
            i.name() for i in self.move_to_front(layer_polygons, "RIGO")
        ])  # plancap
        self.dlg.comboBox_6.addItems([
            i.name() for i in self.move_to_front(layer_polygons, "opp")
        ])  # verhard opp
        self.dlg.comboBox_7.addItems([
            i.name() for i in self.move_to_front(layer_polygons, "bemaling")
        ])  # bemalingsgebieden

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            ##QgsMessageLog.logMessage("sel_index = {}".format(sel_index, level=QgsMessageLog.INFO))
            ##QgsMessageLog.logMessage("layer_index 4 = {}".format(self.move_to_front(layer_points, "VE")[self.dlg.comboBox_4.currentIndex()].name()), level=QgsMessageLog.INFO)
            ##QgsMessageLog.logMessage("layer4 = {}".format([i.name() for i in l4]), level=QgsMessageLog.INFO)

            sel_layers = [
                self.move_to_front(layer_points,
                                   "punt")[self.dlg.comboBox_1.currentIndex()],
                self.move_to_front(layer_lines,
                                   "lijn")[self.dlg.comboBox_2.currentIndex()],
                self.move_to_front(layer_points,
                                   "BAG")[self.dlg.comboBox_3.currentIndex()],
                self.move_to_front(layer_points,
                                   "VE")[self.dlg.comboBox_4.currentIndex()],
                self.move_to_front(layer_polygons,
                                   "RIGO")[self.dlg.comboBox_5.currentIndex()],
                self.move_to_front(layer_polygons,
                                   "opp")[self.dlg.comboBox_6.currentIndex()],
                self.move_to_front(
                    layer_polygons,
                    "bemaling")[self.dlg.comboBox_7.currentIndex()],
            ]

            # refresh input layers, werkt niet... voorlopig dan maar handmatig weggooien.
            ##sel_layernames = [layer.name() for layer in sel_layers]
            ##self.remove_result_layers(settings.l_result_layers_all)
            ##sel_layers = []
            ##layers = self.iface.legendInterface().layers()
            ##for layer in layers:
            ##    if layer.name() in sel_layernames:
            ##        sel_layers.append(layer)

            gdb = self.dlg.lineEdit.text()
            if not gdb or not os.path.exists(gdb):
                print_log(
                    "Script afgebroken! Geen geldige output map opgegeven ({}...)"
                    .format(gdb), "e", self.iface)
                return

            qgis_warnings_log = settings.qgis_warnings_log
            with open(qgis_warnings_log, 'w') as logfile:
                import time
                logfile.write('{level}: date {time}'.format(
                    level="INFO", time=time.asctime()))

            blokje_log("Veld-info ophalen...", "i")
            INP_FIELDS_XLS = settings.INP_FIELDS_XLS
            INP_FIELDS_CSV = settings.INP_FIELDS_CSV
            try:
                from xlrd import open_workbook
                d_velden = get_d_velden(INP_FIELDS_XLS, 0, open_workbook)
            except ImportError:  # for compatibility with iMac
                print_log(
                    "import error 'xlrd': inp_fields.csv wordt gebruikt als input in plaats van inp_fields.xls!",
                    "w", self.iface)
                d_velden = get_d_velden_csv(INP_FIELDS_CSV)
            for fld in d_velden:
                print_log("{}\n{}".format(fld, d_velden[fld]), "d")

            ##self.iface.messageBar().pushMessage("titel", "Start module 1", QgsMessageBar.INFO, duration=5)
            m1.main(self.iface, sel_layers, gdb, d_velden)
            ##self.iface.messageBar().pushMessage("titel", "Start module 2", QgsMessageBar.INFO, duration=5)
            m2.main(self.iface, sel_layers, gdb, d_velden)

            self.remove_result_layers(remove_all=False, delete_source=False)

            ##self.iface.mainWindow().statusBar().showMessage("dit is de mainWindow")
            warnings = []
            with open(qgis_warnings_log, 'r') as log_file:
                for line in log_file.readlines():
                    if "WARNING" in line:
                        warnings.append(line)

            msg = QMessageBox()
            if len(warnings) > 0:
                msg.setIcon(QMessageBox.Warning)
                msg.setWindowTitle("Script completed")
                msg.setText(
                    "{} warnings were encountered when running script".format(
                        len(warnings)))
                msg.setInformativeText(
                    "For more information see details below or view log panel")
                msg.setDetailedText("The details are as follows:")
                msg.setDetailedText("\n".join(warnings))
                # for line in warnings:
                #     msg.setDetailedText(line)
            else:
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle("Script completed")
                msg.setText(
                    "No problems were encountered when running script!")
            retval = msg.exec_()
            ##QMessageBox.information(msg, "Info", "Script completed!")
            QgsMessageLog.logMessage("Script completed!",
                                     level=QgsMessageLog.INFO)