예제 #1
0
    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)
        """
        self.initclass=InitSelafinContour2Shp()
        self.initclass.status.connect(progress.setText)
        self.initclass.error.connect(self.raiseError)
        self.initclass.finished1.connect(self.workerFinished)
        
        #Determine param
        params = ['Hmax','Vmax','SLmax','?SLmax','SUBMERSION']
        if self.getParameterValue(self.SELAFIN_PARAM_SPE) == '':
            param = params[self.getParameterValue(self.SELAFIN_PARAM_STD)]
        else : 
            param = self.getParameterValue(self.SELAFIN_PARAM_SPE)
            
        #define level
        levels= [[-99.0,0.05,0.5,1.0,2.0,5.0,9999.0],
                [-99.0,0.01,0.05,0.1,0.25,0.5,1.0,1.5,2.0,5.0,9999.0],
                [0.0,0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95,1.05,1.15,1.25,1.35,1.45,1.55,1.65,1.75,1.85,1.95,2.05,2.15,2.25,2.35,2.45,2.55,2.65,2.75,2.85,2.95,3.05,9999.0],
                [-99.0,0.5,1.0,2.0,4.0,9999.0],
                [-99.0,0.25,0.5,1.0,2.0,4.0,9999.0],
                [-604800.0,0.0,300.0,600.0,900.0,1800.0,3600.0,7200.0,10800.0,21600.0,43200.0,86400.0,1e21],
                [-9999.0,-0.5,-0.25,-0.10,-0.05,-0.02,-0.01,0.01,0.02,0.05,0.10,0.25,0.50,9999],
                [0,86400.0,172800.0,432000.0,864000.0,2592000.0]]
        if self.getParameterValue(self.SELAFIN_LVL_SPE) == '':
            level = levels[self.getParameterValue(self.SELAFIN_LVL_STD)]
        else : 
            level = [float(self.getParameterValue(self.SELAFIN_LVL_SPE).split(";")[i]) for i in range(len(self.getParameterValue(self.SELAFIN_LVL_SPE).split(";")))]
                
        self.initclass.start(int(self.getParameterValue(self.PROCESS_TYPE))+1,                 #0 : thread inside qgis (plugin) - 1 : thread processing - 2 : modeler (no thread) - 3 : modeler + shpouput - 4: outsideqgis
                         os.path.normpath(self.getParameterValue(self.SELAFIN_FILE)),                 #path to selafin file
                         self.getParameterValue(self.SELAFIN_TIME),                            #time to process (selafin time in seconds)
                         param,                     #parameter to process name (string) or id (int)
                         level,                       #levels to create
                         self.getParameterValue(self.SELAFIN_CRS),      #selafin crs
                         self.getParameterValue(self.SHP_CRS) if self.getParameterValue(self.TRANS_CRS) else None,   #if no none, specify crs of output file
                         self.getParameterValue(self.QUICK_PROCESS),                #quickprocess option - don't make ring
                         self.getParameterValue(self.SHP_NAME),           #change generic outputname to specific one
                          None,         #if not none, create shp in this directory
                        forcedvalue = None,          #force value for plugin
                          self.getOutputValue(self.SHP_PROCESS))
        

        # 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
        """
예제 #2
0
 def saveCopyCheckSetting(self):
     QSettings().setValue('convert_ly/copy_messages', self.copyCheck.isChecked())
예제 #3
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ImportFromHE_{}.qm'.format(locale))

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

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

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

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

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

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

        if not os.path.isdir(wordir):
            os.makedirs(wordir)
        # --------------------------------------------------------------------------------------------------
        # Konfigurationsdatei qkan.json lesen
        #

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with codecs.open(self.configfil, 'r', 'utf-8') as fileconfig:
                self.config = json.loads(fileconfig.read().replace('\\', '/'))
        else:
            self.config = {'epsg': '25832'}  # Projektionssystem
            self.config['database_QKan'] = ''
            self.config['database_HE'] = ''
            self.config['projectfile'] = ''
            with codecs.open(self.configfil, 'w', 'utf-8') as fileconfig:
                fileconfig.write(json.dumps(self.config))

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

        if 'database_QKan' in self.config:
            database_QKan = self.config['database_QKan']
        else:
            database_QKan = ''
        self.dlg.tf_qkanDB.setText(database_QKan)
        self.dlg.pb_selectqkanDB.clicked.connect(self.selectFile_qkanDB)

        if 'database_HE' in self.config:
            database_HE = self.config['database_HE']
        else:
            database_HE = ''
        self.dlg.tf_heDB.setText(database_HE)
        self.dlg.pb_selectHeDB.clicked.connect(self.selectFile_HeDB)

        if 'epsg' in self.config:
            self.epsg = self.config['epsg']
        else:
            self.epsg = '25832'
        self.dlg.tf_epsg.setText(self.epsg)
        self.dlg.pb_selectKBS.clicked.connect(self.selectKBS)

        if 'projectfile' in self.config:
            projectfile = self.config['projectfile']
        else:
            projectfile = ''
        self.dlg.tf_projectFile.setText(projectfile)
        self.dlg.pb_selectProjectFile.clicked.connect(self.selectProjectFile)

        if 'check_copy_forms' in self.config:
            check_copy_forms = self.config['check_copy_forms']
        else:
            check_copy_forms = True
        self.dlg.cb_copy_forms.setChecked(check_copy_forms)

        if 'check_inittab' in self.config:
            check_inittab = self.config['check_inittab']
        else:
            check_inittab = True
        self.dlg.cb_import_tabinit.setChecked(check_inittab)
예제 #4
0
 def __init__(self):
     self.settings = QSettings()
     self.minimum_needs = None
     self._root_directory = None
     self.locale = self.settings.value('locale/userLocale')
     self.load()
