def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""

        # The first thing to do is retrieve the values of the parameters
        # entered by the user
        inputFilename = self.getParameterValue(self.INPUT_LAYER)
        output = self.getOutputValue(self.OUTPUT_LAYER)

        # Input layers vales are always a string with its location.
        # That string can be converted into a QGIS object (a
        # QgsVectorLayer in this case) using the
        # processing.getObjectFromUri() method.
        vectorLayer = dataobjects.getObjectFromUri(inputFilename)

        # And now we can process

        # First we create the output layer. The output value entered by
        # the user is a string containing a filename, so we can use it
        # directly
        settings = QSettings()
        systemEncoding = settings.value('/UI/encoding', 'System')
        provider = vectorLayer.dataProvider()
        writer = QgsVectorFileWriter(output, systemEncoding,
                                     provider.fields(),
                                     provider.geometryType(), provider.crs())

        # Now we take the features from input layer and add them to the
        # output. Method features() returns an iterator, considering the
        # selection that might exist in layer and the configuration that
        # indicates should algorithm use only selected features or all
        # of them
        features = vector.features(vectorLayer)
        for f in features:
            writer.addFeature(f)
Ejemplo n.º 2
0
    def getVectorWriter(self, fields, geomType, crs, options=None):
        """Returns a suitable writer to which features can be added as
        a result of the algorithm. Use this to transparently handle
        output values instead of creating your own method.

        Executing this method might modify the object, adding additional
        information to it, so the writer can be later accessed and
        processed within QGIS. It should be called just once, since a
        new call might result in previous data being replaced, thus
        rendering a previously obtained writer useless.

        @param fields   a list  of QgsField
        @param geomType a suitable geometry type, as it would be passed
                        to a QgsVectorFileWriter constructor
        @param crs      the crs of the layer to create

        @return writer  instance of the vector writer class
        """

        if self.encoding is None:
            settings = QSettings()
            self.encoding = settings.value('/Processing/encoding', 'System', str)

        w = VectorWriter(self.value, self.encoding, fields, geomType,
                         crs, options)
        self.memoryLayer = w.memLayer
        return w
Ejemplo n.º 3
0
    def processAlgorithm(self, progress):
        connection = self.getParameterValue(self.DATABASE)
        settings = QSettings()
        mySettings = '/PostgreSQL/connections/' + connection
        try:
            database = settings.value(mySettings + '/database')
            username = settings.value(mySettings + '/username')
            host = settings.value(mySettings + '/host')
            port = settings.value(mySettings + '/port', type=int)
            password = settings.value(mySettings + '/password')
        except Exception as e:
            raise GeoAlgorithmExecutionException(
                self.tr('Wrong database connection name: %s' % connection))
        try:
            self.db = postgis_utils.GeoDB(host=host, port=port,
                                          dbname=database, user=username, passwd=password)
        except postgis_utils.DbError as e:
            raise GeoAlgorithmExecutionException(
                self.tr("Couldn't connect to database:\n%s" % e.message))

        sql = self.getParameterValue(self.SQL).replace('\n', ' ')
        try:
            self.db._exec_sql_and_commit(unicode(sql))
        except postgis_utils.DbError as e:
            raise GeoAlgorithmExecutionException(
                self.tr('Error executing SQL:\n%s' % e.message))
Ejemplo n.º 4
0
def main(argv):
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(QPixmap(":/logo_small")))
    app.setOrganizationName('Hardcoded Software')
    app.setApplicationName('moneyGuru')
    settings = QSettings()
    LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING
    setupQtLogging(level=LOGGING_LEVEL)
    logging.debug('started in debug mode')
    if ISLINUX:
        stylesheetFile = QFile(':/stylesheet_lnx')
    else:
        stylesheetFile = QFile(':/stylesheet_win')
    stylesheetFile.open(QFile.ReadOnly)
    textStream = QTextStream(stylesheetFile)
    style = textStream.readAll()
    stylesheetFile.close()
    app.setStyleSheet(style)
    lang = settings.value('Language')
    locale_folder = op.join(BASE_PATH, 'locale')
    hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang)
    # Many strings are translated at import time, so this is why we only import after the translator
    # has been installed
    from qt.app import MoneyGuru
    app.setApplicationVersion(MoneyGuru.VERSION)
    mgapp =  MoneyGuru()
    install_excepthook()
    exec_result = app.exec_()
    del mgapp
    # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be
    # caused by some weird crap about C++ instance being deleted with python instance still living.
    # The worst part is that Phil seems to say this is expected behavior. So, whatever, this
    # gc.collect() below is required to avoid a crash.
    gc.collect()
    return exec_result
Ejemplo n.º 5
0
    def __init__(self):
        QDockWidget.__init__(self, None)
        self.setupUi(self)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)

        self.modeComboBox.clear()
        self.modeComboBox.addItems(["Simplified interface", "Advanced interface"])
        settings = QSettings()
        if not settings.contains(self.USE_CATEGORIES):
            settings.setValue(self.USE_CATEGORIES, True)
        useCategories = settings.value(self.USE_CATEGORIES, type=bool)
        if useCategories:
            self.modeComboBox.setCurrentIndex(0)
        else:
            self.modeComboBox.setCurrentIndex(1)
        self.modeComboBox.currentIndexChanged.connect(self.modeHasChanged)

        self.searchBox.textChanged.connect(self.textChanged)
        self.algorithmTree.customContextMenuRequested.connect(self.showPopupMenu)
        self.algorithmTree.doubleClicked.connect(self.executeAlgorithm)

        if hasattr(self.searchBox, "setPlaceholderText"):
            self.searchBox.setPlaceholderText(self.tr("Search..."))

        self.fillTree()
Ejemplo n.º 6
0
    def __init__(self, parent=None, scan_on_startup=False):
        QMainWindow.__init__(self, parent)
        self.resize(800, 500)
        self._widget = MainWidget(self, scan_on_startup=scan_on_startup)
        self.setCentralWidget(self._widget)
        settings = QSettings()
        self.restoreGeometry(settings.value('geometry', b'', QByteArray))
        self.setWindowTitle('Marche')

        menu = self.menuBar()
        menuFile = menu.addMenu('File')
        menuFile.addAction(self._widget.actionAdd_host)
        menuFile.addAction(self._widget.actionScan_network)
        menuFile.addSeparator()
        menuFile.addAction(self._widget.actionLoad_session)
        menuFile.addAction(self._widget.actionSave_session_as)
        menuFile.addSeparator()
        menuFile.addAction(self._widget.actionExit)
        self._widget.actionExit.triggered.connect(self.close)
        menuEdit = menu.addMenu('Edit')
        menuEdit.addAction(self._widget.actionPreferences)
        menuJobs = menu.addMenu('Jobs')
        menuJobs.addAction(self._widget.actionReload)
        menuHelp = menu.addMenu('Help')
        menuHelp.addAction(self._widget.actionAbout)
        menuHelp.addAction(self._widget.actionAbout_Qt)

        self.statusBar().showMessage('Welcome!', 1000)
Ejemplo n.º 7
0
 def __on_click_on_delete(self):
     settings = QSettings()
     recent_projects = settings.value("recentProjects").toMap()
     if self.__project in recent_projects:
         del recent_projects[self.__project]
         settings.setValue("recentProjects", recent_projects)
         self.emit(SIGNAL("deleteMe(QListWidgetItem)"), self.__itemRelated)
 def closeEvent(self, event):
     settings = QSettings()
     settings.setValue(u'/Windows/PlaceMarker/geometry', self.saveGeometry())
     settings.setValue(u'PlaceMarker/CurrentClass', self.comboBoxClass.currentIndex())
     QtGui.QDialog.closeEvent(self, event)
     self.button_box.button(QDialogButtonBox.Apply).setEnabled(False)
     self.lineEditPosition.setText(u'')
 def toggleAutoRefresh(self, checked):
     if checked:
         self.repaintTimer.start(REFRESH_RATE)
     else:
         self.repaintTimer.stop()
     settings = QSettings()
     settings.setValue(u'PlaceMarker/AutoRefreshLayer', checked)
Ejemplo n.º 10
0
    def __init__(self, parent = None):
        QObject.__init__(self, parent)
        self.jinja = Environment(loader = FileSystemLoader("data/templates"), autoescape = True)
        self.jinja.filters["likes"] = filter_likes
        self.jinja.filters["twitterise"] = filter_twitterise
        self.jinja.filters["timesince"] = filter_timesince

        self.mapper = Mapper()
        self.mapper.connect("/", controller = "LolViews", action = "feed")
        self.mapper.connect("/login", controller = "LolViews", action = "login")
        self.mapper.connect("/user/:user", controller = "LolViews", action = "feed")

        self.notes = NotificationServer()

        from PyQt4.QtCore import QSettings
        settings = QSettings()
        if settings.contains("session"):
            from cPickle import loads
            self.session = loads(str(settings.value("session").toString()))
        else:
            self.session = Session()

        self.ff = FriendFeedAPI(self.session)
        
        self.deferredResponses = set()
Ejemplo n.º 11
0
    def __quicktipOnce(self):
        filename = os.path.join(settings.widget_settings_dir(),
                                "user-session-state.ini")
        namespace = ("user-message-history/{0.__module__}.{0.__qualname__}"
                     .format(type(self)))
        session_hist = QSettings(filename, QSettings.IniFormat)
        session_hist.beginGroup(namespace)
        messages = self.UserAdviceMessages

        def _ispending(msg):
            return not session_hist.value(
                "{}/confirmed".format(msg.persistent_id),
                defaultValue=False, type=bool)
        messages = [msg for msg in messages if _ispending(msg)]

        if not messages:
            return

        message = messages[self.__msgchoice % len(messages)]
        self.__msgchoice += 1

        self.__showMessage(message)

        def _userconfirmed():
            session_hist = QSettings(filename, QSettings.IniFormat)
            session_hist.beginGroup(namespace)
            session_hist.setValue(
                "{}/confirmed".format(message.persistent_id), True)
            session_hist.sync()

        self.__msgwidget.accepted.connect(_userconfirmed)
