def new_db(self, set_locale=False):
        if not set_locale:
            set_locale = utils.getcurrentlocale()

        filenamepath = os.path.join(os.path.dirname(__file__),"metadata.txt" )
        iniText = QSettings(filenamepath , QSettings.IniFormat)
        verno = str(iniText.value('version')) 
        from .create_tolkn_db import newdb
        newdbinstance = newdb(verno, set_locale=set_locale)
        if not newdbinstance.dbpath=='':
            self.db = newdbinstance.dbpath
    def new_db(self, set_locale=False):
        if not set_locale:
            set_locale = utils.getcurrentlocale()

        filenamepath = os.path.join(os.path.dirname(__file__), "metadata.txt")
        iniText = QSettings(filenamepath, QSettings.IniFormat)
        verno = str(iniText.value('version'))
        from .create_tolkn_db import newdb
        newdbinstance = newdb(verno, set_locale=set_locale)
        if not newdbinstance.dbpath == '':
            self.db = newdbinstance.dbpath
    def upgrade_db(self, set_locale=False):
        from_db = None
        #get full path to the original db to be updated
        if self.db:
            use_current_db = utils.Askuser(
                "YesNo", """Do you want to upgrade %s?""" % self.db,
                'Current database?')
            if use_current_db.result == 0:
                from_db = None
            elif use_current_db.result == 1:
                from_db = self.db
            elif use_current_db.result == '':
                return
        if not from_db:
            from_db = QFileDialog.getOpenFileName(
                None, 'Ange tolknings-db som ska exporteras', '',
                "Spatialite (*.sqlite)")[0]
        if not from_db:
            QApplication.restoreOverrideCursor()
            return None

        #get EPSG in the original db
        EPSG = utils.sql_load_fr_db(
            """SELECT srid FROM geom_cols_ref_sys WHERE Lower(f_table_name) = Lower('gvmag') AND Lower(f_geometry_column) = Lower('geometry')""",
            from_db)

        #preparations to create new db of new design
        if not set_locale:
            set_locale = utils.getcurrentlocale()

        filenamepath = os.path.join(os.path.dirname(__file__), "metadata.txt")
        iniText = QSettings(filenamepath, QSettings.IniFormat)
        verno = str(iniText.value('version'))

        #now create database of the updated design
        from .create_tolkn_db import newdb
        newdbinstance = newdb(verno,
                              user_select_CRS=False,
                              EPSG_code=EPSG[1][0][0],
                              set_locale=set_locale)

        #transfer data to the new database
        foo = utils.UpgradeDatabase(from_db, newdbinstance.dbpath, EPSG)

        #set new database as the current db and load these layers
        if not newdbinstance.dbpath == '':
            self.db = newdbinstance.dbpath
        self.load_the_layers()
Example #4
0
    def load_and_select_general_settings(self):     # TODO: remove in version 1.4
        locales = [QLocale(QLocale.Swedish, QLocale.Sweden), QLocale(QLocale.English, QLocale.UnitedStates)]
        current_locale = utils.getcurrentlocale()[0]
        items_set = set()
        items_set.add(current_locale)
        items_set.update([localeobj.name() for localeobj in locales])
        items = [u'']
        items.extend(sorted(list(items_set)))

        self.locale_combobox.addItems(items)
        if current_locale:
            idx = self.locale_combobox.findText(current_locale)
            try:
                self.locale_combobox.setCurrentIndex(idx)
            except:
                pass
def PlotHatchDict():
    """
    This dictionary is used by sectionplot (matplotlib) for relating the geoshort names with hatches in plots
    The user may update these fields in the zz_strat table to use other hatches
    Fallback method use dictionary defined in the code below
    """
    success, Dict = utils.create_dict_from_db_2_cols(("strata", "hatch_mplot", "zz_stratigraphy_plots"))
    if not success:
        print("fallback method with PlotHatchDict from code")
        # hatch patterns : ('-', '+', 'x', '\\', '*', 'o', 'O', '.','/')
        if utils.getcurrentlocale() == "sv_SE":  # swedish forms are loaded only if locale settings indicate sweden
            Dict = {
                u"Okänt": u"",
                "Berg": u"x",
                "Grovgrus": u"O",
                "Grus": u"O",
                "Mellangrus": u"o",
                "Fingrus": u"o",
                "Grovsand": u"*",
                "Sand": u"*",
                "Mellansand": u".",
                "Finsand": u".",
                "Silt": u"\\",
                "Lera": u"-",
                u"Morän": u"/",
                "Torv": u"+",
                "Fyll": u"+",
            }
        else:
            Dict = {
                u"Unknown": u"",
                "Rock": u"x",
                "Coarse gravel": u"O",
                "Gravel": u"O",
                "Medium gravel": u"o",
                "Fine gravel": u"o",
                "Coarse sand": u"*",
                "Sand": u"*",
                "Medium sand": u".",
                "Fine sand": u".",
                "Silt": u"\\",
                "Clay": u"-",
                "Till": u"/",
                "Peat": u"+",
                "Fill": u"+",
            }
    return Dict
