Example #1
0
 def initialize(self):
     " Init Class dock "
     self.dock = QDockWidget()
     self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                           QDockWidget.DockWidgetMovable)
     self.dock.setWindowTitle(__doc__)
     self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
     self.boton = QAction(QIcon.fromTheme("list-add"), 'Open', self)
     self.saver = QAction(QIcon.fromTheme("document-save"), 'Save', self)
     self.apiss = QAction(QIcon.fromTheme("help"), 'Python API Help', self)
     QToolBar(self.dock).addActions((self.boton, self.saver, self.apiss))
     try:
         self.factory = KPluginLoader("kigpart").factory()
         self.part = self.factory.create(self)
         self.part.setReadWrite(True)
         self.boton.triggered.connect(lambda: self.part.openUrl(KUrl(str(
             QFileDialog.getOpenFileName(self.dock, ' Open Geometry Plot ',
             path.expanduser("~"),
             ';;'.join(['(*.{})'.format(e) for e in ['fig', 'kig', 'kigz',
                                                     'seg', 'fgeo']]))))))
         self.saver.triggered.connect(lambda: self.part.saveAs(KUrl(str(
             QFileDialog.getSaveFileName(self.dock, ' Save Geometry Plot ',
             path.expanduser("~"),
             ';;'.join(['(*.{})'.format(e) for e in ['kig', 'kigz', 'fig']])
         )))))
         self.apiss.triggered.connect(lambda: open_new_tab(
             'http://edu.kde.org/kig/manual/scripting-api/classObject.html'))
         self.dock.setWidget(self.part.widget())
     except:
         self.dock.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
         ERROR: Please, install KIG and PyKDE ! </h3><br>
         <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))
     self.misc = self.locator.get_service('misc')
     self.misc.add_widget(self.dock,
                         QIcon.fromTheme("accessories-calculator"), __doc__)
Example #2
0
    def saveProjectAs(self):
        ''' Save the project configuration under a different name '''
        try:
            # get the location for the new config file on disk
            start_dir = paths.OPUS_PROJECT_CONFIGS_PATH
            configDialog = QFileDialog()
            filter_str = QString("*.xml")
            fd = configDialog.getSaveFileName(self,QString("Save As..."),
                                              QString(start_dir), filter_str)
            # Check for cancel
            if not fd:
                return

            filename = QString(fd)
            # append xml extension if no extension was given
            if not filename.endsWith('.xml') and len(filename.split('.')) == 1:
                filename = filename + '.xml'

            if not self.saveProject(filename):
                return

            # hack: open the project right after save to properly change the
            # 'active project' related parameters
            self.openProject(filename)

        except:
            errorMessage = formatExceptionInfo(custom_message = \
                                               'Unexpected error saving config')
            QMessageBox.warning(self, 'Warning', errorMessage)
Example #3
0
 def _saveToFile( self, sender, startFolder=None ):
     'save to file'
     #"Shape Files (*.shp);;Geojson File (*.geojson);;GML ( *.gml);;Comma separated value File (excel) (*.csv);;MapInfo TAB (*.TAB);;Any File (*.*)"
     filter = "ESRI Shape Files (*.shp);;SpatiaLite (*.sqlite);;Any File (*.*)" #show only formats with update capabilty
     Fdlg = QFileDialog()
     Fdlg.setFileMode(QFileDialog.AnyFile)
     fName = QFileDialog.getSaveFileName(sender, "open file", filter=filter, directory=startFolder)
     if fName:
       ext = os.path.splitext( fName )[1]
       if "SHP" in ext.upper():
         flType = "ESRI Shapefile"
       elif "SQLITE" in ext.upper():
         flType = "SQLite" 
       elif "GEOJSON" in ext.upper():  #no update possible -> hidden
         flType = "GeoJSON"
       elif "GML" in ext.upper():
         flType = "GML"
       elif 'TAB' in ext.upper():
         flType = 'MapInfo File'
       elif 'KML' in ext.upper():
         flType = 'KML'
       else:
         fName = fName + ".shp"
         flType = "ESRI Shapefile"
       return (fName , flType )
     else:
         return None
Example #4
0
    def exec_dialog(self):
        """ Exec a native file dialog for the declaration state.

        """
        d = self.declaration
        path = d.path
        caption = d.title
        filters = ';;'.join(d.filters)
        selected_filter = d.selected_filter
        if d.mode == 'open_file':
            path, selected_filter = QFileDialog.getOpenFileNameAndFilter(
                self.parent_widget(), caption, path, filters, selected_filter
            )
            paths = [path] if path else []
        elif d.mode == 'open_files':
            paths, selected_filter = QFileDialog.getOpenFileNamesAndFilter(
                self.parent_widget(), caption, path, filters, selected_filter
            )
        elif d.mode == 'save_file':
            path, selected_filter = QFileDialog.getSaveFileNameAndFilter(
                self.parent_widget(), caption, path, filters, selected_filter
            )
            paths = [path] if path else []
        else:
            path = QFileDialog.getExistingDirectory(
                self.parent_widget(), caption, path
            )
            paths = [path] if path else []
        result = 'accepted' if paths else 'rejected'
        d._handle_close(result, paths, selected_filter)
Example #5
0
 def open_dir(self):
     dlg = QFileDialog(self)
     dir = dlg.getExistingDirectory(self,
                                         "选取文件夹",
                                         "/home/magicyang/Music",
                                         )
     self.walk_dir(dir)
 def save_report(self):
     file_dialog = QFileDialog()
     report_filename = file_dialog.getSaveFileName(self, 'Save report', filter='*.xml')
     if report_filename == '' or report_filename is None:
         return
     report = self.gather_report()
     report.saveToFile(report_filename)
Example #7
0
	def __addLocation(self, type, *args):
		"""
		Defines the slot triggered by **Where_lineEdit** Widget when a context menu entry is clicked.

		:param type: Location type.
		:type type: unicode
		:param \*args: Arguments.
		:type \*args: \*
		"""

		if type == "directory":
			location = umbra.ui.common.storeLastBrowsedPath((QFileDialog.getExistingDirectory(self,
																						"Add Directory:",
																						RuntimeGlobals.lastBrowsedPath)))
		elif type == "file":
			location = umbra.ui.common.storeLastBrowsedPath((QFileDialog.getOpenFileName(self,
																						"Add File:",
																						RuntimeGlobals.lastBrowsedPath,
																						"All Files (*)")))
		elif type == "editors":
			location = self.__targetsFormat.format(self.__defaultTarget)
		elif type == "includeFilter":
			location = self.__filtersInFormat.format(self.__defaultFilterIn)
		elif type == "excludeFilter":
			location = self.__filtersOutFormat.format(self.__defaultFilterOut)

		location and self.Where_lineEdit.setText(", ".join(filter(bool, (foundations.strings.toString(
		self.Where_lineEdit.text()), location))))
Example #8
0
    def select_file(self):
        """select file ops"""

        label = self.tr('eXtensible Markup Language (*.xml *.XML)')

        if self.mode == 0:
            slabel = self.tr('Save connections')
            self.filename = QFileDialog.getSaveFileName(self, slabel,
                                                        '.', label)
        else:
            slabel = self.tr('Load connections')
            self.filename = QFileDialog.getOpenFileName(self, slabel,
                                                        '.', label)

        if not self.filename:
            return

        # ensure the user never omitted the extension from the file name
        if not self.filename.lower().endswith('.xml'):
            self.filename = '%s.xml' % self.filename

        self.leFileName.setText(self.filename)

        if self.mode == 1:
            self.populate()

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
Example #9
0
 def connectDatabaseWithGui(self):
     '''
     Connects to database using user interface dialog
     '''
     fd = QFileDialog()
     filename = fd.getOpenFileName(caption=self.tr('Select a DSGTools Spatialite file'),filter=self.tr('Spatialite file databases (*.sqlite)'))
     self.db.setDatabaseName(filename)
Example #10
0
    def __get_datadir(self, app=False, directory=''):
        """
        Draw a dialog for directory selection.
        """

        from PyQt4.QtGui import QFileDialog
        if app:
            dcmdir = QFileDialog.getExistingDirectory(
                caption='Select DICOM Folder',
                options=QFileDialog.ShowDirsOnly,
                directory=directory
            )
        else:
            app = QApplication(sys.argv)
            dcmdir = QFileDialog.getExistingDirectory(
                caption='Select DICOM Folder',
                options=QFileDialog.ShowDirsOnly,
                directory=directory
            )
            # pp.exec_()
            app.exit(0)
        if len(dcmdir) > 0:

            dcmdir = "%s" % (dcmdir)
            dcmdir = dcmdir.encode("utf8")
        else:
            dcmdir = None
        return dcmdir
Example #11
0
    def browseDb_clicked(self, database_type):
        """
        Method run dialog for select database in widget with changes.
        According to pushButton name will fill in relevant lineEdit.
        :type database_type: str
        """
        title = u'Vyber databázi'
        settings = QSettings()
        lastUsedDir = str(settings.value('/UI/' + "lastVectorFileFilter" + "Dir", "."))

        if database_type == 'mainDb':
            self.__databases[database_type] = QFileDialog.getOpenFileName(self, title, lastUsedDir, u'Datábaze (*.db)')
            if not self.__databases[database_type]:
                return
            self.le_mainDb.setText(self.__databases[database_type])

        elif database_type == 'amendmentDb':
            self.__databases[database_type] = QFileDialog.getOpenFileName(self, title, lastUsedDir, u'Datábaze (*.db)')
            if not self.__databases[database_type]:
                return
            self.le_amendmentDb.setText(self.__databases[database_type])

        elif database_type == 'exportDb':
            title = u'Zadej jméno výstupní databáze'
            self.__databases[database_type] = QFileDialog.getSaveFileName(self, u"Jméno výstupní databáze",
                                                                          ".db", u"Databáze (*.db)")
            if not self.__databases[database_type]:
                return
            self.le_exportDb.setText(self.__databases[database_type])

        if len(self.__databases) == 3:
            self.pb_applyChanges.setEnabled(True)
