def test_precision(self):
     """Test different precision"""
     QLocale.setDefault(QLocale(QLocale.English))
     assert QLocale().decimalPoint() == '.'
     field = self.vl.fields()[self.vl.fields().indexFromName('double_field')]
     field.setPrecision(4)
     self._fld_checker(field)
Exemplo n.º 2
0
 def setUpClass(cls):
     """Run before all tests"""
     QCoreApplication.setOrganizationName("QGIS_Test")
     QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com")
     QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme")
     QgsSettings().clear()
     QLocale.setDefault(QLocale(QLocale.English))
     start_app()
Exemplo n.º 3
0
    def testExportFeaturesWithLocale_regression20053(self):
        """ Test exporting feature export with range widgets and locale different than C
        Regression: https://issues.qgis.org/issues/20053 - decimal separator in csv files
        """

        source = QgsVectorLayer("Point?field=name:string&field=cost:double&field=population:int&field=date:date",
                                "parent", "memory")
        self.assertTrue(source.isValid())
        fields = source.fields()

        feature = QgsFeature(fields, 5)
        feature.setGeometry(QgsGeometry(QgsPoint(5, 6)))
        feature.setAttributes(['Valsier Peninsula', 6.8, 198000, '2018-09-10'])

        exporter = QgsJsonExporter()

        # single feature
        expected = """{
  "features": [
    {
      "geometry": {
        "coordinates": [
          5.0,
          6.0
        ],
        "type": "Point"
      },
      "id": 5,
      "properties": {
        "cost": 6.8,
        "date": "2018-09-10",
        "name": "Valsier Peninsula",
        "population": 198000
      },
      "type": "Feature"
    }
  ],
  "type": "FeatureCollection"
}"""
        self.assertEqual(exporter.exportFeatures([feature], 2), expected)

        setup = QgsEditorWidgetSetup('Range', {
            'AllowNull': True,
            'Max': 2147483647,
            'Min': -2147483648,
            'Precision': 4,
            'Step': 1,
            'Style': 'SpinBox'
        }
        )
        source.setEditorWidgetSetup(1, setup)
        source.setEditorWidgetSetup(2, setup)

        QLocale.setDefault(QLocale('it'))
        exporter.setVectorLayer(source)
        self.assertEqual(exporter.exportFeatures([feature], 2), expected)
Exemplo n.º 4
0
def qgisLocale():
    settings = QSettings();
    overrideLocale = settings.value("locale/overrideFlag", False, bool)
    if overrideLocale:
        return settings.value("locale/userLocale", "")
    else:
        return QLocale.system().name()[:2]
Exemplo n.º 5
0
    def __init__(self, iface):
        if not valid:
            return

        # Save reference to the QGIS interface
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

        if QGis.QGIS_VERSION[0:3] < "1.5":
            # For i18n support
            userPluginPath = qgis.utils.home_plugin_path + "/GdalTools"
            systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools"

            overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool)
            if not overrideLocale:
                localeFullName = QLocale.system().name()
            else:
                localeFullName = QSettings().value("locale/userLocale", "", type=str)

            if QFileInfo(userPluginPath).exists():
                translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
            else:
                translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"

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

        # The list of actions added to menus, so we can remove them when unloading the plugin
        self._menuActions = []
Exemplo n.º 6
0
def locale(qsetting=''):
    """Get the name of the currently active locale.

    :param qsetting: String to specify the QSettings. By default,
        use empty string.
    :type qsetting: str

    :returns: Name of the locale e.g. 'id'
    :rtype: str
    """
    override_flag = QSettings(qsetting).value(
        'locale/overrideFlag', True, type=bool)

    default = 'en_US'

    if override_flag:
        locale_name = QSettings(qsetting).value(
            'locale/userLocale', default, type=str)
    else:
        # noinspection PyArgumentList
        locale_name = QLocale.system().name()

    if locale_name == 'C':
        # On travis, locale/userLocale is equal to C. We want 'en'.
        locale_name = default

    # 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]
    return locale_name
Exemplo n.º 7
0
def loadShortHelp():
    h = {}
    path = os.path.dirname(__file__)
    for f in os.listdir(path):
        if f.endswith("yaml"):
            filename = os.path.join(path, f)
            with codecs.open(filename, encoding='utf-8') as stream:
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=DeprecationWarning)
                    for k, v in yaml.load(stream, Loader=yaml.SafeLoader).items():
                        if v is None:
                            continue
                        h[k] = QCoreApplication.translate("{}Algorithm".format(f[:-5].upper()), v)

    version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2])
    overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool)
    if not overrideLocale:
        locale = QLocale.system().name()[:2]
    else:
        locale = QgsSettings().value('locale/userLocale', '')
    locale = locale.split("_")[0]

    def replace(s):
        if s is not None:
            return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale))
        else:
            return None

    h = {k: replace(v) for k, v in list(h.items())}

    return h
 def getFile():
   overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
   localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')
   qmPathFile = "i18n/{0}_{1}.qm".format( pluginName, localeFullName )
   pluginPath = os.path.dirname(__file__)
   translationFile = "{}/{}".format( pluginPath, qmPathFile )
   return translationFile
Exemplo n.º 9
0
def getTranslate(namePlugin, nameDir=None):
    if nameDir is None:
      nameDir = namePlugin

    pluginPath = os.path.join('python', 'plugins', nameDir)

    userPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
    userPluginPath = os.path.join(userPath, pluginPath)
    
    systemPath = QgsApplication.prefixPath()
    systemPluginPath = os.path.join(systemPath, pluginPath)

    overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
    localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')

    qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName))
    pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath
    translationFile = os.path.join(pp, qmPathFile)

    if QFileInfo(translationFile).exists():
        translator = QTranslator()
        translator.load(translationFile)
        QCoreApplication.installTranslator(translator)
        QgsApplication.messageLog().logMessage(('Installed translation file {}'.format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
        return translator
    else:
        QgsApplication.messageLog().logMessage(
            ("translationFile {} didn't exist, no translation file installed!".format(translationFile)), 'Midvatten',
                                               level=Qgis.Info)
Exemplo n.º 10
0
 def pluginMetadata(fct):
     """ calls metadataParser for current l10n.
         If failed, fallbacks to the standard metadata """
     locale = QLocale.system().name()
     if locale and fct in translatableAttributes:
         value = metadataParser("{}[{}]".format(fct, locale))
         if value:
             return value
         value = metadataParser("{}[{}]".format(fct, locale.split("_")[0]))
         if value:
             return value
     return metadataParser(fct)
Exemplo n.º 11
0
 def testFormatDistance(self):
     """Test formatting distances"""
     QLocale.setDefault(QLocale.c())
     self.assertEqual(QgsDistanceArea.formatDistance(45, 3, QgsUnitTypes.DistanceMeters), u"45.000 m")
     self.assertEqual(QgsDistanceArea.formatDistance(1300, 1, QgsUnitTypes.DistanceMeters, False), u"1.3 km")
     self.assertEqual(QgsDistanceArea.formatDistance(0.005, 1, QgsUnitTypes.DistanceMeters, False), u"5.0 mm")
     self.assertEqual(QgsDistanceArea.formatDistance(0.05, 1, QgsUnitTypes.DistanceMeters, False), u"5.0 cm")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceKilometers, True), u"1.500 km")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceKilometers, False), u"1.500 km")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceKilometers, True), u"0.500 km")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceKilometers, False), u"500.000 m")
     self.assertEqual(QgsDistanceArea.formatDistance(6000, 0, QgsUnitTypes.DistanceFeet, True), u"6,000 ft")
     self.assertEqual(QgsDistanceArea.formatDistance(6000, 3, QgsUnitTypes.DistanceFeet, False), u"1.136 mi")
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet, True), u"300 ft")
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet, False), u"300 ft")
     self.assertEqual(QgsDistanceArea.formatDistance(3000, 0, QgsUnitTypes.DistanceYards, True), u"3,000 yd")
     self.assertEqual(QgsDistanceArea.formatDistance(3000, 3, QgsUnitTypes.DistanceYards, False), u"1.705 mi")
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards, True), u"300 yd")
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards, False), u"300 yd")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles, True), u"1.500 mi")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles, False), u"1.500 mi")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceMiles, True), u"0.500 mi")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 0, QgsUnitTypes.DistanceMiles, False), u"2,640 ft")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 1, QgsUnitTypes.DistanceNauticalMiles, True), u"0.5 NM")
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 1, QgsUnitTypes.DistanceNauticalMiles, False), u"0.5 NM")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceNauticalMiles, True), u"1.5 NM")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceNauticalMiles, False), u"1.5 NM")
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceDegrees, True), u"1.5 degrees")
     self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceDegrees, False), u"1.0 degree")
     self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceUnknownUnit, False), u"1.0")
     QLocale.setDefault(QLocale.system())