def PlotColorDict():
    """
    This dictionary is used by sectionplot (matplotlib) for relating the geoshort names with color codes
    The user may update these fields in the zz_strat table to use other colors
    Fallback method use dictionary defined in the code below
    """
    success, Dict = utils.create_dict_from_db_2_cols(("strata", "color_mplot", "zz_stratigraphy_plots"))
    if not success:
        print("fallback method with PlotColorDict from code")
        if utils.getcurrentlocale() == "sv_SE":  # swedish forms are loaded only if locale settings indicate sweden
            Dict = {
                u"Okänt": u"white",
                "Berg": u"red",
                "Grovgrus": u"DarkGreen",
                "Grus": u"DarkGreen",
                "Mellangrus": u"DarkGreen",
                "Fingrus": u"DarkGreen",
                "Grovsand": u"green",
                "Sand": u"green",
                "Mellansand": u"green",
                "Finsand": u"DarkOrange",
                "Silt": u"yellow",
                "Lera": u"yellow",
                u"Morän": u"cyan",
                "Torv": u"DarkGray",
                "Fyll": u"white",
            }
        else:
            Dict = {
                u"Unknown": u"white",
                "Rock": u"red",
                "Coarse gravel": u"DarkGreen",
                "Gravel": u"DarkGreen",
                "Medium gravel": u"DarkGreen",
                "Fine gravel": u"DarkGreen",
                "Coarse sand": u"green",
                "Sand": u"green",
                "Medium sand": u"green",
                "Fine sand": u"DarkOrange",
                "Silt": u"yellow",
                "Clay": u"yellow",
                "Till": u"cyan",
                "Peat": u"DarkGray",
                "Fill": u"white",
            }
    # print Dict#debug!
    return Dict
def apply_style(layer, stylename):
    # now try to load the style file
    stylefile_sv = os.path.join(os.sep, os.path.dirname(__file__), "..", "definitions","{}_sv.qml".format(stylename))
    stylefile = os.path.join(os.sep, os.path.dirname(__file__), "..", "definitions", "{}.qml".format(stylename))
    if utils.getcurrentlocale()[0] == 'sv_SE' and os.path.isfile(stylefile_sv):  # swedish forms are loaded only if locale settings indicate sweden
        try:
            layer.loadNamedStyle(stylefile_sv)
        except:
            try:
                layer.loadNamedStyle(stylefile)
            except:
                pass
    else:
        try:
            layer.loadNamedStyle(stylefile)
        except:
            pass
    def upgrade_db(self, set_locale=False):
        from_db = None
        #get full path to the original db to be updated
        if self.db:
            use_current_db = utils.Askuser("YesNo","""Do you want to upgrade %s?"""%self.db,'Current database?')
            if use_current_db.result == 0:
                from_db = None
            elif use_current_db.result == 1:
                from_db = self.db
            elif use_current_db.result == '':
                return
        if not from_db:
            from_db = QFileDialog.getOpenFileName(None, 'Ange tolknings-db som ska exporteras','',"Spatialite (*.sqlite)")[0]
        if not from_db:
            QApplication.restoreOverrideCursor()
            return None

        #get EPSG in the original db
        EPSG = utils.sql_load_fr_db("""SELECT srid FROM geom_cols_ref_sys WHERE Lower(f_table_name) = Lower('gvmag') AND Lower(f_geometry_column) = Lower('geometry')""",from_db)

        #preparations to create new db of new design
        if not set_locale:
            set_locale = utils.getcurrentlocale()

        filenamepath = os.path.join(os.path.dirname(__file__),"metadata.txt" )
        iniText = QSettings(filenamepath , QSettings.IniFormat)
        verno = str(iniText.value('version'))

        #now create database of the updated design
        from .create_tolkn_db import newdb
        newdbinstance = newdb(verno, user_select_CRS=False, EPSG_code = EPSG[1][0][0], set_locale=set_locale)

        #transfer data to the new database
        foo = utils.UpgradeDatabase(from_db,newdbinstance.dbpath, EPSG)

        #set new database as the current db and load these layers
        if not newdbinstance.dbpath=='':
            self.db = newdbinstance.dbpath
        self.load_the_layers()
