Exemple #1
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale_str = QSettings().value('locale/userLocale')
        if isinstance(locale_str, str):
            locale = QLocale(locale_str)
        else:
            locale = QLocale()

        locale_path = os.path.join(self.plugin_dir, 'i18n')
        self.translator = QTranslator()
        self.translator.load(locale, 'qfieldsync', '_', locale_path)

        QCoreApplication.installTranslator(self.translator)

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

        # instance of the map config widget factory, shown in layer properties
        self.mapLayerConfigWidgetFactory = MapLayerConfigWidgetFactory('QField', QIcon(os.path.join(os.path.dirname(__file__), 'resources/icon.png')))

        # instance of the QgsOfflineEditing
        self.offline_editing = QgsOfflineEditing()
        self.preferences = Preferences()

        QgsProject.instance().readProject.connect(self.update_button_enabled_status)

        # store warnings from last run
        self.last_action_warnings = []
 def show_help_documentation(self):
     os_language = QLocale(
         QSettings().value("locale/userLocale")).name()[:2]
     if os_language in ["es", "de"]:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/{}/".format(
                 os_language))
     else:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/index.html")
Exemple #3
0
 def show_help_documentation(self):
     os_language = QLocale(
         QSettings().value('locale/userLocale')).name()[:2]
     if os_language in ['es', 'de']:
         webbrowser.open(
             'https://opengisch.github.io/QgisModelBaker/docs/{}/'.format(
                 os_language))
     else:
         webbrowser.open(
             'https://opengisch.github.io/QgisModelBaker/docs/index.html')
 def setUpClass(cls):
     """Run before all tests"""
     QCoreApplication.setOrganizationName("QGIS_Test")
     QCoreApplication.setOrganizationDomain(
         "QGIS_TestQgsDateTimeFieldFormatter.com")
     QCoreApplication.setApplicationName(
         "QGIS_TestQgsDateTimeFieldFormatter")
     QgsSettings().clear()
     QLocale.setDefault(QLocale(QLocale.English))
     start_app()
Exemple #5
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)
 def help_requested(self):
     os_language = QLocale(
         QSettings().value("locale/userLocale")).name()[:2]
     if os_language in ["es", "de"]:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/{}/user-guide.html#export-an-interlis-transfer-file-xtf"
             .format(os_language))
     else:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/user-guide.html#export-an-interlis-transfer-file-xtf"
         )
 def help_requested(self):
     os_language = QLocale(
         QSettings().value('locale/userLocale')).name()[:2]
     if os_language in ['es', 'de']:
         webbrowser.open(
             "https://opengisch.github.io/projectgenerator/docs/{}/user-guide.html#generate-project"
             .format(os_language))
     else:
         webbrowser.open(
             "https://opengisch.github.io/projectgenerator/docs/user-guide.html#generate-project"
         )
Exemple #8
0
 def help_requested(self):
     os_language = QLocale(
         QSettings().value('locale/userLocale')).name()[:2]
     if os_language in ['es', 'de']:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/{}/user-guide.html#plugin-configuration"
             .format(os_language))
     else:
         webbrowser.open(
             "https://opengisch.github.io/QgisModelBaker/docs/user-guide.html#plugin-configuration"
         )
Exemple #9
0
    def open_help(self):
        """ Open the online documentation for the panel. """
        locale = QgsSettings().value("locale/userLocale", QLocale().name())
        locale = locale[0:2]

        if locale not in ONLINE_HELP_LANGUAGES:
            locale = 'en'

        url = '{url}/{lang}/{page}'.format(url=DOC_URL,
                                           lang=locale,
                                           page=self.config.help())
        QDesktopServices.openUrl(QUrl(url))