Example #12
0
 def browseLocalRepository(self):
     fd = QFileDialog()
     repoAddress = fd.getOpenFileName(None, "Caption", "/", "Index File (*.xml *.xml.bz2 *.xz)")
     if repoAddress:
         if not self.repoDialog.repoName.text():
             self.repoDialog.repoName.setText(self.generateRepoName(repoAddress))
         self.repoDialog.repoAddress.setEditText(repoAddress)
Example #13
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)

        self.axSlider.valueChanged.connect(self.setAx)
        self.sxSlider.valueChanged.connect(self.setSx)
        self.aSlider.valueChanged.connect(lambda x: self.setA(x/1000))
        self.hSlider.valueChanged.connect(lambda x: self.setH(x/1000))

        self.showOriginal = False
        self.loadButton.clicked.connect(lambda: self.loadImage(QFileDialog.getOpenFileName(self, "Open Image")))
        self.saveButton.clicked.connect(lambda: self.saveImage(QFileDialog.getSaveFileName(self, "Save Image", filter="*.png")))
        self.toggleOriginalButton.clicked.connect(self.toggleImage)

        platform = choose(self, cl.get_platforms(), "OpenCL Platform", "Please choose OpenCL Platform")
        print(platform)
        device = choose(self, platform.get_devices(), "OpenCL Device", "Please choose OpenCL Device")
        print(device)
        ctx = cl.Context([device])
        self.nlmeans = NLMeans(ctx)

        self.imageLabel = QLabel()
        self.imageScrollarea.setWidget(self.imageLabel)
        self.maskScrollarea.setAlignment(Qt.AlignCenter)

        self.maskLabel = QLabel()
        self.maskScrollarea.setWidget(self.maskLabel)
        self.showMask()

        self.loadImage("lena.jpg")

        self.resetButton.clicked.connect(self.resetParameters)
        self.resetParameters()
Example #14
0
 def initialize(self, *args, **kwargs):
     " Init Main Class "
     super(Main, self).initialize(*args, **kwargs)
     self.loca = self.locator.get_service("menuApp")
     self.loca.add_action(
         QAction(
             QIcon.fromTheme("edit-select-all"),
             "PySide to PyQt",
             self,
             triggered=lambda: self.locator.get_service("editor").add_editor(
                 content=str(
                     open(
                         path.abspath(
                             QFileDialog.getOpenFileName(
                                 None, "{} - Open a PySide PY File".format(__doc__), path.expanduser("~"), "PY(*.py)"
                             )
                         ),
                         "r",
                     ).read()
                 )
                 .strip()
                 .replace("PySide", "PyQt4")
                 .replace("Signal", "pyqtSignal")
                 .replace("Slot", "pyqtSlot")
                 .replace("Property", "pyqtProperty")
                 .replace("pyside-uic", "pyuic4")
                 .replace("pyside-rcc", "pyrcc4")
                 .replace("pyside-lupdate", "pylupdate4"),
                 syntax="python",
             ),
         )
     )
     self.loca.add_action(
         QAction(
             QIcon.fromTheme("edit-select-all"),
             "PyQt to PySide",
             self,
             triggered=lambda: self.locator.get_service("editor").add_editor(
                 content=str(
                     open(
                         path.abspath(
                             QFileDialog.getOpenFileName(
                                 None, "{} - Open a PyQt 4 PY File".format(__doc__), path.expanduser("~"), "PY(*.py)"
                             )
                         ),
                         "r",
                     ).read()
                 )
                 .strip()
                 .replace("PyQt4", "PySide")
                 .replace("pyqtSignal", "Signal")
                 .replace("pyqtSlot", "Slot")
                 .replace("pyqtProperty", "Property")
                 .replace("pyuic4", "pyside-uic")
                 .replace("pyrcc4", "pyside-rcc")
                 .replace("pylupdate4", "pyside-lupdate"),
                 syntax="python",
             ),
         )
     )
Example #15
0
    def onSelectFolder(self):

        Fdialog = QFileDialog()
        Fdialog.setFileMode(QFileDialog.DirectoryOnly)
        if Fdialog.exec_():
            folderPath = QStringList(Fdialog.selectedFiles())
            self.ui.dirEdit.setText(folderPath.takeFirst())
Example #16
0
 def on_pushButtonStackPathClicked(self):
     folderDlg = QFileDialog() 
     suffix = str(self.comboBoxStackFileType.currentText())
     path = str(folderDlg.getSaveFileName(self, "Save File",
                                           str(self.lineEditStackPath.displayText()) + str(self.lineEditStackFileName.displayText()
                                              + "." + suffix)))
     self.updateStackPaths(path)
Example #17
0
 def saveWindow(self, fileName=None, fileType=None, window=False):
     self.repaint() # make sure we are uptodate
     if window:
         pixmap = QPixmap.grabWindow(self.winId())
     else:
         pixmap = QPixmap.grabWidget(self)
     if not fileName:
         fileTypes = {unicode(QCoreApplication.translate('SubWindow', 'PNG - compressed image')):('png',),
             unicode(QCoreApplication.translate('SubWindow', 'JPEG - picture')):('jpg', 'jpeg'),
             unicode(QCoreApplication.translate('SubWindow', 'BMP - uncompressed bitmap')):('bmp',)}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('SubWindow', 'Select name of file to save'),
             Globals.defaultFolder or '', filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = unicode(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
         Globals.defaultFolder, tmp = os.path.split(fileName)
     try:
         pixmap.save(unicode(fileName))
     except:
         QMessageBox.critical(self,
             QCoreApplication.translate('SubWindow', 'Could not save file!'),
             QCoreApplication.translate('SubWindow', 'Writing failed! Make sure you have write permissions!'))
	def get_from_fich(self):
		dialog=QFileDialog(self,"Abrir Modulo",self.parent().workdir,"Modelos Criptocefa (*.json)")
		dialog.setAcceptMode(QFileDialog.AcceptOpen)
		if dialog.exec_():
			fichero = dialog.selectedFiles().first().toLocal8Bit().data()
			self.mod_import.emit(fichero)
			self.parent().edited()
Example #19
0
 def saveContents(self, fileName=None):
     if not fileName:
         fileTypes = {'Text':('txt',), 'HTML':('htm', 'html')}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('QPyShell', 'Select name of file to save'),
             os.getcwd(), filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = unicode(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
     if fileType == 'Text':
         txt = self.outputBrowser.toPlainText()
     elif fileType == 'HTML':
         txt = self.outputBrowser.toHtml()
     else:
         raise IOError('Unknown FileType: %s' % fileType)
     try:
         open(fileName, 'w').write(txt)
     except IOError:
         QMessageBox.critical(self,
             QCoreApplication.translate('QPyShell', 'Could not save file!'),
             QCoreApplication.translate('QPyShell', 'Writing failed! Make sure you have write permissions!'))
Example #20
0
def askForFiles(parent, msg = None, isSave = False, allowMultiple = False, exts = "*"):
    msg = msg or 'Select file'
    name = _callerName()
    path = getSetting(LAST_PATH, name)
    f = None
    if not isinstance(exts, list):
        exts = [exts]
    extString = ";; ".join([" %s files (*.%s)" % (e.upper(), e) if e != "*" else "All files (*.*)" for e in exts])
    if allowMultiple:
        ret = QFileDialog.getOpenFileNames(parent, msg, path, '*.' + extString)
        if ret:
            f = ret[0]
        else:
            f = ret = None
    else:
        if isSave:
            ret = QFileDialog.getSaveFileName(parent, msg, path, '*.' + extString) or None
            if ret is not None and not ret.endswith(exts[0]):
                ret += "." + exts[0]
        else:
            ret = QFileDialog.getOpenFileName(parent, msg , path, '*.' + extString) or None
        f = ret

    if f is not None:
        setSetting(LAST_PATH, name, os.path.dirname(f))

    return ret
Example #21
0
 def do_export(self):
     parameters = self.get_parameters()
     layer_name = self.ui.LayerComboBox.currentText() + '_model.stl'
     if parameters != 0:
         if parameters["spacing_mm"] < 0.5 and self.height > 100 and self.width > 100:
             reply = QMessageBox.question(self, self.tr('Export to STL'),
                                          self.tr('The construction of the STL file could takes several minutes. Do you want to continue?'),
                                          QMessageBox.Yes |
                                          QMessageBox.No, QMessageBox.No)
             if reply == QMessageBox.Yes:
                 f = QFileDialog.getSaveFileNameAndFilter(self, self.tr('Export to STL'), layer_name, filter=".stl")
                 stl_file = f[0]
                 if stl_file:
                     export_dlg = Export_dialog.Dialog(parameters, stl_file)
                     if export_dlg.exec_():
                         QMessageBox.information(self, self.tr("Attention"), self.tr("STL model generated"))
                     else:
                         QMessageBox.information(self, self.tr("Attention"), self.tr("Process canceled"))
         else:
             f = QFileDialog.getSaveFileNameAndFilter(self, self.tr('Export to STL'), layer_name, filter=".stl")
             stl_file = f[0]
             if stl_file:
                 export_dlg = Export_dialog.Dialog(parameters, stl_file)
                 if export_dlg.exec_():
                     QMessageBox.information(self, self.tr("Attention"), self.tr("STL model generated"))
                 else:
                     QMessageBox.information(self, self.tr("Attention"), self.tr("Process canceled"))
     else:
         QMessageBox.warning(self, self.tr("Attention"), self.tr("Fill the data correctly"))
Example #22
0
    def __get_datafile(self, app=False, directory=""):
        """
        Draw a dialog for directory selection.
        """

        from PyQt4.QtGui import QFileDialog

        if app:
            dcmdir = QFileDialog.getOpenFileName(
                caption="Select Data File",
                directory=directory
                # ptions=QFileDialog.ShowDirsOnly,
            )
        else:
            app = QApplication(sys.argv)
            dcmdir = QFileDialog.getOpenFileName(
                caption="Select DICOM Folder",
                # ptions=QFileDialog.ShowDirsOnly,
                directory=directory,
            )
            # pp.exec_()
            app.exit(0)
        if len(dcmdir) > 0:

            dcmdir = "%s" % (dcmdir)
            dcmdir = dcmdir.encode("utf8")
        else:
            dcmdir = None
        return dcmdir
Example #23
0
 def saveWindow(self, fileName=None, fileType=None):
     if not fileName:
         fileTypes = {'Text':('txt',), 'HTML':('htm', 'html')}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('LogWindow', 'Select name of file to save'),
             Globals.defaultFolder or '', filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = str(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
         Globals.defaultFolder, tmp = os.path.split(fileName)
     if fileType == 'Text':
         txt = self.logView.TextArea.toPlainText()
     elif fileType == 'HTML':
         txt = self.logView.TextArea.toHtml()
     else:
         raise Errors.IOError('Unknown FileType: %s' % fileType)
     try:
         open(fileName, 'w').write(txt)
     except IOError:
         QMessageBox.critical(self,
             QCoreApplication.translate('LogWindow', 'Could not save file!'),
             QCoreApplication.translate('LogWindow', 'Writing failed! Make sure you have write permissions!'))
    def select_output_file(self):
		if self.dlg.rbSTLASCII.isChecked() or self.dlg.rbSTLbinary.isChecked():
			filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) , '*.stl')
			self.dlg.lineEdit.setText(filename)
		elif self.dlg.rbTXT.isChecked():
			filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) , '*.txt')
			self.dlg.lineEdit.setText(filename)