Example #9
0
    def add_layers_new_method(self):
        try:#qgis>=2.4
            if self.group_name == 'Midvatten_OBS_DB':
                position_index = 0
            else:
                position_index = 1
            MyGroup = self.root.insertGroup(position_index, self.group_name)
        except:#qgis < 2.4
            MyGroup = self.legend.addGroup (self.group_name,1,-1)
        uri = QgsDataSourceURI()
        uri.setDatabase(self.settingsdict['database'])
        canvas = self.iface.mapCanvas()
        layer_list = []
        map_canvas_layer_list=[]

        if self.group_name == 'Midvatten_OBS_DB':
            for tablename in self.default_nonspatlayers: #first load all non-spatial layers
                uristring= 'dbname="' + self.settingsdict['database'] + '" table="' + tablename + '"'
                layer = QgsVectorLayer(uristring,tablename, 'spatialite')
                layer_list.append(layer)

            for tablename in self.default_layers:    # then all the spatial ones
                uri.setDataSource('',tablename, 'Geometry')
                layer = QgsVectorLayer(uri.uri(), tablename, 'spatialite') # Adding the layer as 'spatialite' instead of ogr vector layer is preferred
                layer_list.append(layer)

        elif self.group_name == 'Midvatten_data_domains': #if self.group_name == 'Midvatten_data_domains':
            conn_ok, dd_tables = utils.sql_load_fr_db("select name from sqlite_master where name like 'zz_%'")
            if not conn_ok:
                return
            d_domain_tables = [str(dd_table[0]) for dd_table in dd_tables]
            for tablename in d_domain_tables:
                uristring= 'dbname="' + self.settingsdict['database'] + '" table="' + tablename + '"'
                layer = QgsVectorLayer(uristring,tablename, 'spatialite')
                layer_list.append(layer)

        #now loop over all the layers and set styles etc
        for layer in layer_list:
            if not layer.isValid():
                utils.pop_up_info(layer.name() + ' is not valid layer')
                print(layer.name() + ' is not valid layer')
                pass
            else:
                map_canvas_layer_list.append(QgsMapCanvasLayer(layer))
                try:#qgis>=2.4
                    QgsMapLayerRegistry.instance().addMapLayers([layer],False)
                    MyGroup.insertLayer(0,layer)
                    #MyGroup.addLayer(layer)
                except:#qgis<2.4
                    QgsMapLayerRegistry.instance().addMapLayers([layer])
                    group_index = self.legend.groups().index(self.group_name) 
                    self.legend.moveLayer (self.legend.layers()[0],group_index)

                if self.group_name == 'Midvatten_OBS_DB':
                    layer.setEditorLayout(1)#perhaps this is unnecessary since it gets set from the loaded qml below?

                #now try to load the style file
                stylefile_sv = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",layer.name() + "_sv.qml")
                stylefile = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",layer.name() + ".qml")
                if  utils.getcurrentlocale()[0] == 'sv_SE' and os.path.isfile( stylefile_sv ): #swedish forms are loaded only if locale settings indicate sweden
                    try:
                        layer.loadNamedStyle(stylefile_sv)
                    except:
                        try:
                            layer.loadNamedStyle(stylefile)
                        except:
                            pass
                else:
                    try:
                        layer.loadNamedStyle(stylefile)
                    except:
                        pass

                if layer.name() == 'obs_points':#zoom to obs_points extent
                    obsp_lyr = layer
                    canvas.setExtent(layer.extent())
                elif layer.name() == 'w_lvls_last_geom':#we do not want w_lvls_last_geom to be visible by default
                    self.legend.setLayerVisible(layer,False)
                else:
                    pass

        #finally refresh canvas
        canvas.refresh()