Exemple #10
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 = """{ "type": "FeatureCollection",
    "features":[
{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198000,
      "date":"2018-09-10"
   }
}
]}"""
        self.assertEqual(exporter.exportFeatures([feature]), 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]), expected)
    def __init__(self, iface):
        QObject.__init__(self)
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        self.generate_dlg = None
        self.export_dlg = None
        self.importdata_dlg = None
        self.workflow_wizard_dlg = None
        self.datasetmanager_dlg = None

        self.__generate_action = None
        self.__export_action = None
        self.__importdata_action = None
        self.__workflow_wizard_action = None
        self.__datasetmanager_action = None
        self.__validate_action = None
        self.__configure_action = None
        self.__help_action = None
        self.__about_action = None
        self.__separator = None
        self.__dataset_selector_action = None
        self.__dataset_selector = None
        self.__validate_dock = None
        basepath = pathlib.Path(__file__).parent.absolute()
        metadata = configparser.ConfigParser()
        metadata.read(os.path.join(basepath, "metadata.txt"))
        self.__version__ = metadata["general"]["version"]
        if locale.getlocale() == (None, None):
            locale.setlocale(locale.LC_ALL, "")

        # initialize translation
        qgis_locale_id = str(QSettings().value("locale/userLocale"))
        qgis_locale = QLocale(qgis_locale_id)
        locale_path = os.path.join(self.plugin_dir, "i18n")
        self.translator = QTranslator()
        self.translator.load(qgis_locale, "QgisModelBaker", "_", locale_path)
        QCoreApplication.installTranslator(self.translator)

        self.ili2db_configuration = BaseConfiguration()
        settings = QSettings()
        settings.beginGroup("QgisModelBaker/ili2db")
        self.ili2db_configuration.restore(settings)

        self.event_filter = DropFileFilter(self)
Exemple #12
0
    def carregaIdioma(self, app, idioma='ca'):
        if app is None:
            return
        self.appQgis = app
        self.idioma = self.paramCfg('Idioma', idioma)
        self.qtTranslator = QTranslator()
        self.qgisTranslator = QTranslator()

        path = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        self.qtTranslator.load("qt_" + idioma, path)
        app.installTranslator(self.qtTranslator)

        path = app.i18nPath()
        path = path.replace('/./', '/')
        self.qgisTranslator.load("qgis_" + idioma, path)
        app.installTranslator(self.qgisTranslator)

        self.locale = QLocale(self.idioma + "-ES")
Exemple #13
0
    def testQgsClassificationLogarithmic(self):
        values = [
            2746.71, 66667.49, 77282.52, 986567.01, 1729508.41, 9957836.86,
            35419826.29, 52584164.80, 296572842.00
        ]

        vl = createMemoryLayer(values)

        m = QgsClassificationLogarithmic()
        r = m.classes(vl, 'value', 8)

        self.assertEqual(len(r), 6)
        self.assertEqual(r[0].label(),
                         '{} - 10^4'.format(QLocale().toString(2746.71)))
        self.assertEqual(QgsClassificationMethod.rangesToBreaks(r), [
            10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0
        ])

        self.assertEqual(len(m.classes(vl, 'value', 4)), 4)
    def test_localizedCategories(self):

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

        layer = QgsVectorLayer(
            "Point?field=flddbl:double&field=fldint:integer", "addfeat",
            "memory")
        result = QgsCategorizedSymbolRenderer.createCategories(
            [1234.5, 2345.6, 3456.7], QgsMarkerSymbol(), layer, 'flddouble')

        self.assertEqual(result[0].label(), '1,234.5')
        self.assertEqual(result[1].label(), '2,345.6')
        self.assertEqual(result[2].label(), '3,456.7')

        # Test a non-dot locale
        QLocale().setDefault(QLocale(QLocale.Italian))

        result = QgsCategorizedSymbolRenderer.createCategories(
            [[1234.5, 6789.1], 2345.6, 3456.7], QgsMarkerSymbol(), layer,
            'flddouble')

        self.assertEqual(result[0].label(), '1.234,5;6.789,1')
        self.assertEqual(result[1].label(), '2.345,6')
        self.assertEqual(result[2].label(), '3.456,7')

        # Test round trip
        temp_dir = QTemporaryDir()
        temp_file = os.path.join(temp_dir.path(), 'project.qgs')

        project = QgsProject()
        layer.setRenderer(QgsCategorizedSymbolRenderer('Class', result))
        project.addMapLayers([layer])
        project.write(temp_file)

        QLocale().setDefault(original_locale)

        project = QgsProject()
        project.read(temp_file)
        results = project.mapLayersByName('addfeat')[0].renderer().categories()

        self.assertEqual(result[0].label(), '1.234,5;6.789,1')
        self.assertEqual(result[1].label(), '2.345,6')
        self.assertEqual(result[2].label(), '3.456,7')
        self.assertEqual(result[0].value(), [1234.5, 6789.1])
        self.assertEqual(result[1].value(), 2345.6)
        self.assertEqual(result[2].value(), 3456.7)