Exemplo n.º 12
0
 def testFormatDistance(self):
     """Test formatting distances"""
     QLocale.setDefault(QLocale.c())
     self.assertEqual(QgsDistanceArea.formatDistance(45, 3, QgsUnitTypes.DistanceMeters), '45.000 m')
     self.assertEqual(QgsDistanceArea.formatDistance(1300, 1, QgsUnitTypes.DistanceMeters, False), '1.3 km')
     self.assertEqual(QgsDistanceArea.formatDistance(.005, 1, QgsUnitTypes.DistanceMeters, False), '5.0 mm')
     self.assertEqual(QgsDistanceArea.formatDistance(.05, 1, QgsUnitTypes.DistanceMeters, False), '5.0 cm')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceKilometers, True), '1.500 km')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceKilometers, False), '1.500 km')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceKilometers, True), '0.500 km')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceKilometers, False), '500.000 m')
     self.assertEqual(QgsDistanceArea.formatDistance(6000, 0, QgsUnitTypes.DistanceFeet, True), '6,000 ft')
     self.assertEqual(QgsDistanceArea.formatDistance(6000, 3, QgsUnitTypes.DistanceFeet, False), '1.136 mi')
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet, True), '300 ft')
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet, False), '300 ft')
     self.assertEqual(QgsDistanceArea.formatDistance(3000, 0, QgsUnitTypes.DistanceYards, True), '3,000 yd')
     self.assertEqual(QgsDistanceArea.formatDistance(3000, 3, QgsUnitTypes.DistanceYards, False), '1.705 mi')
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards, True), '300 yd')
     self.assertEqual(QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards, False), '300 yd')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles, True), '1.500 mi')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles, False), '1.500 mi')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceMiles, True), '0.500 mi')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 0, QgsUnitTypes.DistanceMiles, False), '2,640 ft')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 1, QgsUnitTypes.DistanceNauticalMiles, True), '0.5 NM')
     self.assertEqual(QgsDistanceArea.formatDistance(0.5, 1, QgsUnitTypes.DistanceNauticalMiles, False), '0.5 NM')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceNauticalMiles, True), '1.5 NM')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceNauticalMiles, False), '1.5 NM')
     self.assertEqual(QgsDistanceArea.formatDistance(1.5, 1, QgsUnitTypes.DistanceDegrees, True), '1.5 degrees')
     self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceDegrees, False), '1.0 degree')
     self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceUnknownUnit, False), '1.0')
     QLocale.setDefault(QLocale.system())
Exemplo n.º 13
0
    def openHelp(self):
        overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QSettings().value('locale/userLocale', '')

        if locale in ['uk']:
            QDesktopServices.openUrl(
                QUrl('https://github.com/alexbruy/qscatter'))
        else:
            QDesktopServices.openUrl(
                QUrl('https://github.com/alexbruy/qscatter'))
Exemplo n.º 14
0
    def __init__(self, iface):
        self.iface = iface

        overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QSettings().value('locale/userLocale', '')

        qmPath = '{}/i18n/qscatter_{}.qm'.format(pluginPath, locale)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QCoreApplication.installTranslator(self.translator)
Exemplo n.º 15
0
 def __init__(self, iface):
     """Initialize the plugin"""
     global control
     try:
         control
     except NameError:
         try:
             overrideLocale = bool(QSettings().value("locale/overrideFlag", False))
             if not overrideLocale:
                 lang = QLocale.system().name().split("_")[0]
             else:
                 lang = QSettings().value("locale/userLocale", "").split("_")[0]
         except Exception:
             lang = "en"  # could not get locale, OSX may have this bug
         info("Plugin language loaded: {}".format(lang))
         self.changeI18n(lang)
         control = TimeManagerControl(iface)
    def __init__(self, iface):
        self.iface = iface
        self.settings = None

        overrideLocale = QgsSettings().value("locale/overrideFlag", False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QgsSettings().value("locale/userLocale", "")

        QgsMessageLog.logMessage("Locale: {}".format(locale), "VoGis", Qgis.Info)
        qmPath = "{}/i18n/vogisprofiltoolmain_{}.qm".format(pluginPath, locale)

        if locale != 'de' and not os.path.exists(qmPath):
            qmPath = "{}/i18n/vogisprofiltoolmain_en.qm".format(pluginPath)

        if os.path.exists(qmPath):
            self.translator = QTranslator()
            self.translator.load(qmPath)
            QApplication.installTranslator(self.translator)
Exemplo n.º 17
0
def loadShortHelp():
    h = {}
    path = os.path.dirname(__file__)
    for f in os.listdir(path):
        if f.endswith("yaml"):
            filename = os.path.join(path, f)
            with codecs.open(filename, encoding='utf-8') as stream:
                h.update(yaml.load(stream))
    version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2])
    overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool)
    if not overrideLocale:
        locale = QLocale.system().name()[:2]
    else:
        locale = QgsSettings().value('locale/userLocale', '')
    locale = locale.split("_")[0]

    def replace(s):
        if s is not None:
            return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale))
        else:
            return None
    h = {k: replace(v) for k, v in list(h.items())}
    return h
