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
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)
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
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), '6000 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), '3000 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), '2640 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 deg') self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceDegrees, False), '1.0 deg') self.assertEqual(QgsDistanceArea.formatDistance(1.0, 1, QgsUnitTypes.DistanceUnknownUnit, False), '1.0') QLocale.setDefault(QLocale.system())
def qgisLocale(): settings = QSettings() overrideLocale = settings.value("locale/overrideFlag", False, bool) if overrideLocale: return settings.value("locale/userLocale", "") else: return QLocale.system().name()[:2]
def __init__(self, iface): 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)
def qgisLocale(): settings = QSettings(); overrideLocale = settings.value("locale/overrideFlag", False, bool) if overrideLocale: return settings.value("locale/userLocale", "") else: return QLocale.system().name()[:2]
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())
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).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 __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 = []
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())
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 __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 = []
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
def existLocaleConfig(): overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) locale = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '') name = f_name.format( locale=locale ) fileConfig = os.path.join( dirname, name ) if os.path.exists( fileConfig ): return { 'isOk': True, 'fileConfig': fileConfig } return { 'isOk': False }
def getFile(): overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) localeFullName = QLocale.system().name( ) if not overrideLocale else QSettings().value( 'locale/userLocale', '') qmPathFile = f"i18n/{pluginName}_{localeFullName}.qm" pluginPath = os.path.dirname(__file__) translationFile = f"{pluginPath}/{qmPathFile}" return translationFile
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)
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'))
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/photo2shape')) else: QDesktopServices.openUrl( QUrl('https://github.com/alexbruy/photo2shape'))
def helpUrl(self): # helpPath = ChloeUtils.chloeHelpPath() # if helpPath == '': # return None # if os.path.exists(helpPath): # return QUrl.fromLocalFile(os.path.join(helpPath, '{}.html'.format(self.commandName()))).toString() # else: # return helpPath + '{}.html'.format(self.commandName()) localeName = QLocale.system().name() helpFilename = self.name() + "_" + localeName + ".html" helpfile = os.path.dirname( __file__ ) + os.sep + "." + os.sep + "help_algorithm" + os.sep + helpFilename return helpfile
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)
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/photo2shape_{}.qm'.format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator)
def openHelp(self): overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value('locale/userLocale', '') localeShortName = localeFullName[0:2] if localeShortName in ['ru', 'uk']: QDesktopServices.openUrl( QUrl('http://gis-lab.info/qa/osmpoly.html')) else: QDesktopServices.openUrl( QUrl('http://gis-lab.info/qa/osmpoly-en.html'))
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) pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) if overrideLocale: qmPathFilepattern = os.path.join('i18n', '{0}_{1}_*.qm'.format(namePlugin, QSettings().value('locale/userLocale', ''))) qmfiles = glob.glob(os.path.join(pp, qmPathFilepattern)) if qmfiles: translationFile = sorted(qmfiles)[0] QgsApplication.messageLog().logMessage( ("QGIS location overried is activated. Using the first found translationfile for pattern {}.".format(qmPathFilepattern)), 'Midvatten', level=Qgis.Info) else: QgsApplication.messageLog().logMessage( ("QGIS location overried is activated. No translation file found using pattern {}, no translation file installed!".format(qmPathFilepattern)), 'Midvatten', level=Qgis.Info) return else: localeFullName = QLocale.system().name() qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName)) 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)
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 locale(): """Get the name of the currently active locale. :returns: Name of hte locale e.g. 'id' :rtype: str """ override_flag = QSettings().value('locale/overrideFlag', True, type=bool) if override_flag: locale_name = QSettings().value('locale/userLocale', 'en_US', type=str) else: # noinspection PyArgumentList 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] return locale_name
def setup_i18n(the_preferred_locale=None): """ Setup internationalisation for the plugin. See if QGIS wants to override the system locale and then see if we can get a valid translation file for whatever locale is effectively being used. @param the_preferred_locale will override any other locale setting """ logger = logging.getLogger(__name__) my_override_flag = QSettings().value('locale/overrideFlag', False, type=bool) my_locale_name = None if the_preferred_locale is not None: my_locale_name = the_preferred_locale logger.info('Using preferred locale: ' + my_locale_name) elif my_override_flag: my_locale_name = QSettings().value('locale/userLocale', '') logger.info('Using QGIS override locale: ' + my_locale_name) else: my_locale_name = QLocale.system().name() # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc my_locale_name = str(my_locale_name) logger.info('Using system default locale: ' + my_locale_name) # Insert into QT's translation system # As soon as translator gets deleted, the translation will stop # Therefore, QCoreApplication is set as parent to not delete it # while the application is running (but we might end up loading # the same translation twice) translator = QTranslator(QCoreApplication.instance()) my_translator_file = 'qgepplugin_' + my_locale_name my_result = translator.load(my_translator_file, 'i18n') if my_result: QCoreApplication.instance().installTranslator(translator)
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, logo, title, **kwargs): from qgis.core import QgsApplication from qgis.PyQt.QtWidgets import QApplication from qgis.PyQt.QtGui import QFont, QIcon from qgis.PyQt.QtCore import QLocale, QTranslator try: import qgis.PyQt.QtSql except ImportError: pass # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv self.app = QgsApplication(argvb, True) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core if "register_widgets" not in kwargs: register_widgets = True else: register_widgets = False if register_widgets: roam.editorwidgets.core.registerallwidgets() import roam.qgisfunctions return self
def run(self): localeName = QLocale.system().name() for suf in ['pres', 'dev']: htmlFilepath = os.path.join( pluginPath, '..', 'help_algorithm', 'about_' + suf + '_' + localeName + '.html') with open(htmlFilepath, 'r') as htmlFile: html = htmlFile.read() webView = getattr(self, 'webView_' + suf) webView.setHtml( html.decode('UTF-8'), QUrl.fromLocalFile( os.path.join(pluginPath, '..', 'help_algorithm', 'images'))) webView.page().setLinkDelegationPolicy( QWebPage.DelegateExternalLinks) self.setWindowTitle(self.title) self.exec_() return True
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)
def _calc_size(self): realSize = self.realsize canvaswidth = self.canvas.width() mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel()) mapunits = self.canvas.mapUnits() prefered_units = roam.config.settings.get("prefer_units", "meters") newunits = Qgis.fromLiteral(prefered_units, Qgis.Meters) mapunitsperpixel *= Qgis.fromUnitToUnitFactor(mapunits, newunits) mapunits = newunits # Convert the real distance into pixels barwidth = realSize / mapunitsperpixel if barwidth < 30: barwidth = canvaswidth / 4 while barwidth > canvaswidth / 3: barwidth /= 3 realSize = barwidth * mapunitsperpixel # Round powerof10 = math.floor(math.log10(realSize)) scaler = math.pow(10.0, powerof10) realSize = round(realSize / scaler) * scaler barwidth = realSize / mapunitsperpixel label, realSize = self._label_size(mapunits, realSize) metrics = QFontMetrics(self.font) fontwidth = metrics.width(label) fontheight = metrics.height() sizelabel = QLocale.system().toString(realSize) sizelabel = "{} {}".format(sizelabel, label) barwidth = self._adjust_bar_size(barwidth, mapunits) barwidth = barwidth + fontwidth return barwidth, realSize, sizelabel, (fontwidth, fontheight)
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
def __init__(self, iface): self.iface = iface self.settings = None QgsSettings().setValue("vogisprofiltoolmain/isopen", False) 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)
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
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):
def testFormatDistance(self): """Test formatting distances""" QLocale.setDefault(QLocale.c()) self.assertEqual(QgsDistanceArea.formatDistance(45, 3, QGis.Meters), u'45.000 m') self.assertEqual( QgsDistanceArea.formatDistance(1300, 1, QGis.Meters, False), u'1.3 km') self.assertEqual( QgsDistanceArea.formatDistance(.005, 1, QGis.Meters, False), u'5.0 mm') self.assertEqual( QgsDistanceArea.formatDistance(.05, 1, QGis.Meters, False), u'5.0 cm') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 3, QGis.Kilometers, True), u'1.500 km') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 3, QGis.Kilometers, False), u'1.500 km') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 3, QGis.Kilometers, True), u'0.500 km') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 3, QGis.Kilometers, False), u'500.000 m') self.assertEqual( QgsDistanceArea.formatDistance(6000, 0, QGis.Feet, True), u'6,000 ft') self.assertEqual( QgsDistanceArea.formatDistance(6000, 3, QGis.Feet, False), u'1.136 mi') self.assertEqual( QgsDistanceArea.formatDistance(300, 0, QGis.Feet, True), u'300 ft') self.assertEqual( QgsDistanceArea.formatDistance(300, 0, QGis.Feet, False), u'300 ft') self.assertEqual( QgsDistanceArea.formatDistance(3000, 0, QGis.Yards, True), u'3,000 yd') self.assertEqual( QgsDistanceArea.formatDistance(3000, 3, QGis.Yards, False), u'1.705 mi') self.assertEqual( QgsDistanceArea.formatDistance(300, 0, QGis.Yards, True), u'300 yd') self.assertEqual( QgsDistanceArea.formatDistance(300, 0, QGis.Yards, False), u'300 yd') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 3, QGis.Miles, True), u'1.500 mi') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 3, QGis.Miles, False), u'1.500 mi') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 3, QGis.Miles, True), u'0.500 mi') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 0, QGis.Miles, False), u'2,640 ft') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 1, QGis.NauticalMiles, True), u'0.5 NM') self.assertEqual( QgsDistanceArea.formatDistance(0.5, 1, QGis.NauticalMiles, False), u'0.5 NM') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 1, QGis.NauticalMiles, True), u'1.5 NM') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 1, QGis.NauticalMiles, False), u'1.5 NM') self.assertEqual( QgsDistanceArea.formatDistance(1.5, 1, QGis.Degrees, True), u'1.5 degrees') self.assertEqual( QgsDistanceArea.formatDistance(1.0, 1, QGis.Degrees, False), u'1.0 degree') self.assertEqual( QgsDistanceArea.formatDistance(1.0, 1, QGis.UnknownUnit, False), u'1.0') QLocale.setDefault(QLocale.system())
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)
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)
def locale(values, feature, parent): return QSettings().value("locale/userLocale", QLocale.system().name())
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()