Exemple #15
0
    def __init__(self, parent=None, data=None):
        """
        Constructor

        Creates the dialog, connect events
        """
        super().__init__()
        self.ui = Ui_Settings()
        self.ui.setupUi(self)
        self.api = data["api"]
        metadata = get_plugin_metadata()
        # "Picterra account" tab
        self.ui.api_key_text.setText(get_setting("api_key"))
        self.ui.api_server_text.setText(urlparse(get_api_server()).netloc)
        try:
            if self.api.ping() == 200:
                self.ui.nr_rasters.setText(str(len(self.api.get_rasters())))
                self.ui.nr_detectors.setText(str(len(
                    self.api.get_detectors())))
        except ApiError as e:
            logger.error(str(e))
            self.ui.nr_rasters.setText(tr("N/A"))
            self.ui.nr_detectors.setText(tr("N/A"))
        # "QGIS settings" tab
        self.ui.locale_text.setText(str(QLocale().name()))
        self.ui.sw_version_text.setText(str(Qgis.QGIS_VERSION))
        self.ui.plugin_category_text.setText(str(metadata["category"]))
        self.ui.plugin_version_text.setText(str(metadata["version"]))
        # Rejected-close connection is already in the .ui files
        self.ui.button_box_picterra.button(
            QDialogButtonBox.Apply).clicked.connect(self.save_settings)
        self.ui.button_box_qgis.button(QDialogButtonBox.Apply).clicked.connect(
            self.save_settings)
        self.ui.button_box_picterra.button(
            QDialogButtonBox.RestoreDefaults).clicked.connect(
                self.restore_settings)
        self.ui.button_box_qgis.button(
            QDialogButtonBox.RestoreDefaults).clicked.connect(
                self.restore_settings)
Exemple #16
0
def showPluginDoc(
    packageName: Optional[str] = None, filename: str = "index", section: str = ""
) -> None:
    """
    Shows a help in the user's html browser.

    The help file should be named index-ll_CC.html or index-ll.html
    """
    if get_debug_flag():
        helpfile = os.path.dirname(__file__) + "/help/build/html/index.html"
    else:
        source = ""
        if packageName is None:
            import inspect
            source = inspect.currentframe().f_back.f_code.co_filename  # type: ignore
        else:
            source = sys.modules[packageName].__file__
        path = os.path.dirname(source)
        locale = str(QLocale().name())
        helpfile = os.path.join(path, filename + "-" + locale + ".html")
        if not os.path.exists(helpfile):
            helpfile = os.path.join(
                path,
                filename + "-" + locale.split("_")[0] + ".html")
        if not os.path.exists(helpfile):
            helpfile = os.path.join(path, filename + "-en.html")
        if not os.path.exists(helpfile):
            helpfile = os.path.join(path, filename + "-en_US.html")
        if not os.path.exists(helpfile):
            helpfile = os.path.join(path, filename + ".html")
    if os.path.exists(helpfile):
        url = "file://" + helpfile
        if section != "":
            url = url + "#" + section
        QDesktopServices.openUrl(QUrl(url))
    else:
        logger = Logger(__file__)
        logger.error("No file %s" % helpfile)