Example #10
0
 def add_layers_old_method(self):
     """
     this method is depreceated and should no longer be used
     """
     try:    #newstyle
         MyGroup = self.legend.addGroup ("Midvatten_OBS_DB",1,-1)
     except: #olddstyle
         MyGroup = self.legend.addGroup ("Midvatten_OBS_DB")
     uri = QgsDataSourceURI()
     uri.setDatabase(self.settingsdict['database'])#MacOSX fix1 #earlier sent byte string, now intending to send unicode string
     for tablename in self.default_nonspatlayers:    # first the non-spatial tables, THEY DO NOT ALL HAVE CUSTOM UI FORMS
         firststring= 'dbname="' + self.settingsdict['database'] + '" table="' + tablename + '"'#MacOSX fix1  #earlier sent byte string, now unicode
         layer = QgsVectorLayer(firststring,tablename, 'spatialite')   # Adding the layer as 'spatialite' and not ogr vector layer is preferred
         if not layer.isValid():
             qgis.utils.iface.messageBar().pushMessage("Error","""Failed to load layer %s!"""%tablename,2)
         else:
             QgsMapLayerRegistry.instance().addMapLayers([layer])
             group_index = self.legend.groups().index('Midvatten_OBS_DB') 
             self.legend.moveLayer (self.legend.layers()[0],group_index)
             filename = tablename + ".qml"       #  load styles
             stylefile = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",filename)
             layer.loadNamedStyle(stylefile)
             if tablename in ('w_levels','w_flow','stratigraphy'):
                 if  utils.getcurrentlocale()[0] == 'sv_SE': #swedish forms are loaded only if locale settings indicate sweden
                     filename = tablename + ".ui"
                 else:
                     filename = tablename + "_en.ui"
                 try: # python bindings for setEditorLayout were introduced in qgis-master commit 9183adce9f257a097fc54e5a8a700e4d494b2962 november 2012
                     layer.setEditorLayout(2)
                 except:
                     pass
                 uifile = os.path.join(os.sep,os.path.dirname(__file__),"..","ui",filename)
                 layer.setEditForm(uifile)
                 formlogic = "form_logics." + tablename + "_form_open"
                 layer.setEditFormInit(formlogic)
     for tablename in self.default_layers:    # then the spatial ones, NOT ALL HAVE CUSTOM UI FORMS
         uri.setDataSource('',tablename, 'Geometry')
         layer = QgsVectorLayer(uri.uri(), tablename, 'spatialite') # Adding the layer as 'spatialite' instead of ogr vector layer is preferred
         if not layer.isValid():
             qgis.utils.iface.messageBar().pushMessage("Error","""Failed to load layer %s!"""%tablename,2)                
         else:
             filename = tablename + ".qml"
             stylefile = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",filename)
             layer.loadNamedStyle(stylefile)
             if tablename in defs.get_subset_of_tables_fr_db(category='default_layers_w_ui'):        #=   THE ONES WITH CUSTOM UI FORMS
                 if utils.getcurrentlocale()[0] == 'sv_SE': #swedish forms are loaded only if locale settings indicate sweden
                     filename = tablename + ".ui"
                 else:
                     filename = tablename + "_en.ui"
                 uifile = os.path.join(os.sep,os.path.dirname(__file__),"..","ui",filename)
                 try: # python bindings for setEditorLayout were introduced in qgis-master commit 9183adce9f257a097fc54e5a8a700e4d494b2962 november 2012
                     layer.setEditorLayout(2)  
                 except:
                     pass
                 layer.setEditForm(uifile)
                 if tablename in ('obs_points','obs_lines'):
                     formlogic = "form_logics." + tablename + "_form_open"
                     layer.setEditFormInit(formlogic)     
             QgsMapLayerRegistry.instance().addMapLayers([layer])
             group_index = self.legend.groups().index('Midvatten_OBS_DB')   # SIPAPI UPDATE 2.0
             self.legend.moveLayer (self.legend.layers()[0],group_index)
             if tablename == 'obs_points':#zoom to obs_points extent
                 qgis.utils.iface.mapCanvas().setExtent(layer.extent())
             elif tablename == 'w_lvls_last_geom':#we do not want w_lvls_last_geom to be visible by default
                 self.legend.setLayerVisible(layer,False)
    def add_layers_new_method(self):
        if self.group_name == 'Midvatten_OBS_DB':
            position_index = 0
        else:
            position_index = 1
        MyGroup = qgis.core.QgsLayerTreeGroup(name=self.group_name,
                                              checked=True)
        self.root.insertChildNode(position_index, MyGroup)
        dbconnection = db_utils.DbConnectionManager()

        canvas = self.iface.mapCanvas()
        layer_list = []
        if self.group_name == 'Midvatten_OBS_DB':
            add_layers_to_list(layer_list,
                               self.default_nonspatlayers,
                               dbconnection=dbconnection)
            add_layers_to_list(layer_list,
                               self.default_layers,
                               geometrycolumn='geometry',
                               dbconnection=dbconnection)

        elif self.group_name == 'Midvatten_data_domains':  #if self.group_name == 'Midvatten_data_domains':
            tables_columns = db_utils.tables_columns()
            d_domain_tables = [
                x for x in list(tables_columns.keys()) if x.startswith('zz_')
            ]
            add_layers_to_list(layer_list,
                               d_domain_tables,
                               dbconnection=dbconnection)

        w_lvls_last_geom = None

        #now loop over all the layers and set styles etc
        for layer in layer_list:
            # TODO: Made this a comment, but there might be some hidden feature thats still needed!
            #map_canvas_layer_list.append(QgsMapCanvasLayer(layer))

            QgsProject.instance().addMapLayers([layer], False)
            MyGroup.insertLayer(0, layer)
            #MyGroup.addLayer(layer)

            #TODO: Check if this isn't needed.
            #if self.group_name == 'Midvatten_OBS_DB':
            #    layer.setEditorLayout(1) #perhaps this is unnecessary since it gets set from the loaded qml below?

            #now try to load the style file
            stylefile_sv = os.path.join(os.sep, os.path.dirname(__file__),
                                        "..", "definitions",
                                        layer.name() + "_sv.qml")
            stylefile = os.path.join(os.sep, os.path.dirname(__file__), "..",
                                     "definitions",
                                     layer.name() + ".qml")
            if utils.getcurrentlocale()[0] == 'sv_SE' and os.path.isfile(
                    stylefile_sv
            ):  #swedish forms are loaded only if locale settings indicate sweden
                try:
                    layer.loadNamedStyle(stylefile_sv)
                except:
                    try:
                        layer.loadNamedStyle(stylefile)
                    except:
                        pass
            else:
                try:
                    layer.loadNamedStyle(stylefile)
                except:
                    pass

            if layer.name() == 'obs_points':  #zoom to obs_points extent
                obsp_lyr = layer
                canvas.setExtent(layer.extent())
            elif layer.name() == 'w_lvls_last_geom':
                w_lvls_last_geom = layer

        if w_lvls_last_geom is not None:
            midv = self.root.findGroup('Midvatten_OBS_DB')
            w_lvls_last_geom = MyGroup.findLayer(w_lvls_last_geom)
            w_lvls_last_geom.setItemVisibilityCheckedRecursive(False)

        #finally refresh canvas
        dbconnection.closedb()
        canvas.refresh()
 def add_layers_old_method(self):
     """
     this method is depreceated and should no longer be used
     """
     try:  #newstyle
         MyGroup = self.legend.addGroup("Midvatten_OBS_DB", 1, -1)
     except:  #olddstyle
         MyGroup = self.legend.addGroup("Midvatten_OBS_DB")
     uri = QgsDataSourceUri()
     uri.setDatabase(
         self.settingsdict['database']
     )  #MacOSX fix1 #earlier sent byte string, now intending to send unicode string
     for tablename in self.default_nonspatlayers:  # first the non-spatial tables, THEY DO NOT ALL HAVE CUSTOM UI FORMS
         firststring = 'dbname="' + self.settingsdict[
             'database'] + '" table="' + tablename + '"'  #MacOSX fix1  #earlier sent byte string, now unicode
         layer = QgsVectorLayer(
             firststring, self.dbtype
         )  # Adding the layer as 'spatialite' and not ogr vector layer is preferred
         if not layer.isValid():
             utils.MessagebarAndLog.critical(
                 bar_msg='Error, Failed to load layer %s!' % tablename)
         else:
             QgsProject.instance().addMapLayers([layer])
             group_index = self.legend.groups().index('Midvatten_OBS_DB')
             self.legend.moveLayer(self.legend.layers()[0], group_index)
             filename = tablename + ".qml"  #  load styles
             stylefile = os.path.join(os.sep, os.path.dirname(__file__),
                                      "..", "definitions", filename)
             layer.loadNamedStyle(stylefile)
             if tablename in ('w_levels', 'w_flow', 'stratigraphy'):
                 if utils.getcurrentlocale(
                 )[0] == 'sv_SE':  #swedish forms are loaded only if locale settings indicate sweden
                     filename = tablename + ".ui"
                 else:
                     filename = tablename + "_en.ui"
                 try:  # python bindings for setEditorLayout were introduced in qgis-master commit 9183adce9f257a097fc54e5a8a700e4d494b2962 november 2012
                     layer.setEditorLayout(2)
                 except:
                     pass
                 uifile = os.path.join(os.sep, os.path.dirname(__file__),
                                       "..", "ui", filename)
                 layer.setEditForm(uifile)
                 formlogic = "form_logics." + tablename + "_form_open"
                 layer.setEditFormInit(formlogic)
     for tablename in self.default_layers:  # then the spatial ones, NOT ALL HAVE CUSTOM UI FORMS
         uri.setDataSource('', tablename, 'Geometry')
         layer = QgsVectorLayer(
             uri.uri(), self.dbtype
         )  # Adding the layer as 'spatialite' instead of ogr vector layer is preferred
         if not layer.isValid():
             utils.MessagebarAndLog.critical(
                 bar_msg='Error, Failed to load layer %s!' % tablename)
         else:
             filename = tablename + ".qml"
             stylefile = os.path.join(os.sep, os.path.dirname(__file__),
                                      "..", "definitions", filename)
             layer.loadNamedStyle(stylefile)
             if tablename in defs.get_subset_of_tables_fr_db(
                     category='default_layers_w_ui'
             ):  #=   THE ONES WITH CUSTOM UI FORMS
                 if utils.getcurrentlocale(
                 )[0] == 'sv_SE':  #swedish forms are loaded only if locale settings indicate sweden
                     filename = tablename + ".ui"
                 else:
                     filename = tablename + "_en.ui"
                 uifile = os.path.join(os.sep, os.path.dirname(__file__),
                                       "..", "ui", filename)
                 try:  # python bindings for setEditorLayout were introduced in qgis-master commit 9183adce9f257a097fc54e5a8a700e4d494b2962 november 2012
                     layer.setEditorLayout(2)
                 except:
                     pass
                 layer.setEditForm(uifile)
                 if tablename in ('obs_points', 'obs_lines'):
                     formlogic = "form_logics." + tablename + "_form_open"
                     layer.setEditFormInit(formlogic)
             QgsProject.instance().addMapLayers([layer])
             group_index = self.legend.groups().index(
                 'Midvatten_OBS_DB')  # SIPAPI UPDATE 2.0
             self.legend.moveLayer(self.legend.layers()[0], group_index)
             if tablename == 'obs_points':  #zoom to obs_points extent
                 qgis.utils.iface.mapCanvas().setExtent(layer.extent())
             elif tablename == 'w_lvls_last_geom':  #we do not want w_lvls_last_geom to be visible by default
                 self.legend.setLayerVisible(layer, False)