Exemplo n.º 18
0
    def processAlgorithm(self, feedback):
        inLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT))
        boundary = self.getParameterValue(self.MODE) == self.MODE_BOUNDARY
        smallestArea = self.getParameterValue(self.MODE) == self.MODE_SMALLEST_AREA
        keepSelection = self.getParameterValue(self.KEEPSELECTION)
        processLayer = vector.duplicateInMemory(inLayer)

        if not keepSelection:
            # Make a selection with the values provided
            attribute = self.getParameterValue(self.ATTRIBUTE)
            comparison = self.comparisons[self.getParameterValue(self.COMPARISON)]
            comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)

            selectindex = vector.resolveFieldIndex(processLayer, attribute)
            selectType = processLayer.fields()[selectindex].type()
            selectionError = False

            if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' % str(comparisonvalue))
            elif selectType == QVariant.Double:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' % str(comparisonvalue))
            elif selectType == QVariant.String:
                # 10: string, boolean
                try:
                    y = str(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to Unicode' % str(comparisonvalue))
            elif selectType == QVariant.Date:
                # date
                dateAndFormat = comparisonvalue.split(' ')

                if len(dateAndFormat) == 1:
                    # QDate object
                    y = QLocale.system().toDate(dateAndFormat[0])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with system date format %s' % (str(dateAndFormat), QLocale.system().dateFormat()))
                elif len(dateAndFormat) == 2:
                    y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with format string "%s"' % (str(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessful
                    selectionError = True
                    msg += self.tr('Enter the date and the date format, e.g. "07.26.2011" "MM.dd.yyyy".')

            if (comparison == 'begins with' or comparison == 'contains') \
               and selectType != QVariant.String:
                selectionError = True
                msg = self.tr('"%s" can only be used with string fields' % comparison)

            selected = []

            if selectionError:
                raise GeoAlgorithmExecutionException(
                    self.tr('Error in selection input: %s' % msg))
            else:
                for feature in processLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                        x = int(aValue)
                    elif selectType == QVariant.Double:
                        x = float(aValue)
                    elif selectType == QVariant.String:
                        # 10: string, boolean
                        x = str(aValue)
                    elif selectType == QVariant.Date:
                        # date
                        x = aValue  # should be date

                    match = False

                    if comparison == '==':
                        match = x == y
                    elif comparison == '!=':
                        match = x != y
                    elif comparison == '>':
                        match = x > y
                    elif comparison == '>=':
                        match = x >= y
                    elif comparison == '<':
                        match = x < y
                    elif comparison == '<=':
                        match = x <= y
                    elif comparison == 'begins with':
                        match = x.startswith(y)
                    elif comparison == 'contains':
                        match = x.find(y) >= 0

                    if match:
                        selected.append(feature.id())

            processLayer.selectByIds(selected)

        if processLayer.selectedFeatureCount() == 0:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
                                   self.tr('%s: (No selection in input layer "%s")' % (self.commandLineName(), self.getParameterValue(self.INPUT))))

        # Keep references to the features to eliminate
        featToEliminate = []
        for aFeat in processLayer.selectedFeatures():
            featToEliminate.append(aFeat)

        # Delete all features to eliminate in processLayer (we won't save this)
        processLayer.startEditing()
        processLayer.deleteSelectedFeatures()

        # ANALYZE
        if len(featToEliminate) > 0:  # Prevent zero division
            start = 20.00
            add = 80.00 / len(featToEliminate)
        else:
            start = 100

        feedback.setProgress(start)
        madeProgress = True

        # We go through the list and see if we find any polygons we can
        # merge the selected with. If we have no success with some we
        # merge and then restart the whole story.
        while madeProgress:  # Check if we made any progress
            madeProgress = False
            featNotEliminated = []

            # Iterate over the polygons to eliminate
            for i in range(len(featToEliminate)):
                feat = featToEliminate.pop()
                geom2Eliminate = feat.geometry()
                bbox = geom2Eliminate.boundingBox()
                fit = processLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(bbox).setSubsetOfAttributes([]))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

                # use prepared geometries for faster intersection tests
                engine = QgsGeometry.createGeometryEngine(geom2Eliminate.geometry())
                engine.prepareGeometry()

                while fit.nextFeature(selFeat):
                    selGeom = selFeat.geometry()

                    if engine.intersects(selGeom.geometry()):
                        # We have a candidate
                        iGeom = geom2Eliminate.intersection(selGeom)

                        if not iGeom:
                            continue

                        if boundary:
                            selValue = iGeom.length()
                        else:
                            # area. We need a common boundary in
                            # order to merge
                            if 0 < iGeom.length():
                                selValue = selGeom.area()
                            else:
                                selValue = -1

                        if -1 != selValue:
                            useThis = True

                            if smallestArea:
                                if -1 == min:
                                    min = selValue
                                else:
                                    if selValue < min:
                                        min = selValue
                                    else:
                                        useThis = False
                            else:
                                if selValue > max:
                                    max = selValue
                                else:
                                    useThis = False

                            if useThis:
                                mergeWithFid = selFeat.id()
                                mergeWithGeom = QgsGeometry(selGeom)
                # End while fit

                if mergeWithFid is not None:
                    # A successful candidate
                    newGeom = mergeWithGeom.combine(geom2Eliminate)

                    if processLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.tr('Could not replace geometry of feature with id %s' % mergeWithFid))

                    start = start + add
                    feedback.setProgress(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(processLayer.fields(),
                                        processLayer.wkbType(), processLayer.crs())

        # Write all features that are left over to output layer
        iterator = processLayer.getFeatures()
        for feature in iterator:
            writer.addFeature(feature)

        # Leave processLayer untouched
        processLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
Exemplo n.º 19
0
from qgis.PyQt.QtCore import QLocale, QTranslator, QCoreApplication, QSettings
from qgis.PyQt.QtWidgets import QMessageBox

# 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__)))
translation_path = os.path.join(
    root, 'safe', 'i18n',
    'inasafe_' + str(locale_name) + '.qm')

if os.path.exists(translation_path):
Exemplo n.º 20
0
def locale(values, feature, parent):
    return QSettings().value("locale/userLocale", QLocale.system().name())
Exemplo n.º 21
0
    def layers(self, filter_layer_list=[]):
        tables_info = self.get_tables_info()
        layers = list()

        db_factory = self.db_simple_factory.create_factory(self.tool)

        layer_uri = db_factory.get_layer_uri(self.uri)
        layer_uri.pg_estimated_metadata = self.pg_estimated_metadata

        for record in tables_info:
            # When in PostGIS mode, leaving schema blank should load tables from
            # all schemas, except the ignored ones
            if self.schema:
                if record['schemaname'] != self.schema:
                    continue
            elif record['schemaname'] in IGNORED_SCHEMAS:
                continue

            if record['tablename'] in IGNORED_TABLES:
                continue

            if filter_layer_list and record['tablename'] not in filter_layer_list:
                continue

            alias = record['table_alias'] if 'table_alias' in record else ''
            is_domain = record['kind_settings'] == 'ENUM' or record[
                'kind_settings'] == 'CATALOGUE' if 'kind_settings' in record else False
            is_structure = record['kind_settings'] == 'STRUCTURE' if 'kind_settings' in record else False
            is_nmrel = record['kind_settings'] == 'ASSOCIATION' if 'kind_settings' in record else False

            display_expression = ''
            if 'ili_name' in record:
                meta_attrs = self.get_meta_attrs(record['ili_name'])
                for attr_record in meta_attrs:
                    if attr_record['attr_name'] == 'dispExpression':
                        display_expression = attr_record['attr_value']

            layer = Layer(layer_uri.provider,
                          layer_uri.get_data_source_uri(record),
                          record['tablename'],
                          record['srid'],
                          record['extent'] if 'extent' in record else None,
                          record['geometry_column'],
                          QgsWkbTypes.parseType(
                              record['type']) or QgsWkbTypes.Unknown,
                          alias,
                          is_domain,
                          is_structure,
                          is_nmrel,
                          display_expression)

            # Configure fields for current table
            fields_info = self.get_fields_info(record['tablename'])
            constraints_info = self.get_constraints_info(record['tablename'])
            re_iliname = re.compile(r'^@iliname (.*)$')

            for fielddef in fields_info:
                column_name = fielddef['column_name']
                comment = fielddef['comment']
                m = re_iliname.match(comment) if comment else None

                alias = None
                if 'column_alias' in fielddef:
                    alias = fielddef['column_alias']
                if m and not alias:
                    alias = m.group(1)

                field = Field(column_name)
                field.alias = alias

                # Should we hide the field?
                hide_attribute = False

                if 'fully_qualified_name' in fielddef:
                    fully_qualified_name = fielddef['fully_qualified_name']
                    if fully_qualified_name:
                        meta_attrs_column = self.get_meta_attrs(fully_qualified_name)

                        for attr_record in meta_attrs_column:
                            if attr_record['attr_name'] == 'hidden':
                                if attr_record['attr_value'] == 'True':
                                    hide_attribute = True
                                    break

                if column_name in IGNORED_FIELDNAMES:
                    hide_attribute = True

                field.hidden = hide_attribute

                if column_name in READONLY_FIELDNAMES:
                    field.read_only = True

                if column_name in constraints_info:
                    field.widget = 'Range'
                    field.widget_config['Min'] = constraints_info[column_name][0]
                    field.widget_config['Max'] = constraints_info[column_name][1]
                    if 'numeric_scale' in fielddef:
                        field.widget_config['Step'] = pow(10, -1 * fielddef['numeric_scale'])
                    # field.widget_config['Suffix'] = fielddef['unit'] if 'unit' in fielddef else ''
                    if 'unit' in fielddef and fielddef['unit'] is not None:
                        field.alias = '{alias} [{unit}]'.format(
                            alias=alias or column_name, unit=fielddef['unit'])

                if 'texttype' in fielddef and fielddef['texttype'] == 'MTEXT':
                    field.widget = 'TextEdit'
                    field.widget_config['IsMultiline'] = True

                data_type = self._db_connector.map_data_types(
                    fielddef['data_type'])
                if 'time' in data_type or 'date' in data_type:
                    field.widget = 'DateTime'
                    field.widget_config['calendar_popup'] = True

                    dateFormat = QLocale(QgsApplication.instance(
                    ).locale()).dateFormat(QLocale.ShortFormat)
                    timeFormat = QLocale(QgsApplication.instance(
                    ).locale()).timeFormat(QLocale.ShortFormat)
                    dateTimeFormat = QLocale(QgsApplication.instance(
                    ).locale()).dateTimeFormat(QLocale.ShortFormat)

                    if data_type == self._db_connector.QGIS_TIME_TYPE:
                        field.widget_config['display_format'] = timeFormat
                    elif data_type == self._db_connector.QGIS_DATE_TIME_TYPE:
                        field.widget_config['display_format'] = dateTimeFormat
                    elif data_type == self._db_connector.QGIS_DATE_TYPE:
                        field.widget_config['display_format'] = dateFormat

                db_factory.customize_widget_editor(field, data_type)

                if 'default_value_expression' in fielddef:
                    field.default_value_expression = fielddef['default_value_expression']

                layer.fields.append(field)

            layers.append(layer)

        return layers
Exemplo n.º 22
0
 def test_doubleValidatorCommaLocale(self):
     """Test the double with german locale"""
     QLocale.setDefault(QLocale(QLocale.German, QLocale.Germany))
     assert QLocale().decimalPoint() == ','
     field = self.vl.fields()[self.vl.fields().indexFromName('double_field')]
     self._fld_checker(field)
Exemplo n.º 23
0
import os.path
from qgis.PyQt.QtCore import (QLocale, QSettings, QCoreApplication,
                              QTranslator)

DEFAULT_LANGUAGE = 'en'

try:
    # Errors here could happen if the value cannot be converted to string or
    # if it is not subscriptable (see https://github.com/gacarrillor/loadthemall/issues/11)
    locale = QSettings().value("locale/userLocale", type=str)
    QGIS_LANG = str(locale[:2])
except TypeError as e:
    QGIS_LANG = DEFAULT_LANGUAGE
PLUGIN_DIR = os.path.dirname(os.path.dirname(__file__))

# Install Qt Translator
qgis_locale = QLocale(QGIS_LANG)
locale_path = os.path.join(PLUGIN_DIR, 'i18n')
translator = QTranslator()
translator.load(qgis_locale, 'Asistente-LADM-COL', '_', locale_path)
QCoreApplication.installTranslator(translator)
Exemplo n.º 24
0
"""
__author__ = 'Nyall Dawson'
__date__ = '03.02.2016'
__copyright__ = 'Copyright 2016, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '36f115833ea6eb5d801dc458a5d3112993d25e9d'

import qgis  # NOQA

from qgis.testing import unittest
from qgis.core import QgsUnitTypes
from qgis.PyQt.QtCore import QLocale

# enforce C locale because the tests expect it
# (decimal separators / thousand separators)
QLocale.setDefault(QLocale.c())


class TestQgsUnitTypes(unittest.TestCase):

    def testDistanceUnitType(self):
        """Test QgsUnitTypes::unitType() """
        expected = {QgsUnitTypes.DistanceMeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceKilometers: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceFeet: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceYards: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceMiles: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceDegrees: QgsUnitTypes.Geographic,
                    QgsUnitTypes.DistanceCentimeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceMillimeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceUnknownUnit: QgsUnitTypes.UnknownType,
Exemplo n.º 25
0
 def test_doubleValidatorDotLocale(self):
     """Test the double with english locale"""
     QLocale.setDefault(QLocale(QLocale.English))
     assert QLocale().decimalPoint() == '.'
     field = self.vl.fields()[self.vl.fields().indexFromName('double_field')]
     self._fld_checker(field)
Exemplo n.º 26
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
        """

        self.iface = iface

        try:
            self.qgis_version = Qgis.QGIS_VERSION_INT
        except NameError:
            self.qgis_version = QGis.QGIS_VERSION_INT

        # we store geometry type
        self.Point, self.Line, self.Polygon = (
                [QgsWkbTypes.PointGeometry, QgsWkbTypes.LineGeometry, QgsWkbTypes.PolygonGeometry]
                if self.qgis_version >= 29900 else
                [QGis.Point, QGis.Line, QGis.Polygon])

        if QSettings().value('locale/overrideFlag', type=bool):
            locale = QSettings().value('locale/userLocale')
        else:
            locale = QLocale.system().name()

        if locale:
            locale_path = os.path.join(os.path.dirname(__file__), 'i18n', locale)
            self.translator = QTranslator()

            if self.translator.load(locale_path):
                QCoreApplication.installTranslator(self.translator)

        # Save reference to the QGIS interface
        self.iface = iface
        self.mapCanvas = iface.mapCanvas()

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        icon_path = os.path.join(self.plugin_dir, "icons", "quickEdit_edit.png")
        self.mapToolActionEdit = QtWidgets.QAction(QtGui.QIcon(icon_path),"Edit Tree", self.iface.mainWindow())
        self.mapToolActionEdit.setCheckable(True)
        self.mapToolActionEdit.triggered.connect(self.onEditActionTriggered)

        icon_path = os.path.join(self.plugin_dir, "icons", "quickEdit_new.png")
        self.mapToolActionNew = QtWidgets.QAction(QtGui.QIcon(icon_path),"New Tree", self.iface.mainWindow())
        self.mapToolActionNew.setCheckable(True)
        self.mapToolActionNew.triggered.connect(self.onNewActionTriggered)

        icon_path = os.path.join(self.plugin_dir, "icons", "quickEdit_delete.png")
        self.mapToolActionDelete = QtWidgets.QAction(QtGui.QIcon(icon_path),"Delete Tree", self.iface.mainWindow())
        self.mapToolActionDelete.setCheckable(True)
        self.mapToolActionDelete.triggered.connect(self.onDeleteActionTriggered)

        self.actionGroup =  QtWidgets.QActionGroup(self.iface.mainWindow())

        self.actionGroup.addAction(self.mapToolActionEdit)
        self.actionGroup.addAction(self.mapToolActionNew)
        self.actionGroup.addAction(self.mapToolActionDelete)

        self.actionGroup.setExclusive(True)

        self.mapTool = QuickEditMapTool(self.mapCanvas)

        self.mapTool.clicked.connect(self.onCanvasClicked)
        self.mapTool.identified.connect(self.onIdentified)

        self.mapTool.setAction(self.mapToolActionEdit)

        self.mapCanvas.setMapTool(self.mapTool)

        self.treeAttributeDialog = None
Exemplo n.º 27
0
    return LDMPPlugin(iface)

# Function to get a temporary filename that handles closing the file created by 
# NamedTemporaryFile - necessary when the file is for usage in another process 
# (i.e. GDAL)
def GetTempFilename(suffix):
    f = NamedTemporaryFile(suffix=suffix, delete=False)
    f.close()
    return f.name

# initialize translation
i18n_dir = os.path.join(plugin_dir, 'i18n')
log(u'Starting trends.earth version {} (rev: {}, released {}).'.format(__version__, __revision__, __release_date__))

translator = QTranslator()
locale = QLocale(QgsApplication.locale())
log('Trying to load locale {} from {}.'.format(locale.name(), i18n_dir))
translator.load(locale, 'LDMP', prefix='.', directory=i18n_dir, suffix='.qm')
ret = QCoreApplication.installTranslator(translator)
if ret:
    log("Translator installed for {}.".format(locale.name()))
else:
    log("FAILED while trying to install translator for {}.".format(locale.name()))

# Ensure that the ext-libs, and binaries folder (if available) are near the 
# front of the path (important on Linux)
ext_libs_path = os.path.join(plugin_dir, 'ext-libs')
binaries_folder = QSettings().value("LDMP/binaries_folder", None)
sys.path, remainder = sys.path[:1], sys.path[1:]
site.addsitedir(ext_libs_path)
if binaries_folder:
Exemplo n.º 28
0
 def testFormatDistance(self):
     """Test formatting distances"""
     QLocale.setDefault(QLocale.c())
     self.assertEqual(
         QgsDistanceArea.formatDistance(45, 3, QgsUnitTypes.DistanceMeters),
         '45.000 m')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1300, 1,
                                        QgsUnitTypes.DistanceMeters, False),
         '1.3 km')
     self.assertEqual(
         QgsDistanceArea.formatDistance(.005, 1,
                                        QgsUnitTypes.DistanceMeters, False),
         '5.0 mm')
     self.assertEqual(
         QgsDistanceArea.formatDistance(.05, 1, QgsUnitTypes.DistanceMeters,
                                        False), '5.0 cm')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 3,
                                        QgsUnitTypes.DistanceKilometers,
                                        True), '1.500 km')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 3,
                                        QgsUnitTypes.DistanceKilometers,
                                        False), '1.500 km')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 3,
                                        QgsUnitTypes.DistanceKilometers,
                                        True), '0.500 km')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 3,
                                        QgsUnitTypes.DistanceKilometers,
                                        False), '500.000 m')
     self.assertEqual(
         QgsDistanceArea.formatDistance(6000, 0, QgsUnitTypes.DistanceFeet,
                                        True), '6,000 ft')
     self.assertEqual(
         QgsDistanceArea.formatDistance(6000, 3, QgsUnitTypes.DistanceFeet,
                                        False), '1.136 mi')
     self.assertEqual(
         QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet,
                                        True), '300 ft')
     self.assertEqual(
         QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceFeet,
                                        False), '300 ft')
     self.assertEqual(
         QgsDistanceArea.formatDistance(3000, 0, QgsUnitTypes.DistanceYards,
                                        True), '3,000 yd')
     self.assertEqual(
         QgsDistanceArea.formatDistance(3000, 3, QgsUnitTypes.DistanceYards,
                                        False), '1.705 mi')
     self.assertEqual(
         QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards,
                                        True), '300 yd')
     self.assertEqual(
         QgsDistanceArea.formatDistance(300, 0, QgsUnitTypes.DistanceYards,
                                        False), '300 yd')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles,
                                        True), '1.500 mi')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 3, QgsUnitTypes.DistanceMiles,
                                        False), '1.500 mi')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 3, QgsUnitTypes.DistanceMiles,
                                        True), '0.500 mi')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 0, QgsUnitTypes.DistanceMiles,
                                        False), '2,640 ft')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 1,
                                        QgsUnitTypes.DistanceNauticalMiles,
                                        True), '0.5 NM')
     self.assertEqual(
         QgsDistanceArea.formatDistance(0.5, 1,
                                        QgsUnitTypes.DistanceNauticalMiles,
                                        False), '0.5 NM')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 1,
                                        QgsUnitTypes.DistanceNauticalMiles,
                                        True), '1.5 NM')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 1,
                                        QgsUnitTypes.DistanceNauticalMiles,
                                        False), '1.5 NM')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.5, 1,
                                        QgsUnitTypes.DistanceDegrees, True),
         '1.5 degrees')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.0, 1,
                                        QgsUnitTypes.DistanceDegrees,
                                        False), '1.0 degree')
     self.assertEqual(
         QgsDistanceArea.formatDistance(1.0, 1,
                                        QgsUnitTypes.DistanceUnknownUnit,
                                        False), '1.0')
     QLocale.setDefault(QLocale.system())