예제 #5
0
def define_defaults():
    """Define standard defaults such as age ratios etc.

    :returns: A dictionary of standard default definitions.
    :rtype: dict
    """
    settings = QSettings()
    defaults = dict()
    # https://www.cia.gov/library/publications/the-world-factbook/geos/xx.html
    # total population: 1.01 male(s)/female (2011 est.)
    female_ratio = 0.50
    value = settings.value('inasafe/defaultFemaleRatio',
                           female_ratio,
                           type=float)
    defaults['FEMALE_RATIO'] = float(value)

    # https://www.cia.gov/library/publications/the-world-factbook/geos/xx.html
    # Age structure:
    # 0-14 years: 26.3% (male 944,987,919/female 884,268,378)
    # 15-64 years: 65.9% (male 2,234,860,865/female 2,187,838,153)
    # 65 years and over: 7.9% (male 227,164,176/female 289,048,221) (2011 est.)

    # NOTE (MB) CIA can not do maths!!!  this gives 100.1%
    # inaSAFE can, thus we remove 0.1% from the elderly
    # I wrote them and got this contact confirmation number: CTCU1K2

    youth_ratio = 0.263
    value = settings.value('inasafe/defaultYouthRatio',
                           youth_ratio,
                           type=float)
    defaults['YOUTH_RATIO'] = float(value)

    adult_ratio = 0.659
    value = settings.value('inasafe/defaultAdultRatio',
                           adult_ratio,
                           type=float)
    defaults['ADULT_RATIO'] = float(value)

    elderly_ratio = 0.078
    value = settings.value('inasafe/defaultElderlyRatio',
                           elderly_ratio,
                           type=float)
    defaults['ELDERLY_RATIO'] = float(value)

    # Keywords key names
    defaults['FEMALE_RATIO_ATTR_KEY'] = 'female ratio attribute'
    defaults['FEMALE_RATIO_KEY'] = 'female ratio default'
    defaults['YOUTH_RATIO_ATTR_KEY'] = 'youth ratio attribute'
    defaults['YOUTH_RATIO_KEY'] = 'youth ratio default'
    defaults['ADULT_RATIO_ATTR_KEY'] = 'adult ratio attribute'
    defaults['ADULT_RATIO_KEY'] = 'adult ratio default'
    defaults['ELDERLY_RATIO_ATTR_KEY'] = 'elderly ratio attribute'
    defaults['ELDERLY_RATIO_KEY'] = 'elderly ratio default'
    defaults['AGGR_ATTR_KEY'] = 'aggregation attribute'
    defaults['NO_DATA'] = tr('No data')

    # defaults for iso_19115_template.xml
    organisation = 'InaSAFE.org'
    value = settings.value('ISO19115_ORGANIZATION', organisation, type=str)
    defaults['ISO19115_ORGANIZATION'] = value

    url = 'http://inasafe.org'
    value = settings.value('ISO19115_URL', url, type=str)
    defaults['ISO19115_URL'] = value

    email = '*****@*****.**'
    value = settings.value('ISO19115_EMAIL', email, type=str)
    defaults['ISO19115_EMAIL'] = value

    title = 'InaSAFE analysis result'
    value = settings.value('ISO19115_TITLE', title, type=str)
    defaults['ISO19115_TITLE'] = value

    iso_license = 'Free use with accreditation'
    value = settings.value('ISO19115_LICENSE', iso_license, type=str)
    defaults['ISO19115_LICENSE'] = value

    return defaults
예제 #6
0
 def disableCompiler(self):
     QSettings().setValue('/qgis/compileExpressions', False)
예제 #7
0
__copyright__ = "Copyright 2016, Cadasta Project"
__license__ = "GPL version 3"
__email__ = "*****@*****.**"
__revision__ = '$Format:%H$'

sys.path.append(os.path.dirname(__file__))

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 cadasta 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__)))
    def start(self):
        sensorName = self.sensorName()
        self.setWindowTitle('Lock-In Thermometer %s' % sensorName )
        #setAppId(sensorName)
        
        if sensorName == 'BusThermometer':
            icon = QIcon('Icons/LockinThermometer_Bus.ico')
        elif sensorName == 'RuOx2005Thermometer':
            icon = QIcon('Icons/LockinThermometer_BoxOutside.ico')
        elif sensorName == 'BoxThermometer':
            icon = QIcon('Icons/LockinThermometer_BoxInside2.ico')
        else:
            icon = QIcon('Icons/LockinThermometer.ico')

        self.setWindowIcon(icon)

        visa = str(self.visaCombo.currentText())
        self.sr830 = SR830(visa)
        #self.sr830.debug = True

        self.sr830.readAll()
        self.sr830.sineOut.caching = False # Disable caching on this
        
        Sockets = {'BusThermometer':PubSub.LockinThermometerAdr,
                  'RuOx2005Thermometer':PubSub.LockinThermometerRuOx2005,
                  'BoxThermometer':PubSub.LockinThermometerBox}
        socket = Sockets[sensorName]
        self.publisher = ZmqPublisher('LockinThermometer', socket)
        
        self.runPb.setText('Stop')
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.snapSignal)
        self.timer.start()
        self.enableWidgets(False)
        self.rangeChangedTime = 0
        self.exChangedTime = 0
        t = time.time()
        timeString = time.strftime('%Y%m%d-%H%M%S', time.localtime(t))
        dateString = time.strftime('%Y%m%d')
        sensorName = str(self.sensorNameLe.text())

        s = QSettings('WiscXrayAstro', application='ADR3RunInfo')
        path = str(s.value('runPath', '', type=str))
        fileName = os.path.join(path, '%s_%s.dat' % (sensorName, dateString))
        if not os.path.isfile(fileName): # Maybe create new file
            with open(fileName, 'a+') as f:
                f.write('#LockinThermometer.py\n')
                f.write('#Date=%s\n' % timeString)
                f.write('#SensorName=%s\n' % sensorName)
                f.write('#SR830=%s\n' % self.sr830.visaId())
                f.write('#AttenuatorGain=%f\n' % self.attenuatorGainSb.value())
                f.write('#AttenuatorSourceImpedance=%f\n' % self.sourceImpedanceSb.value())
                f.write('#DriveResistance=%f\n' % self.driveResistanceSb.value())
                f.write('#LeadResistance=%f\n' % self.leadResistanceSb.value())
                f.write('#PreampGain=%f\n' % self.preampGainSb.value())
                f.write('#DesiredExcitation=%f\n' % self.sensorVoltageSb.value())
                k = self.sr830.allSettingValues()
                for key,value in k.iteritems():
                    f.write('#SR830/%s=%s\n' % (key,value))
                f.write('#'+'\t'.join(['time', 'VsineOut', 'X', 'Y', 'f', 'Sensitivity', 'RxCalc', 'Rtherm'])+'\n')
        self.fileName = fileName