Example #13
0
    def add_layers_new_method(self):
        try:  #qgis>=2.4
            if self.group_name == 'Midvatten_OBS_DB':
                position_index = 0
            else:
                position_index = 1
            MyGroup = self.root.insertGroup(position_index, self.group_name)
        except:  #qgis < 2.4
            MyGroup = self.legend.addGroup(self.group_name, 1, -1)

        dbconnection = db_utils.DbConnectionManager()
        uri = dbconnection.uri
        dbtype = dbconnection.dbtype
        schema = dbconnection.schemas()
        #For QgsVectorLayer, dbtype has to be postgres instead of postgis
        dbtype = db_utils.get_dbtype(dbtype)

        canvas = self.iface.mapCanvas()
        layer_list = []
        map_canvas_layer_list = []
        if self.group_name == 'Midvatten_OBS_DB':
            self.add_layers_to_list(layer_list, uri, schema,
                                    self.default_nonspatlayers, dbtype)
            self.add_layers_to_list(layer_list, uri, schema,
                                    self.default_layers, dbtype, 'geometry')

        elif self.group_name == 'Midvatten_data_domains':  #if self.group_name == 'Midvatten_data_domains':
            tables_columns = db_utils.tables_columns()
            d_domain_tables = [
                x for x in tables_columns.keys() if x.startswith(u'zz_')
            ]
            self.add_layers_to_list(layer_list, uri, schema, d_domain_tables,
                                    dbtype)

        #now loop over all the layers and set styles etc
        for layer in layer_list:
            map_canvas_layer_list.append(QgsMapCanvasLayer(layer))
            try:  #qgis>=2.4
                QgsMapLayerRegistry.instance().addMapLayers([layer], False)
                MyGroup.insertLayer(0, layer)
                #MyGroup.addLayer(layer)
            except:  #qgis<2.4
                QgsMapLayerRegistry.instance().addMapLayers([layer])
                group_index = self.legend.groups().index(self.group_name)
                self.legend.moveLayer(self.legend.layers()[0], group_index)

            if self.group_name == 'Midvatten_OBS_DB':
                layer.setEditorLayout(
                    1
                )  #perhaps this is unnecessary since it gets set from the loaded qml below?

            #now try to load the style file
            stylefile_sv = os.path.join(os.sep, os.path.dirname(__file__),
                                        "..", "definitions",
                                        layer.name() + "_sv.qml")
            stylefile = os.path.join(os.sep, os.path.dirname(__file__), "..",
                                     "definitions",
                                     layer.name() + ".qml")
            if utils.getcurrentlocale()[0] == 'sv_SE' and os.path.isfile(
                    stylefile_sv
            ):  #swedish forms are loaded only if locale settings indicate sweden
                try:
                    layer.loadNamedStyle(stylefile_sv)
                except:
                    try:
                        layer.loadNamedStyle(stylefile)
                    except:
                        pass
            else:
                try:
                    layer.loadNamedStyle(stylefile)
                except:
                    pass

            if layer.name() == 'obs_points':  #zoom to obs_points extent
                obsp_lyr = layer
                canvas.setExtent(layer.extent())
            elif layer.name(
            ) == 'w_lvls_last_geom':  #we do not want w_lvls_last_geom to be visible by default
                self.legend.setLayerVisible(layer, False)
            else:
                pass

        #finally refresh canvas
        canvas.refresh()
    def add_layers_new_method(self):
        if self.group_name == 'Midvatten_OBS_DB':
            position_index = 0
        else:
            position_index = 1
        MyGroup = qgis.core.QgsLayerTreeGroup(name=self.group_name, checked=True)
        self.root.insertChildNode(position_index, MyGroup)
        dbconnection = db_utils.DbConnectionManager()

        canvas = self.iface.mapCanvas()
        layer_list = []
        if self.group_name == 'Midvatten_OBS_DB':
            add_layers_to_list(layer_list, self.default_nonspatlayers, dbconnection=dbconnection)
            add_layers_to_list(layer_list, self.default_layers, geometrycolumn='geometry',
                               dbconnection=dbconnection)

        elif self.group_name == 'Midvatten_data_domains': #if self.group_name == 'Midvatten_data_domains':
            tables_columns = db_utils.tables_columns()
            d_domain_tables = [x for x in list(tables_columns.keys()) if x.startswith('zz_')]
            add_layers_to_list(layer_list, d_domain_tables, dbconnection=dbconnection)

        w_lvls_last_geom = None

        #now loop over all the layers and set styles etc
        for layer in layer_list:
            # TODO: Made this a comment, but there might be some hidden feature thats still needed!
            #map_canvas_layer_list.append(QgsMapCanvasLayer(layer))

            QgsProject.instance().addMapLayers([layer],False)
            MyGroup.insertLayer(0,layer)
            #MyGroup.addLayer(layer)

            #TODO: Check if this isn't needed.
            #if self.group_name == 'Midvatten_OBS_DB':
            #    layer.setEditorLayout(1) #perhaps this is unnecessary since it gets set from the loaded qml below?

            #now try to load the style file
            stylefile_sv = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",layer.name() + "_sv.qml")
            stylefile = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",layer.name() + ".qml")
            if  utils.getcurrentlocale()[0] == 'sv_SE' and os.path.isfile( stylefile_sv ): #swedish forms are loaded only if locale settings indicate sweden
                try:
                    layer.loadNamedStyle(stylefile_sv)
                except:
                    try:
                        layer.loadNamedStyle(stylefile)
                    except:
                        pass
            else:
                try:
                    layer.loadNamedStyle(stylefile)
                except:
                    pass

            if layer.name() == 'obs_points':#zoom to obs_points extent
                obsp_lyr = layer
                canvas.setExtent(layer.extent())
            elif layer.name() == 'w_lvls_last_geom':
                w_lvls_last_geom = layer

        if w_lvls_last_geom is not None:
            midv = self.root.findGroup('Midvatten_OBS_DB')
            w_lvls_last_geom = MyGroup.findLayer(w_lvls_last_geom)
            w_lvls_last_geom.setItemVisibilityCheckedRecursive(False)

        #finally refresh canvas
        dbconnection.closedb()
        canvas.refresh()