Exemplo n.º 29
0
        def _test(layer, is_gpkg=False):

            # Skip fid and precision tests
            offset = 1 if is_gpkg else 0

            fieldFormatter = QgsFallbackFieldFormatter()

            QLocale.setDefault(QLocale('en'))

            # Precision is ignored for integers and longlongs
            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              '123'), '123')
            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              '123000'), '123,000')
            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              '9999999'), '9,999,999')
            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              None), 'NULL')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '123'), '123')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '123000'), '123,000')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '9999999'), '9,999,999')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              None), 'NULL')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              None), 'NULL')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123'), '123.00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123'), '123')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              None), 'NULL')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123,000.00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123,000')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '0'), '0')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '0.127'), '0.127')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '1.27e-1'), '0.127')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '-123'), '-123.00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '-123'), '-123')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '-0.127'), '-0.127')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '-1.27e-1'), '-0.127')

            # Check with Italian locale
            QLocale.setDefault(QLocale('it'))

            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              '9999999'),
                '9.999.999')  # scientific notation for integers!
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '123'), '123')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '123000'), '123.000')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '9999999'), '9.999.999')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              None), 'NULL')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              None), 'NULL')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123.000,00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123.000')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '0'), '0')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123'), '123,00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123'), '123')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '0.127'), '0,127')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '1.27e-1'), '0,127')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '-123'), '-123,00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '-123'), '-123')

            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '-0.127'), '-0,127')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              '-1.27e-1'), '-0,127')

            # Check with custom locale without thousand separator

            custom = QLocale('en')
            custom.setNumberOptions(QLocale.OmitGroupSeparator)
            QLocale.setDefault(custom)

            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              '9999999'),
                '9999999')  # scientific notation for integers!
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '123'), '123')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              '9999999'), '9999999')

            if not is_gpkg:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123000.00000')
            else:
                self.assertEqual(
                    fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                                  '123000'), '123000')

            # Check string
            self.assertEqual(
                fieldFormatter.representValue(layer, 3 + offset, {}, None,
                                              '123'), '123')
            self.assertEqual(
                fieldFormatter.representValue(layer, 3 + offset, {}, None,
                                              'a string'), 'a string')
            self.assertEqual(
                fieldFormatter.representValue(layer, 3 + offset, {}, None, ''),
                '')
            self.assertEqual(
                fieldFormatter.representValue(layer, 3 + offset, {}, None,
                                              None), 'NULL')

            # Check NULLs (this is what happens in real life inside QGIS)
            self.assertEqual(
                fieldFormatter.representValue(layer, 0 + offset, {}, None,
                                              QVariant(QVariant.String)),
                'NULL')
            self.assertEqual(
                fieldFormatter.representValue(layer, 1 + offset, {}, None,
                                              QVariant(QVariant.String)),
                'NULL')
            self.assertEqual(
                fieldFormatter.representValue(layer, 2 + offset, {}, None,
                                              QVariant(QVariant.String)),
                'NULL')
            self.assertEqual(
                fieldFormatter.representValue(layer, 3 + offset, {}, None,
                                              QVariant(QVariant.String)),
                'NULL')