Exemple #17
0
    def __init__(self, iface):
        QObject.__init__(self)
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        self.generate_dlg = None
        self.export_dlg = None
        self.importdata_dlg = None

        self.__generate_action = None
        self.__export_action = None
        self.__importdata_action = None
        self.__configure_action = None
        self.__help_action = None
        self.__about_action = None
        self.__separator = None
        basepath = pathlib.Path(__file__).parent.absolute()
        metadata = configparser.ConfigParser()
        metadata.read(os.path.join(basepath, 'metadata.txt'))
        self.__version__ = metadata['general']['version']
        if locale.getlocale() == (None, None):
            locale.setlocale(locale.LC_ALL, '')

        # initialize translation
        qgis_locale_id = str(QSettings().value('locale/userLocale'))
        qgis_locale = QLocale(qgis_locale_id)
        locale_path = os.path.join(self.plugin_dir, 'i18n')
        self.translator = QTranslator()
        self.translator.load(qgis_locale, 'QgisModelBaker', '_', locale_path)
        QCoreApplication.installTranslator(self.translator)

        self.ili2db_configuration = BaseConfiguration()
        settings = QSettings()
        settings.beginGroup('QgisModelBaker/ili2db')
        self.ili2db_configuration.restore(settings)

        self.event_filter = DropFileFilter(self)
    def test_representValueWithDefault(self):
        """
        Check representValue behaves correctly when used on a layer which define default values
        """

        dbname = os.path.join(tempfile.mkdtemp(), 'test.sqlite')
        con = spatialite_connect(dbname, isolation_level=None)
        cur = con.cursor()
        cur.execute("BEGIN")
        sql = """
        CREATE TABLE test_table_default_values (
            id integer primary key autoincrement,
            anumber INTEGER DEFAULT 123
        )
        """
        cur.execute(sql)
        cur.execute("COMMIT")
        con.close()

        vl = QgsVectorLayer(dbname + '|layername=test_table_default_values',
                            'test_table_default_values', 'ogr')
        self.assertTrue(vl.isValid())

        fieldFormatter = QgsFallbackFieldFormatter()

        QLocale.setDefault(QLocale('en'))

        self.assertEqual(
            fieldFormatter.representValue(vl, 1, {}, None,
                                          QVariant(QVariant.Int)), 'NULL')
        self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, 4),
                         '4')
        self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, "123"),
                         '123')
        # bad field index
        self.assertEqual(fieldFormatter.representValue(vl, 3, {}, None, 5), "")