def PlotTypesDict(international="no"):
    """
    This dictionary is used by sectionplot (matplotlib) to compare with all possible geoshorts in stratigraphy table
    (Also used to generate dictionaries for stratigraphy plot (Qt))
    Default method is to read the database table zz_strat and generate the dictionary from columns 'strat' and 'geoshorts'
    The user may update these fields in the zz_strat table to use other stratigraphy units and other abbreviations (in geoshorts)
    Fallback method use dictionary defined in the code below
    """
    # success, Dict = utils.create_dict_from_db_2_cols(('strata','geoshort','zz_strat'))
    success, Dict = utils.get_sql_result_as_dict("select strata, geoshort from zz_strat")
    succss_strata, strata_order = utils.sql_load_fr_db("select strata from zz_stratigraphy_plots order by ROWID")
    if not success:
        print("fallback method using PlotTypesDict from code")
        if international == "no" and utils.getcurrentlocale() == "sv_SE":
            """
            Dict = {u"Okänt" : u"not in ('berg','b','rock','ro','grovgrus','grg','coarse gravel','cgr','grus','gr','gravel','mellangrus','grm','medium gravel','mgr','fingrus','grf','fine gravel','fgr','grovsand','sag','coarse sand','csa','sand','sa','mellansand','sam','medium sand','msa','finsand','saf','fine sand','fsa','silt','si','lera','ler','le','clay','cl','morän','moran','mn','till','ti','torv','t','peat','pt','fyll','fyllning','f','made ground','mg','land fill')",
            "Berg"  : u"in ('berg','b','rock','ro')",
            "Grovgrus" : u"in ('grovgrus','grg','coarse gravel','cgr')",
            "Grus" : u"in ('grus','gr','gravel')",
            "Mellangrus" : u"in ('mellangrus','grm','medium gravel','mgr')",
            "Fingrus" : u"in ('fingrus','grf','fine gravel','fgr')",
            "Grovsand" : u"in ('grovsand','sag','coarse sand','csa')",
            "Sand" : u"in ('sand','sa')",
            "Mellansand" : u"in ('mellansand','sam','medium sand','msa')",
            "Finsand" : u"in ('finsand','saf','fine sand','fsa')",
            "Silt" : u"in ('silt','si')",
            "Lera" : u"in ('lera','ler','le','clay','cl')",
            u"Morän" : u"in ('morän','moran','mn','till','ti')",
            "Torv" : u"in ('torv','t','peat','pt')",
            "Fyll":u"in ('fyll','fyllning','f','made ground','mg','land fill')"}
            """
            dictionary = OrderedDict(
                [
                    (
                        u"Okänt",
                        u"not in ('berg','b','rock','ro','grovgrus','grg','coarse gravel','cgr','grus','gr','gravel','mellangrus','grm','medium gravel','mgr','fingrus','grf','fine gravel','fgr','grovsand','sag','coarse sand','csa','sand','sa','mellansand','sam','medium sand','msa','finsand','saf','fine sand','fsa','silt','si','lera','ler','le','clay','cl','morän','moran','mn','till','ti','torv','t','peat','pt','fyll','fyllning','f','made ground','mg','land fill')",
                    ),
                    ("Berg", u"in ('berg','b','rock','ro')"),
                    ("Grovgrus", u"in ('grovgrus','grg','coarse gravel','cgr')"),
                    ("Grus", u"in ('grus','gr','gravel')"),
                    ("Mellangrus", u"in ('mellangrus','grm','medium gravel','mgr')"),
                    ("Fingrus", u"in ('fingrus','grf','fine gravel','fgr')"),
                    ("Grovsand", u"in ('grovsand','sag','coarse sand','csa')"),
                    ("Sand", u"in ('sand','sa')"),
                    ("Mellansand", u"in ('mellansand','sam','medium sand','msa')"),
                    ("Finsand", u"in ('finsand','saf','fine sand','fsa')"),
                    ("Silt", u"in ('silt','si')"),
                    ("Lera", u"in ('lera','ler','le','clay','cl')"),
                    (u"Morän", u"in ('morän','moran','mn','till','ti')"),
                    ("Torv", u"in ('torv','t','peat','pt')"),
                    ("Fyll", u"in ('fyll','fyllning','f','made ground','mg','land fill')"),
                ]
            )
        else:
            """
            Dict = {u"Unknown" : u"not in ('berg','b','rock','ro','grovgrus','grg','coarse gravel','cgr','grus','gr','gravel','mellangrus','grm','medium gravel','mgr','fingrus','grf','fine gravel','fgr','grovsand','sag','coarse sand','csa','sand','sa','mellansand','sam','medium sand','msa','finsand','saf','fine sand','fsa','silt','si','lera','ler','le','clay','cl','morän','moran','mn','till','ti','torv','t','peat','pt','fyll','fyllning','f','made ground','mg','land fill')",
            "Rock"  : u"in ('berg','b','rock','ro')",
            "Coarse gravel" : u"in ('grovgrus','grg','coarse gravel','cgr')",
            "Gravel" : u"in ('grus','gr','gravel')",
            "Medium gravel" : u"in ('mellangrus','grm','medium gravel','mgr')",
            "Fine gravel" : u"in ('fingrus','grf','fine gravel','fgr')",
            "Coarse sand" : u"in ('grovsand','sag','coarse sand','csa')",
            "Sand" : u"in ('sand','sa')",
            "Medium sand" : u"in ('mellansand','sam','medium sand','msa')",
            "Fine sand" : u"in ('finsand','saf','fine sand','fsa')",
            "Silt" : u"in ('silt','si')",
            "Clay" : u"in ('lera','ler','le','clay','cl')",
            "Till" : u"in ('morän','moran','mn','till','ti')",
            "Peat" : u"in ('torv','t','peat','pt')",
            "Fill":u"in ('fyll','fyllning','f','made ground','mg','land fill')"}
            """
            dictionary = OrderedDict(
                [
                    (
                        "Unknown",
                        u"not in ('berg','b','rock','ro','grovgrus','grg','coarse gravel','cgr','grus','gr','gravel','mellangrus','grm','medium gravel','mgr','fingrus','grf','fine gravel','fgr','grovsand','sag','coarse sand','csa','sand','sa','mellansand','sam','medium sand','msa','finsand','saf','fine sand','fsa','silt','si','lera','ler','le','clay','cl','morän','moran','mn','till','ti','torv','t','peat','pt','fyll','fyllning','f','made ground','mg','land fill')",
                    ),
                    ("Rock", u"in ('berg','b','rock','ro')"),
                    ("Coarse gravel", u"in ('grovgrus','grg','coarse gravel','cgr')"),
                    ("Gravel", u"in ('grus','gr','gravel')"),
                    ("Medium gravel", u"in ('mellangrus','grm','medium gravel','mgr')"),
                    ("Fine gravel", u"in ('fingrus','grf','fine gravel','fgr')"),
                    ("Coarse sand", u"in ('grovsand','sag','coarse sand','csa')"),
                    ("Sand", u"in ('sand','sa')"),
                    ("Medium sand", u"in ('mellansand','sam','medium sand','msa')"),
                    ("Fine sand", u"in ('finsand','saf','fine sand','fsa')"),
                    ("Silt", u"in ('silt','si')"),
                    ("Clay", u"in ('lera','ler','le','clay','cl')"),
                    ("Till", u"in ('morän','moran','mn','till','ti')"),
                    ("Peat", u"in ('torv','t','peat','pt')"),
                    ("Fill", u"in ('fyll','fyllning','f','made ground','mg','land fill')"),
                ]
            )
    else:
        """manually create dictionary to reuse old code"""
        dictionary = OrderedDict({})
        # all_geoshorts = r"""not in ('"""
        # for key, value in sorted(Dict.iteritems()):
        for strata in strata_order:
            tl = r"""in ('"""
            for geoshort in Dict[strata[0]]:
                tl += geoshort[0] + r"""', '"""
                # all_geoshorts+=geoshort[0] + r"""', '"""
            tl = utils.rstrip(r""", '""", tl) + r""")"""
            # all_geoshorts = utils.rstrip(r""", '""",all_geoshorts) + r""")"""
            dictionary[strata[0]] = tl
        # all_geoshorts+=r"""')"""
    return dictionary