Ejemplo n.º 12
0
class Preferences(PrefsBA):

    prefsSaved = pyqtSignal()

    def __init__(self, parent, autoload=0):
        self.parent = parent
        PrefsBA.__init__(self, parent)

        self.settings = QSettings()

        if autoload:
            self.load()

    def load(self):
        for preference in self.settings.childKeys():
            try:
                setting = self.settings.value(preference)
                if preference == "Font":
                    self.parent.setfont(setting.toPyObject())
                if preference == "Match Font":
                    self.parent.setMatchFont(setting.toPyObject())
                if preference == "Email Server":
                    self.emailServerEdit.setText(setting.toPyObject())
                if preference == "Recent Files Count":
                    self.recentFilesSpinBox.setValue(int(setting.toPyObject()))
            except Exception, e:
                print "Loading of configuration key", preference, "failed."
                self.settings.remove(preference)
Ejemplo n.º 13
0
    def chooseOutputFile(self):
        # get last used dir
        settings = QSettings()
        lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".")

        # get selected filter
        selectedFilter = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex())

        # ask for a filename
        filename = QFileDialog.getSaveFileName(self, self.tr("Choose where to save the file"), lastUsedDir,
                                               selectedFilter)
        if filename == "":
            return

        filterString = qgis.core.QgsVectorFileWriter.filterForDriver(selectedFilter)
        ext = filterString[filterString.find('.'):]
        ext = ext[:ext.find(' ')]

        if not filename.lower().endswith(ext):
            filename += ext

        # store the last used dir
        settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath())

        self.editOutputFile.setText(filename)
Ejemplo n.º 14
0
    def define_user_analysis_extent(self, extent, crs):
        """Slot called when user has defined a custom analysis extent.

        .. versionadded: 2.2.0

        :param extent: Extent of the user's preferred analysis area.
        :type extent: QgsRectangle

        :param crs: Coordinate reference system for user defined analysis
            extent.
        :type crs: QgsCoordinateReferenceSystem
        """
        self.hide_user_analysis_extent()

        try:
            extent = self.validate_rectangle(extent)
            self.user_extent = extent
            self.user_extent_crs = crs
        except InvalidGeometryError:
            # keep existing user extent without updating it
            raise InvalidGeometryError

        # Persist this extent for the next session
        settings = QSettings()
        user_extent = [
            self.user_extent.xMinimum(),
            self.user_extent.yMinimum(),
            self.user_extent.xMaximum(),
            self.user_extent.yMaximum()]
        extent_string = ', '.join(('%f' % x) for x in user_extent)
        settings.setValue('inasafe/analysis_extent', extent_string)
        settings.setValue('inasafe/analysis_extent_crs', crs.authid())

        self.show_user_analysis_extent()
Ejemplo n.º 15
0
    def __init__(self, parent=None, title=None, description=None,
                 working_directory=None, workspace_units=None):
        settings = QSettings()

        self.__working_directory = (
            working_directory or
            settings.value("output/default-working-directory",
                           os.path.expanduser("~/Oasys"), type=str))

        if not os.path.exists(self.__working_directory):
            os.makedirs(self.__working_directory, exist_ok=True)

        #QSettings().setValue("output/default-units", 1)

        self.__workspace_units = (
            workspace_units or
            settings.value("output/default-units", 1, type=int))

        super().__init__(parent, title=title, description=description)

        # Replace the signal manager from.
        self.signal_manager.setParent(None)
        self.signal_manager.deleteLater()
        sip.delete(self.signal_manager)
        sip.delete(self.widget_manager)

        self.set_loop_flags(Scheme.AllowLoops)
        self.signal_manager = OASYSSignalManager(self)
        self.widget_manager = OASYSWidgetManager()
        self.widget_manager.set_scheme(self)
Ejemplo n.º 16
0
    def __init__(self, parent, network_analyzer, url=None):
        QWidget.__init__(self, parent)

        self.webView = QWebView()
        self.webView.setPage(QgepWebPage(self.webView))

        self.networkAnalyzer = network_analyzer

        settings = QSettings()

        layout = QVBoxLayout(self)
        if url is None:
            url = settings.value("/QGEP/SvgProfilePath", u'qrc:///plugins/qgepplugin/svgprofile/index.html')

        developermode = settings.value("/QGEP/DeveloperMode", False, type=bool)

        if developermode is True:
            self.webView.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        else:
            self.webView.setContextMenuPolicy(Qt.NoContextMenu)

        self.webView.load(QUrl(url))
        self.frame = self.webView.page().mainFrame()
        self.frame.javaScriptWindowObjectCleared.connect(self.initJs)

        layout.addWidget(self.webView)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
 def dropEvent(self, event):
     if event.mimeData().hasFormat('text/uri-list'):
         paths = [str(u.toLocalFile().toUtf8()) for u in event.mimeData().urls()]
         fileName = paths[0] #If we drop many files, only the first one will be take into acount
         index = self.indexAt(event.pos())
         row, col = index.row(), index.column()
         settings = QSettings()
         if col == UploadListView.COL_VIDEO:
             if(VideoTools.isVideofile(fileName)): 
                 settings.setValue("mainwindow/workingDirectory", QVariant(fileName))
                 video = VideoFile(fileName) 
                 self.model().emit(SIGNAL("layoutAboutToBeChanged()"))
                 self.model().addVideos(row, [video])
                 subtitle = Subtitle.AutoDetectSubtitle(video.getFilePath())
                 if subtitle:
                     sub = SubtitleFile(False,subtitle) 
                     self.model().addSubs(row, [sub])
                     thread.start_new_thread(self.uploadModel.ObtainUploadInfo, ())
                 self.resizeRowsToContents()
                 self.model().emit(SIGNAL("layoutChanged()"))
         else: #if it's the column in SUBTITLES
             print fileName
             if(Subtitle.isSubtitle(fileName)): 
                 settings.setValue("mainwindow/workingDirectory", QVariant(fileName))
                 sub = SubtitleFile(False, fileName) 
                 self.model().emit(SIGNAL("layoutAboutToBeChanged()"))
                 self.model().addSubs(row, [sub])
                 self.resizeRowsToContents()
                 self.model().emit(SIGNAL("layoutChanged()"))
                 thread.start_new_thread(self.uploadModel.ObtainUploadInfo, ())