Exemplo n.º 30
0
    def test_representValue(self):
        layer = QgsVectorLayer(
            "point?field=datetime:datetime&field=date:date&field=time:time",
            "layer", "memory")
        self.assertTrue(layer.isValid())
        QgsProject.instance().addMapLayers([layer])

        field_formatter = QgsDateTimeFieldFormatter()

        # if specific display format is set then use that
        config = {"display_format": "dd/MM/yyyy HH:mm:ss"}
        self.assertEqual(
            field_formatter.representValue(
                layer, 0, config, None,
                QDateTime(QDate(2020, 3, 4), QTime(12, 13, 14), Qt.UTC)),
            '04/03/2020 12:13:14')
        self.assertEqual(
            field_formatter.representValue(
                layer, 0, config, None,
                QDateTime(QDate(2020, 3, 4), QTime(12, 13, 14),
                          Qt.OffsetFromUTC, 3600)), '04/03/2020 12:13:14')

        locale_assertions = {
            QLocale(QLocale.English): {
                "date_format": 'M/d/yy',
                "time_format": 'HH:mm:ss',
                "datetime_format": 'M/d/yy HH:mm:ss',
                "datetime_utc": '3/4/20 12:13:14 (UTC)',
                "datetime_utc+1": '3/4/20 12:13:14 (UTC+01:00)'
            },
            QLocale(QLocale.Finnish): {
                "date_format": 'd.M.yyyy',
                "time_format": 'HH:mm:ss',
                "datetime_format": 'd.M.yyyy HH:mm:ss',
                "datetime_utc": '4.3.2020 12:13:14 (UTC)',
                "datetime_utc+1": '4.3.2020 12:13:14 (UTC+01:00)'
            },
        }

        for locale, assertions in locale_assertions.items():
            QgsApplication.setLocale(locale)
            field_formatter = QgsDateTimeFieldFormatter()

            self.assertEqual(field_formatter.defaultFormat(QVariant.Date),
                             assertions["date_format"], locale.name())
            self.assertEqual(field_formatter.defaultFormat(QVariant.Time),
                             assertions["time_format"], locale.name())
            self.assertEqual(field_formatter.defaultFormat(QVariant.DateTime),
                             assertions["datetime_format"], locale.name())

            # default configuration should show timezone information
            config = {}
            self.assertEqual(
                field_formatter.representValue(
                    layer, 0, config, None,
                    QDateTime(QDate(2020, 3, 4), QTime(12, 13, 14), Qt.UTC)),
                assertions["datetime_utc"], locale.name())
            self.assertEqual(
                field_formatter.representValue(
                    layer, 0, config, None,
                    QDateTime(QDate(2020, 3, 4), QTime(12, 13, 14),
                              Qt.OffsetFromUTC, 3600)),
                assertions["datetime_utc+1"], locale.name())
            self.assertEqual(
                field_formatter.representValue(layer, 1, config, None,
                                               QDate(2020, 3, 4)),
                assertions["datetime_utc"].split(" ")[0], locale.name())
            config = {"display_format": "HH:mm:s"}
            self.assertEqual(
                field_formatter.representValue(layer, 2, config, None,
                                               QTime(12, 13, 14)),
                assertions["datetime_utc"].split(" ")[1], locale.name())