Example #25
0
    def selectPath(self):
        """Pops up the 'select a file/directory' dialog"""
        # todo: This probably needs some reworking to work properly with different scenarios... (file + dir)
        self._editing = True
        current_directory = self.getPath()

        #if not os.path.exists(currentDirectory):
        #    currentDirectory = "~"

        if self._model.pathMustBeAFile():
            current_directory = QFileDialog.getOpenFileName(self, "Select a file path", current_directory)
        else:
            current_directory = QFileDialog.getExistingDirectory(self, "Select a directory", current_directory)

        if not current_directory == "":
            if not self._model.pathMustBeAbsolute():
                cwd = os.getcwd()
                match = re.match(cwd + "/(.*)", current_directory)
                if match:
                    current_directory = match.group(1)

            self._path_line.setText(current_directory)
            self._model.setPath(self.getPath())

        self._editing = False
Example #26
0
 def load_file_dialog(self):
     fd = QFileDialog()
     self.filename = fd.getOpenFileName(None, "Load Saved Game", 
                                 "saves", "MapMaster Save files (*.save)")
     if isfile(self.filename):
         self.loadSaved = True
         self.newGame()
Example #27
0
 def browse(self):
     if self.select_dir:
         path = QFileDialog.getExistingDirectory(self, u'Choose folder', '')
     else:
         path = QFileDialog.getSaveFileName(self, u'Save as', '')
     if path:
         self.setPath(path)
Example #28
0
 def saveDir(self, selector):
     text={'WrkDir':'intermediate processing'}
     dialog = QFileDialog()
     dname = dialog.getExistingDirectory(self.dlg, self.tr("Choose a directory to save {}".format(text[selector])), os.path.expanduser("~"))
     if dname:
         if selector=='WrkDir':
             self.dlg.editWrkDir.setText(dname)
Example #29
0
    def showSelectionDialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = settings.value('/Processing/LastInputPath')
        else:
            path = ''

        if self.isFolder:
            folder = QFileDialog.getExistingDirectory(self,
                self.tr('Select folder'), path)
            if folder:
                self.leText.setText(folder)
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(folder))
        else:
            filenames = QFileDialog.getOpenFileNames(self,
                self.tr('Select file'), path, '*.' + self.ext)
            if filenames:
                self.leText.setText(u';'.join(filenames))
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(filenames[0]))
Example #30
0
class OpenDialog(ActionDialog):
    def __init__(self, parent=None, caption = ""):
        super(OpenDialog, self).__init__(parent)
        
        self._filedlg = QFileDialog(None, Qt.Widget)
        self._filedlg.setFileMode(QFileDialog.ExistingFile)
        nameFilter = "Images (*.png *.tif *.tiff *.jpg *.jpeg *.png *.bmp)" +\
            ";;Float images (*.flt)"
        self._filedlg.setNameFilter(nameFilter)
        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0,0,0,0)
        layout.addWidget(self._filedlg)
        
        self.setLayout(layout)
        self.setWindowTitle(caption)
        
        self._filedlg.finished.connect(self.fileDlgDone)

    def fileDlgDone(self, result):
        self._process = OpenFile()
        if result == 1:
            files = self._filedlg.selectedFiles()
            self._process.setInput(files[0])
        self.done(result)
Example #31
0
 def _choosePoints(self):
     fname = QFileDialog.getOpenFileName()
     self._widget.pointsPathTextEdit.setText(fname[0])
Example #32
0
 def selectRootDirectory(self):
     filename = QFileDialog.getExistingDirectory(
         self.dlg, "Select base directory ", self.dlg.rncRootLabel.text())
     self.dlg.rncRootLabel.setText(filename)
     QSettings().setValue('RNCLoader/rnc_root', filename)
     self.scanCharts(filename)
Example #33
0
 def _get_save_file_name(self):
     save_dialog = QFileDialog(parent=self, caption=_('Save listing as...'),
                               filter=_('Data file (*.csv)'))
     save_dialog.setOptions(QFileDialog.DontUseNativeDialog)
     save_dialog.setDefaultSuffix('csv')
     save_dialog.setFileMode(QFileDialog.AnyFile)
     save_dialog.setAcceptMode(QFileDialog.AcceptSave)
     filename = None
     if save_dialog.exec_():
         filename_list = save_dialog.selectedFiles()
         if len(filename_list) == 1:
             filename = unicode(filename_list[0])
     return filename