Ejemplo n.º 19
0
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename = QFileDialog.getOpenFileName(self.toolbox,
            self.tr('Open model', 'AddModelFromFileAction'), lastDir,
            self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction'))
        if filename:
            try:
                settings.setValue('Processing/lastModelsDir',
                    QFileInfo(fileName).absoluteDir().absolutePath())

                ModelerAlgorithm.fromFile(filename)
            except WrongModelException:
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction'))
                return
            except:
                QMessageBox.warning(self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('Cannot read file', 'AddModelFromFileAction'))
            destFilename = os.path.join(ModelerUtils.modelsFolder(), os.path.basename(filename))
            shutil.copyfile(filename,destFilename)
            self.toolbox.updateProvider('model')
Ejemplo n.º 20
0
 def get_db_tables(self):
     """Retrieve all tables from the selected database."""
     self.dlg.cmb_geo.clear()
     db_name = self.dlg.cmb_db.currentText()
     con_name = self.dlg.cmb_con.currentText()
     con_str = "{db}/connections/{con}/".format(db=db_name, con=con_name)
     qs = QSettings()
     db_host = qs.value(con_str + "host")
     db_port = qs.value(con_str + "port")
     db_name = qs.value(con_str + "database")
     con_usr = qs.value(con_str + "username")
     con_pwd = qs.value(con_str + "password")
     uri = QgsDataSourceURI()
     uri.setConnection(db_host, db_port, db_name, con_usr, con_pwd)
     post_c = pg_con.PostGisDBConnector(uri)
     tbl_list = []
     for table in post_c.getTables():
         if table[3] or table[1] == 'spatial_ref_sys':
             pass
         else:
             tbl_list.append(table[1])
     if len(tbl_list) == 0:
         QMessageBox.warning(None,
                             'Layer and Tables',
                             """There are no tables to geo-code in this database.""")
     else:
         self.dlg.cmb_geo.addItems(tbl_list)
Ejemplo n.º 21
0
    def run(self):
        """Run method that performs all the real work"""
        # get all available Databases and their connections.
        db_default = ['PostgreSQL', 'SpatialLite']
        db_con_dict = {}
        qs = QSettings()
        for k in qs.allKeys():
            qsk = k.split('/')
            if qsk[0] in db_default and qsk[0] not in db_con_dict.keys():
                db_con_dict.update({qsk[0]: qsk[2]})

        self.dlg.cmb_db.clear()
        self.dlg.cmb_db.addItems(db_con_dict.keys())
        self.get_connections()
        self.get_db_tables()
        # list tables to select geonames
        tables = self.iface.legendInterface().layers()
        layers_list = []
        for layer in tables:
            layers_list.append(layer.name())

        self.dlg.cmb_lay.clear()
        self.dlg.cmb_lay.addItems(layers_list)
        # list field names of initial table
        self.get_field_names()
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Ejemplo n.º 22
0
 def showEvent(self, event):
     # Show Event
     QWidget.showEvent(self, event)
     # Avoid recalculate the panel sizes if they are already loaded
     if self._splitterArea.count() == 2:
         return
     # Rearrange widgets on Window
     self._splitterArea.insertWidget(0, self._splitterMain)
     qsettings = QSettings()
     # Lists of sizes as list of QVariant- heightList = [QVariant, QVariant]
     heightList = list(qsettings.value("window/central/mainSize", [(self.height() / 3) * 2, self.height() / 3]))
     widthList = list(qsettings.value("window/central/areaSize", [(self.width() / 6) * 5, self.width() / 6]))
     self._splitterMainSizes = [int(heightList[0]), int(heightList[1])]
     self._splitterAreaSizes = [int(widthList[0]), int(widthList[1])]
     if not event.spontaneous():
         self.change_misc_visibility()
     if bin(settings.UI_LAYOUT)[-1] == "1":
         self.splitter_central_rotate()
     if bin(settings.UI_LAYOUT >> 1)[-1] == "1":
         self.splitter_misc_rotate()
     if bin(settings.UI_LAYOUT >> 2)[-1] == "1":
         self.splitter_central_orientation()
     # Set the sizes to splitters
     self._splitterMain.setSizes(self._splitterMainSizes)
     self._splitterArea.setSizes(self._splitterAreaSizes)
Ejemplo n.º 23
0
    def __init__(self, parent=None):
        '''
        Constructor
        '''
        super(GuidanceDock, self).__init__(parent)

        self.setupUi(self)
        self.compass = CompassWidget()
        self.compass.setMinimumHeight(80)
        self.verticalLayout.addWidget(self.compass)
        self.verticalLayout.setStretch(5, 8)
        self.distArea = QgsDistanceArea()
        self.distArea.setEllipsoid(u'WGS84')
        self.distArea.setEllipsoidalMode(True)
        self.distArea.setSourceCrs(3452L)
        self.fontSize = 11
        self.source = None
        self.target = None
        self.srcPos = [None, 0.0]
        self.trgPos = [None, 0.0]
        self.srcHeading = 0.0
        self.trgHeading = 0.0
        s = QSettings()
        self.format = s.value('PosiView/Guidance/Format', defaultValue=1, type=int)
        self.showUtc = s.value('PosiView/Misc/ShowUtcClock', defaultValue=False, type=bool)
        self.timer = 0
        self.setUtcClock()
    def save_state(self):
        """ Store current state of GUI to configuration file.

        .. versionadded: 3.3
        """
        settings = QSettings()
        settings.setValue('directory', self.output_directory.text())
Ejemplo n.º 25
0
    def __init__(self):
        """ Initializer.

        """
        format = self.IniFormat if isWin else self.NativeFormat
        scope = self.UserScope
        QSettings.__init__(self, format, scope, self.keys.org, self.keys.app)
Ejemplo n.º 26
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(QFile.decodeName(__file__))
        # initialize locale
        settings = QSettings()
        locale = settings.value("locale/userLocale", "")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n', '{0}.qm'.format(locale))

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

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

        self.pluginName = self.tr("TileLayerPlugin")
        self.downloadTimeout = int(settings.value("/TileLayerPlugin/timeout", 30, type=int))
        self.navigationMessagesEnabled = int(settings.value("/TileLayerPlugin/naviMsg", Qt.Checked, type=int))
        self.crs3857 = None
        self.layers = {}

        # register plugin layer type
        self.tileLayerType = TileLayerType(self)
        QgsPluginLayerRegistry.instance().addPluginLayerType(self.tileLayerType)

        # connect signal-slot
        QgsMapLayerRegistry.instance().layerRemoved.connect(self.layerRemoved)
Ejemplo n.º 27
0
    def showFileSelectionDialog(self):
        settings = QSettings()
        text = unicode(self.text.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 = unicode(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        ret = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path,
                self.tr('All files(*.*);;') + self.param.getFileFilter())
        if ret:
            files = list(ret)
            settings.setValue('/Processing/LastInputPath',
                              os.path.dirname(unicode(files[0])))
            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(unicode(f) for f in files))
                else:
                    rowdif = len(files) - (self.table.rowCount() - self.row)
                    for i in range(rowdif):
                        self.panel.addRow()
                    for i, f in enumerate(files):
                        self.table.cellWidget(i + self.row,
                                self.col).setText(f)
Ejemplo n.º 28
0
def defaultJob(document, preview):
    """Returns a default job for the document."""
    filename, mode, includepath = documentinfo.info(document).jobinfo(True)
    includepath.extend(documentinfo.info(document).includepath())
    i = info(document)
    j = job.Job()
    
    command = [i.command]
    s = QSettings()
    s.beginGroup("lilypond_settings")
    if s.value("delete_intermediate_files", True) not in (False, "false"):
        command.append('-ddelete-intermediate-files')
    else:
        command.append('-dno-delete-intermediate-files')
    command.append('-dpoint-and-click' if preview else '-dno-point-and-click')
    command.append('--pdf')
    command.extend('-I' + path for path in includepath)
    j.directory = os.path.dirname(filename)
    command.append(filename)
    j.command = command
    if s.value("no_translation", False) in (True, "true"):
        j.environment['LANG'] = 'C'
    j.setTitle("{0} {1} [{2}]".format(
        os.path.basename(i.command), i.versionString(), document.documentName()))
    return j
Ejemplo n.º 29
0
 def find_most_old_open(self):
     recent_project_list = QSettings().value("recentProjects", {})
     listFounder = []
     for recent_project_path, content in list(recent_project_list.items()):
         listFounder.append((recent_project_path, int(content["lastopen"].toString("yyyyMMddHHmmzzz"))))
     listFounder = sorted(listFounder, key=lambda date: listFounder[1], reverse=True)  # sort by date last used
     return listFounder[0][0]
Ejemplo n.º 30
0
 def __init__(self, rules, flux):
   QDialog.__init__(self)
   self.rules = rules
   self.flux = flux
   
   self.setModal(True)
   self.ui = Ui_ExpertivityDialog()
   self.ui.setupUi(self)
   
   R = len(rules)
   self.ui.tableWidget.setColumnCount(R)
   self.ui.tableWidget.setRowCount(R)
   
   ruleNames = [rule.name[:3] for rule in self.rules]
   self.ui.tableWidget.setHorizontalHeaderLabels(ruleNames)
   self.ui.tableWidget.setVerticalHeaderLabels(ruleNames)
   
   for i in range(R):
     self.ui.tableWidget.setColumnWidth(i, 50)
     
   s = QSettings()
   s.beginGroup('Expertivity')
   for i in range(R):
     s.beginGroup('Row%d' % i)
     for j in range(R):
       if j != i:
         self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(s.value('Column%d' % j, 0, float))))
     s.endGroup()
   s.endGroup()
   
   self.ui.tableWidget.itemChanged.connect(self.recalculateExpertivity)
   self.recalculateExpertivity();