Exemplo n.º 31
0
 def tearDownClass(cls):
     """Reset locale"""
     QgsApplication.setLocale(QLocale(QLocale.English))
Exemplo n.º 32
0
 def test_doubleValidatorCommaLocale(self):
     """Test the double with german locale"""
     QLocale.setDefault(QLocale(QLocale.German, QLocale.Germany))
     assert QLocale().decimalPoint() == ','
     field = self.vl.fields()[self.vl.fields().indexFromName('double_field')]
     self._fld_checker(field)
Exemplo n.º 33
0
    def test_representValue(self):

        layer = QgsVectorLayer("point?field=int:integer&field=double:double&field=long:long",
                               "layer", "memory")
        self.assertTrue(layer.isValid())
        QgsProject.instance().addMapLayers([layer])

        fieldFormatter = QgsRangeFieldFormatter()

        # Precision is ignored for integers and longlongs
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123000'), '123,000')
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'), '9,999,999')  # no scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123,000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9,999,999')  # no scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, '123'), '123.0')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123,000.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0.12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0.13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0.000')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0.127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0.127')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0.12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0.13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0.127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0.127')

        # Check with Italian locale
        QLocale.setDefault(QLocale('it'))

        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'),
                         '9.999.999')  # scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123.000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9.999.999')  # scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123.000,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0,12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0,13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0,000')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0,127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0,127')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0,12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0,13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0,127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0,127')

        # Check with custom locale without thousand separator

        custom = QLocale('en')
        custom.setNumberOptions(QLocale.OmitGroupSeparator)
        QLocale.setDefault(custom)

        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'),
                         '9999999')  # scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9999999')  # scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123000.00')

        QgsProject.instance().removeAllMapLayers()
Exemplo n.º 34
0
 def test_doubleValidatorDotLocale(self):
     """Test the double with english locale"""
     QLocale.setDefault(QLocale(QLocale.English))
     assert QLocale().decimalPoint() == '.'
     field = self.vl.fields()[self.vl.fields().indexFromName('double_field')]
     self._fld_checker(field)
Exemplo n.º 35
0
from qgis.PyQt.QtCore import QLocale, QTranslator, QCoreApplication, QSettings
from qgis.PyQt.QtWidgets import QMessageBox

# 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__)))
translation_path = os.path.join(root, 'safe', 'i18n',
                                'inasafe_' + str(locale_name) + '.qm')

if os.path.exists(translation_path):
    translator = QTranslator()
 def installTranslator(self):
     qgis_locale = QLocale(QGIS_LANG)
     locale_path = os.path.join(PLUGIN_DIR, 'i18n')
     self.translator = QTranslator()
     self.translator.load(qgis_locale, 'Asistente-LADM_COL', '_', locale_path)
     QCoreApplication.installTranslator(self.translator)