예제 #9
0
 def __saveSettings(self):
     settings = QSettings("Equinor", "Ert-Gui")
     settings.setValue("geometry", self.saveGeometry())
     settings.setValue("windowState", self.saveState())
 def loadParameterSets(self):
     s = QSettings()
     s.beginGroup('ParameterSets')
     names = s.childGroups()
     self.configCombo.addItems(names)
 def saveSettings(self):
     s = QSettings()
     #s.setValue('visa', self.visaCombo.currentText())
     s.setValue('parameterSet', self.configCombo.currentText())
예제 #12
0
 def reset_default(self):
     if self.scope == Scope.Project:
         QgsProject.instance().removeEntry(self.plugin_name, self.name)
     else:
         QSettings().remove(self.global_name())
예제 #13
0
def settings():
    """Returns the QSettings group for our settings."""
    settings = QSettings()
    settings.beginGroup("hyphenation")
    return settings
예제 #14
0
 def fetchGenPaths(self):
     """Fetch paths from general preferences."""
     return qsettings.get_string_list(QSettings(),
                                      "lilypond_settings/include_path")
예제 #15
0
def setup_logger(logger_name, log_file=None, sentry_url=None):
    """Run once when the module is loaded and enable logging.

    :param logger_name: The logger name that we want to set up.
    :type logger_name: str

    :param log_file: Optional full path to a file to write logs to.
    :type log_file: str

    :param sentry_url: Optional url to sentry api for remote
        logging. Defaults to http://c64a83978732474ea751d432ab943a6b:
        [email protected]/5 which is the
        sentry project for InaSAFE desktop.
    :type sentry_url: str

    Borrowed heavily from this:
    http://docs.python.org/howto/logging-cookbook.html

    Now to log a message do::

       LOGGER.debug('Some debug message')

    .. note:: The file logs are written to the inasafe user tmp dir e.g.:
       /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log
    """
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    default_handler_level = logging.DEBUG

    # create formatter that will be added to the handlers
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # create syslog handler which logs even debug messages
    # (ariel): Make this log to /var/log/safe.log instead of
    #               /var/log/syslog
    # (Tim) Ole and I discussed this - we prefer to log into the
    # user's temporary working directory.
    inasafe_log_path = log_file_path()
    if log_file is None:
        file_handler = logging.FileHandler(inasafe_log_path)
    else:
        file_handler = logging.FileHandler(log_file)
    file_handler.setLevel(default_handler_level)
    file_handler.setFormatter(formatter)
    add_logging_handler_once(logger, file_handler)

    if 'MUTE_LOGS' not in os.environ:
        # create console handler with a higher log level
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        add_logging_handler_once(logger, console_handler)

    # create a QGIS handler
    qgis_handler = QgsLogHandler()
    qgis_handler.setFormatter(formatter)
    add_logging_handler_once(logger, qgis_handler)

    # Sentry handler - this is optional hence the localised import
    # It will only log if pip install raven. If raven is available
    # logging messages will be sent to http://sentry.linfiniti.com
    # We will log exceptions only there. You need to either:
    #  * Set env var 'INASAFE_SENTRY=1' present (value can be anything)
    # before this will be enabled or sentry is enabled in QSettings
    flag = QSettings().value('inasafe/useSentry', False, type=bool)
    env_inasafe_sentry = 'INASAFE_SENTRY' in os.environ

    if env_inasafe_sentry or flag:
        if sentry_url is None:
            client = Client(
                'http://11b7c9cb73874f97807ebc1934575e92'
                ':[email protected]/5')
        else:
            client = Client(sentry_url)
        sentry_handler = SentryHandler(client)
        sentry_handler.setFormatter(formatter)
        sentry_handler.setLevel(logging.ERROR)
        if add_logging_handler_once(logger, sentry_handler):
            logger.debug('Sentry logging enabled in safe')
    else:
        logger.debug('Sentry logging disabled in safe')
예제 #16
0
 def setUp(self):
     """Fixture run before all tests"""
     self.qsetting = QSettings('InaSAFETest')
     self.qsetting.clear()
예제 #17
0
 def enableCompiler(self):
     QSettings().setValue('/qgis/compileExpressions', True)