Ejemplo n.º 31
0
    def initGui(self):

        settings = QSettings()
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        # Add toolbar
        self.menu = QMenu()
        self.menu.setTitle(
            QCoreApplication.translate("CADDigitize", "&CADDigitize"))
        self.caddigitize_help = QAction(
            QCoreApplication.translate("CADDigitize", "Help"),
            self.iface.mainWindow())
        self.caddigitize_settings = QAction(
            QCoreApplication.translate("CADDigitize", "Settings"),
            self.iface.mainWindow())

        self.menu.addActions(
            [self.caddigitize_help, self.caddigitize_settings])

        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)

        self.caddigitize_help.triggered.connect(self.doHelp)
        self.caddigitize_settings.triggered.connect(self.doSettings)

        # Add button
        self.toolBar = self.iface.addToolBar("CADDigitize")
        self.toolBar.setObjectName("CADDigitize")

        self.optionsToolBar = self.iface.addToolBar("CADDigitize Options")
        self.optionsToolBar.setObjectName("CADDigitize Options")

        self.circleToolButton = QToolButton(self.toolBar)
        self.rectToolButton = QToolButton(self.toolBar)
        self.ellipseToolButton = QToolButton(self.toolBar)
        self.arcToolButton = QToolButton(self.toolBar)
        self.rpolygonToolButton = QToolButton(self.toolBar)
        self.circleToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.rectToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.ellipseToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.arcToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.rpolygonToolButton.setPopupMode(QToolButton.MenuButtonPopup)

        ###
        # Circles
        ###

        # Add actions
        self.circleBy2Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/circleBy2Points.png"),
            "Circle by 2 points", self.iface.mainWindow())
        self.circleBy3Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/circleBy3Points.png"),
            "Circle by 3 points", self.iface.mainWindow())
        self.circleByCenterRadius = QAction(
            QIcon(":/plugins/CADDigitize/icons/circleByCenterRadius.png"),
            "Circle by center and radius", self.iface.mainWindow())
        self.circleByCenterPoint = QAction(
            QIcon(":/plugins/CADDigitize/icons/circleByCenterPoint.png"),
            "Circle by center and a point", self.iface.mainWindow())

        self.circleToolButton.addActions([
            self.circleBy2Points, self.circleBy3Points,
            self.circleByCenterRadius, self.circleByCenterPoint
        ])
        self.circleToolButton.setDefaultAction(self.circleBy2Points)
        self.toolBar.addWidget(self.circleToolButton)

        self.circleBy2Points.setCheckable(True)
        self.circleBy2Points.setEnabled(False)
        self.circleBy3Points.setCheckable(True)
        self.circleBy3Points.setEnabled(False)
        self.circleByCenterRadius.setCheckable(True)
        self.circleByCenterRadius.setEnabled(False)
        self.circleByCenterPoint.setCheckable(True)
        self.circleByCenterPoint.setEnabled(False)

        self.toolBar.addSeparator()

        ###
        # Rectangles
        ###

        self.rectBy3Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/rectBy3Points.png"),
            "Rectangle by 3 points", self.iface.mainWindow())
        self.rectByExtent = QAction(
            QIcon(":/plugins/CADDigitize/icons/rectByExtent.png"),
            "Rectangle by extent", self.iface.mainWindow())
        self.rectFromCenter = QAction(
            QIcon(":/plugins/CADDigitize/icons/rectFromCenter.png"),
            "Rectangle from center", self.iface.mainWindow())
        self.squareFromCenter = QAction(
            QIcon(":/plugins/CADDigitize/icons/squareFromCenter.png"),
            "Square from center", self.iface.mainWindow())
        self.rectToolButton.addActions([
            self.rectBy3Points, self.rectByExtent, self.rectFromCenter,
            self.squareFromCenter
        ])
        self.rectToolButton.setDefaultAction(self.rectBy3Points)
        self.toolBar.addWidget(self.rectToolButton)

        self.rectBy3Points.setEnabled(False)
        self.rectBy3Points.setCheckable(True)
        self.rectByExtent.setEnabled(False)
        self.rectByExtent.setCheckable(True)
        self.rectFromCenter.setEnabled(False)
        self.rectFromCenter.setCheckable(True)
        self.squareFromCenter.setEnabled(False)
        self.squareFromCenter.setCheckable(True)

        self.toolBar.addSeparator()

        ###
        # Ellipses
        ###

        # Add actions
        self.ellipseByCenter2Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseByCenter2Points.png"),
            "Ellipse by center and 2 points", self.iface.mainWindow())
        self.ellipseByCenter3Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseByCenter3Points.png"),
            "Ellipse by center and 3 points", self.iface.mainWindow())
        self.ellipseBy4Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseBy4Points.png"),
            "Ellipse by 4 points", self.iface.mainWindow())
        self.ellipseByFociPoint = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseByFociPoint.png"),
            "Ellipse by foci and a point", self.iface.mainWindow())
        self.ellipseFromCenter = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseFromCenter.png"),
            "Ellipse from center", self.iface.mainWindow())
        self.ellipseByExtent = QAction(
            QIcon(":/plugins/CADDigitize/icons/ellipseByExtent.png"),
            "Ellipse by extent", self.iface.mainWindow())

        self.ellipseToolButton.addActions([
            self.ellipseByCenter2Points, self.ellipseByFociPoint,
            self.ellipseFromCenter, self.ellipseByExtent
        ])
        self.ellipseToolButton.setDefaultAction(self.ellipseByCenter2Points)
        self.toolBar.addWidget(self.ellipseToolButton)

        self.ellipseByCenter2Points.setCheckable(True)
        self.ellipseByCenter2Points.setEnabled(False)
        self.ellipseByCenter3Points.setCheckable(True)
        self.ellipseByCenter3Points.setEnabled(False)
        self.ellipseBy4Points.setCheckable(True)
        self.ellipseBy4Points.setEnabled(False)
        self.ellipseByFociPoint.setCheckable(True)
        self.ellipseByFociPoint.setEnabled(False)
        self.ellipseFromCenter.setCheckable(True)
        self.ellipseFromCenter.setEnabled(False)
        self.ellipseByExtent.setCheckable(True)
        self.ellipseByExtent.setEnabled(False)

        self.toolBar.addSeparator()

        ###
        # Arcs
        ###

        # Add actions
        self.arcByCenter2Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/arcByCenter2Points.png"),
            "Arc by center and 2 points", self.iface.mainWindow())
        self.arcBy3Points = QAction(
            QIcon(":/plugins/CADDigitize/icons/arcBy3Points.png"),
            "Arc by 3 points", self.iface.mainWindow())
        self.arcByCenterPointAngle = QAction(
            QIcon(":/plugins/CADDigitize/icons/arcByCenterPointAngle.png"),
            "Arc by center, point and angle", self.iface.mainWindow())

        self.arcToolButton.addActions([
            self.arcByCenter2Points, self.arcBy3Points,
            self.arcByCenterPointAngle
        ])
        self.arcToolButton.setDefaultAction(self.arcByCenter2Points)
        self.toolBar.addWidget(self.arcToolButton)

        self.arcByCenter2Points.setCheckable(True)
        self.arcByCenter2Points.setEnabled(False)
        self.arcBy3Points.setCheckable(True)
        self.arcBy3Points.setEnabled(False)
        self.arcByCenterPointAngle.setCheckable(True)
        self.arcByCenterPointAngle.setEnabled(False)

        self.toolBar.addSeparator()

        ###
        # Regular Polygon
        ###

        self.rpolygonByCenterPoint = QAction(
            QIcon(":/plugins/CADDigitize/icons/rpolygonByCenterPoint.png"),
            "Regular polygon by center and point", self.iface.mainWindow())
        self.rpolygonBy2Corners = QAction(
            QIcon(":/plugins/CADDigitize/icons/rpolygonBy2Corners.png"),
            "Regular polygon by 2 corners", self.iface.mainWindow())

        self.rpolygonToolButton.addActions(
            [self.rpolygonByCenterPoint, self.rpolygonBy2Corners])
        self.rpolygonToolButton.setDefaultAction(self.rpolygonByCenterPoint)
        self.toolBar.addWidget(self.rpolygonToolButton)

        self.rpolygonByCenterPoint.setCheckable(True)
        self.rpolygonByCenterPoint.setEnabled(False)
        self.rpolygonBy2Corners.setCheckable(True)
        self.rpolygonBy2Corners.setEnabled(False)

        self.toolBar.addSeparator()

        ### Conect

        QObject.connect(self.circleBy2Points, SIGNAL("activated()"),
                        self.circleBy2PointsDigit)
        QObject.connect(self.circleBy3Points, SIGNAL("activated()"),
                        self.circleBy3PointsDigit)
        QObject.connect(self.circleByCenterRadius, SIGNAL("activated()"),
                        self.circleByCenterRadiusDigit)
        QObject.connect(self.circleByCenterPoint, SIGNAL("activated()"),
                        self.circleByCenterPointDigit)
        QObject.connect(self.rectBy3Points, SIGNAL("activated()"),
                        self.rectBy3PointsDigit)
        QObject.connect(self.rectByExtent, SIGNAL("activated()"),
                        self.rectByExtentDigit)
        QObject.connect(self.rectFromCenter, SIGNAL("activated()"),
                        self.rectFromCenterDigit)
        QObject.connect(self.squareFromCenter, SIGNAL("activated()"),
                        self.squareFromCenterDigit)
        QObject.connect(self.ellipseByCenter2Points, SIGNAL("activated()"),
                        self.ellipseByCenter2PointsDigit)
        QObject.connect(self.ellipseByCenter3Points, SIGNAL("activated()"),
                        self.ellipseByCenter3PointsDigit)
        QObject.connect(self.ellipseBy4Points, SIGNAL("activated()"),
                        self.ellipseBy4PointsDigit)
        QObject.connect(self.ellipseByFociPoint, SIGNAL("activated()"),
                        self.ellipseByFociPointDigit)
        QObject.connect(self.ellipseFromCenter, SIGNAL("activated()"),
                        self.ellipseFromCenterDigit)
        QObject.connect(self.ellipseByExtent, SIGNAL("activated()"),
                        self.ellipseByExtentDigit)
        QObject.connect(self.arcByCenter2Points, SIGNAL("activated()"),
                        self.arcByCenter2PointsDigit)
        QObject.connect(self.arcBy3Points, SIGNAL("activated()"),
                        self.arcBy3PointsDigit)
        QObject.connect(self.arcByCenterPointAngle, SIGNAL("activated()"),
                        self.arcByCenterPointAngleDigit)
        QObject.connect(self.rpolygonByCenterPoint, SIGNAL("activated()"),
                        self.rpolygonByCenterPointDigit)
        QObject.connect(self.rpolygonBy2Corners, SIGNAL("activated()"),
                        self.rpolygonBy2CornersDigit)

        QObject.connect(self.iface,
                        SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                        self.toggle)
        QObject.connect(self.canvas, SIGNAL("mapToolSet(QgsMapTool*)"),
                        self.deactivate)

        # Get the tools
        self.circleBy2Points_tool = CircleBy2PointsTool(self.canvas)
        self.circleBy3Points_tool = CircleBy3PointsTool(self.canvas)
        self.circleByCenterRadius_tool = CircleByCenterRadiusTool(self.canvas)
        self.circleByCenterPoint_tool = CircleByCenterPointTool(self.canvas)
        self.rectBy3Points_tool = RectBy3PointsTool(self.canvas)
        self.rectByExtent_tool = RectByExtentTool(self.canvas)
        self.rectFromCenter_tool = RectFromCenterTool(self.canvas)
        self.squareFromCenter_tool = SquareFromCenterTool(self.canvas)
        self.ellipseByCenter2Points_tool = EllipseByCenter2PointsTool(
            self.canvas)
        self.ellipseByCenter3Points_tool = EllipseByCenter3PointsTool(
            self.canvas)
        self.ellipseBy4Points_tool = EllipseBy4PointsTool(self.canvas)
        self.ellipseByFociPoint_tool = EllipseByFociPointTool(self.canvas)
        self.ellipseByExtent_tool = EllipseByExtentTool(self.canvas)
        self.ellipseFromCenter_tool = EllipseFromCenterTool(self.canvas)
        self.arcByCenter2Points_tool = ArcByCenter2PointsTool(self.canvas)
        self.arcBy3Points_tool = ArcBy3PointsTool(self.canvas)
        self.arcByCenterPointAngle_tool = ArcByCenterPointAngleTool(
            self.canvas)
        self.rpolygonByCenterPoint_tool = RPolygonByCenterPointTool(
            self.canvas)
        self.rpolygonBy2Corners_tool = RPolygon2CornersTool(self.canvas)