Exemplo n.º 37
0
    def test_displayString(self):
        """Test the displayString method"""

        # Default locale for tests is EN
        original_locale = QLocale()
        locale = QLocale(QLocale.English)
        locale.setNumberOptions(QLocale.DefaultNumberOptions)
        QLocale().setDefault(locale)

        self.assertEqual(QgsCategorizedSymbolRenderer.displayString(1234.56),
                         "1,234.56")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234.56, 4),
            "1,234.5600")
        self.assertEqual(QgsCategorizedSymbolRenderer.displayString(1234567),
                         "1,234,567")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234567.0, 4),
            "1,234,567.0000")
        # Precision is ignored for integers
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234567, 4),
            "1,234,567")

        # Test list
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString([1234567, 891234], 4),
            "1,234,567;891,234")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(
                [1234567.123, 891234.123], 4), "1,234,567.1230;891,234.1230")

        locale.setNumberOptions(QLocale.OmitGroupSeparator)
        QLocale().setDefault(locale)
        self.assertTrue(QLocale().numberOptions() & QLocale.OmitGroupSeparator)
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString([1234567, 891234], 4),
            "1234567;891234")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(
                [1234567.123, 891234.123], 4), "1234567.1230;891234.1230")

        # Test a non-dot locale
        locale = QLocale(QLocale.Italian)
        locale.setNumberOptions(QLocale.DefaultNumberOptions)
        QLocale().setDefault(locale)
        self.assertEqual(QgsCategorizedSymbolRenderer.displayString(1234.56),
                         "1.234,56")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234.56, 4),
            "1.234,5600")
        self.assertEqual(QgsCategorizedSymbolRenderer.displayString(1234567),
                         "1.234.567")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234567.0, 4),
            "1.234.567,0000")
        # Precision is ignored for integers
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(1234567, 4),
            "1.234.567")

        # Test list
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString([1234567, 891234], 4),
            "1.234.567;891.234")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(
                [1234567.123, 891234.123], 4), "1.234.567,1230;891.234,1230")

        locale.setNumberOptions(QLocale.OmitGroupSeparator)
        QLocale().setDefault(locale)
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString([1234567, 891234], 4),
            "1234567;891234")
        self.assertEqual(
            QgsCategorizedSymbolRenderer.displayString(
                [1234567.123, 891234.123], 4), "1234567,1230;891234,1230")

        QLocale().setDefault(original_locale)
Exemplo n.º 38
0
    def _fld_checker(self, field):
        """
        Expected results from validate
        QValidator::Invalid 0 The string is clearly invalid.
        QValidator::Intermediate 1 The string is a plausible intermediate value.
        QValidator::Acceptable 2 The string is acceptable as a final result; i.e. it is valid.
        """
        DECIMAL_SEPARATOR = QLocale().decimalPoint()
        OTHER_SEPARATOR = ',' if DECIMAL_SEPARATOR == '.' else '.'

        validator = QgsFieldValidator(None, field, '0.0', '')

        def _test(value, expected):
            ret = validator.validate(value, 0)
            self.assertEqual(ret[0], expected, "%s != %s" % (ret[0], expected))
            if value:
                self.assertEqual(
                    validator.validate('-' + value, 0)[0], expected,
                    '-' + value)

        # Valid
        _test('0.1234', QValidator.Acceptable)

        # Apparently we accept comma only when locale say so
        if DECIMAL_SEPARATOR != '.':
            _test('0,1234', QValidator.Acceptable)

        # If precision is > 0, regexp validator is used (and it does not support sci notation)
        if field.precision() == 0:
            _test('12345.1234e+123', QValidator.Acceptable)
            _test('12345.1234e-123', QValidator.Acceptable)
            if DECIMAL_SEPARATOR != '.':
                _test('12345,1234e+123', QValidator.Acceptable)
                _test('12345,1234e-123', QValidator.Acceptable)
            _test('', QValidator.Acceptable)

            # Out of range
            _test('12345.1234e+823', QValidator.Intermediate)
            _test('12345.1234e-823', QValidator.Intermediate)
            if DECIMAL_SEPARATOR != '.':
                _test('12345,1234e+823', QValidator.Intermediate)
                _test('12345,1234e-823', QValidator.Intermediate)

        # Invalid
        _test('12345-1234', QValidator.Invalid)
        _test('onetwothree', QValidator.Invalid)

        int_field = self.vl.fields()[self.vl.fields().indexFromName(
            'int_field')]
        self.assertEqual(int_field.precision(),
                         0)  # this is what the provider reports :(
        self.assertEqual(int_field.length(), 0)  # not set
        self.assertEqual(int_field.type(), QVariant.Int)

        validator = QgsFieldValidator(None, int_field, '0', '')

        # Valid
        _test('0', QValidator.Acceptable)
        _test('1234', QValidator.Acceptable)
        _test('', QValidator.Acceptable)

        # Invalid
        _test('12345-1234', QValidator.Invalid)
        _test('12345%s1234' % DECIMAL_SEPARATOR, QValidator.Invalid)
        _test('onetwothree', QValidator.Invalid)
Exemplo n.º 39
0
    def export_dock_content(self, output_format: OutputFormats):
        """ Export the current displayed metadata sheet to the given format. """
        layer_name = iface.activeLayer().name()

        file_path = os.path.join(
            self.settings.value("UI/lastFileNameWidgetDir"),
            '{name}.{ext}'.format(name=layer_name, ext=output_format.ext)
        )
        output_file = QFileDialog.getSaveFileName(
            self,
            tr("Save File as {format}").format(format=output_format.label),
            file_path,
            "{label} (*.{ext})".format(
                label=output_format.label,
                ext=output_format.ext,
            )
        )
        if output_file[0] == '':
            return

        self.settings.setValue("UI/lastFileNameWidgetDir", os.path.dirname(output_file[0]))

        output_file_path = output_file[0]
        parent_folder = str(Path(output_file_path).parent)

        if output_format == OutputFormats.PDF:
            printer = QPrinter()
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setPageMargins(20, 20, 20, 20, QPrinter.Millimeter)
            printer.setOutputFileName(output_file_path)
            self.viewer.print(printer)
            iface.messageBar().pushSuccess(
                tr("Export PDF"),
                tr(
                    "The metadata has been exported as PDF successfully in "
                    "<a href=\"{}\">{}</a>").format(parent_folder, output_file_path)
            )

        elif output_format in [OutputFormats.HTML, OutputFormats.DCAT]:
            if output_format == OutputFormats.HTML:
                data_str = self.viewer.page().currentFrame().toHtml()
            else:
                sql = self.sql_for_layer(
                    self.current_datasource_uri, output_format=OutputFormats.DCAT)
                data = self.current_connection.executeSql(sql)
                with open(resources_path('xml', 'dcat.xml')) as xml_file:
                    xml_template = xml_file.read()

                locale = QgsSettings().value("locale/userLocale", QLocale().name())
                locale = locale.split('_')[0].lower()

                xml = parseString(xml_template.format(locale=locale, content=data[0][0]))
                data_str = xml.toprettyxml()

            with open(output_file[0], "w") as file_writer:
                file_writer.write(data_str)
            iface.messageBar().pushSuccess(
                tr("Export") + ' ' + output_format.label,
                tr(
                    "The metadata has been exported as {format} successfully in "
                    "<a href=\"{folder}\">{path}</a>").format(
                    format=output_format.label, folder=parent_folder, path=output_file_path)
            )
Exemplo n.º 40
0
 def tearDownClass(cls):
     """Reset locale"""
     QLocale.setDefault(QLocale(QLocale.English))
Exemplo n.º 41
0
    def test_representValue(self):

        layer = QgsVectorLayer("point?field=int:integer&field=double:double&field=long:long",
                               "layer", "memory")
        self.assertTrue(layer.isValid())
        QgsProject.instance().addMapLayers([layer])

        fieldFormatter = QgsRangeFieldFormatter()

        # Precision is ignored for integers and longlongs
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123000'), '123,000')
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'), '9,999,999')  # no scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123,000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9,999,999')  # no scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, '123'), '123.0')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123,000.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0.12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0.13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0.000')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0.127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0.127')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123.00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0.12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0.13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0.127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0.127')

        # Check with Italian locale
        QLocale.setDefault(QLocale('it'))

        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'),
                         '9.999.999')  # scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123.000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9.999.999')  # scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123.000,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0,12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0,13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0,000')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0,127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0,127')

        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123,00')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0,12')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0,13')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0,127')
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0,127')

        # Check with custom locale without thousand separator

        custom = QLocale('en')
        custom.setNumberOptions(QLocale.OmitGroupSeparator)
        QLocale.setDefault(custom)

        self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'),
                         '9999999')  # scientific notation for integers!
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123000')
        self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9999999')  # scientific notation for long longs!
        self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123000.00')

        QgsProject.instance().removeAllMapLayers()