예제 #18
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)

        self.shellOutWidget = QWidget(self)
        self.shellOutWidget.setLayout(QVBoxLayout())
        self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0)
        self.shellOutWidget.layout().addWidget(self.shellOut)

        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOutWidget)
        self.splitter.addWidget(self.shell)

        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)

        openExtEditorBt = QCoreApplication.translate(
            "PythonConsole", "Open in external editor")
        self.openInEditorButton = QAction(self)
        self.openInEditorButton.setCheckable(False)
        self.openInEditorButton.setEnabled(True)
        self.openInEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.openInEditorButton.setMenuRole(QAction.PreferencesRole)
        self.openInEditorButton.setIconVisibleInMenu(True)
        self.openInEditorButton.setToolTip(openExtEditorBt)
        self.openInEditorButton.setText(openExtEditorBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate(
            "PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(
            QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole",
                                                  "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole",
                                                 "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(16, 16))
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(16, 16))
        self.toolBarEditor.setMovable(False)
        self.toolBarEditor.setFloatable(False)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addAction(self.openInEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.shellOutWidget.layout().insertWidget(0, self.toolBar)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        if pyqtconfig.Configuration().qt_version >= 0x40700:
            self.lineEditFind.setPlaceholderText(placeHolderTxt)
        else:
            self.lineEditFind.setToolTip(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod,
                     SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)
예제 #19
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'Flaechenzuordnungen_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg_at = AssigntgebDialog()
        self.dlg_cl = CreatelineflDialog()
        self.dlg_sw = CreatelineswDialog()
        self.dlg_ul = UpdateLinksDialog()
        self.dlg_mg = ManagegroupsDialog()

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

        logger.info(u'\n\nQKan_LinkFlaechen initialisiert...')

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

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

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

        self.configfil = os.path.join(wordir, 'qkan.json')
        if os.path.exists(self.configfil):
            with open(self.configfil, 'r') as fileconfig:
                self.config = json.loads(fileconfig.read())
        else:
            self.config = {'epsg': '25832'}                     # Projektionssystem
            self.config['autokorrektur'] = False
            self.config['suchradius'] = u'50'
            self.config['mindestflaeche'] = u'0.5'
            self.config['bezug_abstand'] = 'kante'
            with open(self.configfil, 'w') as fileconfig:
                fileconfig.write(json.dumps(self.config))

        # Formularereignisse anbinden ----------------------------------------------

        # Dialog dlg_cl
        self.dlg_cl.lw_flaechen_abflussparam.itemClicked.connect(self.cl_lw_flaechen_abflussparamClick)
        self.dlg_cl.lw_hal_entw.itemClicked.connect(self.cl_lw_hal_entwClick)
        self.dlg_cl.lw_teilgebiete.itemClicked.connect(self.cl_lw_teilgebieteClick)
        self.dlg_cl.cb_selFlActive.stateChanged.connect(self.cl_selFlActiveClick)
        self.dlg_cl.cb_selHalActive.stateChanged.connect(self.cl_selHalActiveClick)
        self.dlg_cl.cb_selTgbActive.stateChanged.connect(self.cl_selTgbActiveClick)
        self.dlg_cl.button_box.helpRequested.connect(self.cl_helpClick)

        # Dialog dlg_sw
        self.dlg_sw.lw_hal_entw.itemClicked.connect(self.sw_lw_hal_entwClick)
        self.dlg_sw.lw_teilgebiete.itemClicked.connect(self.sw_lw_teilgebieteClick)
        self.dlg_sw.cb_selHalActive.stateChanged.connect(self.sw_selHalActiveClick)
        self.dlg_sw.cb_selTgbActive.stateChanged.connect(self.sw_selTgbActiveClick)
        self.dlg_sw.button_box.helpRequested.connect(self.sw_helpClick)

        # Dialog dlg_at
        self.dlg_at.rb_within.clicked.connect(self.select_within)
        self.dlg_at.rb_overlaps.clicked.connect(self.select_overlaps)

        # Dialog dlg_mg
        self.dlg_mg.lw_gruppen.itemClicked.connect(self.listGroupAttr)
        self.dlg_mg.pb_storegroup.clicked.connect(self.storegrouptgb)
        self.dlg_mg.pb_reloadgroup.clicked.connect(self.reloadgrouptgb)
예제 #20
0
 def get_locale(cls):
     return QSettings().value('locale/userLocale')[0:2]
예제 #21
0
파일: LabGui.py 프로젝트: anjunhu/LabGUI
    def __init__(self, argv=[]):

        # run the initializer of the class inherited from6
        super(LabGuiMain, self).__init__()

        self.settings = QSettings(self)
        self.settings.setValue("state", self.saveState())

        #debug parameter used to run labgui even when there is no instrument
        #to connect to, used to plot past data or test the code
        self.DEBUG = True

        #variable to store the configfile name
        self.config_file = ''

        #parse the argument(s) passed inline
        try:
            #option c is to provide a name for config file
            opts, args = getopt.getopt(argv, "c:")

            #loop through the arguments on the inline command
            for opt, arg in opts:

                #user passed configfile
                if opt == '-c':

                    self.config_file = arg

        except getopt.GetoptError:

            logging.error('configuration file : option -c argument missing')

        #verify if the config file passed by the user is valid and exists
        if self.config_file:

            if not exists(self.config_file):

                logging.error("The config file you provided ('%s') doesn't \
exist, '%s' will be used instead" % (self.config_file, CONFIG_FILE))

                self.config_file = CONFIG_FILE

        else:

            #check whether the default config file exists or not
            if exists(CONFIG_FILE) == False:

                logging.warning("A '%s' file has been generated for you." %
                                (CONFIG_FILE))
                logging.warning("Please modify it to change the default \
    script, settings and data locations, or to enter debug mode.")

                # creates a config.txt with basic needs
                IOTool.create_config_file()

            #sets default config file name
            self.config_file = CONFIG_FILE

        #to make sure the config file is of the right format
        #ie that the user didn't specify the name of an existing file which
        #isn't a configuration file
        config_file_ok = False

        while not config_file_ok:

            try:
                #try to read the DEBUG parameter from the configuration file
                #as a test of the good formatting of the file
                self.DEBUG = IOTool.get_debug_setting(
                    config_file_path=self.config_file)

                #if this didn't generate errors we allow to get out of the loop
                config_file_ok = True

            except IOError:

                logging.error("The config file you provided ('%s') doesn't \
have the right format, '%s' will be used instead" %
                              (self.config_file, CONFIG_FILE))

                #check whether the default config file exists or not
                if exists(CONFIG_FILE) == False:

                    logging.warning("A '%s' file has been generated for you." %
                                    (CONFIG_FILE))
                    logging.warning("Please modify it to change the default \
    script, settings and data locations, or to enter debug mode.")

                    # creates a config.txt with basic needs
                    IOTool.create_config_file()

                #sets default config file name
                self.config_file = CONFIG_FILE

        print("Configuration loaded from : %s" % (self.config_file))

        if self.DEBUG == True:

            print("*" * 20)
            print("Debug mode is set to True")
            print("*" * 20)

            self.option_display_debug_state()

        else:

            self.option_display_normal_state()

        #create the central part of the application
        self.zoneCentrale = QtGui.QMdiArea()
        self.zoneCentrale.subWindowActivated.connect(
            self.update_current_window)
        self.setCentralWidget(self.zoneCentrale)

        #load the parameter for the GPIB interface setting of the instruments
        interface = IOTool.get_interface_setting(
            config_file_path=self.config_file)

        #test if the parameter is correct
        if interface not in [Tool.INTF_VISA, Tool.INTF_PROLOGIX]:

            msg = """The %s variable of the config file '%s' is not correct
            The only two allowed values are : '%s' and '%s' """ % (
                IOTool.GPIB_INTF_ID, IOTool.CONFIG_FILE, Tool.INTF_VISA,
                Tool.INTF_PROLOGIX)
            logging.warning(msg)
            #default setting
            Tool.INTF_GPIB = Tool.INTF_PROLOGIX

        else:

            Tool.INTF_GPIB = interface

        print("*" * 20)
        print("The GPIB setting for connecting instruments is %s" %
              (Tool.INTF_GPIB))
        print("*" * 20)

        # the lock is something for multithreading... not sure if it's important in our application.
        self.lock = QReadWriteLock()

        # InstrumentHub is responsible for storing and managing the user
        # choices about which instrument goes on which port
        self.instr_hub = Tool.InstrumentHub(parent=self, debug=self.DEBUG)

        # DataTaker is responsible for taking data from instruments in the
        # InstrumentHub object
        self.datataker = DataManagement.DataTaker(self.lock, self.instr_hub)

        # handle data emitted by datataker (basically stuff it into a shared,
        # central array)
        self.connect(self.datataker, SIGNAL("data(PyQt_PyObject)"),
                     self.update_data_array)

        #a signal to signify the data taking script is over
        self.connect(self.datataker, SIGNAL("script_finished(bool)"),
                     self.finished_DTT)

        #the array in which the data will be stored
        self.data_array = np.array([])

        # all actions related to the figure widget (mplZoomWidget.py) are
        # set up in the actionmanager
        self.action_manager = mplZoomWidget.ActionManager(self)

        #this will contain the widget of the latest pdw created upon
        #connecting the instrument Hub
        self.actual_pdw = None

        #this will contain windows settings (labels, checkboxes states, colors)
        #of the plotdisplaw window which is created when the user click on
        #the connect button
        self.plot_window_settings = None

        #### set up menus and toolbars

        self.fileMenu = self.menuBar().addMenu("File")
        self.plotMenu = self.menuBar().addMenu("&Plot")
        self.instMenu = self.menuBar().addMenu("&Meas/Connect")
        self.windowMenu = self.menuBar().addMenu("&Window")
        self.optionMenu = self.menuBar().addMenu("&Options")

        self.loggingSubMenu = self.optionMenu.addMenu("&Logger output level")

        self.plotToolbar = self.addToolBar("Plot")
        self.instToolbar = self.addToolBar("Instruments")

        # start/stop/pause buttons
        self.start_DTT_action = QtTools.create_action(
            self,
            "Start DTT",
            slot=self.start_DTT,
            shortcut=QtGui.QKeySequence("F5"),
            icon="start",
            tip="Start script")

        self.stop_DTT_action = QtTools.create_action(
            self,
            "Stop DTT",
            slot=self.stop_DTT,
            shortcut=QtGui.QKeySequence("F6"),
            icon="stop",
            tip="stop script")

        self.pause_DTT_action = QtTools.create_action(
            self,
            "Pause DTT",
            slot=self.pause_DTT,
            shortcut=QtGui.QKeySequence("F7"),
            icon="pause",
            tip="pause script")

        self.pause_DTT_action.setEnabled(False)
        self.stop_DTT_action.setEnabled(False)

        self.instToolbar.setObjectName("InstToolBar")

        self.instToolbar.addAction(self.start_DTT_action)
        self.instToolbar.addAction(self.pause_DTT_action)
        self.instToolbar.addAction(self.stop_DTT_action)

        #this will contain the different widgets in the window
        self.widgets = {}

        cur_path = os.path.dirname(__file__)

        #find the path to the widgets folders
        widget_path = os.path.join(cur_path, 'LabTools')

        #these are widgets essential to the interface
        core_widget_path = os.path.join(widget_path, 'CoreWidgets')

        #these are widgets which were added by users
        user_widget_path = os.path.join(widget_path, 'UserWidgets')

        #this is the legitimate list of core widgets
        widgets_list = [
            o.rstrip('.py') for o in os.listdir(core_widget_path)
            if o.endswith(".py") and not "__init__" in o
        ]

        #this is the legitimate list of user widgets
        user_widgets_list = [
            o.rstrip('.py') for o in os.listdir(user_widget_path)
            if o.endswith(".py") and not "__init__" in o
        ]

        #the user widgets the user would like to run, given in the config file
        user_widgets = IOTool.get_user_widgets(
            config_file_path=self.config_file)

        if user_widgets:

            for user_widget in user_widgets:
                #check that the given widget is legitimate
                if user_widget in user_widgets_list:
                    #add the given widget to the widget list which will be
                    #loaded
                    widgets_list.append(user_widget)

                else:

                    logging.warning("The user widget '%s' is not found at %s" %
                                    (user_widget, user_widget_path))

        #add the widgets to the interface
        for widget in widgets_list:

            widget_name = widget
            try:
                widget_module = import_module("." + widget_name,
                                              package=COREWIDGETS_PACKAGE_NAME)
            except ImportError:

                widget_module = import_module("." + widget_name,
                                              package=USERWIDGETS_PACKAGE_NAME)

            self.add_widget(widget_module.add_widget_into_main)

###### FILE MENU SETUP ######

        self.fileSaveSettingsAction = QtTools.create_action(
            self,
            "Save Instrument Settings",
            slot=self.file_save_settings,
            shortcut=QtGui.QKeySequence.SaveAs,
            icon=None,
            tip="Save the current instrument settings")

        self.fileLoadSettingsAction = QtTools.create_action(
            self,
            "Load Instrument Settings",
            slot=self.file_load_settings,
            shortcut=QtGui.QKeySequence.Open,
            icon=None,
            tip="Load instrument settings from file")

        self.fileLoadDataAction = QtTools.create_action(
            self,
            "Load Previous Data",
            slot=self.file_load_data,
            shortcut=None,
            icon=None,
            tip="Load previous data from file")
        """this is not working I will leave it commented right now"""
        #        self.filePrintAction = QtTools.create_action(self, "&Print Report", slot=self.file_print, shortcut=QtGui.QKeySequence.Print,
        #                                                     icon=None, tip="Print the figure along with relevant information")

        self.fileSaveCongfigAction = QtTools.create_action(
            self,
            "Save current configuration",
            slot=self.file_save_config,
            shortcut=None,
            icon=None,
            tip="Save the setting file path, \
the script path and the data output path into the config file")

        self.fileMenu.addAction(self.fileLoadSettingsAction)
        self.fileMenu.addAction(self.fileSaveSettingsAction)
        self.fileMenu.addAction(self.fileLoadDataAction)
        #        self.fileMenu.addAction(self.filePrintAction)
        self.fileMenu.addAction(self.action_manager.saveFigAction)
        self.fileMenu.addAction(self.fileSaveCongfigAction)

        ###### PLOT MENU + TOOLBAR SETUP ######

        self.plotToolbar.setObjectName("PlotToolBar")

        for action in self.action_manager.actions:
            self.plotMenu.addAction(action)
            self.plotToolbar.addAction(action)

        self.clearPlotAction = QtTools.create_action(
            self,
            "Clear All Plots",
            slot=self.clear_plot,
            shortcut=None,
            icon="clear_plot",
            tip="Clears the live data arrays")

        self.removeFitAction = QtTools.create_action(
            self,
            "Remove Fit",
            slot=self.remove_fit,
            shortcut=None,
            icon="clear",
            tip="Reset the fit data to an empty array")

        self.plotMenu.addAction(self.clearPlotAction)
        self.plotMenu.addAction(self.removeFitAction)

        ###### INSTRUMENT MENU SETUP ######
        self.read_DTT = QtTools.create_action(
            self,
            "Read",
            slot=self.single_measure_DTT,
            shortcut=None,
            icon=None,
            tip="Take a one shot measure with DTT")

        self.connect_hub = QtTools.create_action(
            self,
            "Connect Instruments",
            slot=self.connect_instrument_hub,
            shortcut=QtGui.QKeySequence("Ctrl+I"),
            icon=None,
            tip="Refresh the list of selected instruments")

        self.refresh_ports_list_action = QtTools.create_action(
            self,
            "Refresh ports list",
            slot=self.refresh_ports_list,
            icon=None,
            tip="Refresh the list of availiable ports")

        self.instMenu.addAction(self.start_DTT_action)
        self.instMenu.addAction(self.read_DTT)
        self.instMenu.addAction(self.connect_hub)
        self.instMenu.addAction(self.refresh_ports_list_action)

        ###### WINDOW MENU SETUP ######
        self.add_pdw = QtTools.create_action(self,
                                             "Add a Plot",
                                             slot=self.create_pdw,
                                             shortcut=None,
                                             icon=None,
                                             tip="Add a recordsweep window")

        self.add_pqtw = QtTools.create_action(self,
                                              "Add a PyQtplot",
                                              slot=self.create_pqtw,
                                              shortcut=None,
                                              icon=None,
                                              tip="Add a pyqt window")

        self.windowMenu.addAction(self.add_pdw)

        try:

            import PyQTWindow
            self.windowMenu.addAction(self.add_pqtw)

        except:
            logging.info("pyqtgraph is unable to load, \
the pyqt window option is disabled")

###### OPTION MENU SETUP ######
        self.toggle_debug_state = QtTools.create_action(
            self,
            "Change debug mode",
            slot=self.option_change_debug_state,
            shortcut=None,
            icon=None,
            tip="Change the state of the debug mode")

        #        self.toggle_debug_state = QtTools.create_action(self,
        #        "Change debug mode", slot = self.option_change_debug_state,
        #        shortcut = None, icon = None,
        #        tip = "Change the state of the debug mode")

        self.optionMenu.addAction(self.toggle_debug_state)

        for log_level in ["DEBUG", "INFO", "WARNING", "ERROR"]:
            action = QtTools.create_action(
                self,
                log_level,
                slot=self.option_change_log_level,
                shortcut=None,
                icon=None,
                tip="Change the state of the logger to %s" % log_level)

            self.loggingSubMenu.addAction(action)

###############################

#Load the user settings for the instrument connectic and parameters

        self.default_settings_fname = IOTool.get_settings_name(
            config_file_path=self.config_file)

        if not exists(self.default_settings_fname):

            logging.warning(
                "The filename '%s' wasn't found, using '%s'" %
                (self.default_settings_fname, 'settings/default_settings.txt'))

            self.default_settings_fname = 'settings/default_settings.txt'

        if os.path.isfile(self.default_settings_fname):

            self.widgets['CalcWidget'].load_settings(
                self.default_settings_fname)

            self.widgets['InstrumentWidget'].load_settings(
                self.default_settings_fname)

        # Create the object responsible to display information send by the
        # datataker
        self.data_displayer = DataManagement.DataDisplayer(self.datataker)

        # platform-independent way to restore settings such as toolbar positions,
        # dock widget configuration and window size from previous session.
        # this doesn't seem to be working at all on my computer (win7 system)
        self.settings = QSettings("Gervais Lab", "RecordSweep")
        try:
            self.restoreState(self.settings.value("windowState").toByteArray())
            self.restoreGeometry(self.settings.value("geometry").toByteArray())
        except:
            logging.info(
                'Using default window configuration'
            )  # no biggie - probably means settings haven't been saved on this machine yet
예제 #22
0
def start(filenames=None,
          projects_path=None,
          extra_plugins=None,
          linenos=None):
    app = QApplication(sys.argv)
    QCoreApplication.setOrganizationName('NINJA-IDE')
    QCoreApplication.setOrganizationDomain('NINJA-IDE')
    QCoreApplication.setApplicationName('NINJA-IDE')
    app.setWindowIcon(QIcon(resources.IMAGES['icon']))

    # Check if there is another session of ninja-ide opened
    # and in that case send the filenames and projects to that session
    running = ipc.is_running()
    start_server = not running[0]
    if running[0] and (filenames or projects_path):
        sended = ipc.send_data(running[1], filenames, projects_path, linenos)
        running[1].close()
        if sended:
            sys.exit()
    else:
        running[1].close()

    # Create and display the splash screen
    splash_pix = QPixmap(resources.IMAGES['splash'])
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    # Set the cursor to unblinking
    global cursor_flash_time
    cursor_flash_time = app.cursorFlashTime()
    app.setCursorFlashTime(0)

    #Set the codec for strings (QString)
    QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8'))

    #Translator
    qsettings = QSettings()
    language = QLocale.system().name()
    lang = qsettings.value('preferences/interface/language', language) + '.qm'
    lang_path = file_manager.create_path(resources.LANGS, lang)
    if file_manager.file_exists(lang_path):
        settings.LANGUAGE = lang_path
    elif file_manager.file_exists(
            file_manager.create_path(resources.LANGS_DOWNLOAD, lang)):
        settings.LANGUAGE = file_manager.create_path(resources.LANGS_DOWNLOAD,
                                                     lang)
    translator = QTranslator()
    if settings.LANGUAGE:
        translator.load(settings.LANGUAGE)
        app.installTranslator(translator)

    #Loading Syntax
    splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black)
    json_manager.load_syntax()

    #Read Settings
    splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop,
                       Qt.black)
    settings.load_settings()

    #Set Stylesheet
    style_applied = False
    if settings.NINJA_SKIN not in ('Default', 'Classic Theme'):
        file_name = ("%s.qss" % settings.NINJA_SKIN)
        qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD,
                                            file_name)
        if file_manager.file_exists(qss_file):
            with open(qss_file) as f:
                qss = f.read()
                app.setStyleSheet(qss)
                style_applied = True
    if not style_applied:
        if settings.NINJA_SKIN == 'Default':
            with open(resources.NINJA_THEME) as f:
                qss = f.read()
        else:
            with open(resources.NINJA__THEME_CLASSIC) as f:
                qss = f.read()
        app.setStyleSheet(qss)

    #Loading Schemes
    splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop,
                       Qt.black)
    scheme = qsettings.value('preferences/editor/scheme', "default")
    if scheme != 'default':
        scheme = file_manager.create_path(resources.EDITOR_SKINS,
                                          scheme + '.color')
        if file_manager.file_exists(scheme):
            resources.CUSTOM_SCHEME = json_manager.parse(open(scheme))

    #Loading Shortcuts
    resources.load_shortcuts()
    #Loading GUI
    splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black)
    ide = IDE(start_server)

    #Showing GUI
    ide.show()

    #Loading Session Files
    splash.showMessage("Loading Files and Projects",
                       Qt.AlignRight | Qt.AlignTop, Qt.black)
    #Files in Main Tab
    main_files = qsettings.value('openFiles/mainTab', [])
    if main_files is not None:
        mainFiles = list(main_files)
    else:
        mainFiles = list()
    tempFiles = []
    for file_ in mainFiles:
        fileData = list(file_)
        tempFiles.append((fileData[0], int(fileData[1])))
    mainFiles = tempFiles
    #Files in Secondary Tab
    sec_files = qsettings.value('openFiles/secondaryTab', [])
    if sec_files is not None:
        secondaryFiles = list(sec_files)
    else:
        secondaryFiles = list()
    tempFiles = []
    for file_ in secondaryFiles:
        fileData = list(file_)
        tempFiles.append((fileData[0], int(fileData[1])))
    secondaryFiles = tempFiles
    # Recent Files
    recent = qsettings.value('openFiles/recentFiles', [])
    if recent is not None:
        recent_files = list(recent)
    else:
        recent_files = list()
    recent_files = [file_ for file_ in recent_files]
    #Current File
    current_file = qsettings.value('openFiles/currentFile', '')
    #Projects
    projects_list = qsettings.value('openFiles/projects', [])
    if projects_list is not None:
        projects = list(projects_list)
    else:
        projects = list()
    projects = [project for project in projects]
    #Include files received from console args
    file_with_nro = list(
        map(lambda f: (f[0], f[1] - 1), zip(filenames, linenos)))
    file_without_nro = list(map(lambda f: (f, 0), filenames[len(linenos):]))
    mainFiles += file_with_nro + file_without_nro
    #Include projects received from console args
    if projects_path:
        projects += projects_path
    ide.load_session_files_projects(mainFiles, secondaryFiles, projects,
                                    current_file, recent_files)
    #Load external plugins
    if extra_plugins:
        ide.load_external_plugins(extra_plugins)

    splash.finish(ide)
    ide.notify_plugin_errors()
    sys.exit(app.exec_())