Ejemplo n.º 32
0
    def __init__(self, iface, parent=None, extent=None, crs=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog
        :type parent: QWidget

        :param extent: Extent of the user's preferred analysis area.
        :type extent: QgsRectangle

        :param crs: Coordinate reference system for user defined analysis
            extent.
        :type crs: QgsCoordinateReferenceSystem
        """
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.iface = iface
        self.parent = parent
        self.canvas = iface.mapCanvas()
        self.previous_map_tool = None
        # Prepare the map tool
        self.tool = RectangleMapTool(self.canvas)
        self.previous_map_tool = self.canvas.mapTool()

        if extent is None and crs is None:
            # Use the current map canvas extents as a starting point
            self.tool.set_rectangle(self.canvas.extent())
        else:
            # Ensure supplied extent is in current canvas crs
            transform = QgsCoordinateTransform(
                crs,
                self.canvas.mapRenderer().destinationCrs())
            transformed_extent = transform.transformBoundingBox(extent)
            self.tool.set_rectangle(transformed_extent)

        self._populate_coordinates()

        # Observe inputs for changes
        self.x_minimum.valueChanged.connect(self._coordinates_changed)
        self.y_minimum.valueChanged.connect(self._coordinates_changed)
        self.x_maximum.valueChanged.connect(self._coordinates_changed)
        self.y_maximum.valueChanged.connect(self._coordinates_changed)

        # Draw the rubberband
        self._coordinates_changed()

        # Wire up button events
        self.capture_button.clicked.connect(self.start_capture)
        # Handle cancel
        cancel_button = self.button_box.button(QtGui.QDialogButtonBox.Cancel)
        cancel_button.clicked.connect(self.reject)
        # Make sure to reshow this dialog when rectangle is captured
        self.tool.rectangle_created.connect(self.stop_capture)
        # Setup ok button
        self.ok_button = self.button_box.button(QtGui.QDialogButtonBox.Ok)
        self.ok_button.clicked.connect(self.accept)
        # Set up context help
        self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)
        # Reset / Clear button
        clear_button = self.button_box.button(QtGui.QDialogButtonBox.Reset)
        clear_button.setText(self.tr('Clear'))
        clear_button.clicked.connect(self.clear)

        # Populate the bookmarks list and connect the combobox
        self._populate_bookmarks_list()
        self.bookmarks_list.currentIndexChanged.connect(
            self.bookmarks_index_changed)

        # Reinstate the last used radio button
        settings = QSettings()
        mode = settings.value('inasafe/analysis_extents_mode',
                              'HazardExposureView')
        if mode == 'HazardExposureView':
            self.hazard_exposure_view_extent.setChecked(True)
        elif mode == 'HazardExposure':
            self.hazard_exposure_only.setChecked(True)
        elif mode == 'HazardExposureBookmark':
            self.hazard_exposure_bookmark.setChecked(True)
        elif mode == 'HazardExposureBoundingBox':
            self.hazard_exposure_user_extent.setChecked(True)

        show_warnings = settings.value('inasafe/show_extent_warnings',
                                       True,
                                       type=bool)
        if show_warnings:
            self.show_warnings.setChecked(True)
        else:
            self.show_warnings.setChecked(False)

        show_confirmations = settings.value(
            'inasafe/show_extent_confirmations', True, type=bool)
        if show_confirmations:
            self.show_confirmations.setChecked(True)
        else:
            self.show_confirmations.setChecked(False)
Ejemplo n.º 33
0
 def setUp(self):
     """Fixture run before all tests"""
     self.qsetting = QSettings('InaSAFETest')
     self.qsetting.clear()
Ejemplo n.º 34
0
class TestOptionsDialog(unittest.TestCase):

    """Test Options Dialog"""

    def setUp(self):
        """Fixture run before all tests"""
        self.qsetting = QSettings('InaSAFETest')
        self.qsetting.clear()

    def tearDown(self):
        """Fixture run after each test."""
        # Make sure it's empty
        self.qsetting.clear()

    def test_setup_dialog(self):
        """Test Setup Options Dialog."""
        dialog = OptionsDialog(
            parent=PARENT, iface=IFACE, qsetting='InaSAFETest')
        self.assertIsNotNone(dialog)

        # Check default values
        self.assertEqual(
            dialog.cbxVisibleLayersOnly.isChecked(),
            inasafe_default_settings['visibleLayersOnlyFlag'])
        self.assertEqual(
            dialog.cbxSetLayerNameFromTitle.isChecked(),
            inasafe_default_settings['set_layer_from_title_flag'])
        self.assertEqual(
            dialog.cbxZoomToImpact.isChecked(),
            inasafe_default_settings['setZoomToImpactFlag'])
        self.assertEqual(
            dialog.cbxHideExposure.isChecked(),
            inasafe_default_settings['setHideExposureFlag'])
        self.assertEqual(
            dialog.cbxUseSelectedFeaturesOnly.isChecked(),
            inasafe_default_settings['useSelectedFeaturesOnly'])
        self.assertEqual(
            dialog.leKeywordCachePath.text(),
            inasafe_default_settings['keywordCachePath'])
        self.assertEqual(
            dialog.template_warning_checkbox.isChecked(),
            inasafe_default_settings['template_warning_verbose'])
        self.assertEqual(
            dialog.organisation_on_dock_checkbox.isChecked(),
            inasafe_default_settings['showOrganisationLogoInDockFlag'])
        self.assertEqual(
            dialog.cbxDevMode.isChecked(),
            inasafe_default_settings['developer_mode'])

        self.assertEqual(
            dialog.leNorthArrowPath.text(), default_north_arrow_path())
        self.assertEqual(
            dialog.leOrganisationLogoPath.text(), supporters_logo_path())
        self.assertEqual(dialog.leReportTemplatePath.text(), '')
        self.assertEqual(dialog.txtDisclaimer.toPlainText(), disclaimer())
        self.assertEqual(
            dialog.leUserDirectoryPath.text(), temp_dir('impacts'))

        self.assertEqual(
            dialog.iso19115_organization_le.text(),
            inasafe_default_settings['ISO19115_ORGANIZATION'])
        self.assertEqual(
            dialog.iso19115_url_le.text(),
            inasafe_default_settings['ISO19115_URL'])
        self.assertEqual(
            dialog.iso19115_email_le.text(),
            inasafe_default_settings['ISO19115_EMAIL'])
        self.assertEqual(
            dialog.iso19115_license_le.text(),
            inasafe_default_settings['ISO19115_LICENSE'])

    def test_update_settings(self):
        """Test update InaSAFE Option works."""
        # Create new option dialog
        dialog = OptionsDialog(
            parent=PARENT, iface=IFACE, qsetting='InaSAFETest')

        # Update some state
        new_state = not inasafe_default_settings['visibleLayersOnlyFlag']
        dialog.cbxVisibleLayersOnly.setChecked(new_state)

        new_organization = 'Super Organization'
        dialog.iso19115_organization_le.setText(new_organization)

        # Accept the dialog
        dialog.accept()

        # Check the value in QSettings
        # Next two lines a hack because windows qsettings returns a string
        # rather than a bool...TS
        value = self.qsetting.value('inasafe/visibleLayersOnlyFlag')
        if value == u'false':
            value = False
        if value == u'true':
            value = True
        self.assertEquals(
            new_state, value)
        self.assertEqual(
            new_organization,
            self.qsetting.value('inasafe/ISO19115_ORGANIZATION'))

        # Open the options dialog
        dialog = OptionsDialog(
            iface=IFACE, parent=PARENT, qsetting='InaSAFETest')

        # Check the state of the dialog after save the settings
        self.assertEqual(new_state, dialog.cbxVisibleLayersOnly.isChecked())
        self.assertEqual(
            new_organization, dialog.iso19115_organization_le.text())
Ejemplo n.º 35
0
 def _on_click_on_delete(self, path):
     settings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
     recent_projects = settings.value("recentProjects")
     if path in recent_projects:
         del recent_projects[path]
         settings.setValue("recentProjects", recent_projects)
Ejemplo n.º 36
0
    def __init__(self, field_group=None, parent=None, iface=None):
        """Constructor."""
        # Init from parent class
        QWidget.__init__(self, parent)

        # Attributes
        self.layer = None
        self.metadata = {}
        self.parent = parent
        self.iface = iface
        self.field_group = field_group
        self.setting = QSettings()  # TODO(IS): Make dynamic

        # Main container
        self.main_layout = QVBoxLayout()

        # Inner layout
        self.header_layout = QHBoxLayout()
        self.content_layout = QHBoxLayout()
        self.footer_layout = QHBoxLayout()

        # Header
        self.header_label = QLabel()
        self.header_label.setWordWrap(True)

        # Content
        self.field_layout = QVBoxLayout()
        self.parameter_layout = QHBoxLayout()

        self.field_description = QLabel(tr('List of fields'))

        self.field_list = QListWidget()
        self.field_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.field_list.setDragDropMode(QAbstractItemView.DragDrop)
        self.field_list.setDefaultDropAction(Qt.MoveAction)

        self.field_list.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        # noinspection PyUnresolvedReferences
        self.field_list.itemSelectionChanged.connect(self.update_footer)

        # Footer
        self.footer_label = QLabel()

        # Parameters
        self.extra_parameters = [(GroupSelectParameter,
                                  GroupSelectParameterWidget)]

        self.parameters = []
        self.parameter_container = None

        # Adding to layout
        self.header_layout.addWidget(self.header_label)

        self.field_layout.addWidget(self.field_description)
        self.field_layout.addWidget(self.field_list)
        self.field_layout.setSizeConstraint(QLayout.SetMaximumSize)

        self.content_layout.addLayout(self.field_layout)
        self.content_layout.addLayout(self.parameter_layout)

        self.footer_layout.addWidget(self.footer_label)

        self.main_layout.addLayout(self.header_layout)
        self.main_layout.addLayout(self.content_layout)
        self.main_layout.addLayout(self.footer_layout)

        self.setLayout(self.main_layout)
Ejemplo n.º 37
0
 def settings(self):
     return QSettings("myrdp", "settings")
Ejemplo n.º 38
0
 def segmentsettingsCircle(self):
     settings = QSettings()
     settings.setValue("/CADDigitize/circle/segments", self.spinBox.value())
Ejemplo n.º 39
0
 def angleDirectionArc(self):
     settings = QSettings()
     if self.ArcAngleDirectionCombo.currentText() == "ClockWise":
         settings.setValue("/CADDigitize/arc/direction", "ClockWise")
     else:
         settings.setValue("/CADDigitize/arc/direction", "CounterClockWise")
Ejemplo n.º 40
0
 def segmentsettingsEllipse(self):
     settings = QSettings()
     settings.setValue("/CADDigitize/ellipse/segments",
                       self.spinBox.value())
Ejemplo n.º 41
0
    def arcOptions(self):
        settings = QSettings()
        self.optionsToolBar.clear()

        self.arc_featurePitch = settings.value("/CADDigitize/arc/pitch",
                                               2,
                                               type=float)
        self.arc_featureAngle = settings.value("/CADDigitize/arc/angle",
                                               1,
                                               type=int)
        self.arc_method = settings.value("/CADDigitize/arc/method", "pitch")
        self.arc_angleDirection = settings.value("/CADDigitize/arc/direction",
                                                 "ClockWise")

        mc = self.canvas
        layer = mc.currentLayer()
        if layer.geometryType() == 2:
            self.arc_polygonCreation = settings.value(
                "/CADDigitize/arc/polygon", "pie")
            self.ArcPolygonCombo = QComboBox(self.iface.mainWindow())
            self.ArcPolygonCombo.addItems(["pie", "chord"])
            self.ArcPolygonComboAction = self.optionsToolBar.addWidget(
                self.ArcPolygonCombo)
            if self.arc_polygonCreation == "pie":
                self.ArcPolygonCombo.setCurrentIndex(0)
            else:
                self.ArcPolygonCombo.setCurrentIndex(1)

            QObject.connect(self.ArcPolygonCombo,
                            SIGNAL("currentIndexChanged(int)"),
                            self.polygonArc)

        self.ArcFeatureSpin = QDoubleSpinBox(self.iface.mainWindow())
        self.ArcAngleDirectionCombo = QComboBox(self.iface.mainWindow())
        self.ArcAngleDirectionCombo.addItems(["ClockWise", "CounterClockWise"])
        self.ArcAngleDirectionComboAction = self.optionsToolBar.addWidget(
            self.ArcAngleDirectionCombo)
        self.ArcFeatureCombo = QComboBox(self.iface.mainWindow())
        self.ArcFeatureCombo.addItems(["pitch", "angle"])
        self.ArcFeatureComboAction = self.optionsToolBar.addWidget(
            self.ArcFeatureCombo)

        if self.arc_method == "pitch":
            self.ArcFeatureCombo.setCurrentIndex(0)
            self.ArcFeatureSpin.setMinimum(1)
            self.ArcFeatureSpin.setMaximum(1000)
            self.ArcFeatureSpin.setDecimals(1)
            self.ArcFeatureSpin.setValue(self.arc_featurePitch)
            self.ArcFeatureSpinAction = self.optionsToolBar.addWidget(
                self.ArcFeatureSpin)
            self.ArcFeatureSpin.setToolTip("Pitch")
            self.ArcFeatureSpinAction.setEnabled(True)
        else:
            self.ArcFeatureCombo.setCurrentIndex(1)
            self.ArcFeatureSpin.setMinimum(1)
            self.ArcFeatureSpin.setMaximum(3600)
            self.ArcFeatureSpin.setDecimals(0)
            self.ArcFeatureSpin.setValue(self.arc_featureAngle)
            self.ArcFeatureSpinAction = self.optionsToolBar.addWidget(
                self.ArcFeatureSpin)
            self.ArcFeatureSpin.setToolTip("Angle")
            self.ArcFeatureSpinAction.setEnabled(True)

        if self.arc_angleDirection == "ClockWise":
            self.ArcAngleDirectionCombo.setCurrentIndex(0)
        else:
            self.ArcAngleDirectionCombo.setCurrentIndex(1)

        QObject.connect(self.ArcFeatureSpin, SIGNAL("valueChanged(double)"),
                        self.segmentsettingsArc)
        QObject.connect(self.ArcFeatureCombo,
                        SIGNAL("currentIndexChanged(int)"), self.featureArc)
        QObject.connect(self.ArcAngleDirectionCombo,
                        SIGNAL("currentIndexChanged(int)"),
                        self.angleDirectionArc)
Ejemplo n.º 42
0
 def segmentsettingsRPolygon(self):
     settings = QSettings()
     settings.setValue("/CADDigitize/rpolygon/nbedges",
                       self.spinBox.value())
Ejemplo n.º 43
0
    def getConsoleCommands(self):
        connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)]
        settings = QSettings()
        mySettings = '/PostgreSQL/connections/' + connection
        dbname = settings.value(mySettings + '/database')
        user = settings.value(mySettings + '/username')
        host = settings.value(mySettings + '/host')
        port = settings.value(mySettings + '/port')
        password = settings.value(mySettings + '/password')
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        ssrs = unicode(self.getParameterValue(self.S_SRS))
        tsrs = unicode(self.getParameterValue(self.T_SRS))
        asrs = unicode(self.getParameterValue(self.A_SRS))
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        pk = unicode(self.getParameterValue(self.PK))
        pkstring = "-lco FID=" + pk
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        geocolumn = unicode(self.getParameterValue(self.GEOCOLUMN))
        geocolumnstring = "-lco GEOMETRY_NAME=" + geocolumn
        dim = self.DIMLIST[self.getParameterValue(self.DIM)]
        dimstring = "-lco DIM=" + dim
        simplify = unicode(self.getParameterValue(self.SIMPLIFY))
        segmentize = unicode(self.getParameterValue(self.SEGMENTIZE))
        spat = self.getParameterValue(self.SPAT)
        clip = self.getParameterValue(self.CLIP)
        where = unicode(self.getParameterValue(self.WHERE))
        wherestring = '-where "' + where + '"'
        gt = unicode(self.getParameterValue(self.GT))
        overwrite = self.getParameterValue(self.OVERWRITE)
        append = self.getParameterValue(self.APPEND)
        addfields = self.getParameterValue(self.ADDFIELDS)
        launder = self.getParameterValue(self.LAUNDER)
        launderstring = "-lco LAUNDER=NO"
        index = self.getParameterValue(self.INDEX)
        indexstring = "-lco SPATIAL_INDEX=OFF"
        skipfailures = self.getParameterValue(self.SKIPFAILURES)
        promotetomulti = self.getParameterValue(self.PROMOTETOMULTI)
        precision = self.getParameterValue(self.PRECISION)
        options = unicode(self.getParameterValue(self.OPTIONS))

        arguments = []
        arguments.append('-progress')
        arguments.append('--config PG_USE_COPY YES')
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append('PG:"host=' + host)
        arguments.append('port=' + port)
        if len(dbname) > 0:
            arguments.append('dbname=' + dbname)
        if len(password) > 0:
            arguments.append('password='******'active_schema=' + schema)
        else:
            arguments.append('active_schema=public')
        arguments.append('user='******'"')
        arguments.append(dimstring)
        arguments.append(ogrLayer)
        arguments.append(ogrLayerName(inLayer))
        if index:
            arguments.append(indexstring)
        if launder:
            arguments.append(launderstring)
        if append:
            arguments.append('-append')
        if addfields:
            arguments.append('-addfields')
        if overwrite:
            arguments.append('-overwrite')
        if len(self.GEOMTYPE[self.getParameterValue(self.GTYPE)]) > 0:
            arguments.append('-nlt')
            arguments.append(self.GEOMTYPE[self.getParameterValue(self.GTYPE)])
        if len(geocolumn) > 0:
            arguments.append(geocolumnstring)
        if len(pk) > 0:
            arguments.append(pkstring)
        elif primary_key is not None:
            arguments.append("-lco FID=" + primary_key)
        if len(table) > 0:
            arguments.append('-nln')
            arguments.append(table)
        if len(ssrs) > 0:
            arguments.append('-s_srs')
            arguments.append(ssrs)
        if len(tsrs) > 0:
            arguments.append('-t_srs')
            arguments.append(tsrs)
        if len(asrs) > 0:
            arguments.append('-a_srs')
            arguments.append(asrs)
        if len(spat) > 0:
            regionCoords = spat.split(',')
            arguments.append('-spat')
            arguments.append(regionCoords[0])
            arguments.append(regionCoords[2])
            arguments.append(regionCoords[1])
            arguments.append(regionCoords[3])
            if clip:
                arguments.append('-clipsrc spat_extent')
        if skipfailures:
            arguments.append('-skipfailures')
        if where:
            arguments.append(wherestring)
        if len(simplify) > 0:
            arguments.append('-simplify')
            arguments.append(simplify)
        if len(segmentize) > 0:
            arguments.append('-segmentize')
            arguments.append(segmentize)
        if len(gt) > 0:
            arguments.append('-gt')
            arguments.append(gt)
        if promotetomulti:
            arguments.append('-nlt PROMOTE_TO_MULTI')
        if precision is False:
            arguments.append('-lco PRECISION=NO')
        if len(options) > 0:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'ogr2ogr.exe',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Ejemplo n.º 44
0
 def polygonArc(self):
     settings = QSettings()
     if self.ArcPolygonCombo.currentText() == "pie":
         settings.setValue("/CADDigitize/arc/polygon", "pie")
     else:
         settings.setValue("/CADDigitize/arc/polygon", "chord")
Ejemplo n.º 45
0
class Generator():

    def __init__(self, notebookPath):
        self.notebookPath = notebookPath
        self.notepath = os.path.join(notebookPath, "notes").replace(os.sep, '/')
        self.sitepath = os.path.join(notebookPath, "_site").replace(os.sep, '/')
        self.htmlpath = os.path.join(notebookPath, "_site/notes").replace(os.sep, '/')
        self.configfile = os.path.join(self.notebookPath, "notebook.conf").replace(os.sep, '/')
        self.qsettings = QSettings(self.configfile, QSettings.NativeFormat)
        self.extName = ['.md', '.mkd', '.markdown']
        if os.path.exists(self.configfile):
            extensions = readListFromSettings(self.qsettings,
                                                   "extensions")
            defExt = self.qsettings.value("fileExt")
            extCfg = readDictFromSettings(self.qsettings, "extensionsConfig")
            if defExt in self.extName:
                self.extName.remove(defExt)
                self.extName.insert(0, defExt)
                self.exts = extensions
                self.md = markdown.Markdown(extensions, extension_configs=extCfg)
        else:
            print("ERROR: Not a valid mikidown notebook folder")
            sys.exit(1)

    def generate(self):
        # clear sitepath
        self.count = 0
        if os.path.exists(self.sitepath):
            for file_object in os.listdir(self.sitepath):
                file_object_path = os.path.join(self.sitepath, file_object)
                if os.path.isfile(file_object_path):
                    os.unlink(file_object_path)
                else:
                    shutil.rmtree(file_object_path)
        QDir().mkpath(self.htmlpath)
        self.initTree(self.notepath, "")

        # copy css and attachments folder
        cssSrcPath = os.path.join(self.notebookPath, "css")
        cssDstPath = os.path.join(self.sitepath, "css")
        attachSrcPath = os.path.join(self.notebookPath, "attachments")
        attachDstPath = os.path.join(self.sitepath, "attachments")
        shutil.copytree(cssSrcPath, cssDstPath)
        if os.path.exists(attachSrcPath):
            shutil.copytree(attachSrcPath, attachDstPath)

        print('Finished: Processed', self.count, 'notes.')

    def regenerate(self):

        def recursiveAddPath(filePath):
            """ recursively add files and directories to watcher """
            watcher.addPath(filePath)
            fileList = QDir(filePath).entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot)
            for f in fileList:
                recursiveAddPath(f.absoluteFilePath())

        def directoryChanged(filePath):
            watchedFiles = watcher.directories() + watcher.files()
            fileList = QDir(filePath).entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot)
            for f in fileList:
                if f.absoluteFilePath() not in watchedFiles:
                    watcher.addPath(f.absoluteFilePath())

            self.generate()

        # QFileSystemWatcher won't work without a QApplication!
        app = QApplication(sys.argv)
        watcher = QFileSystemWatcher()
        recursiveAddPath(self.notepath)

        # add/remove file triggers this
        watcher.directoryChanged.connect(directoryChanged)
        # edit file triggers this
        watcher.fileChanged.connect(self.generate)
        sys.exit(app.exec_())

    def preview(self, port=3131):
        processWatcher = Thread(target=self.regenerate)
        processWatcher.start()
        self.generate()

        from http.server import HTTPServer, SimpleHTTPRequestHandler

        HandlerClass = SimpleHTTPRequestHandler
        HandlerClass.protocol_version = "HTTP/1.1"
        ServerClass = HTTPServer
        server_address = ('', port)
        httpd = ServerClass(server_address, HandlerClass)
        sa = httpd.socket.getsockname()
        os.chdir(self.sitepath)
        print("Serving HTTP on", sa[0], "port", sa[1], "...")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            processWatcher.terminate()
            httpd.server_close()
            sys.exit(0)

    def initTree(self, notepath, parent):
        if parent == "":
        # site wide index page
            htmlfile = os.path.join(self.sitepath, "index.html")
        else:
        # append subpages to page
            htmlfile = os.path.join(self.htmlpath, parent + ".html")
        html = QFile(htmlfile)
        html.open(QIODevice.Append)
        savestream = QTextStream(html)

        noteDir = QDir(notepath)
        notesList = noteDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                          QDir.NoFilter,
                                          QDir.Name|QDir.IgnoreCase)
        nl = [note.completeBaseName() for note in notesList]
        noduplicate = list(set(nl))
        noduplicate.sort(key=str.lower)
        htmlDir = os.path.join(self.htmlpath, parent)
        if len(noduplicate) > 0 and not QDir(htmlDir).exists():
            QDir().mkdir(htmlDir)

        for name in noduplicate:
            path = notepath + '/' + name
            filename = os.path.join(parent, name)
            for ext in self.extName:
                notefile = os.path.join(self.notepath, filename + ext)
                if QFile.exists(notefile):
                    break
            htmlfile = os.path.join(self.htmlpath, filename + ".html")
            #print(notefile, htmlfile)
            self.convert(notefile, htmlfile, os.path.join(parent,name))
            self.initTree(path, os.path.join(parent,name))

            # append subpages to page
            savestream << '<li><a href="/notes/' + filename + '.html">' + name + '</a></li>'
        html.close()

    def convert(self, notefile, htmlfile, page):

        self.count += 1
        note = QFile(notefile)
        note.open(QIODevice.ReadOnly)
        html = QFile(htmlfile)
        html.open(QIODevice.WriteOnly)
        savestream = QTextStream(html)
        savestream << '<html><head>' \
                      '<meta charset="utf-8">' \
                      '<link rel="stylesheet" href="/css/notebook.css" type="text/css" />' \
                      '</head>'
        savestream << "<header>" + self.breadcrumb(page) + "</header>"
        # Note content
        if 'asciimathml' in self.exts:
            savestream << JSCRIPT_TPL.format(self.qsettings.value('mathJax'))
        savestream << self.md.reset().convert(QTextStream(note).readAll())
        savestream << "</html>"
        note.close()
        html.close()

    def breadcrumb(self, page):
        """ Generate breadcrumb from page hierarchy.
            e.g. page github/mikidown will be shown as:
            <a>github</a> / <a>mikidown</a>
        """

        parts = page.split('/')
        crumb = '<a href="/">Index</a>'
        for i in range(len(parts)):
            crumb += ' / '
            crumb += '<a href="/notes/' + '/'.join(parts[0:i+1]) + '.html">' + parts[i] + '</a>'

        return crumb
Ejemplo n.º 46
0
 def dbConnectionNames(self):
     settings = QSettings()
     settings.beginGroup('/PostgreSQL/connections/')
     return settings.childGroups()
Ejemplo n.º 47
0
def setNetworkTimeout(value=60000):
    global _networkTimeout
    _networkTimeout = QSettings().value("Qgis/networkAndProxy/networkTimeout")
    QSettings().setValue("Qgis/networkAndProxy/networkTimeout", value)
Ejemplo n.º 48
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from PyQt4 import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from PyQt4.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication(sys.argv, gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        settings.setValue('inasafe/show_extent_confirmations', False)
        settings.setValue('inasafe/show_extent_warnings', False)
        settings.setValue('inasafe/showRubberBands', True)
        settings.setValue('inasafe/analysis_extents_mode', HAZARD_EXPOSURE)

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Ejemplo n.º 49
0
sys.path.extend(
    [os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))])

# DO NOT REMOVE THIS
# noinspection PyUnresolvedReferences
import qgis  # pylint: disable=unused-import

from PyQt4.QtCore import (QLocale, QTranslator, QCoreApplication, QSettings)

# Setup internationalisation for the plugin.
#
# See if QGIS wants to override the system locale
# and then see if we can get a valid translation file
# for whatever locale is effectively being used.

override_flag = QSettings().value('locale/overrideFlag', True, type=bool)

if override_flag:
    locale_name = QSettings().value('locale/userLocale', 'en_US', type=str)
else:
    locale_name = QLocale.system().name()
    # NOTES: we split the locale name because we need the first two
    # character i.e. 'id', 'af, etc
    locale_name = str(locale_name).split('_')[0]

# Also set the system locale to the user overridden local
# so that the inasafe library functions gettext will work
# .. see:: :py:func:`common.utilities`
os.environ['LANG'] = str(locale_name)

root = os.path.abspath(os.path.join(os.path.dirname(__file__)))
Ejemplo n.º 50
0
def resetNetworkTimeout():
    QSettings().setValue("Qgis/networkAndProxy/networkTimeout",
                         _networkTimeout)
Ejemplo n.º 51
0
 def saveApplicationSettings(self):
     settings = QSettings()
     settings.setValue("MainWindow/Size",        self.size())
     settings.setValue("MainWindow/Position",    self.pos())
     settings.setValue("MainWindow/State",       self.saveState())
     settings.setValue("MainWindow/ViewsLocked", self.ui.actionLocked.isChecked())
     if self.labeltool.getCurrentFilename() is not None:
         filename = self.labeltool.getCurrentFilename()
     else:
         filename = None
     settings.setValue("LastFile", filename)
Ejemplo n.º 52
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)
Ejemplo n.º 53
0
 def save_state(self):
     """ Store current state of GUI to configuration file """
     settings = QSettings()
     settings.setValue('directory', self.output_directory.text())
Ejemplo n.º 54
0
class WelcomeTab(QWidget, Ui_WelcomeTab):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setupUi(self)
        self.retranslate(all=False)
        self.settings = QSettings()
        show = self.settings.value('showWelcome', 2).toInt()[0]
        self.checkBox.setCheckState(Qt.CheckState(show))

    def dontShow(self, state):
        self.settings.setValue('showWelcome', state)

    def changeEvent(self, event):
        """For dynamic translation support.
        """
        if QEvent.LanguageChange == event.type():
            self.retranslate()
        else:
            QWidget.changeEvent(self, event)

    def retranslate(self, all=True):
        """For dynamic translation.
        """
        if all:
            self.retranslateUi(self)
        # In order to make the job a little bit easier for translators
        # we should avoid the (ultra verbose) Qt Designer generated
        # html. If you are going to edit the following html, it might
        # be more convenient to edit the ``welcome.html`` file in the
        # resource folder, and copy paste in here afterwards.
        self.textBrowser.setHtml(
            QApplication.translate(
                'WelcomeTab', """
<html>
<head>
<style type="text/css">
body { padding: 5px; margin: 5px; font-family: sans-serif; }
h1, h2 { color: #61a7e0; }
a { color: #306ebd; }
p { font-size: 10pt; }
</style>
</head>
<body>
<h1>Welcome to Luma</h1>

<p><strong><em>Luma is LDAP management made easy</em></strong></p>

<p><em>Luma</em> provides useful LDAP administration and management
functionality, through a number of plugins.</p>

<h2>Getting started</h2>

<p>The first thing you need to do is to edit the <em>serverlist</em>: Select
(<b>Edit</b> &rarr; <b>Server List</b>) from the menubar or use the keyboard
shortcut (<b>CTRL</b>+<b>SHIFT</b>+<b>S</b> on Linux/Windwos, <b>CMD</b>+<b>SHIFT</b>+<b>S</b> on Mac Os X).</p>

<p>After you have added one or more servers, you must activate the plugins you
want to use: Select (<b>Edit</b> &rarr; <b>Settings</b>) from the
menubar to open the <em>Settings dialog</em>, and select the <b>Plugins</b> tab.</p>

<p>If you need additional help on how to use the application and/or a spesific
plugin, please refer to the online
<a href="http://folk.ntnu.no/einaru/luma/doc/userguide.html">User guide</a>.</p>

<p>If you cannot find a plugin that suits your needs or you have ideas for a
great Luma plugin, please feel free to
<a href="http://luma.sf.net/">contact us</a> or even
<a href="http://folk.ntnu.no/einaru/luma/doc/HACKING.html">contribute one your self</a>.</p>

<h2>Problems and bugs</h2>

<p>Application errors and various debug information can be seen in the Logger
Window: Select (<b>View</b> &rarr; <b>Logger Window</b>) from the menubar or
use the keyboard shortcut (<b>CTRL</b>+<b>L</b> on Linux/Windows, <b>CMD</b>+<b>L</b> on Mac Os X).</p>

<p>If you encounter errors or bugs in the application, please take your time
to fill in a bugreport on our
<a href="http://sourceforge.net/tracker/?group_id=89105">bugtracker</a>.</p>

<h2>Contact</h2>

<p>You can find contact information in the About Luma dialog: Select
(<b>Help</b> &rarr; <b>About Luma</b>) or use the keyboard shortcut
(<b>F12</b>), and on the <a href="http://luma.sf.net/">Luma website</a>.</p>

<p style="font-size: 8pt; color: #306ebd; padding-top: 25px">
<em>Copyright &copy; 2003 - 2011 Wido Depping and the Luma devel team</em></p>
</body>
</html>
"""))
Ejemplo n.º 55
0
 def _saveSettings(self):
     settings = QSettings("Statoil", "ErtGui")
     settings.setValue("geometry", self.saveGeometry())
     settings.setValue("windowState", self.saveState())
Ejemplo n.º 56
0
    def __init__(self,
                 destination,
                 encoding,
                 fields,
                 geometryType,
                 crs,
                 options=None):
        self.destination = destination
        self.isNotFileBased = False
        self.layer = None
        self.writer = None

        if encoding is None:
            settings = QSettings()
            encoding = settings.value('/Processing/encoding',
                                      'System',
                                      type=str)

        if self.destination.startswith(self.MEMORY_LAYER_PREFIX):
            self.isNotFileBased = True

            uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + unicode(
                uuid.uuid4())
            if crs.isValid():
                uri += '&crs=' + crs.authid()
            fieldsdesc = []
            for f in fields:
                qgsfield = _toQgsField(f)
                fieldsdesc.append(
                    'field=%s:%s' %
                    (qgsfield.name(),
                     TYPE_MAP_MEMORY_LAYER.get(qgsfield.type(), "string")))
            if fieldsdesc:
                uri += '&' + '&'.join(fieldsdesc)

            self.layer = QgsVectorLayer(uri, self.destination, 'memory')
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.POSTGIS_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceURI(
                self.destination[len(self.POSTGIS_LAYER_PREFIX):])
            connInfo = uri.connectionInfo()
            (success, user,
             passwd) = QgsCredentials.instance().get(connInfo, None, None)
            if success:
                QgsCredentials.instance().put(connInfo, user, passwd)
            else:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database")
            print uri.uri()
            try:
                db = postgis_utils.GeoDB(host=uri.host(),
                                         port=int(uri.port()),
                                         dbname=uri.database(),
                                         user=user,
                                         passwd=passwd)
            except postgis_utils.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(unicode(sql))
                except postgis_utils.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output PostGIS table:\n%s' % e.message)

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join(
                '%s %s' %
                (f.name(), TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR"))
                for f in fields)

            _runSQL("CREATE TABLE %s.%s (%s)" %
                    (uri.schema(), uri.table().lower(), fieldsdesc))
            _runSQL(
                "SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)"
                .format(table=uri.table().lower(),
                        schema=uri.schema(),
                        srid=crs.authid().split(":")[-1],
                        typmod=GEOM_TYPE_MAP[geometryType].upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres")
            self.writer = self.layer.dataProvider()
        elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX):
            self.isNotFileBased = True
            uri = QgsDataSourceURI(
                self.destination[len(self.SPATIALITE_LAYER_PREFIX):])
            print uri.uri()
            try:
                db = spatialite_utils.GeoDB(uri=uri)
            except spatialite_utils.DbError as e:
                raise GeoAlgorithmExecutionException(
                    "Couldn't connect to database:\n%s" % e.message)

            def _runSQL(sql):
                try:
                    db._exec_sql_and_commit(unicode(sql))
                except spatialite_utils.DbError as e:
                    raise GeoAlgorithmExecutionException(
                        'Error creating output Spatialite table:\n%s' %
                        e.message)

            fields = [_toQgsField(f) for f in fields]
            fieldsdesc = ",".join(
                '%s %s' %
                (f.name(), TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR"))
                for f in fields)

            _runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower())
            _runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc))
            _runSQL(
                "SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)"
                .format(table=uri.table().lower(),
                        srid=crs.authid().split(":")[-1],
                        typmod=GEOM_TYPE_MAP[geometryType].upper()))

            self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite")
            self.writer = self.layer.dataProvider()
        else:
            formats = QgsVectorFileWriter.supportedFiltersAndFormats()
            OGRCodes = {}
            for (key, value) in formats.items():
                extension = unicode(key)
                extension = extension[extension.find('*.') + 2:]
                extension = extension[:extension.find(' ')]
                OGRCodes[extension] = value

            extension = self.destination[self.destination.rfind('.') + 1:]
            if extension not in OGRCodes:
                extension = 'shp'
                self.destination = self.destination + '.shp'

            qgsfields = QgsFields()
            for field in fields:
                qgsfields.append(_toQgsField(field))

            self.writer = QgsVectorFileWriter(self.destination, encoding,
                                              qgsfields, geometryType, crs,
                                              OGRCodes[extension])
Ejemplo n.º 57
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
Ejemplo n.º 58
0
 def _fetchSettings(self):
     settings = QSettings("Statoil", "ErtGui")
     self.restoreGeometry(settings.value("geometry").toByteArray())
     self.restoreState(settings.value("windowState").toByteArray())
Ejemplo n.º 59
0
 def acceptedAction(self):
     try:
         number = int(self.dlg.interval.text())
     except Exception:
         QMessageBox.about(None, 'Error','Interval can only be a number')
         return None
     s = QSettings()
     if self.dlg.enableAutoSave.isChecked():
         s.setValue("autoSaver/enabled","true")
         if self.dlg.enableAlternate.isChecked():
             s.setValue("autoSaver/alternateBak","true")
         else:
             s.setValue("autoSaver/alternateBak","false")
         if self.dlg.enableSaveLayers.isChecked():
             s.setValue("autoSaver/saveLayerInEditMode","true")
         else:
             s.setValue("autoSaver/saveLayerInEditMode","false")
         if self.dlg.enableSaveLayersBuffer.isChecked():
             s.setValue("autoSaver/saveLayerBuffer","true")
         else:
             s.setValue("autoSaver/saveLayerBuffer","false")
         s.setValue("autoSaver/interval",self.dlg.interval.text())
         self.startAutosave(self.dlg.interval.text())
     else:
         s.setValue("autoSaver/enabled","false")
         if self.dlg.enableAlternate.isChecked():
             s.setValue("autoSaver/alternateBak","true")
         else:
             s.setValue("autoSaver/alternateBak","false")
         if self.dlg.enableSaveLayers.isChecked():
             s.setValue("autoSaver/saveLayerInEditMode","true")
         else:
             s.setValue("autoSaver/saveLayerInEditMode","false")
         if self.dlg.enableSaveLayersBuffer.isChecked():
             s.setValue("autoSaver/saveLayerBuffer","true")
         else:
             s.setValue("autoSaver/saveLayerBuffer","false")
         s.setValue("autoSaver/interval",self.dlg.interval.text())
         self.stopAutosave()
     self.dlg.hide()
Ejemplo n.º 60
0
    def initGui(self):


        # Import Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/database.png")
        self.import_action = QAction(icon, u"Importer des données", self.iface.mainWindow())
        QObject.connect(self.import_action, SIGNAL("triggered()"), self.open_import_dialog)

        # Search Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/search.png")
        self.search_action = QAction(icon, u"Outils de recherche", self.iface.mainWindow())
        QObject.connect(self.search_action, SIGNAL("triggered()"), self.toggle_search_dialog)
        if not self.cadastre_search_dialog:
            dialog = cadastre_search_dialog(self.iface)
            self.cadastre_search_dialog = dialog

        # Load Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/output.png")
        self.load_action = QAction(icon, u"Charger des données", self.iface.mainWindow())
        QObject.connect(self.load_action, SIGNAL("triggered()"), self.open_load_dialog)

        # Composer Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/mActionSaveAsPDF.png")
        self.export_action = QAction(icon, u"Exporter la vue", self.iface.mainWindow())
        QObject.connect(self.export_action, SIGNAL("triggered()"), self.export_view)

        # Options Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/config.png")
        self.option_action = QAction(icon, u"Configurer le plugin", self.iface.mainWindow())
        QObject.connect(self.option_action, SIGNAL("triggered()"), self.open_option_dialog)

        # About Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/about.png")
        self.about_action = QAction(icon, u"À propos", self.iface.mainWindow())
        QObject.connect(self.about_action, SIGNAL("triggered()"), self.open_about_dialog)

        # Help Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/about.png")
        self.help_action = QAction(icon, u"Aide", self.iface.mainWindow())
        QObject.connect(self.help_action, SIGNAL("triggered()"), self.open_help)

        # version Submenu
        icon = QIcon(os.path.dirname(__file__) + "/icons/about.png")
        self.version_action = QAction(icon, u"Notes de version", self.iface.mainWindow())
        QObject.connect(self.version_action, SIGNAL("triggered()"), self.open_message_dialog)

        # Add Cadastre to Extension menu
        self.iface.addPluginToMenu(u"&Cadastre", self.import_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.load_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.search_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.export_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.option_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.about_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.version_action)
        self.iface.addPluginToMenu(u"&Cadastre", self.help_action)


        # Add cadastre toolbar
        self.toolbar = self.iface.addToolBar(u'&Cadastre');

        # open import dialog
        self.openImportAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/database.png"),
            u"Importer des données",
            self.iface.mainWindow()
        )
        self.openImportAction.triggered.connect(self.open_import_dialog)
        self.toolbar.addAction(self.openImportAction)
        self.toolbar.setObjectName("cadastreToolbar");

        # open load dialog
        self.openLoadAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/output.png"),
            u"Charger des données",
            self.iface.mainWindow()
        )
        self.openLoadAction.triggered.connect(self.open_load_dialog)
        self.toolbar.addAction(self.openLoadAction)

        # open search dialog
        self.openSearchAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/search.png"),
            u"Outils de recherche",
            self.iface.mainWindow()
        )
        self.openSearchAction.triggered.connect(self.toggle_search_dialog)
        #~ self.openSearchAction.setCheckable(True)
        self.toolbar.addAction(self.openSearchAction)

        # export composer
        self.runExportAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/mActionSaveAsPDF.png"),
            u"Exporter la vue",
            self.iface.mainWindow()
        )
        self.runExportAction.triggered.connect(self.export_view)
        self.toolbar.addAction(self.runExportAction)

        # open Option dialog
        self.openOptionAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/config.png"),
            u"Configurer le plugin",
            self.iface.mainWindow()
        )
        self.openOptionAction.triggered.connect(self.open_option_dialog)
        self.toolbar.addAction(self.openOptionAction)

        # open About dialog
        self.openAboutAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/about.png"),
            u"À propos",
            self.iface.mainWindow()
        )
        self.openAboutAction.triggered.connect(self.open_about_dialog)
        self.toolbar.addAction(self.openAboutAction)

        # Create action for "Parcelle information"
        self.identifyParcelleAction = QAction(
            QIcon(os.path.dirname(__file__) +"/icons/toolbar/get-parcelle-info.png"),
            "Infos parcelle",
            self.iface.mainWindow()
        )
        self.identifyParcelleAction.setCheckable(True)
        self.identifyParcelleAction.triggered.connect( self.setIndentifyParcelleTool )
        self.toolbar.addAction( self.identifyParcelleAction )

        self.setActionsExclusive()

        # Display About window on first use
        s = QSettings()
        firstUse = s.value("cadastre/isFirstUse" , 1, type=int)
        if firstUse == 1:
            s.setValue("cadastre/isFirstUse", 0)
            self.open_about_dialog()

        # Display some messages depending on version number
        mConfig = ConfigParser.ConfigParser()
        metadataFile = os.path.dirname(__file__) + "/metadata.txt"
        mConfig.read( metadataFile )
        self.mConfig = mConfig
        myVersion = mConfig.get('general', 'version').replace('.', '_')
        myVersionMsg = s.value("cadastre/version_%s" % myVersion , 1, type=int)
        if myVersionMsg == 1:
            s.setValue("cadastre/version_%s" % myVersion , 0)
            self.open_message_dialog()

        # Project load or create : refresh search and identify tool
        self.iface.projectRead.connect(self.onProjectRead)
        self.iface.newProjectCreated.connect(self.onNewProjectCreated)

        # Delete layers from table when deleted from registry
        lr = QgsMapLayerRegistry.instance()
        lr.layersRemoved.connect( self.checkIdentifyParcelleTool )