Exemple #19
0
def showPluginHelp(packageName: str = None,
                   filename: str = "index",
                   section: str = ""):
    """Open help in the user's html browser. The help file should be named index-ll_CC.html or index-ll.html or index.html.

    :param str packageName: name of package folder, if None it's using the current file package. Defaults to None. Optional.
    :param str filename: name of file to open. It can be a path like 'doc/index' for example. Defaults to 'index'.
    :param str section: URL path to open. Defaults to empty string.
    """
    try:
        source = ""
        if packageName is None:
            import inspect

            source = inspect.currentframe().f_back.f_code.co_filename
        else:
            source = sys.modules[packageName].__file__
    except:
        return
    path = os.path.dirname(source)
    locale = str(QLocale().name())
    helpfile = os.path.join(path, filename + "-" + locale + ".html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(
            path, filename + "-" + locale.split("_")[0] + ".html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + "-en.html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + "-en_US.html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + ".html")
    if os.path.exists(helpfile):
        url = "file://" + helpfile
        if section != "":
            url = url + "#" + section
        QDesktopServices.openUrl(QUrl(url))
Exemple #20
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')
Exemple #21
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()
Exemple #22
0
 def tearDownClass(cls):
     """Reset locale"""
     QLocale.setDefault(QLocale(QLocale.English))
Exemple #23
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)
Exemple #24
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)
Exemple #25
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)
Exemple #26
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:
Exemple #27
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)
Exemple #28
0
    def layers(self, filter_layer_list=[]):
        tables_info = self.get_tables_info_without_ignored_tables()
        basket_handling = self.get_basket_handling()
        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

        # When a table has multiple geometry columns, it will be loaded multiple times (supported e.g. by PostGIS).
        table_appearance_count = {}

        for record in tables_info:
            if self.schema:
                if record["schemaname"] != self.schema:
                    continue
            if filter_layer_list and record[
                    "tablename"] not in filter_layer_list:
                continue
            table_appearance_count[record["tablename"]] = (
                table_appearance_count.get(record["tablename"], 0) + 1)

        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

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

            is_domain = (record.get("kind_settings") == "ENUM"
                         or record.get("kind_settings") == "CATALOGUE")
            is_attribute = bool(record.get("attribute_name"))
            is_structure = record.get("kind_settings") == "STRUCTURE"
            is_nmrel = record.get("kind_settings") == "ASSOCIATION"
            is_basket_table = (record.get("tablename") ==
                               self._db_connector.basket_table_name)
            is_dataset_table = (record.get("tablename") ==
                                self._db_connector.dataset_table_name)

            alias = record["table_alias"] if "table_alias" in record else None
            if not alias:
                short_name = None
                if is_domain and is_attribute:
                    short_name = ""
                    if "ili_name" in record and record["ili_name"]:
                        short_name = (record["ili_name"].split(".")[-2] + "_" +
                                      record["ili_name"].split(".")[-1])
                else:
                    if (table_appearance_count[record["tablename"]] > 1
                            and "geometry_column" in record):
                        # multiple layers for this table - append geometry column to name
                        fields_info = self.get_fields_info(record["tablename"])
                        for field_info in fields_info:
                            if field_info["column_name"] == record[
                                    "geometry_column"]:
                                if ("fully_qualified_name" in field_info and
                                        field_info["fully_qualified_name"]):
                                    short_name = (
                                        field_info["fully_qualified_name"].
                                        split(".")[-2] + " (" +
                                        field_info["fully_qualified_name"].
                                        split(".")[-1] + ")")
                                else:
                                    short_name = record["tablename"]
                    elif "ili_name" in record and record["ili_name"]:
                        match = re.search(r"([^\(]*).*", record["ili_name"])
                        if match.group(0) == match.group(1):
                            short_name = match.group(1).split(".")[-1]
                        else:
                            # additional brackets in the the name - extended layer in geopackage
                            short_name = (match.group(1).split(".")[-2] +
                                          " (" +
                                          match.group(1).split(".")[-1] + ")")
                alias = short_name

            model_topic_name = ""
            if "ili_name" in record and record["ili_name"]:
                if record["ili_name"].count(".") > 1:
                    model_topic_name = f"{record['ili_name'].split('.')[0]}.{record['ili_name'].split('.')[1]}"

            display_expression = ""
            if is_basket_table:
                display_expression = "coalesce(attribute(get_feature('{dataset_layer_name}', '{tid}', dataset), 'datasetname') || ' (' || topic || ') ', coalesce( attribute(get_feature('{dataset_layer_name}', '{tid}', dataset), 'datasetname'), {tilitid}))".format(
                    tid=self._db_connector.tid,
                    tilitid=self._db_connector.tilitid,
                    dataset_layer_name=self._db_connector.dataset_table_name,
                )
            elif "ili_name" in record and record["ili_name"]:
                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"]

            coord_decimals = (record["coord_decimals"]
                              if "coord_decimals" in record else None)
            coordinate_precision = None
            if coord_decimals:
                coordinate_precision = 1 / (10**coord_decimals)

            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,
                coordinate_precision,
                is_basket_table,
                is_dataset_table,
                model_topic_name,
            )

            # Configure fields for current table
            fields_info = self.get_fields_info(record["tablename"])
            min_max_info = self.get_min_max_info(record["tablename"])
            value_map_info = self.get_value_map_info(record["tablename"])
            re_iliname = re.compile(r".*\.(.*)$")

            for fielddef in fields_info:
                column_name = fielddef["column_name"]
                fully_qualified_name = (fielddef["fully_qualified_name"]
                                        if "fully_qualified_name" in fielddef
                                        else None)
                m = (re_iliname.match(fully_qualified_name)
                     if fully_qualified_name 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

                if not basket_handling and column_name in BASKET_FIELDNAMES:
                    hide_attribute = True

                field.hidden = hide_attribute

                if column_name in READONLY_FIELDNAMES:
                    field.read_only = True

                if column_name in min_max_info:
                    field.widget = "Range"
                    field.widget_config["Min"] = min_max_info[column_name][0]
                    field.widget_config["Max"] = min_max_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 column_name in value_map_info:
                    field.widget = "ValueMap"
                    field.widget_config["map"] = [{
                        val: val
                    } for val in value_map_info[column_name]]

                if "attr_mapping" in fielddef and fielddef[
                        "attr_mapping"] == "ARRAY":
                    field.widget = "List"

                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"]

                if basket_handling and column_name in BASKET_FIELDNAMES:
                    if self.tool in [
                            DbIliMode.pg,
                            DbIliMode.ili2pg,
                            DbIliMode.mssql,
                            DbIliMode.ili2mssql,
                    ]:
                        schema_topic_identificator = slugify(
                            f"{layer.source().host()}_{layer.source().database()}_{layer.source().schema()}_{model_topic_name}"
                        )
                        field.default_value_expression = (
                            f"@{schema_topic_identificator}")
                    elif self.tool in [DbIliMode.ili2gpkg, DbIliMode.gpkg]:
                        schema_topic_identificator = slugify(
                            f"@{layer.source().uri().split('|')[0].strip()}_{model_topic_name}"
                        )
                        field.default_value_expression = (
                            f"@{schema_topic_identificator}")

                if "enum_domain" in fielddef and fielddef["enum_domain"]:
                    field.enum_domain = fielddef["enum_domain"]

                layer.fields.append(field)

            layers.append(layer)

        self.print_messages()

        return layers
Exemple #29
0
    def __init__(self):
        if hasattr(self, 'gh'):                     # Se inicializa una vez
            return

        self.gh = None
        self.ruta, self.rutaBase = self.calcRuta()  # Path de la aplicación
        self.cfg = self.readCfg()                   # Config de instalación
        val = self.paramCfg("Debug", "False")       # Errores no controlados
        if val != "True":
            sys.excepthook = _fatalError

        self.entorn = self.calcEntorn()             # 'DSV' o 'PRO'

        self.usuari = getpass.getuser().upper()     # Id de usuario
        self.sessio = str(uuid.uuid1())             # Id único de sesión

        self.intranet = self.calcIntranet()         # True si en la intranet
        self.dbQvista = _DB_QVISTA[self.entorn]     # Conexión Oracle entorno
        self.dbGeo = QvSqlite().dbGeoConnexio()     # Conexión Geocod SQlite

        self.proxy = self.setProxy()                # Establecer proxy

        val = self.paramCfg('Log', 'False')         # Activación log
        if val == 'True':
            self.log = True
        else:
            self.log = False

        val = self.paramCfg('Github', 'False')      # Establecer rama Github
        if val == 'False':
            self.github = None
        elif val == 'True':
            self.github = 'master'
        else:
            self.github = val

        if self.github is None:
            self.gh = None
        else:
            val = self.paramCfg('Id', '')
            self.gh = QvGithub(self.data(), self.github, val)

        val = self.paramCfg('Stdout', 'False')      # Activación fichero salida
        if val == 'True':
            try:
                # print(os.getcwd())
                sys.stdout = open('../Salida.txt', 'w')
            except Exception:
                print('Error al redirigir stdout')

        self.dbLog = None
        self.queryLog = None
        self.familyLog = None
        self.nameLog = None
        self.queryGeo = None
        self.appQgis = None
        self.idioma = None
        self.qtTranslator = None
        self.qgisTranslator = None
        self.locale = QLocale("ca-ES")

        QgsPythonRunner.setInstance(QvPythonRunner())   # Ejecuciones Python
Exemple #30
0
    def layers(self, filter_layer_list=[]):
        tables_info = self.get_tables_info()
        layers = list()

        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

            if self.tool_name == 'ili2pg':
                provider = 'postgres'
                if record['geometry_column']:
                    data_source_uri = '{uri} key={primary_key} estimatedmetadata=true srid={srid} type={type} table="{schema}"."{table}" ({geometry_column})'.format(
                        uri=self.uri,
                        primary_key=record['primary_key'],
                        srid=record['srid'],
                        type=record['type'],
                        schema=record['schemaname'],
                        table=record['tablename'],
                        geometry_column=record['geometry_column'])
                else:
                    data_source_uri = '{uri} key={primary_key} table="{schema}"."{table}"'.format(
                        uri=self.uri,
                        primary_key=record['primary_key'],
                        schema=record['schemaname'],
                        table=record['tablename'])
            elif self.tool_name == 'ili2gpkg':
                provider = 'ogr'
                data_source_uri = '{uri}|layername={table}'.format(
                    uri=self.uri, table=record['tablename'])

            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_nmrel = record[
                'kind_settings'] == 'ASSOCIATION' if 'kind_settings' in record else False
            layer = Layer(
                provider, data_source_uri, record['tablename'],
                record['geometry_column'],
                QgsWkbTypes.parseType(record['type']) or QgsWkbTypes.Unknown,
                alias, is_domain, is_nmrel)

            # 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

                if column_name in IGNORED_FIELDNAMES:
                    field.widget = 'Hidden'

                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]
                    # field.widget_config['Suffix'] = fielddef['unit'] if 'unit' in fielddef else ''
                    if 'unit' in fielddef:
                        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

                layer.fields.append(field)

            layers.append(layer)

        return layers