예제 #23
0
 def set(key, val):
     if tlSettings.settings == None:
         tlSettings.settings = QSettings(QSettings.NativeFormat,
                                         QSettings.UserScope, 'QuantumGIS',
                                         'TelemetryLayer')
     tlSettings.settings.setValue(key, str(val))
예제 #24
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'SEBE_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.dlg = SEBEDialog()
        self.dlg.runButton.clicked.connect(self.start_progress)
        self.dlg.pushButtonHelp.clicked.connect(self.help)
        # self.dlg.shadowCheckBox.stateChanged.connect(self.checkbox_changed)
        self.dlg.pushButtonSave.clicked.connect(self.folder_path)
        self.dlg.pushButtonImport.clicked.connect(self.read_metdata)
        self.dlg.pushButtonSaveIrradiance.clicked.connect(self.save_radmat)
        self.fileDialog = QFileDialog()
        self.fileDialog.setFileMode(4)
        self.fileDialog.setAcceptMode(1)
        self.fileDialogFile = QFileDialog()

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

        # self.layerComboManagerDSM = RasterLayerCombo(self.dlg.comboBox_dsm)
        # RasterLayerCombo(self.dlg.comboBox_dsm, initLayer="")
        # self.layerComboManagerVEGDSM = RasterLayerCombo(self.dlg.comboBox_vegdsm)
        # RasterLayerCombo(self.dlg.comboBox_vegdsm, initLayer="")
        # self.layerComboManagerVEGDSM2 = RasterLayerCombo(self.dlg.comboBox_vegdsm2)
        # RasterLayerCombo(self.dlg.comboBox_vegdsm2, initLayer="")
        # self.layerComboManagerWH = RasterLayerCombo(self.dlg.comboBox_wallheight)
        # RasterLayerCombo(self.dlg.comboBox_wallheight, initLayer="")
        # self.layerComboManagerWA = RasterLayerCombo(self.dlg.comboBox_wallaspect)
        # RasterLayerCombo(self.dlg.comboBox_wallaspect, initLayer="")

        self.layerComboManagerDSM = QgsMapLayerComboBox(self.dlg.widgetDSM)
        self.layerComboManagerDSM.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerDSM.setFixedWidth(175)
        self.layerComboManagerDSM.setCurrentIndex(-1)
        self.layerComboManagerVEGDSM = QgsMapLayerComboBox(self.dlg.widgetCDSM)
        self.layerComboManagerVEGDSM.setFilters(
            QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerVEGDSM.setFixedWidth(175)
        self.layerComboManagerVEGDSM.setCurrentIndex(-1)
        self.layerComboManagerVEGDSM2 = QgsMapLayerComboBox(
            self.dlg.widgetTDSM)
        self.layerComboManagerVEGDSM2.setFilters(
            QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerVEGDSM2.setFixedWidth(175)
        self.layerComboManagerVEGDSM2.setCurrentIndex(-1)
        self.layerComboManagerWH = QgsMapLayerComboBox(self.dlg.widgetWH)
        self.layerComboManagerWH.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerWH.setFixedWidth(175)
        self.layerComboManagerWH.setCurrentIndex(-1)
        self.layerComboManagerWA = QgsMapLayerComboBox(self.dlg.widgetWA)
        self.layerComboManagerWA.setFilters(QgsMapLayerProxyModel.RasterLayer)
        self.layerComboManagerWA.setFixedWidth(175)
        self.layerComboManagerWA.setCurrentIndex(-1)

        self.folderPath = None
        self.usevegdem = 0
        self.scale = None
        self.gdal_dsm = None
        self.dsm = None
        self.vegdsm = None
        self.vegdsm2 = None
        self.usevegdem = None
        self.folderPathMetdata = None
        self.metdata = None
        self.radmatfile = None

        self.thread = None
        self.worker = None
        self.steps = 0
 def __init__(self, iface):
     self.iface = iface
     self.settings = QSettings()
예제 #26
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, 'i18n',
                                  'sun_{}.qm'.format(locale))

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

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

        # Create the dialog (after translation) and keep reference
        self.visDlg = VisualizerDialog()

        self.polyLayer = None
        self.dir_path = None
        self.layer = None
        self.point1 = None
        self.point2 = None
        self.gl_widget = None
        self.max_energy = 0
        self.energy_array = None
        self.asc_array = None

        self.ncols = None
        self.nrows = None
        self.xllcorner = None
        self.yllcorner = None
        self.cellsize = None

        self.roofground_file = 'Energyyearroof.tif'
        self.veg_file = 'Vegetationdata.txt'
        self.wall_file = 'Energyyearwall.txt'
        self.height_file = 'dsm.tif'

        self.fileDialog = QFileDialog()
        self.fileDialog.setFileMode(2)
        self.fileDialog.setAcceptMode(0)

        #Create a reference to the map canvas
        self.canvas = self.iface.mapCanvas()

        #Create tools
        self.areaTool = AreaTool(self.canvas)

        self.thread = None
        self.worker = None
        self.steps = 0

        self.areaTool.areaComplete.connect(self.display_area)

        self.visDlg.pushButtonSelect.clicked.connect(self.area)
        self.visDlg.pushButtonDirectory.clicked.connect(self.path_directory)
        self.visDlg.pushButtonVisualize.clicked.connect(self.visualize)
        self.visDlg.helpButton.clicked.connect(self.help)
예제 #27
0
 def __init__(self, filename):
     if path.isfile(filename) and filename.endswith('.ini'):
         self.psettings = QSettings(filename, QSettings.IniFormat)
예제 #28
0
    def pg_path_to_uri(self, path):
        """Convert layer path from QgsBrowserModel to full QgsDataSourceURI

        :param path: The layer path from QgsBrowserModel
        :type path: string

        :returns: layer uri
        :rtype: QgsDataSourceURI
        """

        conn_name = path.split('/')[1]
        schema = path.split('/')[2]
        table = path.split('/')[3]

        settings = QSettings()
        key = "/PostgreSQL/connections/" + conn_name
        service = settings.value(key + "/service")
        host = settings.value(key + "/host")
        port = settings.value(key + "/port")
        if not port:
            port = "5432"
        db = settings.value(key + "/database")
        use_estimated_metadata = settings.value(key + "/estimatedMetadata",
                                                False,
                                                type=bool)
        sslmode = settings.value(key + "/sslmode",
                                 QgsDataSourceURI.SSLprefer,
                                 type=int)
        username = ""
        password = ""
        if settings.value(key + "/saveUsername") == "true":
            username = settings.value(key + "/username")

        if settings.value(key + "/savePassword") == "true":
            password = settings.value(key + "/password")

        # Old save setting
        if settings.contains(key + "/save"):
            username = settings.value(key + "/username")
            if settings.value(key + "/save") == "true":
                password = settings.value(key + "/password")

        uri = QgsDataSourceURI()
        if service:
            uri.setConnection(service, db, username, password, sslmode)
        else:
            uri.setConnection(host, port, db, username, password, sslmode)

        uri.setUseEstimatedMetadata(use_estimated_metadata)

        # Obtain the geometry column name
        connector = PostGisDBConnector(uri)
        tbls = connector.getVectorTables(schema)
        tbls = [tbl for tbl in tbls if tbl[1] == table]
        # if len(tbls) != 1:
        #    In the future, also look for raster layers?
        #    tbls = connector.getRasterTables(schema)
        #    tbls = [tbl for tbl in tbls if tbl[1]==table]
        if not tbls:
            return None
        tbl = tbls[0]
        geom_col = tbl[8]

        uri.setDataSource(schema, table, geom_col)
        return uri
예제 #29
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()
        self.footer_label.setWordWrap(True)

        # 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)
예제 #30
0
def _saveLastUsedSession():
    s = QSettings()
    s.beginGroup("session")
    s.setValue("lastused", _currentSession or "")