Exemplo n.º 42
0
 def tearDownClass(cls):
     """Reset locale"""
     QLocale.setDefault(QLocale(QLocale.English))
Exemplo n.º 43
0
"""
__author__ = 'Nyall Dawson'
__date__ = '03.02.2016'
__copyright__ = 'Copyright 2016, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = 'fddffb168c7efc390ef8ee12146c6eaaaacd6f2e'

import qgis  # NOQA

from qgis.testing import unittest
from qgis.core import QgsUnitTypes
from qgis.PyQt.QtCore import QLocale

# enforce C locale because the tests expect it
# (decimal separators / thousand separators)
QLocale.setDefault(QLocale.c())


class TestQgsUnitTypes(unittest.TestCase):

    def testDistanceUnitType(self):
        """Test QgsUnitTypes::unitType() """
        expected = {QgsUnitTypes.DistanceMeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceKilometers: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceFeet: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceYards: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceMiles: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceDegrees: QgsUnitTypes.Geographic,
                    QgsUnitTypes.DistanceCentimeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceMillimeters: QgsUnitTypes.Standard,
                    QgsUnitTypes.DistanceUnknownUnit: QgsUnitTypes.UnknownType,
Exemplo n.º 44
0
    def processAlgorithm(self, progress):
        inLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT))
        boundary = self.getParameterValue(self.MODE) == self.MODE_BOUNDARY
        smallestArea = self.getParameterValue(self.MODE) == self.MODE_SMALLEST_AREA
        keepSelection = self.getParameterValue(self.KEEPSELECTION)
        processLayer = vector.duplicateInMemory(inLayer)

        if not keepSelection:
            # Make a selection with the values provided
            attribute = self.getParameterValue(self.ATTRIBUTE)
            comparison = self.comparisons[self.getParameterValue(self.COMPARISON)]
            comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)

            selectindex = vector.resolveFieldIndex(processLayer, attribute)
            selectType = processLayer.fields()[selectindex].type()
            selectionError = False

            if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' % str(comparisonvalue))
            elif selectType == QVariant.Double:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' % str(comparisonvalue))
            elif selectType == QVariant.String:
                # 10: string, boolean
                try:
                    y = str(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to unicode' % str(comparisonvalue))
            elif selectType == QVariant.Date:
                # date
                dateAndFormat = comparisonvalue.split(' ')

                if len(dateAndFormat) == 1:
                    # QDate object
                    y = QLocale.system().toDate(dateAndFormat[0])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with system date format %s' % (str(dateAndFormat), QLocale.system().dateFormat()))
                elif len(dateAndFormat) == 2:
                    y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with format string "%s"' % (str(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessfull
                    selectionError = True
                    msg += self.tr('Enter the date and the date format, e.g. "07.26.2011" "MM.dd.yyyy".')

            if (comparison == 'begins with' or comparison == 'contains') \
               and selectType != QVariant.String:
                selectionError = True
                msg = self.tr('"%s" can only be used with string fields' % comparison)

            selected = []

            if selectionError:
                raise GeoAlgorithmExecutionException(
                    self.tr('Error in selection input: %s' % msg))
            else:
                for feature in processLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                        x = int(aValue)
                    elif selectType == QVariant.Double:
                        x = float(aValue)
                    elif selectType == QVariant.String:
                        # 10: string, boolean
                        x = str(aValue)
                    elif selectType == QVariant.Date:
                        # date
                        x = aValue  # should be date

                    match = False

                    if comparison == '==':
                        match = x == y
                    elif comparison == '!=':
                        match = x != y
                    elif comparison == '>':
                        match = x > y
                    elif comparison == '>=':
                        match = x >= y
                    elif comparison == '<':
                        match = x < y
                    elif comparison == '<=':
                        match = x <= y
                    elif comparison == 'begins with':
                        match = x.startswith(y)
                    elif comparison == 'contains':
                        match = x.find(y) >= 0

                    if match:
                        selected.append(feature.id())

            processLayer.selectByIds(selected)

        if processLayer.selectedFeatureCount() == 0:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
                                   self.tr('%s: (No selection in input layer "%s")' % (self.commandLineName(), self.getParameterValue(self.INPUT))))

        # Keep references to the features to eliminate
        featToEliminate = []
        for aFeat in processLayer.selectedFeatures():
            featToEliminate.append(aFeat)

        # Delete all features to eliminate in processLayer (we won't save this)
        processLayer.startEditing()
        processLayer.deleteSelectedFeatures()

        # ANALYZE
        if len(featToEliminate) > 0:  # Prevent zero division
            start = 20.00
            add = 80.00 / len(featToEliminate)
        else:
            start = 100

        progress.setPercentage(start)
        madeProgress = True

        # We go through the list and see if we find any polygons we can
        # merge the selected with. If we have no success with some we
        # merge and then restart the whole story.
        while madeProgress:  # Check if we made any progress
            madeProgress = False
            featNotEliminated = []

            # Iterate over the polygons to eliminate
            for i in range(len(featToEliminate)):
                feat = featToEliminate.pop()
                geom2Eliminate = feat.geometry()
                bbox = geom2Eliminate.boundingBox()
                fit = processLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(bbox).setSubsetOfAttributes([]))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

                # use prepared geometries for faster intersection tests
                engine = QgsGeometry.createGeometryEngine(geom2Eliminate.geometry())
                engine.prepareGeometry()

                while fit.nextFeature(selFeat):
                    selGeom = selFeat.geometry()

                    if engine.intersects(selGeom.geometry()):
                        # We have a candidate
                        iGeom = geom2Eliminate.intersection(selGeom)

                        if not iGeom:
                            continue

                        if boundary:
                            selValue = iGeom.length()
                        else:
                            # area. We need a common boundary in
                            # order to merge
                            if 0 < iGeom.length():
                                selValue = selGeom.area()
                            else:
                                selValue = -1

                        if -1 != selValue:
                            useThis = True

                            if smallestArea:
                                if -1 == min:
                                    min = selValue
                                else:
                                    if selValue < min:
                                        min = selValue
                                    else:
                                        useThis = False
                            else:
                                if selValue > max:
                                    max = selValue
                                else:
                                    useThis = False

                            if useThis:
                                mergeWithFid = selFeat.id()
                                mergeWithGeom = QgsGeometry(selGeom)
                # End while fit

                if mergeWithFid is not None:
                    # A successful candidate
                    newGeom = mergeWithGeom.combine(geom2Eliminate)

                    if processLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.tr('Could not replace geometry of feature with id %s' % mergeWithFid))

                    start = start + add
                    progress.setPercentage(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(processLayer.fields(),
                                        processLayer.wkbType(), processLayer.crs())

        # Write all features that are left over to output layer
        iterator = processLayer.getFeatures()
        for feature in iterator:
            writer.addFeature(feature)

        # Leave processLayer untouched
        processLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
Exemplo n.º 45
0
 def setUp(self):
     super().setUp()
     QLocale.setDefault(QLocale(QLocale.English))