Example #34
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.RUNS, self.FAILS = 0, 0
        self.group0 = QGroupBox()
        self.group0.setTitle(' Source and Target ')
        self.baseurl = QLineEdit('http://google.com')
        self.outfile = QLineEdit(path.join(path.expanduser("~"), 'test.py'))
        self.outfile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.clicked.connect(lambda: self.outfile.setText(
            QFileDialog.getSaveFileName(self.dock, "Save", path.expanduser(
                "~"), 'PYTHON(*.py)')))
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Base URL'), self.baseurl,
                            QLabel('<b>Local File Target'), self.outfile,
                            self.open):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Selenium ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_group)
        self.ckcss1 = QCheckBox('Test for correct Page Loading behaviour')
        self.ckcss2 = QCheckBox('Test for Sucessfull Status Code return')
        self.ckcss3 = QCheckBox('Test for valid Title of the web page')
        self.ckcss4 = QCheckBox('Test for Cookies Basic functionality')
        self.ckcss5 = QCheckBox('Test for Back, Forward, Reload behaviour')
        self.ckcss6 = QCheckBox('Take a Screenshot of page (CSS Debug)')
        self.ckcss7 = QCheckBox('Test for Search Form Field of the page')
        self.ckcss8 = QCheckBox(
            'Test for Arbitrary Javascript (User provided)')
        self.ckcss9 = QCheckBox('Test for iFrame of the web page')
        self.ckcss10 = QCheckBox('Test for HTML5 Canvas element on the page')
        self.ckcss11 = QCheckBox('Test for HTML5 SVG element on the page')
        self.ckcss12 = QCheckBox('Test for HTML5 Audio element on the page')
        self.ckcss13 = QCheckBox('Test for HTML5 Video element on the page')
        self.ckcss14 = QCheckBox('Test for File Upload form on the page')
        self.ckcss15 = QCheckBox('Add ChromeDriver path to sys.path')
        self.webdriver = QComboBox()
        self.webdriver.addItems(
            ['firefox', 'chrome', 'zope.testbrowser', 'phantomjs'])
        self.titletxt = QLineEdit('Google')
        self.javascript = QLineEdit('console.log("test")')
        self.authdata, self.formdata = QLineEdit(), QLineEdit()
        self.authdata.setPlaceholderText(
            "{'username':'******','password':'******'}")
        self.formdata.setPlaceholderText("{'name': 'Joe', 'age': '25'}")
        self.iframurl = QLineEdit()
        self.chrmedrv = QLineEdit('/usr/bin/chromedriver')
        self.timeout = QSpinBox()
        self.timeout.setMaximum(99)
        self.timeout.setMinimum(0)
        self.timeout.setValue(9)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
                self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                self.ckcss9, self.ckcss10, self.ckcss11,
                self.ckcss12, self.ckcss13, self.ckcss14, self.ckcss15,
                QLabel('<b>WebDriver'), self.webdriver,
                QLabel('''<center><small><i>Firefox is only Driver that dont
                   require additional configuration'''),
                QLabel('<b>Title Content must contain'), self.titletxt,
                QLabel('<b>Minified Javascript for Test'), self.javascript,
                QLabel('<b>Arbitrary Authentication Data for Test'),
                self.authdata, QLabel('<b>Arbitrary Form Data for Test'),
                self.formdata, QLabel('<b>iFrame URL for Test'), self.iframurl,
                QLabel('<b>Chrome Driver'), self.chrmedrv,
                QLabel('<b>Timeout Timer Limit'), self.timeout):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Run the Tests after Writing')
        self.chckbx2 = QCheckBox('Open the Tests with Ninja after Writing')
        self.chckbx3 = QCheckBox('Add SheBang, Encoding and Metadata to Tests')
        self.nice = QSpinBox()
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.nice.setValue(20)
        self.help1 = QLabel(
            '''<a href="http://splinter.cobrateam.info/docs/api"
            ><center><b>API Reference</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2, self.chckbx3,
                            QLabel('Backend CPU priority:'), self.nice,
                            self.help1):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [
            a.setChecked(True)
            for a in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                      self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                      self.ckcss15, self.chckbx1, self.chckbx2, self.chckbx3)
        ]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Write and Run Test')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)
        self.output = QPlainTextEdit()
        self.runs = QLabel('<font color="green"><b>Runs: 0')
        self.failures = QLabel('<font color="red"><b>Failures: 0')

        class TransientWidget(QWidget):
            ' persistant widget thingy '

            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget(
            (QLabel('<b>Selenium Tests'), self.group0, self.group1,
             self.group4, QLabel('<b>Log'), self.output, self.runs,
             self.failures, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Selenium")
        QPushButton(
            QIcon.fromTheme("help-about"), 'About', self.dock).clicked.connect(
                lambda: QMessageBox.information(self.dock, __doc__, HELPMSG))
        QPushButton(
            QIcon.fromTheme("media-record"),
            'Record',
            self.group1,
        ).clicked.connect(lambda: QMessageBox.information(
            self.dock, __doc__,
            'Not working. If you know how to make it Record, send me Pull Request'
        ))
Example #35
0
 def on_directory_button_clicked(self):
     """Show a dialog to choose directory."""
     # noinspection PyCallByClass,PyTypeChecker
     self.output_directory.setText(
         QFileDialog.getExistingDirectory(
             self, self.tr('Select download directory')))
Example #36
0
 def load_folder_venv(self):
     self.vtxtPlace.setText(QFileDialog.getExistingDirectory(
         self, self.tr("Select Virtualenv Folder")))
Example #37
0
 def load_folder(self):
     self.txtPlace.setText(QFileDialog.getExistingDirectory(
         self, self.tr("New Project Folder")))
     self.emit(SIGNAL("completeChanged()"))
Example #38
0
def get_workinglayer_on_opening(iface):
    settings = QSettings()
    last_folder = settings.value("terre_image_last_folder")

    if last_folder:
        path = last_folder
    else:
        path = QDir.currentPath()

    file_opened = QFileDialog.getOpenFileName(None, "Selectionner un fichier raster", path)

    settings.setValue("terre_image_last_folder", os.path.dirname(file_opened))
    settings.sync()

    if file_opened:
        #         try:
        #             str(file_opened)
        #         except UnicodeEncodeError:
        #             QMessageBox.warning( None , "Erreur", u'L\'image que vous essayez d\'ouvrir contient un ou des caractères spéciaux. \
        # La version actuelle du plugin ne gère pas ce type de fichiers. \
        # Veuillez renommer le fichier et ou les répertoires le contenant.', QMessageBox.Ok )
        #             return None, None
        #         else:
        #             if file_opened.find(" ") != -1:
        #                 QMessageBox.warning( None , "Attention", u'L\'image que vous essayez d\'ouvrir contient un ou plusieurs espaces. Les traitements sur cette image provoqueront une erreur.'.encode('utf8'), QMessageBox.Ok )

        if file_opened.endswith(".qgs"):
            # open new qgis project
            pass
        else:
            raster_layer = manage_QGIS.get_raster_layer(file_opened, os.path.splitext(os.path.basename(file_opened))[0])
            if not os.name == "posix":
                terre_image_run_process.set_OTB_PATH()
            type_image = terre_image_processing.get_sensor_id(file_opened)
            logger.debug("type_image " + str(type_image))
            layer = WorkingLayer(file_opened, raster_layer)
            layer.set_type(type_image)
            # self.layer = self.canvas.currentLayer()
            if layer:
                # self.define_bands(self.layer)
                # manage_bands()
                # self.red, self.green, self.blue, self.pir, self.mir = manage_bands().get_values()
                red, green, blue, pir, mir, type_satellite = manage_bands(type_image, layer.get_band_number()).get_values()

                if red != -1 or green != -1 or blue != -1 or pir != -1 or mir != -1:
                    all_set = True
                    bands = {'red': red, 'green': green, 'blue': blue, 'pir': pir, 'mir': mir}
                    for i in range(1, layer.get_band_number() + 1):
                        if i not in bands.values():
                            all_set = False
                    if all_set:
                        layer.set_bands(bands)
                        if layer.type is None:
                            layer.set_type(type_satellite)

                        logger.debug(str(red) + " " + str(green) + " " + str(blue) + " " + str(pir) + " " + str(mir))

                        cst = TerreImageConstant()
                        cst.index_group = cst.iface.legendInterface().addGroup("Terre Image", True, None)

                        manage_QGIS.add_qgis_raser_layer(raster_layer, iface.mapCanvas(), bands)
                        OTBApplications.compute_overviews(file_opened)
                        return layer, bands
                    else:
                        QMessageBox.warning(None, "Erreur",
                                            u'Il y a un problème dans la définition des bandes spectrales.',
                                            QMessageBox.Ok)
                        return None, None
                else:
                    return None, None
    else:
        return None, None
 def save_profile_as(self):
     """Save the minimum needs under a new profile name.
     """
     # noinspection PyCallByClass,PyTypeChecker
     file_name_dialog = QFileDialog(self)
     file_name_dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
     file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
     file_name_dialog.setDefaultSuffix('json')
     file_name_dialog.setDirectory(expanduser('~/.qgis2/minimum_needs'))
     if file_name_dialog.exec_():
         file_name = file_name_dialog.selectedFiles()[0]
     else:
         return
     file_name = basename(file_name)
     file_name = file_name.replace('.json', '')
     minimum_needs = {'resources': []}
     self.mark_current_profile_as_saved()
     for index in xrange(self.resources_list.count()):
         item = self.resources_list.item(index)
         minimum_needs['resources'].append(item.resource_full)
     minimum_needs['provenance'] = self.provenance.text()
     minimum_needs['profile'] = file_name
     self.minimum_needs.update_minimum_needs(minimum_needs)
     self.minimum_needs.save()
     self.minimum_needs.save_profile(file_name)
     if self.profile_combo.findText(file_name) == -1:
         self.profile_combo.addItem(file_name)
     self.profile_combo.setCurrentIndex(
         self.profile_combo.findText(file_name))
Example #40
0
 def _chooseProgram(self):
     fname = QFileDialog.getOpenFileName()
     self._widget.programPathTextEdit.setText(fname[0])
Example #41
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',
            'ImageMorphParmsPoint_{}.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 = ImageMorphParmsPointDialog()
        self.dlg.runButton.clicked.connect(self.start_process)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.dlg.selectpoint.clicked.connect(self.select_point)
        self.dlg.generateArea.clicked.connect(self.generate_area)
        self.dlg.helpButton.clicked.connect(self.help)
        self.dlg.progressBar.setValue(0)
        self.dlg.checkBoxOnlyBuilding.toggled.connect(self.text_enable)

        self.fileDialog = QFileDialog()
        self.fileDialog.setFileMode(4)
        self.fileDialog.setAcceptMode(1)

        for i in range(1, 25):
            if 360 % i == 0:
                self.dlg.degreeBox.addItem(str(i))
        self.dlg.degreeBox.setCurrentIndex(4)

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

        # get reference to the canvas
        self.canvas = self.iface.mapCanvas()
        self.poiLayer = None
        self.polyLayer = None
        self.folderPath = 'None'
        self.degree = 5.0
        self.point = None
        self.pointx = None
        self.pointy = None

        # #g pin tool
        self.pointTool = QgsMapToolEmitPoint(self.canvas)
        self.pointTool.canvasClicked.connect(self.create_point)

        # self.layerComboManagerPoint = VectorLayerCombo(self.dlg.comboBox_Point)
        # fieldgen = VectorLayerCombo(self.dlg.comboBox_Point, initLayer="", options={"geomType": QGis.Point})
        # self.layerComboManagerPointField = FieldCombo(self.dlg.comboBox_Field, fieldgen, initField="")
        self.layerComboManagerPoint = QgsMapLayerComboBox(self.dlg.widgetPointLayer)
        self.layerComboManagerPoint.setCurrentIndex(-1)
        self.layerComboManagerPoint.setFilters(QgsMapLayerProxyModel.PointLayer)
        self.layerComboManagerPoint.setFixedWidth(175)
        # self.layerComboManagerDSMbuildground = RasterLayerCombo(self.dlg.comboBox_DSMbuildground)
        # RasterLayerCombo(self.dlg.comboBox_DSMbuildground, initLayer="")
        # self.layerComboManagerDEM = RasterLayerCombo(self.dlg.comboBox_DEM)
        # RasterLayerCombo(self.dlg.comboBox_DEM, initLayer="")
        # self.layerComboManagerDSMbuild = RasterLayerCombo(self.dlg.comboBox_DSMbuild)
        # RasterLayerCombo(self.dlg.comboBox_DSMbuild, initLayer="")
        self.layerComboManagerDSMbuildground = QgsMapLayerComboBox(self.dlg.widgetDSMbuildground)
        self.layerComboManagerDSMbuildground.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDSMbuildground.setFixedWidth(175)
        self.layerComboManagerDSMbuildground.setCurrentIndex(-1)
        self.layerComboManagerDEM = QgsMapLayerComboBox(self.dlg.widgetDEM)
        self.layerComboManagerDEM.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDEM.setFixedWidth(175)
        self.layerComboManagerDEM.setCurrentIndex(-1)
        self.layerComboManagerDSMbuild = QgsMapLayerComboBox(self.dlg.widgetDSMbuild)
        self.layerComboManagerDSMbuild.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDSMbuild.setFixedWidth(175)
        self.layerComboManagerDSMbuild.setCurrentIndex(-1)


        if not (os.path.isdir(self.plugin_dir + '/data')):
            os.mkdir(self.plugin_dir + '/data')
Example #42
0
    def openProject(self, project_filename = None):
        '''
        Open and initialize a project.
        If the project_filename parameter is None, the user is asked for a file
        @param project_filename (String): absolute path to project file to load
        '''
        # Ask to save any changes before openeing a new project
        if self.okToCloseProject() == False: return

        # Close the currently opened project
        self.closeProject()

        # Ask for filename if one was not provided
        if project_filename is None:
            start_dir = ''
            project_configs = os.path.join((os.environ.get('OPUS_HOME') or '.'),
                                           'project_configs')
            if os.path.exists(project_configs):
                start_dir = project_configs

            filter_str = QString("*.xml")
            msg = "Select project file to load"
            project_filename = QFileDialog().getOpenFileName(self, msg,
                                                     start_dir, filter_str)
            if not project_filename:
                return # Cancel

        loaded_ok, msg = self.project.open(project_filename)
        if not loaded_ok:
            QMessageBox.warning(self, 'Failed to load project', msg)
            return

        # update latest project config
        self.gui_config.latest_project_filename = self.project.filename
        self.gui_config.save()

        # Initialize managers for the different tabs

        self.managers['general'] = \
        GeneralManager(self.generalmanager_page, self.tabWidget, self.project)

        self.managers['model_manager'] = \
        ModelsManager(self.modelmanager_page, self.tabWidget, self.project)

        self.managers['scenario_manager'] = \
        ScenariosManager(self.runmanager_page, self.tabWidget, self.project)

        self.managers['results_manager'] = \
        ResultsManager(self.resultsmanager_page, self.tabWidget, self.project)

        # DataManager is a little special since it has two "base_widgets"
        self.managers['data_manager'] = \
        DataManager(self.datamanager_xmlconfig, # XmlController
                    self.datamanager_dirview, # FileController
                    self.tabWidget, self.project)

        self.managers['results_manager'].scanForRuns()

        # Enable actions on opened project
        self.actLaunchResultBrowser.setEnabled(True)
        self.actVariableLibrary.setEnabled(True)

        self.actCloseProject.setEnabled(True)
        self.actSaveProject.setEnabled(True)
        self.actSaveProjectAs.setEnabled(True)
        self.updateFontSize()

        self.update_saved_state()
        update_models_to_run_lists()
Example #43
0
 def setWriteFilename(self):
     self.setFilename(
         QFileDialog.getSaveFileName(None, 'Write Realization', '',
                                     'RevLib Realization (*.real)'))
    def import_profile(self):
        """ Import minimum needs from an existing json file.

        The minimum needs are loaded from a file into the table. This state
        is only saved if the form is accepted.
        """
        # noinspection PyCallByClass,PyTypeChecker
        file_name_dialog = QFileDialog(self)
        file_name_dialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
        file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
        file_name_dialog.setDefaultSuffix('json')
        path_name = resources_path('minimum_needs')
        file_name_dialog.setDirectory(path_name)
        if file_name_dialog.exec_():
            file_name = file_name_dialog.selectedFiles()[0]
        else:
            return -1

        if self.minimum_needs.read_from_file(file_name) == -1:
            return -1

        self.clear_resource_list()
        self.populate_resource_list()
        self.switch_context(self.profile_edit_page)
Example #45
0
    def new_scheme_from(self, filename):
        """
        Reimplemented from `CanvasMainWindow.new_scheme_from`.

        Create and return a new :class:`WidgetsScheme` from `filename`.

        Return `None` if an error occurs or the user aborts the process.
        """
        log = logging.getLogger(__name__)
        default_workdir = QSettings().value(
            "output/default-working-directory",
            os.path.expanduser("~/Oasys"), type=str)
        default_units = QSettings().value(
            "output/default-units", 1, type=int)

        contents = io.BytesIO(open(filename, "rb").read())
        doc = ElementTree.parse(contents)
        root = doc.getroot()
        workdir = root.get("working_directory")
        workunits = root.get("workspace_units")
        title = root.get("title", "untitled")
        # First parse the contents into intermediate representation
        # to catch format errors early (will be re-parsed later).
        try:
            readwrite.parse_ows_etree_v_2_0(doc)
        except Exception:
            message_critical(
                 self.tr("Could not load an Orange Workflow file"),
                 title=self.tr("Error"),
                 informative_text=self.tr("An unexpected error occurred "
                                          "while loading '%s'.") % filename,
                 exc_info=True,
                 parent=self)
            return None

        # ensure we have a valid working directory either default or
        # stored.
        if not workdir or not os.path.isdir(workdir):
            new_workdir = QFileDialog.getExistingDirectory(
                self, "Set working directory for project '%s'" % (title or "untitled"),
                default_workdir)
            if new_workdir:
                workdir = new_workdir
            else:
                log.info("Replacement of not existing Working Directory "
                         "'%s' aborted by user", workdir)
                message_information(
                    "Working directory not set by user:\n\n"
                    "project load aborted",
                    parent=self)
                return None
        else:
            ret = message_question(
                "Working directory set to:\n\n" + workdir,
                "Working Directory",
                informative_text="Do you want to change it?",
                buttons=QMessageBox.Yes | QMessageBox.No,
                default_button=QMessageBox.No,
                parent=self)

            if ret == QMessageBox.Yes:
                new_wd = QFileDialog.getExistingDirectory(
                    self, "Set working directory for project '%s'" % (title or "untitled"),
                    default_workdir)
                if new_wd:
                    workdir = new_wd
                    if not os.path.isdir(workdir):
                        os.mkdir(workdir)
                else:
                    log.info("Replacement of not existing Working Directory "
                             "'%s' aborted by user.", workdir)
                    message_information(
                        "Working directory not set by user:\n\n"
                        "project load aborted",
                        parent=self)
                    return None

        # now start the actual load with a valid working directory
        log.info("Changing current work dir to '%s'", workdir)
        os.chdir(workdir)

        # ensure we have a valid working directory either default or
        # stored.
        if workunits is None:
            new_units = OptionDialog.get_option(self,
                                                "Set user's units for project '%s'" % (title or "untitled"),
                                                "Set user's units",
                                                ["m", "cm", "mm"], default_units)
            if not new_units is None:
                workunits = new_units
            else:
                log.info("Replacement of not existing User's Units "
                         "'%s' aborted by user", "")
                message_information(
                    "Project units not set by user:\n\n"
                    "project load aborted",
                    parent=self)
                return None
        else:
            workunits = int(workunits)
            ret = message_question(
                "User's units set to: " + self.getWorkspaceUnitsLabel(workunits),
                "User's Units",
                informative_text="Do you want to change it?",
                buttons=QMessageBox.Yes | QMessageBox.No,
                default_button=QMessageBox.No,
                parent=self)

            if ret == QMessageBox.Yes:
                new_units = OptionDialog.get_option(self,
                                                    "Set user's units for project '%s'" % (title or "untitled"),
                                                    "Set user's units",
                                                    ["m", "cm", "mm"], workunits)
                if not new_units is None:
                    workunits = new_units

                    message_information(
                        "Project new units set by user: "******"\n\nWarning: values relating to the previous units are not converted",
                        parent=self)
                else:
                    log.info("Replacement of existing User's Units "
                             "'%s' aborted by user", "")
                    message_information(
                        "Project units not set by user:\n\n"
                        "project load aborted",
                        parent=self)
                    return None

        new_scheme = widgetsscheme.OASYSWidgetsScheme(parent=self)
        new_scheme.working_directory = workdir
        new_scheme.workspace_units = workunits
        errors = []
        contents.seek(0)
        try:
            readwrite.scheme_load(
                new_scheme, contents, error_handler=errors.append)
        except Exception:
            message_critical(
                 self.tr("Could not load an Orange Workflow file"),
                 title=self.tr("Error"),
                 informative_text=self.tr("An unexpected error occurred "
                                          "while loading '%s'.") % filename,
                 exc_info=True,
                 parent=self)
            return None

        if errors:
            message_warning(
                self.tr("Errors occurred while loading the workflow."),
                title=self.tr("Problem"),
                informative_text=self.tr(
                     "There were problems loading some "
                     "of the widgets/links in the "
                     "workflow."
                ),
                details="\n".join(map(repr, errors)),
                parent=self
            )
        return new_scheme
Example #46
0
class ImageMorphParmsPoint:
    """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',
            'ImageMorphParmsPoint_{}.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 = ImageMorphParmsPointDialog()
        self.dlg.runButton.clicked.connect(self.start_process)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.dlg.selectpoint.clicked.connect(self.select_point)
        self.dlg.generateArea.clicked.connect(self.generate_area)
        self.dlg.helpButton.clicked.connect(self.help)
        self.dlg.progressBar.setValue(0)
        self.dlg.checkBoxOnlyBuilding.toggled.connect(self.text_enable)

        self.fileDialog = QFileDialog()
        self.fileDialog.setFileMode(4)
        self.fileDialog.setAcceptMode(1)

        for i in range(1, 25):
            if 360 % i == 0:
                self.dlg.degreeBox.addItem(str(i))
        self.dlg.degreeBox.setCurrentIndex(4)

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

        # get reference to the canvas
        self.canvas = self.iface.mapCanvas()
        self.poiLayer = None
        self.polyLayer = None
        self.folderPath = 'None'
        self.degree = 5.0
        self.point = None
        self.pointx = None
        self.pointy = None

        # #g pin tool
        self.pointTool = QgsMapToolEmitPoint(self.canvas)
        self.pointTool.canvasClicked.connect(self.create_point)

        # self.layerComboManagerPoint = VectorLayerCombo(self.dlg.comboBox_Point)
        # fieldgen = VectorLayerCombo(self.dlg.comboBox_Point, initLayer="", options={"geomType": QGis.Point})
        # self.layerComboManagerPointField = FieldCombo(self.dlg.comboBox_Field, fieldgen, initField="")
        self.layerComboManagerPoint = QgsMapLayerComboBox(self.dlg.widgetPointLayer)
        self.layerComboManagerPoint.setCurrentIndex(-1)
        self.layerComboManagerPoint.setFilters(QgsMapLayerProxyModel.PointLayer)
        self.layerComboManagerPoint.setFixedWidth(175)
        # self.layerComboManagerDSMbuildground = RasterLayerCombo(self.dlg.comboBox_DSMbuildground)
        # RasterLayerCombo(self.dlg.comboBox_DSMbuildground, initLayer="")
        # self.layerComboManagerDEM = RasterLayerCombo(self.dlg.comboBox_DEM)
        # RasterLayerCombo(self.dlg.comboBox_DEM, initLayer="")
        # self.layerComboManagerDSMbuild = RasterLayerCombo(self.dlg.comboBox_DSMbuild)
        # RasterLayerCombo(self.dlg.comboBox_DSMbuild, initLayer="")
        self.layerComboManagerDSMbuildground = QgsMapLayerComboBox(self.dlg.widgetDSMbuildground)
        self.layerComboManagerDSMbuildground.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDSMbuildground.setFixedWidth(175)
        self.layerComboManagerDSMbuildground.setCurrentIndex(-1)
        self.layerComboManagerDEM = QgsMapLayerComboBox(self.dlg.widgetDEM)
        self.layerComboManagerDEM.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDEM.setFixedWidth(175)
        self.layerComboManagerDEM.setCurrentIndex(-1)
        self.layerComboManagerDSMbuild = QgsMapLayerComboBox(self.dlg.widgetDSMbuild)
        self.layerComboManagerDSMbuild.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDSMbuild.setFixedWidth(175)
        self.layerComboManagerDSMbuild.setCurrentIndex(-1)


        if not (os.path.isdir(self.plugin_dir + '/data')):
            os.mkdir(self.plugin_dir + '/data')

    # 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('ImageMorphParmsPoint', 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/ImageMorphParmsPoint/ImageMorphIconPoint.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Image Morphometric Parameters Point'),
            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'&Image Morphometric Parameters Point'),
                action)
            self.iface.removeToolBarIcon(action)

    def folder_path(self):
        self.fileDialog.open()
        result = self.fileDialog.exec_()
        if result == 1:
            self.folderPath = self.fileDialog.selectedFiles()
            self.dlg.textOutput.setText(self.folderPath[0])

    def create_point(self, point):  # Var kommer point ifran???
        # report map coordinates from a canvas click
        # coords = "{}, {}".format(point.x(), point.y())
        # self.iface.messageBar().pushMessage("Coordinate selected", str(coords))
        self.dlg.closeButton.setEnabled(1)
        QgsMapLayerRegistry.instance().addMapLayer(self.poiLayer)

        # create the feature
        fc = int(self.provider.featureCount())
        feature = QgsFeature()
        feature.setGeometry(QgsGeometry.fromPoint(point))
        feature.setAttributes([fc, point.x(), point.y()])
        self.poiLayer.startEditing()
        self.poiLayer.addFeature(feature, True)
        self.poiLayer.commitChanges()
        self.poiLayer.triggerRepaint()
        # self.create_poly_layer(point) # Flyttad till generate_area
        self.dlg.setEnabled(True)
        self.dlg.activateWindow()
        self.pointx = point.x()
        self.pointy = point.y()
        self.point = point

    def generate_area(self):

        if self.dlg.checkBoxVectorLayer.isChecked():
            point = self.layerComboManagerPoint.currentLayer()
            if point is None:
                QMessageBox.critical(None, "Error", "No valid point layer is selected")
                return
            if not point.geometryType() == 0:
                QMessageBox.critical(None, "Error", "No valid Polygon layer is selected")
                return

            for poi in point.getFeatures():
                loc = poi.geometry().asPoint()
                self.pointx = loc[0]
                self.pointy = loc[1]
        else:
            if not self.pointx:
                QMessageBox.critical(None, "Error", "No click registred on map canvas")
                return

        self.dlg.runButton.setEnabled(1)
        self.create_poly_layer()

    def select_point(self):  # Connected to "Secelct Point on Canves"
        if self.poiLayer is not None:
            QgsMapLayerRegistry.instance().removeMapLayer(self.poiLayer.id())
        if self.polyLayer is not None:
            self.polyLayer.startEditing()
            self.polyLayer.selectAll()
            self.polyLayer.deleteSelectedFeatures()
            self.polyLayer.commitChanges()
            QgsMapLayerRegistry.instance().removeMapLayer(self.polyLayer.id())

        self.canvas.setMapTool(self.pointTool)  # Calls a canvas click and create_point

        self.dlg.setEnabled(False)
        self.create_point_layer()

    def create_point_layer(self):
        canvas = self.iface.mapCanvas()
        srs = canvas.mapSettings().destinationCrs()
        crs = str(srs.authid())
        uri = "Point?field=id:integer&field=x:double&field=y:double&index=yes&crs=" + crs
        self.poiLayer = QgsVectorLayer(uri, "Point of Interest", "memory")
        self.provider = self.poiLayer.dataProvider()

    def create_poly_layer(self):
        canvas = self.iface.mapCanvas()
        srs = canvas.mapSettings().destinationCrs()
        crs = str(srs.authid())
        uri = "Polygon?field=id:integer&index=yes&crs=" + crs
        # dir_poly = self.plugin_dir + '/data/poly_temp.shp'
        #self.polyLayer = QgsVectorLayer(dir_poly, "Study area", "ogr")
        self.polyLayer = QgsVectorLayer(uri, "Study area", "memory")
        self.provider = self.polyLayer.dataProvider()
        #QgsMapLayerRegistry.instance().addMapLayer(self.polyLayer)

        # create buffer feature
        fc = int(self.provider.featureCount())
        featurepoly = QgsFeature()

        # Assign feature the buffered geometry
        radius = self.dlg.spinBox.value()
        featurepoly.setGeometry(QgsGeometry.fromPoint(
            QgsPoint(self.pointx, self.pointy)).buffer(radius, 1000, 1, 1, 1.0))
        featurepoly.setAttributes([fc])
        self.polyLayer.startEditing()
        self.polyLayer.addFeature(featurepoly, True)
        self.polyLayer.commitChanges()
        QgsMapLayerRegistry.instance().addMapLayer(self.polyLayer)

        # props = {'color_border': '255,165,0,125', 'style': 'no', 'style_border': 'solid'}
        # s = QgsFillSymbolV2.createSimple(props)
        # self.polyLayer.setRendererV2(QgsSingleSymbolRendererV2(s))

        self.polyLayer.setLayerTransparency(42)
        # self.polyLayer.repaintRequested(None)
        # self.polyLayer.setCacheImage(None)
        self.polyLayer.triggerRepaint()
        #QObject.connect(self.dlg.selectpoint, SIGNAL("clicked()"), self.select_point)

    #def whatsthisclicked(self, href):
        #webbrowser.open_new_tab(href)

    def text_enable(self):
        if self.dlg.checkBoxOnlyBuilding.isChecked():
            self.dlg.label_2.setEnabled(False)
            self.dlg.label_3.setEnabled(False)
            self.dlg.label_4.setEnabled(True)
        else:
            self.dlg.label_2.setEnabled(True)
            self.dlg.label_3.setEnabled(True)
            self.dlg.label_4.setEnabled(False)

    def start_process(self):

        #Check OS and dep
        # if sys.platform == 'darwin':
        #     gdalwarp_os_dep = '/Library/Frameworks/GDAL.framework/Versions/Current/Programs/gdalwarp'
        # else:
        #     gdalwarp_os_dep = 'gdalwarp'

        # pydevd.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True)
        self.dlg.progressBar.setValue(0)

        if self.folderPath == 'None':
            QMessageBox.critical(None, "Error", "Select a valid output folder")
            return

        poly = self.iface.activeLayer()
        if poly is None:
            QMessageBox.critical(None, "Error", "No valid Polygon layer is selected")
            return
        if not poly.geometryType() == 2:
            QMessageBox.critical(None, "Error", "No valid Polygon layer is selected")
            return

        prov = poly.dataProvider()
        fields = prov.fields()

        dir_poly = self.plugin_dir + '/data/poly_temp.shp'

        writer = QgsVectorFileWriter(dir_poly, "CP1250", fields, prov.geometryType(),
                                     prov.crs(), "ESRI shapefile")

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

        poly.selectAll()
        selection = poly.selectedFeatures()

        for feature in selection:
            writer.addFeature(feature)
        del writer

        if sys.platform == 'win32':
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        else:
            si = None

        x = self.pointx
        y = self.pointy
        r = self.dlg.spinBox.value()

        if self.dlg.checkBoxOnlyBuilding.isChecked():  # Only building heights
            dsm_build = self.layerComboManagerDSMbuild.currentLayer()
            if dsm_build is None:
                QMessageBox.critical(None, "Error", "No valid building DSM raster layer is selected")
                return

            provider = dsm_build.dataProvider()
            filePath_dsm_build = str(provider.dataSourceUri())
            # Kolla om memorylayer går att användas istället för dir_poly tempfilen.
            # gdalruntextdsm_build = gdalwarp_os_dep + ' -dstnodata -9999 -q -overwrite -te ' + str(x - r) + ' ' + str(y - r) + \
            #                        ' ' + str(x + r) + ' ' + str(y + r) + ' -of GTiff "' + \
            #                        filePath_dsm_build + '" "' + self.plugin_dir + '/data/clipdsm.tif"'
            # # byta till gdal.Warp("aae.tif","aaa.asc", xRes=2.0, yRes=2.0, dstSRS='EPSG:3007')
            # if sys.platform == 'win32':
            #     subprocess.call(gdalruntextdsm_build, startupinfo=si)
            # else:
            #     os.system(gdalruntextdsm_build)


            # Remove gdalwarp with gdal.Translate
            bigraster = gdal.Open(filePath_dsm_build)
            bbox = (x - r, y + r, x + r, y - r)
            gdal.Translate(self.plugin_dir + '/data/clipdsm.tif', bigraster, projWin=bbox)
            bigraster = None

            dataset = gdal.Open(self.plugin_dir + '/data/clipdsm.tif')
            dsm = dataset.ReadAsArray().astype(np.float)
            sizex = dsm.shape[0]
            sizey = dsm.shape[1]
            dem = np.zeros((sizex, sizey))

        else:  # Both building ground heights
            dsm = self.layerComboManagerDSMbuildground.currentLayer()
            dem = self.layerComboManagerDEM.currentLayer()

            if dsm is None:
                QMessageBox.critical(None, "Error", "No valid ground and building DSM raster layer is selected")
                return
            if dem is None:
                QMessageBox.critical(None, "Error", "No valid ground DEM raster layer is selected")
                return

            # # get raster source - gdalwarp
            provider = dsm.dataProvider()
            filePath_dsm = str(provider.dataSourceUri())
            provider = dem.dataProvider()
            filePath_dem = str(provider.dataSourceUri())

            # gdalruntextdsm = gdalwarp_os_dep + ' -dstnodata -9999 -q -overwrite -te ' + str(x - r) + ' ' + str(y - r) + \
            #                                    ' ' + str(x + r) + ' ' + str(y + r) + ' -of GTiff "' + \
            #                                    filePath_dsm + '" "' + self.plugin_dir + '/data/clipdsm.tif"'
            # gdalruntextdem = gdalwarp_os_dep + ' -dstnodata -9999 -q -overwrite -te ' + str(x - r) + ' ' + str(y - r) + \
            #                        ' ' + str(x + r) + ' ' + str(y + r) + ' -of GTiff "' + \
            #                        filePath_dem + '" "' + self.plugin_dir + '/data/clipdem.tif"'
            #
            # if sys.platform == 'win32':
            #     si = subprocess.STARTUPINFO()
            #     si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            #     subprocess.call(gdalruntextdsm, startupinfo=si)
            #     subprocess.call(gdalruntextdem, startupinfo=si)
            # else:
            #     os.system(gdalruntextdsm)
            #     os.system(gdalruntextdem)

            # Testing with gdal.Translate
            bigraster = gdal.Open(filePath_dsm)
            bbox = (x - r, y + r, x + r, y - r)
            gdal.Translate(self.plugin_dir + '/data/clipdsm.tif', bigraster, projWin=bbox)
            bigraster = gdal.Open(filePath_dem)
            bbox = (x - r, y + r, x + r, y - r)
            gdal.Translate(self.plugin_dir + '/data/clipdem.tif', bigraster, projWin=bbox)

            dataset = gdal.Open(self.plugin_dir + '/data/clipdsm.tif')
            dsm = dataset.ReadAsArray().astype(np.float)
            dataset2 = gdal.Open(self.plugin_dir + '/data/clipdem.tif')
            dem = dataset2.ReadAsArray().astype(np.float)

            if not (dsm.shape[0] == dem.shape[0]) & (dsm.shape[1] == dem.shape[1]):
                QMessageBox.critical(None, "Error", "All grids must be of same extent and resolution")
                return

        geotransform = dataset.GetGeoTransform()
        scale = 1 / geotransform[1]
        self.degree = float(self.dlg.degreeBox.currentText())
        nd = dataset.GetRasterBand(1).GetNoDataValue()
        nodata_test = (dsm == nd)
        if nodata_test.any():
            QMessageBox.critical(None, "Error", "Clipped grid includes nodata pixels")
            return
        else:
            immorphresult = imagemorphparam_v2(dsm, dem, scale, 1, self.degree, self.dlg, 1)

        # #Calculate Z0m and Zdm depending on the Z0 method
        ro = self.dlg.comboBox_Roughness.currentIndex()
        if ro == 0:
            Roughnessmethod = 'RT'
        elif ro == 1:
            Roughnessmethod = 'Rau'
        elif ro == 2:
            Roughnessmethod = 'Bot'
        elif ro == 3:
            Roughnessmethod = 'Mac'
        elif ro == 4:
            Roughnessmethod = 'Mho'
        else:
            Roughnessmethod = 'Kan'

        zH = immorphresult["zH"]
        fai = immorphresult["fai"]
        pai = immorphresult["pai"]
        zMax = immorphresult["zHmax"]
        zSdev = immorphresult["zH_sd"]

        zd,z0 = rg.RoughnessCalcMany(Roughnessmethod, zH, fai, pai, zMax, zSdev)

        # save to file
        pre = self.dlg.textOutput_prefix.text()
        header = ' Wd pai   fai   zH  zHmax   zHstd zd z0'
        numformat = '%3d %4.3f %4.3f %5.3f %5.3f %5.3f %5.3f %5.3f'
        arr = np.concatenate((immorphresult["deg"], immorphresult["pai"], immorphresult["fai"],
                            immorphresult["zH"], immorphresult["zHmax"], immorphresult["zH_sd"],zd,z0), axis=1)
        np.savetxt(self.folderPath[0] + '/' + pre + '_' + 'IMPPoint_anisotropic.txt', arr,
                   fmt=numformat, delimiter=' ', header=header, comments='')

        zHall = immorphresult["zH_all"]
        faiall = immorphresult["fai_all"]
        paiall = immorphresult["pai_all"]
        zMaxall = immorphresult["zHmax_all"]
        zSdevall = immorphresult["zH_sd_all"]
        zdall,z0all = rg.RoughnessCalc(Roughnessmethod, zHall, faiall, paiall, zMaxall, zSdevall)
        # If zd and z0 are lower than open country, set to open country
        if zdall < 0.2:
            zdall = 0.2
        if z0all < 0.03:
            z0all = 0.03
        header = ' pai  fai   zH    zHmax    zHstd zd z0'
        numformat = '%4.3f %4.3f %5.3f %5.3f %5.3f %5.3f %5.3f'
        arr2 = np.array([[immorphresult["pai_all"], immorphresult["fai_all"], immorphresult["zH_all"],
                          immorphresult["zHmax_all"], immorphresult["zH_sd_all"],zdall,z0all]])
        np.savetxt(self.folderPath[0] + '/' + pre + '_' + 'IMPPoint_isotropic.txt', arr2,
                   fmt=numformat, delimiter=' ', header=header, comments='')

        dataset = None
        dataset2 = None
        dataset3 = None

        QMessageBox.information(None, "Image Morphometric Parameters", "Process successful!")

    def run(self):
        self.dlg.show()
        self.dlg.exec_()
        gdal.UseExceptions()
        gdal.AllRegister()

    def help(self):
        url = "http://umep-docs.readthedocs.io/en/latest/pre-processor/Urban%20Morphology%20Morphometric%20" \
              "Calculator%20(Point).html"
        webbrowser.open_new_tab(url)
Example #47
0
 def on_open(self):
     filePath = QFileDialog.getOpenFileName(self, '选择程序')
     self.ui.le_exe.setText(filePath)
     self.modify = True
     self.ui.btn_apply.setEnabled(True)
Example #48
0
 def select_output_directory(self):
     output_dir = QFileDialog.getExistingDirectory(
         self.dlg, "Select output directory ", "")
     self.dlg.lineEdit.setText(output_dir)
Example #49
0
 def _set_file_path(sk, file_extension):
     new_path = str(QFileDialog.getOpenFileName(Dialog, 'Open a file', os.sep, "*."+file_extension))
     if new_path: vip.set(sk, {k : new_path}) # this is a le change, triggered from this bn action
     return new_path
Example #50
0
 def Select_Ouput_File(self):
     self.txtOutput.clear()
     dir = os.path.dirname(_layerPath)
     filename = QFileDialog.getSaveFileName(self, "select output file ",
                                            dir, "*.tif")
     self.txtOutput.setText(filename)
def GetOutputFileName(clss, box_name, file_types, default_type, start_path):
    dlg = QFileDialog(clss)
    dlg.setDirectory(start_path)
    dlg.setWindowTitle(box_name)
    dlg.setViewMode(QFileDialog.Detail)
    a = []
    for i in file_types:
        a.append(clss.tr(i))
    dlg.setNameFilters(a)
    dlg.setDefaultSuffix(default_type)
    new_name = None
    extension = None
    if dlg.exec_():
        new_name = dlg.selectedFiles()[0]
        if new_name[-4] == '.':
            extension = new_name[-3:]
        else:
            extension = new_name[-4:]
    return new_name, extension
Example #52
0
 def _set_dir_path(sk):
     new_path = str(QFileDialog.getExistingDirectory(Dialog, 'Open a folder', os.sep, QFileDialog.ShowDirsOnly))
     if new_path: vip.set(sk, {k : new_path}) # this is a le change, triggered from this bn action
     return new_path
Example #53
0
    def get_file_name(self):
        file_dialog = QFileDialog()
        file_dialog.setDefaultSuffix('xml')
        out_file_name = unicode(file_dialog.getSaveFileName(self, "Save XML File", filter='XML Files (*.xml);;Text Files (*.txt)'))

        return out_file_name
 def OpenFile(self):
     self.__file = str( QFileDialog.getOpenFileName(self, caption="Select file"))
     self.__loadFile()
     self.__draw()
Example #55
0
 def SelecionarOutputPath(self):
     OutputPath = QFileDialog.getExistingDirectory(
         self.dlg, "Guardar em", "/Users/bsargento/Desktop/")
     self.dlg.lineEdit_3.setText(OutputPath)
Example #56
0
    def on_readBoundingBoxButton_clicked(self):
        """
        Launches function allowing user to automatically populate geographic
        bounding box information from a NetCDF file. If NetCDF has global attributes
        geospatial_lat_max, geospatial_lat_min, geospatial_lon_max, geospatial_lon_min,
        geospatial_alt_max or geospatial_alt_min, then these are used to populate
        information. Otherwise, user is prompted to select correct fields from 
        NetCDF file.
        """

        lat_min = None
        lat_max = None
        lon_min = None
        lon_max = None
        alt_min = None
        alt_max = None


        filename = QFileDialog.getOpenFileName(self,
                                               'Open associated NetCDF',
                                               '',
                                               'NetCDF files (*.nc *.cdf);;All Files (*.*)')

        f = netCDF4.Dataset(str(filename))


        var_list = f.variables.keys()
        var_list.sort()

        try:

            lat_min = f.__dict__['geospatial_lat_min']
            lat_max = f.__dict__['geospatial_lat_max']
        except KeyError:
            [var_name, ok] = QInputDialog.getItem(self, "Latitude Variable Name", "ERROR: Latitude values not found. Please enter latitude variable name.", var_list, current=0, editable=False)
            if var_name and ok:
                lat_values = f.variables[str(var_name)][:]
                lat_min = min(lat_values[lat_values != 0])
                lat_max = max(lat_values[lat_values != 0])

                lat_values = f.variables[str(var_name)][:]

        try:

            lon_min = f.__dict__['geospatial_lon_min']
            lon_max = f.__dict__['geospatial_lon_max']
        except KeyError:
            [var_name, ok] = QInputDialog.getItem(self, "Longitude Variable Name", "ERROR: Longitude values not found. Please select longitude variable name.", var_list, current=0, editable=False)
            if var_name and ok:
                lon_values = f.variables[str(var_name)][:]
                lon_min = min(lon_values[lon_values != 0])
                lon_max = max(lon_values[lon_values != 0])

        try:

            alt_min = f.__dict__['geospatial_vertical_min']
            alt_max = f.__dict__['geospatial_vertical_max']
        except KeyError:
            [var_name, ok] = QInputDialog.getItem(self, "Altitude Variable Name", "ERROR: Altitude values not found. Please enter altitude variable name.", var_list, current=0, editable=False)
            if var_name and ok:
                alt_values = f.variables[str(var_name)][:]
                alt_min = min(alt_values[alt_values != 0])
                alt_max = max(alt_values[alt_values != 0])

        if lon_min:
            self.westBoundLongitudeLine.setText(str(lon_min))

        if lon_max:
            self.eastBoundLongitudeLine.setText(str(lon_max))

        if lat_max:
            self.northBoundLatitudeLine.setText(str(lat_max))

        if lat_min:
            self.southBoundLatitudeLine.setText(str(lat_min))

        if alt_min:
            self.minAltitudeLine.setText(str(alt_min))

        if alt_max:
            self.maxAltitudeLine.setText(str(alt_max))
Example #57
0
 def slotImport(self):
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import color theme"))
     filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(), filetypes)
     if filename:
         self.parent().import_(filename)
    def run(self):
        '''
        Runs the widget
        '''
        project = PagLuxembourg.main.current_project

        if not project.isPagProject():
            return

        # Check data and selected entities before exporting
        self.data_checker = DataChecker()
        if not self.data_checker.run():
            return

        # Select file to export
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setNameFilter('GML file (*.gml)')
        dialog.setDefaultSuffix('gml')
        dialog.setWindowTitle(
            QCoreApplication.translate('ExportGML', 'Select the gml location'))
        dialog.setSizeGripEnabled(False)
        result = dialog.exec_()

        if result == 0:
            return

        selected_files = dialog.selectedFiles()

        if len(selected_files) == 0:
            return

        # GML filename and directory
        gml_filename = selected_files[0]
        gml_directory = os.path.dirname(gml_filename)
        temp_dir = os.path.join(gml_directory, str(uuid.uuid1()))
        os.makedirs(temp_dir)

        # Progress bar
        progressMessageBar = PagLuxembourg.main.qgis_interface.messageBar(
        ).createMessage(
            QCoreApplication.translate('ExportGML', 'Exporting to GML'))
        progress = QProgressBar()
        progress.setMaximum(len(QgsMapLayerRegistry.instance().mapLayers()))
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        PagLuxembourg.main.qgis_interface.messageBar().pushWidget(
            progressMessageBar, QgsMessageBar.INFO)

        # Create final GML document
        gml = getDOMImplementation().createDocument(
            'http://www.interlis.ch/INTERLIS2.3/GML32/INTERLIS',
            'ili:TRANSFER', None)
        gml_root = gml.documentElement
        gml_root.setAttribute(
            'xmlns:ili', 'http://www.interlis.ch/INTERLIS2.3/GML32/INTERLIS')
        gml_root.setAttribute('xmlns:gml', 'http://www.opengis.net/gml/3.2')
        gml_root.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink')
        gml_root.setAttribute('xmlns:xsi',
                              'http://www.w3.org/2001/XMLSchema-instance')
        gml_root.setAttribute('xmlns',
                              'http://www.interlis.ch/INTERLIS2.3/GML32/PAG')
        gml_root.setAttribute(
            'xsi:schemaLocation',
            'http://www.interlis.ch/INTERLIS2.3/GML32/PAG PAG.xsd')
        gml_root.setAttribute('gml:id', 'x' + str(uuid.uuid1()))

        # Baskets topic
        topic_baskets = dict()

        # 'MODIFICATION PAG' layer definition
        layer_PAG = project.getModificationPagLayer()

        # 'MODIFICATION PAG' selection definition
        selection_PAG = layer_PAG.selectedFeatures()

        # Counting number entities in 'MODIFICATION PAG' selection
        entity_count_PAG = layer_PAG.selectedFeatureCount()

        # Iterates through XSD types
        for type in PagLuxembourg.main.xsd_schema.types:
            layer = project.getLayer(type)

            if layer is None:
                continue

            # Progression message
            progressMessageBar.setText(
                QCoreApplication.translate('ExportGML', 'Exporting {}').format(
                    layer.name()))

            filename = os.path.join(temp_dir,
                                    '{}.gml'.format(type.friendlyName()))

            # Selection test in 'MODIFICATION PAG'
            QgsVectorFileWriter.writeAsVectorFormat(
                layer,
                filename,
                'utf-8',
                None,
                'GML',
                entity_count_PAG > 0,
                datasourceOptions=[
                    'FORMAT=GML3.2',
                    'TARGET_NAMESPACE={}'.format(self.DEFAULT_XLMNS),
                    'GML3_LONGSRS=YES', 'SRSDIMENSION_LOC=GEOMETRY',
                    'WRITE_FEATURE_BOUNDED_BY=NO', 'STRIP_PREFIX=TRUE',
                    'SPACE_INDENTATION=NO'
                ])

            members = self._getXsdCompliantGml(filename, gml, type)

            if type.topic() not in topic_baskets:
                basket = gml.createElement('ili:baskets')
                gml_root.appendChild(basket)

                topic = gml.createElement(type.topic())
                topic.setAttribute('gml:id', 'x' + str(uuid.uuid1()))
                basket.appendChild(topic)

                topic_baskets[type.topic()] = topic

            for member in members:
                topic_baskets[type.topic()].appendChild(member)

            progress.setValue(progress.value() + 1)

        file = open(gml_filename, 'wb')
        file.write(gml.toprettyxml('', '\n', 'utf-8'))
        file.close()
        shutil.rmtree(temp_dir)

        # Messages display for number of selected entities
        if entity_count_PAG == 1:
            PagLuxembourg.main.qgis_interface.messageBar().clearWidgets()
            PagLuxembourg.main.qgis_interface.messageBar().pushSuccess(
                QCoreApplication.translate('ExportGML', 'Success'),
                QCoreApplication.translate(
                    'ExportGML',
                    'GML export was successful with 1 selected entity in MODIFICATION PAG layer'
                ))
        elif entity_count_PAG == 0:
            PagLuxembourg.main.qgis_interface.messageBar().clearWidgets()
            PagLuxembourg.main.qgis_interface.messageBar().pushSuccess(
                QCoreApplication.translate('ExportGML_without', 'Success'),
                QCoreApplication.translate(
                    'ExportGML_without',
                    'GML export was successful without selected entity in MODIFICATION PAG layer'
                ))
        else:
            PagLuxembourg.main.qgis_interface.messageBar().clearWidgets()
            PagLuxembourg.main.qgis_interface.messageBar().pushSuccess(
                QCoreApplication.translate('ExportGML_many', 'Success'),
                QCoreApplication.translate(
                    'ExportGML_many',
                    'GML export was successful with {} selected entities in MODIFICATION PAG layer'
                ).format(entity_count_PAG))
Example #59
0
 def showRestoreSessionDialog(self):
     filename = str(
         QFileDialog.getOpenFileName(None, "Restore Session", "", "*.xml"))
     if (filename != ""):
         self.restoreSession(filename)
Example #60
0
 def select_file(self):
     fileName = QFileDialog.getOpenFileName(self.dlg, "Select file ", "",
                                            '*.hasc')
     self.dlg.lineEdit.setText(fileName)