예제 #1
0
    def init_config(self):

        # initialize plugin directory
        user_folder = os.path.expanduser("~")
        self.plugin_name = 'giswater'
        self.plugin_dir = os.path.join(
            user_folder, '.qgis2/python/plugins/' + self.plugin_name)

        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: " + setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            self.close()
            return

        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            return

        self.schema_name = self.controller.getSchemaName()
        self.dao = self.controller.getDao()
예제 #2
0
    def initConfig(self):

        self.node_id = utils_giswater.getStringValue2("node_id")
        self.epa_type = utils_giswater.getSelectedItem("epa_type")

        # initialize plugin directory
        user_folder = os.path.expanduser("~")
        self.plugin_name = 'giswater'
        self.plugin_dir = os.path.join(
            user_folder, '.qgis2/python/plugins/' + self.plugin_name)

        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: " + setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            self.close()
            return

        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Get widget controls
        self.cbo_cat_nodetype_id = self.dialog.findChild(
            QComboBox, "cat_nodetype_iddd")
        self.cbo_nodecat_id = self.dialog.findChild(QComboBox, "nodecat_id")
        self.tab_analysis = self.dialog.findChild(QTabWidget, "tab_analysis")
        self.tab_event = self.dialog.findChild(QTabWidget, "tab_event")

        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            return

        self.schema_name = self.controller.getSchemaName()
        self.dao = self.controller.getDao()

        # Manage tab visibility
        self.setTabsVisibility()

        # Manage i18n
        self.translateForm()

        # Fill combo 'node type' from 'epa_type'
        self.fillNodeType()

        # Load data from related tables
        self.loadData()

        # Set layer in editing mode
        self.layer.startEditing()
예제 #3
0
    def __init__(self, iface):
        ''' Constructor 
        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        '''
        super(Giswater, self).__init__()

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

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

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   self.plugin_name + '_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()
        self.dao = self.controller.getDao()
        self.schema_name = self.controller.getSchemaName()

        # Declare instance attributes
        self.icon_folder = self.plugin_dir + '/icons/'
        self.actions = {}
        self.search_plus = None

        # {function_name, map_tool}
        self.map_tools = {}

        # Define signals
        self.set_signals()
예제 #4
0
 def init_config(self):    
     
     # initialize plugin directory
     user_folder = os.path.expanduser("~") 
     self.plugin_name = 'giswater'  
     self.plugin_dir = os.path.join(user_folder, '.qgis2/python/plugins/'+self.plugin_name)    
     
     # Get config file
     setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
     if not os.path.isfile(setting_file):
         message = "Config file not found at: "+setting_file
         self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5)  
         self.close()
         return
         
     self.settings = QSettings(setting_file, QSettings.IniFormat)
     self.settings.setIniCodec(sys.getfilesystemencoding())
     
     # Set controller to handle settings and database connection
     # TODO: Try to make only one connection
     self.controller = DaoController(self.settings, self.plugin_name, iface)
     status = self.controller.set_database_connection()      
     if not status:
         message = self.controller.getLastError()
         self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5) 
         return 
          
     self.schema_name = self.settings.value("db/schema_name")           
     self.dao = self.controller.dao
예제 #5
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
        '''
        super(Giswater, self).__init__()
        
        # Save reference to the QGIS interface
        self.iface = iface
        self.legend = iface.legendInterface()    
            
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)    
        self.plugin_name = os.path.basename(self.plugin_dir)   

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n', self.plugin_name+'_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
         
        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())    
        
        # Declare instance attributes
        self.icon_folder = self.plugin_dir+'/icons/'        
        self.actions = {}
        self.map_tools = {}
        self.search_plus = None
        self.srid = None
        
        # Set controller to handle settings and database connection
        self.controller = DaoController(self.settings, self.plugin_name, self.iface)
        
        # Check if config file exists    
        if not os.path.exists(setting_file):
            msg = "Config file not found at: "+setting_file
            self.controller.show_message(msg, 1, 100) 
            return    
        
        # Check connection status   
        connection_status = self.controller.set_database_connection()
        self.dao = self.controller.dao        
        if not connection_status:
            msg = self.controller.last_error  
            self.controller.show_message(msg, 1, 100) 
            return 
        
        # Set actions classes
        self.ed = Ed(self.iface, self.settings, self.controller, self.plugin_dir)
        self.mg = Mg(self.iface, self.settings, self.controller, self.plugin_dir)
        
        # Define signals
        self.set_signals()
 def initConfig(self):    
     
     self.node_id = utils_giswater.getStringValue2("node_id")
     self.epa_type = utils_giswater.getSelectedItem("epa_type")
         
     # initialize plugin directory
     user_folder = os.path.expanduser("~") 
     self.plugin_name = 'giswater'  
     self.plugin_dir = os.path.join(user_folder, '.qgis2/python/plugins/'+self.plugin_name)    
     
     # Get config file
     setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
     if not os.path.isfile(setting_file):
         message = "Config file not found at: "+setting_file
         self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5)  
         self.close()
         return
         
     self.settings = QSettings(setting_file, QSettings.IniFormat)
     self.settings.setIniCodec(sys.getfilesystemencoding())
     
     # Get widget controls
     self.cbo_cat_nodetype_id = self.dialog.findChild(QComboBox, "cat_nodetype_iddd")      
     self.cbo_nodecat_id = self.dialog.findChild(QComboBox, "nodecat_id")   
     self.tab_analysis = self.dialog.findChild(QTabWidget, "tab_analysis")            
     self.tab_event = self.dialog.findChild(QTabWidget, "tab_event")         
     
     # Set controller to handle settings and database connection
     # TODO: Try to make only one connection
     self.controller = DaoController(self.settings, self.plugin_name)
     status = self.controller.set_database_connection()      
     if not status:
         message = self.controller.getLastError()
         self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5) 
         return 
          
     self.schema_name = self.controller.getSchemaName()            
     self.dao = self.controller.getDao()
          
     # Manage tab visibility
     self.setTabsVisibility()
     
     # Manage i18n
     self.translateForm()
     
     # Fill combo 'node type' from 'epa_type'
     self.fillNodeType()
     
     # Load data from related tables
     self.loadData()
     
     # Set layer in editing mode
     self.layer.startEditing()
예제 #7
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
        '''
        super(Giswater, self).__init__()
        
        # Save reference to the QGIS interface
        self.iface = iface
        self.legend = iface.legendInterface()    
            
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)    
        self.plugin_name = os.path.basename(self.plugin_dir)   

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n', self.plugin_name+'_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
         
        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())    
        
        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()     
        self.dao = self.controller.getDao()     
        self.schema_name = self.controller.getSchemaName()      
        
        # Declare instance attributes
        self.icon_folder = self.plugin_dir+'/icons/'        
        self.actions = {}
        self.search_plus = None
        
        # {function_name, map_tool}
        self.map_tools = {}
        
        # Define signals
        self.set_signals()
class NodeDialog():   
    
    def __init__(self, iface, dialog, layer, feature):
        self.iface = iface
        self.dialog = dialog
        self.layer = layer
        self.feature = feature
        self.initConfig()
    
        
    def initConfig(self):    
        
        self.node_id = utils_giswater.getStringValue2("node_id")
        self.epa_type = utils_giswater.getSelectedItem("epa_type")
            
        # initialize plugin directory
        user_folder = os.path.expanduser("~") 
        self.plugin_name = 'giswater'  
        self.plugin_dir = os.path.join(user_folder, '.qgis2/python/plugins/'+self.plugin_name)    
        
        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: "+setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5)  
            self.close()
            return
            
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())
        
        # Get widget controls
        self.cbo_cat_nodetype_id = self.dialog.findChild(QComboBox, "cat_nodetype_iddd")      
        self.cbo_nodecat_id = self.dialog.findChild(QComboBox, "nodecat_id")   
        self.tab_analysis = self.dialog.findChild(QTabWidget, "tab_analysis")            
        self.tab_event = self.dialog.findChild(QTabWidget, "tab_event")         
        
        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()      
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5) 
            return 
             
        self.schema_name = self.controller.getSchemaName()            
        self.dao = self.controller.getDao()
             
        # Manage tab visibility
        self.setTabsVisibility()
        
        # Manage i18n
        self.translateForm()
        
        # Fill combo 'node type' from 'epa_type'
        self.fillNodeType()
        
        # Load data from related tables
        self.loadData()
        
        # Set layer in editing mode
        self.layer.startEditing()
            
            
    def translateForm(self):
        
        # Get objects of type: QLabel
        context_name = 'ws_node'
        widget_list = self.dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translateWidget(context_name, widget)
            
            
    def translateWidget(self, context_name, widget):
        
        if widget:
            widget_name = widget.objectName()
            text = utils_giswater.tr(context_name, widget_name)
            if text != widget_name:
                widget.setText(text)        
        
   
    def loadData(self):
        # Tab 'Add. info'
        if self.epa_type == 'TANK':
            sql = "SELECT vmax, area FROM "+self.schema_name+".man_tank WHERE node_id = "+self.node_id
            row = self.dao.get_row(sql)
            if row:
                utils_giswater.setText("man_tank_vmax", str(row[0]))
                utils_giswater.setText("man_tank_area", str(row[1]))
        
        
        
    ''' Slots '''  
    
    def fillNodeType(self):
        """ Define and execute query to populate combo 'cat_nodetype_id' """
        cat_nodetype_id = utils_giswater.getSelectedItem("cat_nodetype_id")     
        sql = "SELECT id, man_table, epa_table FROM "+self.schema_name+".arc_type WHERE epa_default = '"+self.epa_type+"' UNION "
        sql+= "SELECT id, man_table, epa_table FROM "+self.schema_name+".node_type WHERE epa_default = '"+self.epa_type+"' ORDER BY id"
        rows = self.dao.get_rows(sql)     
        self.cbo_cat_nodetype_id = self.dialog.findChild(QComboBox, "cat_nodetype_id")    
        utils_giswater.fillComboBox(self.cbo_cat_nodetype_id, rows)
        utils_giswater.setSelectedItem('cat_nodetype_id', cat_nodetype_id)
            
            
    def changeNodeType(self, index):
        """ Define and execute query to populate combo 'nodecat_id_dummy' """
        cat_nodetype_id = utils_giswater.getSelectedItem("cat_nodetype_id")     
        sql = "SELECT id FROM "+self.schema_name+".cat_arc WHERE arctype_id = '"+cat_nodetype_id+"' UNION "
        sql+= "SELECT id FROM "+self.schema_name+".cat_node WHERE nodetype_id = '"+cat_nodetype_id+"' ORDER BY id"   
        rows = self.dao.get_rows(sql)
        self.cbo_nodecat_id = self.dialog.findChild(QComboBox, "nodecat_id_dummy")
        utils_giswater.fillComboBox(self.cbo_nodecat_id, rows, False)  
        self.changeNodeCat(0)       
        
                       
    def changeNodeCat(self, index):
        """ Just select item to 'real' combo 'nodecat_id' (that is hidden) """
        dummy = utils_giswater.getSelectedItem("nodecat_id_dummy")
        utils_giswater.setSelectedItem("nodecat_id", dummy)   
        
                
    def changeEpaType(self, index):
        """ Just select item to 'real' combo 'nodecat_id' (that is hidden) """
        epa_type = utils_giswater.getSelectedItem("epa_type")
        self.save()
        self.iface.openFeatureForm(self.layer, self.feature)        
    
    
    def setTabsVisibility(self):
        
        man_visible = False
        index_tab = 0      
        if self.epa_type == 'JUNCTION':
            index_tab = 0
        if self.epa_type == 'RESERVOIR' or self.epa_type == 'HYDRANT':
            index_tab = 1
        if self.epa_type == 'TANK':
            index_tab = 2
            man_visible = True           
        if self.epa_type == 'PUMP':
            index_tab = 3
        if self.epa_type == 'VALVE':
            index_tab = 4
        if self.epa_type == 'SHORTPIPE' or self.epa_type == 'FILTER':
            index_tab = 5
        if self.epa_type == 'MEASURE INSTRUMENT':
            index_tab = 6
        
        # Tab 'Add. info': Manage visibility of these widgets 
        utils_giswater.setWidgetVisible("label_man_tank_vmax", man_visible) 
        utils_giswater.setWidgetVisible("label_man_tank_area", man_visible) 
        utils_giswater.setWidgetVisible("man_tank_vmax", man_visible) 
        utils_giswater.setWidgetVisible("man_tank_area", man_visible) 
                    
        # Move 'visible' tab to last position and remove previous ones
        self.tab_analysis.tabBar().moveTab(index_tab, 5);
        for i in range(0, self.tab_analysis.count() - 1):
            self.tab_analysis.removeTab(0)    
        self.tab_event.tabBar().moveTab(index_tab, 6);
        for i in range(0, self.tab_event.count() - 1):
            self.tab_event.removeTab(0)    
            
               
    def save(self):
        if self.epa_type == 'TANK':
            vmax = utils_giswater.getStringValue2("man_tank_vmax")
            area = utils_giswater.getStringValue2("man_tank_area")
            sql = "UPDATE "+self.schema_name+".man_tank SET vmax = "+str(vmax)+ ", area = "+str(area)
            sql+= " WHERE node_id = "+str(self.node_id)
            print sql
            self.dao.execute_sql(sql)
        self.dialog.accept()
        self.layer.commitChanges()    
        self.close()     
        
        
    def close(self):
        self.layer.rollBack()   
        self.dialog.parent().setVisible(False)    
예제 #9
0
class Giswater(QObject):
   
    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
        '''
        super(Giswater, self).__init__()
        
        # Save reference to the QGIS interface
        self.iface = iface
        self.legend = iface.legendInterface()    
            
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)    
        self.plugin_name = os.path.basename(self.plugin_dir)   

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n', self.plugin_name+'_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
         
        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())    
        
        # Declare instance attributes
        self.icon_folder = self.plugin_dir+'/icons/'        
        self.actions = {}
        self.map_tools = {}
        self.search_plus = None
        self.srid = None
        
        # Set controller to handle settings and database connection
        self.controller = DaoController(self.settings, self.plugin_name, self.iface)
        
        # Check if config file exists    
        if not os.path.exists(setting_file):
            msg = "Config file not found at: "+setting_file
            self.controller.show_message(msg, 1, 100) 
            return    
        
        # Check connection status   
        connection_status = self.controller.set_database_connection()
        self.dao = self.controller.dao        
        if not connection_status:
            msg = self.controller.last_error  
            self.controller.show_message(msg, 1, 100) 
            return 
        
        # Set actions classes
        self.ed = Ed(self.iface, self.settings, self.controller, self.plugin_dir)
        self.mg = Mg(self.iface, self.settings, self.controller, self.plugin_dir)
        
        # Define signals
        self.set_signals()
        
               
    def set_signals(self): 
        ''' Define widget and event signals '''
        self.iface.projectRead.connect(self.project_read)                
        self.legend.currentLayerChanged.connect(self.current_layer_changed)       
        
                   
    def tr(self, message):
        if self.controller:
            return self.controller.tr(message)      
        
        
    def create_action(self, index_action=None, text='', toolbar=None, menu=None, is_checkable=True, function_name=None, parent=None):
        
        if parent is None:
            parent = self.iface.mainWindow()

        icon = None
        if index_action is not None:
            icon_path = self.icon_folder+index_action+'.png'
            if os.path.exists(icon_path):        
                icon = QIcon(icon_path)
                
        if icon is None:
            action = QAction(text, parent) 
        else:
            action = QAction(icon, text, parent)  
                                    
        if toolbar is not None:
            toolbar.addAction(action)  
             
        if menu is not None:
            self.iface.addPluginToMenu(menu, action)
            
        if index_action is not None:         
            self.actions[index_action] = action
        else:
            self.actions[text] = action
                                     
        if function_name is not None:
            try:
                action.setCheckable(is_checkable) 
                # Management toolbar actions
                if int(index_action) in (19, 21, 24, 25, 27, 28, 99):
                    callback_function = getattr(self.mg, function_name)  
                    action.triggered.connect(callback_function)
                # Edit toolbar actions
                elif int(index_action) in (32, 33, 34, 36):    
                    callback_function = getattr(self.ed, function_name)  
                    action.triggered.connect(callback_function)                    
                # Generic function
                else:        
                    water_soft = function_name[:2] 
                    callback_function = getattr(self, water_soft+'_generic')  
                    action.triggered.connect(partial(callback_function, function_name))
            except AttributeError:
                #print index_action+". Callback function not found: "+function_name
                action.setEnabled(False)                
        else:
            action.setEnabled(False)
            
        return action
          
        
    def add_action(self, index_action, toolbar, parent):
        ''' Add new action into specified toolbar 
        This action has to be defined in the configuration file ''' 
        
        action = None
        text_action = self.tr(index_action+'_text')
        function_name = self.settings.value('actions/'+str(index_action)+'_function')
        if function_name:
            map_tool = None
            if int(index_action) in (3, 5, 13):
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = LineMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) in (1, 2, 4, 10, 11, 12, 14, 15, 8, 29):
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = PointMapTool(self.iface, self.settings, action, index_action, self.controller, self.srid)   
            elif int(index_action) == 16:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = MoveNodeMapTool(self.iface, self.settings, action, index_action, self.controller, self.srid)
            elif int(index_action) == 17:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = DeleteNodeMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) == 18:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = ExtractRasterValue(self.iface, self.settings, action, index_action)
            elif int(index_action) == 26:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = MincutMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) == 20:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = ConnecMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) == 56:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = FlowTraceFlowExitMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) == 57:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
                map_tool = FlowTraceFlowExitMapTool(self.iface, self.settings, action, index_action)
            elif int(index_action) in (27, 99):
                # 27 should be not checkeable
                action = self.create_action(index_action, text_action, toolbar, None, False, function_name, parent)
            else:
                action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)

            if map_tool:
                self.map_tools[function_name] = map_tool
        
        return action         
        
        
    def initGui(self):
        ''' Create the menu entries and toolbar icons inside the QGIS GUI ''' 
        
        if self.dao is None:
            return
        
        # Create plugin main menu
        self.menu_name = self.tr('menu_name')    
        
        # Get tables or views specified in 'db' config section         
        self.table_arc = self.settings.value('db/table_arc', 'v_edit_arc')        
        self.table_node = self.settings.value('db/table_node', 'v_edit_node')   
        self.table_connec = self.settings.value('db/table_connec', 'v_edit_connec')  
        self.table_gully = self.settings.value('db/table_gully', 'v_edit_gully')    
        self.table_version = self.settings.value('db/table_version', 'version')     
        
        # Create UD, WS, MANAGEMENT and EDIT toolbars or not?
        parent = self.iface.mainWindow()
        self.toolbar_ud_enabled = bool(int(self.settings.value('status/toolbar_ud_enabled', 1)))
        self.toolbar_ws_enabled = bool(int(self.settings.value('status/toolbar_ws_enabled', 1)))
        self.toolbar_mg_enabled = bool(int(self.settings.value('status/toolbar_mg_enabled', 1)))
        self.toolbar_ed_enabled = bool(int(self.settings.value('status/toolbar_ed_enabled', 1)))
        if self.toolbar_ud_enabled:
            self.toolbar_ud_name = self.tr('toolbar_ud_name')
            self.toolbar_ud = self.iface.addToolBar(self.toolbar_ud_name)
            self.toolbar_ud.setObjectName(self.toolbar_ud_name)   
        if self.toolbar_ws_enabled:
            self.toolbar_ws_name = self.tr('toolbar_ws_name')
            self.toolbar_ws = self.iface.addToolBar(self.toolbar_ws_name)
            self.toolbar_ws.setObjectName(self.toolbar_ws_name)   
        if self.toolbar_mg_enabled:
            self.toolbar_mg_name = self.tr('toolbar_mg_name')
            self.toolbar_mg = self.iface.addToolBar(self.toolbar_mg_name)
            self.toolbar_mg.setObjectName(self.toolbar_mg_name)      
        if self.toolbar_ed_enabled:
            self.toolbar_ed_name = self.tr('toolbar_ed_name')
            self.toolbar_ed = self.iface.addToolBar(self.toolbar_ed_name)
            self.toolbar_ed.setObjectName(self.toolbar_ed_name)      
                
        # UD toolbar   
        if self.toolbar_ud_enabled:        
            self.ag_ud = QActionGroup(parent);
            self.add_action('01', self.toolbar_ud, self.ag_ud)   
            self.add_action('02', self.toolbar_ud, self.ag_ud)   
            self.add_action('04', self.toolbar_ud, self.ag_ud)   
            self.add_action('05', self.toolbar_ud, self.ag_ud)   
            #self.add_action('03', self.toolbar_ud, self.ag_ud)   
                
        # WS toolbar 
        if self.toolbar_ws_enabled:  
            self.ag_ws = QActionGroup(parent);
            self.add_action('10', self.toolbar_ws, self.ag_ws)
            self.add_action('11', self.toolbar_ws, self.ag_ws)
            self.add_action('12', self.toolbar_ws, self.ag_ws)
            self.add_action('14', self.toolbar_ws, self.ag_ws)
            self.add_action('15', self.toolbar_ws, self.ag_ws)
            self.add_action('08', self.toolbar_ws, self.ag_ws)
            self.add_action('29', self.toolbar_ws, self.ag_ws)
            self.add_action('13', self.toolbar_ws, self.ag_ws)
                
        # MANAGEMENT toolbar 
        if self.toolbar_mg_enabled:      
            self.ag_mg = QActionGroup(parent);
            self.add_action('16', self.toolbar_mg, self.ag_mg)
            self.add_action('28', self.toolbar_mg, self.ag_mg)            
            for i in range(17,28):
                self.add_action(str(i), self.toolbar_mg, self.ag_mg)
            self.add_action('99', self.toolbar_mg, self.ag_mg)
            self.add_action('56', self.toolbar_mg, self.ag_mg)
            self.add_action('57', self.toolbar_mg, self.ag_mg)
                    
        # EDIT toolbar 
        if self.toolbar_ed_enabled:      
            self.ag_ed = QActionGroup(parent);
            for i in range(30,37):
                self.add_action(str(i), self.toolbar_ed, self.ag_ed)                   
         
        # Disable and hide all toolbars
        self.enable_actions(False)
        self.hide_toolbars() 
        
        # Get files to execute giswater jar
        self.java_exe = self.settings.value('files/java_exe')          
        self.giswater_jar = self.settings.value('files/giswater_jar')          
        self.gsw_file = self.settings.value('files/gsw_file')   
                         
        # Load automatically custom forms for layers 'arc', 'node', and 'connec'   
        self.load_custom_forms = bool(int(self.settings.value('status/load_custom_forms', 1)))   
                                 
        # Project initialization
        self.project_read()               


    def unload(self):
        ''' Removes the plugin menu item and icon from QGIS GUI '''
        
        try:
            for action_index, action in self.actions.iteritems():   #@UnusedVariable
                self.iface.removePluginMenu(self.menu_name, action)
                self.iface.removeToolBarIcon(action)
            if self.toolbar_ud_enabled:    
                del self.toolbar_ud
            if self.toolbar_ws_enabled:    
                del self.toolbar_ws
            if self.toolbar_mg_enabled:    
                del self.toolbar_mg
            if self.toolbar_ed_enabled:    
                del self.toolbar_ed
                if self.search_plus is not None:
                    self.search_plus.unload()
        except AttributeError:
            pass
        except KeyError:
            pass
    
    
    ''' Slots '''             

    def enable_actions(self, enable=True, start=1, stop=36):
        ''' Utility to enable all actions '''
        for i in range(start, stop+1):
            self.enable_action(enable, i)              


    def enable_action(self, enable=True, index=1):
        ''' Enable selected action '''
        key = str(index).zfill(2)
        if key in self.actions:
            action = self.actions[key]
            action.setEnabled(enable)                   


    def hide_toolbars(self):
        ''' Hide all toolbars from QGIS GUI '''
        
        try:
            if self.toolbar_ud_enabled:            
                self.toolbar_ud.setVisible(False)
            if self.toolbar_ws_enabled:                
                self.toolbar_ws.setVisible(False)
            if self.toolbar_mg_enabled:                
                self.toolbar_mg.setVisible(False)
            if self.toolbar_ed_enabled:                
                self.toolbar_ed.setVisible(False)
        except AttributeError:
            pass
        except KeyError:
            pass                      
                                  
        
    def search_project_type(self):
        ''' Search in table 'version' project type of current QGIS project '''
        
        try:
            self.mg.project_type = None
            features = self.layer_version.getFeatures()
            for feature in features:
                wsoftware = feature['wsoftware']
                if wsoftware.lower() == 'epanet':
                    self.mg.project_type = 'ws'
                    self.actions['26'].setVisible(True)
                    self.actions['27'].setVisible(True)
                    self.actions['56'].setVisible(False)
                    self.actions['57'].setVisible(False)
                    if self.toolbar_ws_enabled:
                        self.toolbar_ws.setVisible(True)                            
                elif wsoftware.lower() == 'epaswmm':
                    self.mg.project_type = 'ud'
                    self.actions['26'].setVisible(False)
                    self.actions['27'].setVisible(False)
                    self.actions['56'].setVisible(True)
                    self.actions['57'].setVisible(True)
                    if self.toolbar_ud_enabled:
                        self.toolbar_ud.setVisible(True)                
            
            # Set visible MANAGEMENT and EDIT toolbar  
            if self.toolbar_mg_enabled:         
                self.toolbar_mg.setVisible(True)
            if self.toolbar_ed_enabled: 
                self.toolbar_ed.setVisible(True)
            self.ed.search_plus = self.search_plus                   
        except:
            pass                  

                                
    def project_read(self): 
        ''' Function executed when a user opens a QGIS project (*.qgs) '''
        
        if self.dao is None:
            return
                
        # Hide all toolbars
        self.hide_toolbars()
                    
        # Check if we have any layer loaded
        layers = self.iface.legendInterface().layers()
        if len(layers) == 0:
            return    
        
        # Initialize variables
        self.layer_arc = None
        self.layer_node = None
        self.layer_connec = None
        self.layer_gully = None
        self.layer_version = None
        
        # Iterate over all layers to get the ones specified in 'db' config section 
        for cur_layer in layers:     
            (uri_schema, uri_table) = self.controller.get_layer_source(cur_layer)   #@UnusedVariable
            if uri_table is not None:
                if self.table_arc in uri_table:  
                    self.layer_arc = cur_layer
                if self.table_node in uri_table:  
                    self.layer_node = cur_layer
                if self.table_connec in uri_table:  
                    self.layer_connec = cur_layer
                if self.table_gully in uri_table:  
                    self.layer_gully = cur_layer
                if self.table_version in uri_table:  
                    self.layer_version = cur_layer     
        
        # Check if table 'version' exists
        if self.layer_version is None:
            self.controller.show_warning("Layer version not found")
            return
                 
        # Get schema name from table 'version'
        # Check if really exists
        (self.schema_name, uri_table) = self.controller.get_layer_source(self.layer_version)  
        schema_name = self.schema_name.replace('"', '')
        if self.schema_name is None or not self.dao.check_schema(schema_name):
            self.controller.show_warning("Schema not found: "+self.schema_name)            
            return
        
        # Set schema_name in controller and in config file
        self.settings.setValue("db/schema_name", self.schema_name)    
        self.controller.set_schema_name(self.schema_name)    
        
        # Cache error message with log_code = -1 (uncatched error)
        self.controller.get_error_message(-1)        
        
        # Set SRID from table node
        sql = "SELECT Find_SRID('"+schema_name+"', '"+self.table_node+"', 'the_geom');"
        row = self.dao.get_row(sql)
        if row:
            self.srid = row[0]   
            self.settings.setValue("db/srid", self.srid)                           
        
        # Search project type in table 'version'
        self.search_project_type()
                                         
        # Set layer custom UI form and init function   
        if self.layer_arc is not None and self.load_custom_forms:       
            file_ui = os.path.join(self.plugin_dir, 'ui', self.mg.project_type+'_arc.ui')
            file_init = os.path.join(self.plugin_dir, self.mg.project_type+'_arc_init.py')                     
            self.layer_arc.editFormConfig().setUiForm(file_ui) 
            self.layer_arc.editFormConfig().setInitCodeSource(1)
            self.layer_arc.editFormConfig().setInitFilePath(file_init)           
            self.layer_arc.editFormConfig().setInitFunction('formOpen') 
         
        if self.layer_node is not None and self.load_custom_forms:       
            file_ui = os.path.join(self.plugin_dir, 'ui', self.mg.project_type+'_node.ui')
            file_init = os.path.join(self.plugin_dir, self.mg.project_type+'_node_init.py')       
            self.layer_node.editFormConfig().setUiForm(file_ui) 
            self.layer_node.editFormConfig().setInitCodeSource(1)
            self.layer_node.editFormConfig().setInitFilePath(file_init)           
            self.layer_node.editFormConfig().setInitFunction('formOpen')                         
                                    
        if self.layer_connec is not None and self.load_custom_forms:       
            file_ui = os.path.join(self.plugin_dir, 'ui', self.mg.project_type+'_connec.ui')
            file_init = os.path.join(self.plugin_dir, self.mg.project_type+'_connec_init.py')       
            self.layer_connec.editFormConfig().setUiForm(file_ui) 
            self.layer_connec.editFormConfig().setInitCodeSource(1)
            self.layer_connec.editFormConfig().setInitFilePath(file_init)           
            self.layer_connec.editFormConfig().setInitFunction('formOpen')   
            
        if self.layer_gully is not None and self.load_custom_forms:       
            file_ui = os.path.join(self.plugin_dir, 'ui', self.mg.project_type+'_gully.ui')
            file_init = os.path.join(self.plugin_dir, self.mg.project_type+'_gully_init.py')       
            self.layer_connec.editFormConfig().setUiForm(file_ui) 
            self.layer_connec.editFormConfig().setInitCodeSource(1)
            self.layer_connec.editFormConfig().setInitFilePath(file_init)           
            self.layer_connec.editFormConfig().setInitFunction('formOpen')                       

                      
        # Manage current layer selected     
        self.current_layer_changed(self.iface.activeLayer())   
        
        # Set objects for map tools classes
        map_tool = self.map_tools['mg_move_node']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)
        
        map_tool = self.map_tools['mg_delete_node']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)
        
        map_tool = self.map_tools['mg_mincut']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)

        map_tool = self.map_tools['mg_flow_trace']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)

        map_tool = self.map_tools['mg_flow_exit']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)

        map_tool = self.map_tools['mg_connec_tool']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)

        map_tool = self.map_tools['mg_extract_raster_value']
        map_tool.set_layers(self.layer_arc, self.layer_connec, self.layer_node)
        map_tool.set_controller(self.controller)
        map_tool.set_config_action(self.actions['99'])

        # Create SearchPlus object
        try:
            if self.search_plus is None:
                self.search_plus = SearchPlus(self.iface, self.srid, self.controller)
                self.search_plus.remove_memory_layers() 
            self.ed.search_plus = self.search_plus             
            status = self.search_plus.populate_dialog()
            self.actions['32'].setVisible(status) 
            self.actions['32'].setEnabled(status) 
            self.actions['32'].setCheckable(False) 
        except KeyError as e:
            self.controller.show_warning("Error setting searchplus button: "+str(e))
            self.actions['32'].setVisible(False)                     
            pass   
        except RuntimeError as e:
            self.controller.show_warning("Error setting searchplus button: "+str(e))
            self.actions['32'].setVisible(False)                     
        
        self.custom_enable_actions()
            
                                
    def current_layer_changed(self, layer):
        ''' Manage new layer selected '''

        # Disable all actions (buttons)
        self.enable_actions(False)
        
        self.custom_enable_actions()     
        
        if layer is None:
            layer = self.iface.activeLayer() 
            if layer is None:
                return            
        self.current_layer = layer
        
        # Check is selected layer is 'arc', 'node' or 'connec'
        setting_name = None
        (uri_schema, uri_table) = self.controller.get_layer_source(layer)  #@UnusedVariable  
        if uri_table is not None:
            if self.table_arc in uri_table:  
                setting_name = 'buttons_arc'
            elif self.table_node in uri_table:  
                setting_name = 'buttons_node'
            elif self.table_connec in uri_table:  
                setting_name = 'buttons_connec' 
            elif self.table_gully in uri_table:  
                setting_name = 'buttons_gully' 
                               
        if setting_name is not None:
            try:
                list_index_action = self.settings.value('layers/'+setting_name, None)
                if list_index_action:
                    if type(list_index_action) is list:
                        for index_action in list_index_action:
                            if index_action != '-1' and str(index_action) in self.actions:
                                self.actions[index_action].setEnabled(True)
                    elif type(list_index_action) is unicode:
                        index_action = str(list_index_action)
                        if index_action != '-1' and str(index_action) in self.actions:
                            self.actions[index_action].setEnabled(True)                
            except AttributeError, e:
                print "current_layer_changed: "+str(e)
            except KeyError, e:
                print "current_layer_changed: "+str(e)
예제 #10
0
class Giswater(QObject):
   
    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
        '''
        super(Giswater, self).__init__()
        
        # Save reference to the QGIS interface
        self.iface = iface
        self.legend = iface.legendInterface()    
            
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)    
        self.plugin_name = os.path.basename(self.plugin_dir)   

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n', self.plugin_name+'_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
         
        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())    
        
        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()     
        self.dao = self.controller.getDao()     
        self.schema_name = self.controller.getSchemaName()      
        
        # Declare instance attributes
        self.icon_folder = self.plugin_dir+'/icons/'        
        self.actions = {}
        self.search_plus = None
        
        # {function_name, map_tool}
        self.map_tools = {}
        
        # Define signals
        self.set_signals()
               

    def set_signals(self): 
        ''' Define widget and event signals '''
        self.iface.projectRead.connect(self.project_read)                
        self.legend.currentLayerChanged.connect(self.current_layer_changed)       
        
                   
    def tr(self, message):
        if self.controller:
            return self.controller.tr(message)
        
        
    def showInfo(self, text, duration = 5):
        self.iface.messageBar().pushMessage("", text, QgsMessageBar.INFO, duration)            
        
        
    def showWarning(self, text, duration = 5):
        self.iface.messageBar().pushMessage("", text, QgsMessageBar.WARNING, duration)            
        
        
    def create_action(self, index_action=None, text='', toolbar=None, menu=None, is_checkable=True, function_name=None, parent=None):
        
        if parent is None:
            parent = self.iface.mainWindow()

        icon = None
        if index_action is not None:
            icon_path = self.icon_folder+index_action+'.png'
            if os.path.exists(icon_path):        
                icon = QIcon(icon_path)
                
        if icon is None:
            action = QAction(text, parent) 
        else:
            action = QAction(icon, text, parent)  
                                    
        if toolbar is not None:
            toolbar.addAction(action)  
             
        if menu is not None:
            self.iface.addPluginToMenu(menu, action)
            
        if index_action is not None:         
            self.actions[index_action] = action
        else:
            self.actions[text] = action
            
        if function_name is not None:
            try:
                action.setCheckable(is_checkable) 
                if int(index_action) in (17, 20, 26, 32):    
                    callback_function = getattr(self, function_name)  
                    action.triggered.connect(callback_function)
                else:        
                    water_soft = function_name[:2] 
                    callback_function = getattr(self, water_soft+'_generic')  
                    action.triggered.connect(partial(callback_function, function_name))
            except AttributeError:
                print index_action+". Callback function not found: "+function_name
                action.setEnabled(False)                
        else:
            action.setEnabled(False)
            
        return action
          
        
    def add_action(self, index_action, toolbar, parent):
        ''' Add new action into specified toolbar 
        This action has to be defined in the configuration file ''' 
        
        action = None
        text_action = self.tr(index_action+'_text')
        function_name = self.settings.value('actions/'+str(index_action)+'_function')
        if function_name:
            map_tool = None
            action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
            if int(index_action) == 13:
                map_tool = LineMapTool(self.iface, self.settings, action, index_action, self.controller)
            elif int(index_action) == 16:
                map_tool = MoveNode(self.iface, self.settings, action, index_action, self.controller)         
            elif int(index_action) in (10, 11, 12, 14, 15, 8, 29):
                map_tool = PointMapTool(self.iface, self.settings, action, index_action, self.controller)   
            else:
                pass
            if map_tool:      
                self.map_tools[function_name] = map_tool       
        
        return action         
        
        
    def initGui(self):
        ''' Create the menu entries and toolbar icons inside the QGIS GUI ''' 
        
        parent = self.iface.mainWindow()
        if self.controller is None:
            return
        
        # Create plugin main menu
        self.menu_name = self.tr('menu_name')    
        
        # Get table or view related with 'arc' and 'node'
        self.table_arc = self.settings.value('db/table_arc', 'v_edit_arc')        
        self.table_node = self.settings.value('db/table_node', 'v_edit_node')   
        
        # Get SRID
        self.srid = self.settings.value('status/srid')             
                
        # Create UD, WS, MANAGEMENT and EDIT toolbars or not?
        self.toolbar_ud_enabled = bool(int(self.settings.value('status/toolbar_ud_enabled', 1)))
        self.toolbar_ws_enabled = bool(int(self.settings.value('status/toolbar_ws_enabled', 1)))
        self.toolbar_mg_enabled = bool(int(self.settings.value('status/toolbar_mg_enabled', 1)))
        self.toolbar_ed_enabled = bool(int(self.settings.value('status/toolbar_ed_enabled', 1)))
        if self.toolbar_ud_enabled:
            self.toolbar_ud_name = self.tr('toolbar_ud_name')
            self.toolbar_ud = self.iface.addToolBar(self.toolbar_ud_name)
            self.toolbar_ud.setObjectName(self.toolbar_ud_name)   
        if self.toolbar_ws_enabled:
            self.toolbar_ws_name = self.tr('toolbar_ws_name')
            self.toolbar_ws = self.iface.addToolBar(self.toolbar_ws_name)
            self.toolbar_ws.setObjectName(self.toolbar_ws_name)   
        if self.toolbar_mg_enabled:
            self.toolbar_mg_name = self.tr('toolbar_mg_name')
            self.toolbar_mg = self.iface.addToolBar(self.toolbar_mg_name)
            self.toolbar_mg.setObjectName(self.toolbar_mg_name)      
        if self.toolbar_ed_enabled:
            self.toolbar_ed_name = self.tr('toolbar_ed_name')
            self.toolbar_ed = self.iface.addToolBar(self.toolbar_ed_name)
            self.toolbar_ed.setObjectName(self.toolbar_ed_name)      
                
        # UD toolbar
        if self.toolbar_ud_enabled:        
            self.ag_ud = QActionGroup(parent);
            self.add_action('01', self.toolbar_ud, self.ag_ud)   
            self.add_action('02', self.toolbar_ud, self.ag_ud)   
            self.add_action('04', self.toolbar_ud, self.ag_ud)   
            self.add_action('05', self.toolbar_ud, self.ag_ud)   
            self.add_action('03', self.toolbar_ud, self.ag_ud)   
                
        # WS toolbar
        if self.toolbar_ws_enabled:  
            self.ag_ws = QActionGroup(parent);
            self.add_action('10', self.toolbar_ws, self.ag_ws)
            self.add_action('11', self.toolbar_ws, self.ag_ws)
            self.add_action('12', self.toolbar_ws, self.ag_ws)
            self.add_action('14', self.toolbar_ws, self.ag_ws)
            self.add_action('15', self.toolbar_ws, self.ag_ws)
            self.add_action('08', self.toolbar_ws, self.ag_ws)
            self.add_action('29', self.toolbar_ws, self.ag_ws)
            self.add_action('13', self.toolbar_ws, self.ag_ws)
                
        # MANAGEMENT toolbar 
        if self.toolbar_mg_enabled:      
            self.ag_mg = QActionGroup(parent);
            self.add_action('16', self.toolbar_mg, self.ag_mg)
            self.add_action('28', self.toolbar_mg, self.ag_mg)            
            for i in range(17,28):
                self.add_action(str(i), self.toolbar_mg, self.ag_mg)
                    
        # EDIT toolbar 
        if self.toolbar_ed_enabled:      
            self.ag_ed = QActionGroup(parent);
            for i in range(30,36):
                self.add_action(str(i), self.toolbar_ed, self.ag_ed)
                
        # Project initialization
        self.project_read()               


    def unload(self):
        ''' Removes the plugin menu item and icon from QGIS GUI '''
        for action_index, action in self.actions.iteritems():
            self.iface.removePluginMenu(self.menu_name, action)
            self.iface.removeToolBarIcon(action)
        if self.toolbar_ud_enabled:    
            del self.toolbar_ud
        if self.toolbar_ws_enabled:    
            del self.toolbar_ws
        if self.toolbar_mg_enabled:    
            del self.toolbar_mg
        if self.toolbar_ed_enabled:    
            del self.toolbar_ed
            if self.search_plus is not None:
                self.search_plus.unload()
            
    
    
    ''' Slots '''
            
    def disable_actions(self):
        ''' Utility to disable all actions '''
        for i in range(1,30):
            key = str(i).zfill(2)
            if key in self.actions:
                action = self.actions[key]
                action.setEnabled(False)         

                                
    def project_read(self): 
        ''' Function executed when a user opens a QGIS project (*.qgs) '''
        
        # Check if we have any layer loaded
        layers = self.iface.legendInterface().layers()
        if len(layers) == 0:
            return    
        
        # Initialize variables
        self.layer_arc = None
        self.layer_node = None
        table_arc = '"'+self.schema_name+'"."'+self.table_arc+'"'
        table_node = '"'+self.schema_name+'"."'+self.table_node+'"'
        
        # Iterate over all layers to get 'arc' and 'node' layer '''      
        for cur_layer in layers:     
            uri = cur_layer.dataProvider().dataSourceUri().lower()   
            pos_ini = uri.find('table=')
            pos_fi = uri.find('" ')  
            uri_table = uri   
            if pos_ini <> -1 and pos_fi <> -1:
                uri_table = uri[pos_ini+6:pos_fi+1]                           
                if uri_table == table_arc:  
                    self.layer_arc = cur_layer
                if uri_table == table_node:  
                    self.layer_node = cur_layer
        
        # Disable toolbar actions and manage current layer selected
        self.disable_actions()       
        self.current_layer_changed(self.iface.activeLayer())   
        
        # Create SearchPlus object
        try:
            if self.search_plus is None:
                self.search_plus = SearchPlus(self.iface, self.srid)
                self.search_plus.removeMemoryLayers()   
            status = self.search_plus.populateGui()
            self.actions['32'].setEnabled(status) 
            self.actions['32'].setCheckable(False) 
            if not status:
                self.search_plus.dlg.setVisible(False)                     
        except:
            pass       
                               
                               
    def current_layer_changed(self, layer):
        ''' Manage new layer selected '''

        self.disable_actions()
        if layer is None:
            layer = self.iface.activeLayer() 
        self.current_layer = layer
        try:
            list_index_action = self.settings.value('layers/'+self.current_layer.name(), None)
            if list_index_action:
                if type(list_index_action) is list:
                    for index_action in list_index_action:
                        if index_action != '-1' and str(index_action) in self.actions:
                            self.actions[index_action].setEnabled(True)
                elif type(list_index_action) is unicode:
                    index_action = str(list_index_action)
                    if index_action != '-1' and str(index_action) in self.actions:
                        self.actions[index_action].setEnabled(True)                
        except AttributeError, e:
            print "current_layer_changed: "+str(e)
        except KeyError, e:
            print "current_layer_changed: "+str(e)
예제 #11
0
class Giswater(QObject):
   
    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
        '''
        super(Giswater, self).__init__()
        
        # Save reference to the QGIS interface
        self.iface = iface
        self.legend = iface.legendInterface()    
            
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)    
        self.plugin_name = os.path.basename(self.plugin_dir)   

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n', self.plugin_name+'_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)
         
        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())    
        
        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()     
        self.dao = self.controller.getDao()           
        
        # Declare instance attributes
        self.icon_folder = self.plugin_dir+'/icons/'        
        self.actions = {}
        
        # {function_name, map_tool}
        self.map_tools = {}
        
        # Define signals
        self.set_signals()
        

    def set_signals(self): 
        ''' Define widget and event signals '''
        self.legend.currentLayerChanged.connect(self.current_layer_changed)
        self.current_layer_changed(None)
    
                   
    def tr(self, message):
        if self.controller:
            return self.controller.tr(message)
        
        
    def create_action(self, index_action=None, text='', toolbar=None, menu=None, is_checkable=True, function_name=None, parent=None):
        
        if parent is None:
            parent = self.iface.mainWindow()

        icon = None
        if index_action is not None:
            icon_path = self.icon_folder+index_action+'.png'
            if os.path.exists(icon_path):        
                icon = QIcon(icon_path)
                
        if icon is None:
            action = QAction(text, parent) 
        else:
            action = QAction(icon, text, parent)  
                                    
        if toolbar is not None:
            toolbar.addAction(action)  
             
        if menu is not None:
            self.iface.addPluginToMenu(menu, action)
            
        if index_action is not None:         
            self.actions[index_action] = action
        else:
            self.actions[text] = action
            
        if function_name is not None:
            try:
                action.setCheckable(is_checkable) 
                if int(index_action) < 16:    
                    water_soft = function_name[:2] 
                    callback_function = getattr(self, water_soft+'_generic')  
                    action.toggled.connect(partial(callback_function, function_name))
                    #function_name = sys._getframe().f_code.co_name    
                else:                    
                    callback_function = getattr(self, function_name)  
                    action.toggled.connect(callback_function)
            except AttributeError:
                print index_action+". Callback function not found: "+function_name
                action.setEnabled(False)                
        else:
            action.setEnabled(False)
            
        return action
          
        
    def add_action(self, index_action, toolbar, parent):
        
        action = None
        text_action = self.tr(index_action+'_text')
        function_name = self.settings.value('actions/'+str(index_action)+'_function')
        # Only create action if is defined in configuration file
        if function_name:
            action = self.create_action(index_action, text_action, toolbar, None, True, function_name, parent)
            # TODO: Parametrize it
            if int(index_action) == 13:
                map_tool = LineMapTool(self.iface, self.settings, action, index_action, self.controller)
            else:
                map_tool = PointMapTool(self.iface, self.settings, action, index_action, self.controller)         
            self.map_tools[function_name] = map_tool       
        
        return action         
        
        
    def initGui(self):
        ''' Create the menu entries and toolbar icons inside the QGIS GUI ''' 
        
        parent = self.iface.mainWindow()
        if self.controller is None:
            return
        
        # Create plugin main menu
        self.menu_name = self.tr('menu_name')    
                
        # Create edit, epanet and swmm toolbars or not?
        self.toolbar_edit_enabled = bool(int(self.settings.value('status/toolbar_edit_enabled', 1)))
        self.toolbar_epanet_enabled = bool(int(self.settings.value('status/toolbar_epanet_enabled', 1)))
        self.toolbar_swmm_enabled = bool(int(self.settings.value('status/toolbar_swmm_enabled', 1)))
        if self.toolbar_swmm_enabled:
            self.toolbar_swmm_name = self.tr('toolbar_swmm_name')
            self.toolbar_swmm = self.iface.addToolBar(self.toolbar_swmm_name)
            self.toolbar_swmm.setObjectName(self.toolbar_swmm_name)   
        if self.toolbar_epanet_enabled:
            self.toolbar_epanet_name = self.tr('toolbar_epanet_name')
            self.toolbar_epanet = self.iface.addToolBar(self.toolbar_epanet_name)
            self.toolbar_epanet.setObjectName(self.toolbar_epanet_name)   
        if self.toolbar_edit_enabled:
            self.toolbar_edit_name = self.tr('toolbar_edit_name')
            self.toolbar_edit = self.iface.addToolBar(self.toolbar_edit_name)
            self.toolbar_edit.setObjectName(self.toolbar_edit_name)      
                    
        # Edit&Analysis toolbar 
        if self.toolbar_edit_enabled:      
            self.ag_edit = QActionGroup(parent);
            for i in range(16,28):
                self.add_action(str(i), self.toolbar_edit, self.ag_edit)
                
        # Epanet toolbar
        if self.toolbar_epanet_enabled:  
            self.ag_epanet = QActionGroup(parent);
            for i in range(10,16):
                self.add_action(str(i), self.toolbar_epanet, self.ag_epanet)
                
        # SWMM toolbar
        if self.toolbar_swmm_enabled:        
            for i in range(1,10):
                self.ag_swmm = QActionGroup(parent);                
                self.add_action(str(i).zfill(2), self.toolbar_swmm, self.ag_swmm)                    
            
        # Menu entries
        self.create_action(None, self.tr('New network'), None, self.menu_name, False)
        self.create_action(None, self.tr('Copy network as'), None, self.menu_name, False)
            
        self.menu_network_configuration = QMenu(self.tr('Network configuration'))
        action1 = self.create_action(None, self.tr('Snapping tolerance'), None, None, False)               
        action2 = self.create_action(None, self.tr('Node tolerance'), None, None, False)         
        self.menu_network_configuration.addAction(action1)
        self.menu_network_configuration.addAction(action2)
        self.iface.addPluginToMenu(self.menu_name, self.menu_network_configuration.menuAction())  
           
        self.menu_network_management = QMenu(self.tr('Network management'))
        action1 = self.create_action('21', self.tr('Table wizard'), None, None, False)               
        action2 = self.create_action('22', self.tr('Undo wizard'), None, None, False)         
        self.menu_network_management.addAction(action1)
        self.menu_network_management.addAction(action2)
        self.iface.addPluginToMenu(self.menu_name, self.menu_network_management.menuAction())         
           
        self.menu_analysis = QMenu(self.tr('Analysis'))          
        action2 = self.create_action('25', self.tr('Result selector'), None, None, False)               
        action3 = self.create_action('27', self.tr('Flow trace node'), None, None, False)         
        action4 = self.create_action('26', self.tr('Flow trace arc'), None, None, False)         
        self.menu_analysis.addAction(action2)
        self.menu_analysis.addAction(action3)
        self.menu_analysis.addAction(action4)
        self.iface.addPluginToMenu(self.menu_name, self.menu_analysis.menuAction())    
         
#         self.menu_go2epa = QMenu(self.tr('Go2Epa'))
#         action1 = self.create_action('23', self.tr('Giswater interface'), None, None, False)               
#         action2 = self.create_action('24', self.tr('Run simulation'), None, None, False)         
#         self.menu_go2epa.addAction(action1)
#         self.menu_go2epa.addAction(action2)
#         self.iface.addPluginToMenu(self.menu_name, self.menu_go2epa.menuAction())     
            

    def unload(self):
        ''' Removes the plugin menu item and icon from QGIS GUI '''
        for action_index, action in self.actions.iteritems():
            self.iface.removePluginMenu(self.menu_name, self.menu_network_management.menuAction())
            self.iface.removePluginMenu(self.menu_name, action)
            self.iface.removeToolBarIcon(action)
        if self.toolbar_edit_enabled:    
            del self.toolbar_edit
        if self.toolbar_epanet_enabled:    
            del self.toolbar_epanet
        if self.toolbar_swmm_enabled:    
            del self.toolbar_swmm
            
    
    
    ''' Slots '''
            
    def disable_actions(self):
        ''' Utility to disable all actions '''
        for i in range(1,27):
            key = str(i)
            if key in self.actions:
                action = self.actions[key]
                action.setEnabled(False)
                
                            
    def current_layer_changed(self, layer):
        ''' Manage new layer selected '''
        self.disable_actions()
        if layer is None:
            layer = self.iface.activeLayer() 
        self.current_layer = layer
        try:
            list_index_action = self.settings.value('layers/'+self.current_layer.name(), None)
            print list_index_action
            if list_index_action:
                if type(list_index_action) is list:
                    for index_action in list_index_action:
                        if index_action != '-1':
                            self.actions[index_action].setEnabled(True)
                elif type(list_index_action) is unicode:
                    index_action = str(list_index_action)
                    if index_action != '-1':
                        self.actions[index_action].setEnabled(True)                
        except AttributeError, e:
            print "current_layer_changed: "+str(e)
예제 #12
0
class Giswater(QObject):
    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
        '''
        super(Giswater, self).__init__()

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

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

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   self.plugin_name + '_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()
        self.dao = self.controller.getDao()
        self.schema_name = self.controller.getSchemaName()

        # Declare instance attributes
        self.icon_folder = self.plugin_dir + '/icons/'
        self.actions = {}
        self.search_plus = None

        # {function_name, map_tool}
        self.map_tools = {}

        # Define signals
        self.set_signals()

    def set_signals(self):
        ''' Define widget and event signals '''
        self.iface.projectRead.connect(self.project_read)
        self.legend.currentLayerChanged.connect(self.current_layer_changed)

    def tr(self, message):
        if self.controller:
            return self.controller.tr(message)

    def showInfo(self, text, duration=5):
        self.iface.messageBar().pushMessage("", text, QgsMessageBar.INFO,
                                            duration)

    def showWarning(self, text, duration=5):
        self.iface.messageBar().pushMessage("", text, QgsMessageBar.WARNING,
                                            duration)

    def create_action(self,
                      index_action=None,
                      text='',
                      toolbar=None,
                      menu=None,
                      is_checkable=True,
                      function_name=None,
                      parent=None):

        if parent is None:
            parent = self.iface.mainWindow()

        icon = None
        if index_action is not None:
            icon_path = self.icon_folder + index_action + '.png'
            if os.path.exists(icon_path):
                icon = QIcon(icon_path)

        if icon is None:
            action = QAction(text, parent)
        else:
            action = QAction(icon, text, parent)

        if toolbar is not None:
            toolbar.addAction(action)

        if menu is not None:
            self.iface.addPluginToMenu(menu, action)

        if index_action is not None:
            self.actions[index_action] = action
        else:
            self.actions[text] = action

        if function_name is not None:
            try:
                action.setCheckable(is_checkable)
                if int(index_action) in (17, 20, 26, 32):
                    callback_function = getattr(self, function_name)
                    action.triggered.connect(callback_function)
                else:
                    water_soft = function_name[:2]
                    callback_function = getattr(self, water_soft + '_generic')
                    action.triggered.connect(
                        partial(callback_function, function_name))
            except AttributeError:
                print index_action + ". Callback function not found: " + function_name
                action.setEnabled(False)
        else:
            action.setEnabled(False)

        return action

    def add_action(self, index_action, toolbar, parent):
        ''' Add new action into specified toolbar 
        This action has to be defined in the configuration file '''

        action = None
        text_action = self.tr(index_action + '_text')
        function_name = self.settings.value('actions/' + str(index_action) +
                                            '_function')
        if function_name:
            map_tool = None
            action = self.create_action(index_action, text_action, toolbar,
                                        None, True, function_name, parent)
            if int(index_action) == 13:
                map_tool = LineMapTool(self.iface, self.settings, action,
                                       index_action, self.controller)
            elif int(index_action) == 16:
                map_tool = MoveNode(self.iface, self.settings, action,
                                    index_action, self.controller)
            elif int(index_action) in (10, 11, 12, 14, 15, 8, 29):
                map_tool = PointMapTool(self.iface, self.settings, action,
                                        index_action, self.controller)
            else:
                pass
            if map_tool:
                self.map_tools[function_name] = map_tool

        return action

    def initGui(self):
        ''' Create the menu entries and toolbar icons inside the QGIS GUI '''

        parent = self.iface.mainWindow()
        if self.controller is None:
            return

        # Create plugin main menu
        self.menu_name = self.tr('menu_name')

        # Get table or view related with 'arc' and 'node'
        self.table_arc = self.settings.value('db/table_arc', 'v_edit_arc')
        self.table_node = self.settings.value('db/table_node', 'v_edit_node')

        # Get SRID
        self.srid = self.settings.value('status/srid')

        # Create UD, WS, MANAGEMENT and EDIT toolbars or not?
        self.toolbar_ud_enabled = bool(
            int(self.settings.value('status/toolbar_ud_enabled', 1)))
        self.toolbar_ws_enabled = bool(
            int(self.settings.value('status/toolbar_ws_enabled', 1)))
        self.toolbar_mg_enabled = bool(
            int(self.settings.value('status/toolbar_mg_enabled', 1)))
        self.toolbar_ed_enabled = bool(
            int(self.settings.value('status/toolbar_ed_enabled', 1)))
        if self.toolbar_ud_enabled:
            self.toolbar_ud_name = self.tr('toolbar_ud_name')
            self.toolbar_ud = self.iface.addToolBar(self.toolbar_ud_name)
            self.toolbar_ud.setObjectName(self.toolbar_ud_name)
        if self.toolbar_ws_enabled:
            self.toolbar_ws_name = self.tr('toolbar_ws_name')
            self.toolbar_ws = self.iface.addToolBar(self.toolbar_ws_name)
            self.toolbar_ws.setObjectName(self.toolbar_ws_name)
        if self.toolbar_mg_enabled:
            self.toolbar_mg_name = self.tr('toolbar_mg_name')
            self.toolbar_mg = self.iface.addToolBar(self.toolbar_mg_name)
            self.toolbar_mg.setObjectName(self.toolbar_mg_name)
        if self.toolbar_ed_enabled:
            self.toolbar_ed_name = self.tr('toolbar_ed_name')
            self.toolbar_ed = self.iface.addToolBar(self.toolbar_ed_name)
            self.toolbar_ed.setObjectName(self.toolbar_ed_name)

        # UD toolbar
        if self.toolbar_ud_enabled:
            self.ag_ud = QActionGroup(parent)
            self.add_action('01', self.toolbar_ud, self.ag_ud)
            self.add_action('02', self.toolbar_ud, self.ag_ud)
            self.add_action('04', self.toolbar_ud, self.ag_ud)
            self.add_action('05', self.toolbar_ud, self.ag_ud)
            self.add_action('03', self.toolbar_ud, self.ag_ud)

        # WS toolbar
        if self.toolbar_ws_enabled:
            self.ag_ws = QActionGroup(parent)
            self.add_action('10', self.toolbar_ws, self.ag_ws)
            self.add_action('11', self.toolbar_ws, self.ag_ws)
            self.add_action('12', self.toolbar_ws, self.ag_ws)
            self.add_action('14', self.toolbar_ws, self.ag_ws)
            self.add_action('15', self.toolbar_ws, self.ag_ws)
            self.add_action('08', self.toolbar_ws, self.ag_ws)
            self.add_action('29', self.toolbar_ws, self.ag_ws)
            self.add_action('13', self.toolbar_ws, self.ag_ws)

        # MANAGEMENT toolbar
        if self.toolbar_mg_enabled:
            self.ag_mg = QActionGroup(parent)
            self.add_action('16', self.toolbar_mg, self.ag_mg)
            self.add_action('28', self.toolbar_mg, self.ag_mg)
            for i in range(17, 28):
                self.add_action(str(i), self.toolbar_mg, self.ag_mg)

        # EDIT toolbar
        if self.toolbar_ed_enabled:
            self.ag_ed = QActionGroup(parent)
            for i in range(30, 36):
                self.add_action(str(i), self.toolbar_ed, self.ag_ed)

        # Project initialization
        self.project_read()

    def unload(self):
        ''' Removes the plugin menu item and icon from QGIS GUI '''
        for action_index, action in self.actions.iteritems():
            self.iface.removePluginMenu(self.menu_name, action)
            self.iface.removeToolBarIcon(action)
        if self.toolbar_ud_enabled:
            del self.toolbar_ud
        if self.toolbar_ws_enabled:
            del self.toolbar_ws
        if self.toolbar_mg_enabled:
            del self.toolbar_mg
        if self.toolbar_ed_enabled:
            del self.toolbar_ed
            if self.search_plus is not None:
                self.search_plus.unload()

    ''' Slots '''

    def disable_actions(self):
        ''' Utility to disable all actions '''
        for i in range(1, 30):
            key = str(i).zfill(2)
            if key in self.actions:
                action = self.actions[key]
                action.setEnabled(False)

    def project_read(self):
        ''' Function executed when a user opens a QGIS project (*.qgs) '''

        # Check if we have any layer loaded
        layers = self.iface.legendInterface().layers()
        if len(layers) == 0:
            return

        # Initialize variables
        self.layer_arc = None
        self.layer_node = None
        table_arc = '"' + self.schema_name + '"."' + self.table_arc + '"'
        table_node = '"' + self.schema_name + '"."' + self.table_node + '"'

        # Iterate over all layers to get 'arc' and 'node' layer '''
        for cur_layer in layers:
            uri = cur_layer.dataProvider().dataSourceUri().lower()
            pos_ini = uri.find('table=')
            pos_fi = uri.find('" ')
            uri_table = uri
            if pos_ini <> -1 and pos_fi <> -1:
                uri_table = uri[pos_ini + 6:pos_fi + 1]
                if uri_table == table_arc:
                    self.layer_arc = cur_layer
                if uri_table == table_node:
                    self.layer_node = cur_layer

        # Disable toolbar actions and manage current layer selected
        self.disable_actions()
        self.current_layer_changed(self.iface.activeLayer())

        # Create SearchPlus object
        try:
            if self.search_plus is None:
                self.search_plus = SearchPlus(self.iface, self.srid)
                self.search_plus.removeMemoryLayers()
            status = self.search_plus.populateGui()
            self.actions['32'].setEnabled(status)
            self.actions['32'].setCheckable(False)
            if not status:
                self.search_plus.dlg.setVisible(False)
        except:
            pass

    def current_layer_changed(self, layer):
        ''' Manage new layer selected '''

        self.disable_actions()
        if layer is None:
            layer = self.iface.activeLayer()
        self.current_layer = layer
        try:
            list_index_action = self.settings.value(
                'layers/' + self.current_layer.name(), None)
            if list_index_action:
                if type(list_index_action) is list:
                    for index_action in list_index_action:
                        if index_action != '-1' and str(
                                index_action) in self.actions:
                            self.actions[index_action].setEnabled(True)
                elif type(list_index_action) is unicode:
                    index_action = str(list_index_action)
                    if index_action != '-1' and str(
                            index_action) in self.actions:
                        self.actions[index_action].setEnabled(True)
        except AttributeError, e:
            print "current_layer_changed: " + str(e)
        except KeyError, e:
            print "current_layer_changed: " + str(e)
예제 #13
0
class ParentDialog(object):   
    
    def __init__(self, dialog, layer, feature):
        ''' Constructor class '''     
        self.dialog = dialog
        self.layer = layer
        self.feature = feature
        self.context_name = "ws_parent"    
        self.iface = iface    
        self.init_config()             
    
        
    def init_config(self):    
        
        # initialize plugin directory
        user_folder = os.path.expanduser("~") 
        self.plugin_name = 'giswater'  
        self.plugin_dir = os.path.join(user_folder, '.qgis2/python/plugins/'+self.plugin_name)    
        
        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: "+setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5)  
            self.close()
            return
            
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())
        
        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name, iface)
        status = self.controller.set_database_connection()      
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5) 
            return 
             
        self.schema_name = self.settings.value("db/schema_name")           
        self.dao = self.controller.dao
            
            
    def translate_form(self, context_name):
        ''' Translate widgets of the form to current language '''
        # Get objects of type: QLabel
        widget_list = self.dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translate_widget(context_name, widget)
            
            
    def translate_widget(self, context_name, widget):
        ''' Translate widget text '''
        if widget:
            widget_name = widget.objectName()
            text = self.controller.tr(widget_name, context_name)
            if text != widget_name:
                widget.setText(text)         
         
       
    def load_tab_add_info(self):
        ''' Load data from tab 'Add. info' '''                
        pass

    def load_tab_analysis(self):
        ''' Load data from tab 'Analysis' '''          
        pass
                
    def load_tab_document(self):
        ''' TODO: Load data from tab 'Document' '''   
        pass
                
    def load_tab_picture(self):
        ''' TODO: Load data from tab 'Document' '''   
        pass
                
    def load_tab_event(self):
        ''' TODO: Load data from tab 'Event' '''   
        pass
                
    def load_tab_log(self):
        ''' TODO: Load data from tab 'Log' '''   
        pass
        
    def load_tab_rtc(self):
        ''' TODO: Load data from tab 'RTC' '''   
        pass
    
    def load_data(self):
        ''' Load data from related tables '''
        
        self.load_tab_add_info()
        self.load_tab_analysis()
        self.load_tab_document()
        self.load_tab_picture()
        self.load_tab_event()
        self.load_tab_log()
        self.load_tab_rtc()
        

    def save_tab_add_info(self):
        ''' Save tab from tab 'Add. info' '''                
        pass

    def save_tab_analysis(self):
        ''' Save tab from tab 'Analysis' '''          
        pass
                
    def save_tab_document(self):
        ''' TODO: Save tab from tab 'Document' '''   
        pass
                
    def save_tab_picture(self):
        ''' TODO: Save tab from tab 'Document' '''   
        pass
                
    def save_tab_event(self):
        ''' TODO: Save tab from tab 'Event' '''   
        pass
                
    def save_tab_log(self):
        ''' TODO: Save tab from tab 'Log' '''   
        pass
        
    def save_tab_rtc(self):
        ''' TODO: Save tab from tab 'RTC' '''   
        pass
        
                        
    def save_data(self):
        ''' Save data from related tables '''        
        self.save_tab_add_info()
        self.save_tab_analysis()
        self.save_tab_document()
        self.save_tab_picture()
        self.save_tab_event()
        self.save_tab_log()
        self.save_tab_rtc()       
                
        
        
    ''' Slot functions '''           
               
    def save(self):
        ''' Save feature '''
        self.save_data()   
        self.dialog.accept()
        self.layer.commitChanges()    
        self.close()     
        
        
    def close(self):
        ''' Close form without saving '''
        self.layer.rollBack()   
        self.dialog.parent().setVisible(False)         
        
        
    def set_model_to_table(self, widget, table_name, filter_): 
        ''' Set a model with selected filter.
        Attach that model to selected table '''
        
        # Set model
        model = QSqlTableModel();
        model.setTable(table_name)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)        
        model.setFilter(filter_)
        model.select()         

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())      

        # Attach model to table view
        widget.setModel(model)    
        
        
    def delete_records(self, widget, table_name):
        ''' Delete selected elements of the table '''
        
        # Get selected rows
        selected_list = widget.selectionModel().selectedRows()    
        if len(selected_list) == 0:
            message = "Any record selected"
            self.controller.show_warning(message, context_name='ui_message' ) 
            return
        
        inf_text = ""
        list_id = ""
        for i in range(0, len(selected_list)):
            row = selected_list[i].row()
            id_ = widget.model().record(row).value("id")
            inf_text+= str(id_)+", "
            list_id = list_id+"'"+str(id_)+"', "
        inf_text = inf_text[:-2]
        list_id = list_id[:-2]
        answer = self.controller.ask_question("Are you sure you want to delete these records?", "Delete records", inf_text)
        if answer:
            sql = "DELETE FROM "+self.schema_name+"."+table_name 
            sql+= " WHERE id IN ("+list_id+")"
            self.dao.execute_sql(sql)
            widget.model().select()
            
   
    def open_selected_document(self):
        ''' Get value from selected cell ("PATH")
        Open the document ''' 
        
        # Check if clicked value is from the column "PATH"
        position_column = self.tbl_document.currentIndex().column()
        if position_column == 4:      
            # Get data from address in memory (pointer)
            self.path = self.tbl_document.selectedIndexes()[0].data()
            # Check if file exist
            if not os.path.exists(self.path):
                message = "File not found!"
                self.controller.show_warning(message, context_name='ui_message')
               
            else:
                # Open the document
                os.startfile(self.path)                      


    def set_filter_table(self, widget):
        ''' Get values selected by the user and sets a new filter for its table model '''
        
        # Get selected dates
        date_from = self.date_document_from.date().toString('yyyyMMdd') 
        date_to = self.date_document_to.date().toString('yyyyMMdd') 
        if (date_from > date_to):
            message = "Selected date interval is not valid"
            self.controller.show_warning(message, context_name='ui_message')                   
            return
        
        # Set filter
        expr = self.field_id+" = '"+self.id+"'"
        expr+= " AND date >= '"+date_from+"' AND date <= '"+date_to+"'"
        
        # Get selected values in Comboboxes        
        doc_type_value = utils_giswater.getWidgetText("doc_type")
        if doc_type_value != 'null': 
            expr+= " AND doc_type = '"+doc_type_value+"'"
        doc_tag_value = utils_giswater.getWidgetText("doc_tag")
        if doc_tag_value != 'null': 
            expr+= " AND tagcat_id = '"+doc_tag_value+"'"
        doc_user_value = utils_giswater.getWidgetText("doc_user")
        if doc_user_value != 'null':
            expr+= " AND user_name = '"+doc_user_value+"'"
  
        # Refresh model with selected filter
        widget.model().setFilter(expr)
        widget.model().select()   
        
        
    def set_configuration(self, widget, table_name):
        ''' Configuration of tables 
        Set visibility of columns
        Set width of columns '''
        
        # Set width and alias of visible columns
        columns_to_delete = []
        sql = "SELECT column_index, width, alias, status"
        sql+= " FROM "+self.schema_name+".config_ui_forms"
        sql+= " WHERE ui_table = '"+table_name+"'"
        sql+= " ORDER BY column_index"
        rows = self.controller.get_rows(sql)
        if rows:
            for row in rows:        
                if not row['status']:
                    columns_to_delete.append(row['column_index']-1)
                else:
                    width = row['width']
                    if width is None:
                        width = 100
                    widget.setColumnWidth(row['column_index']-1, width)
                    widget.model().setHeaderData(row['column_index']-1, Qt.Horizontal, row['alias'])
        
        # Set order
        widget.model().setSort(0, Qt.AscendingOrder)    
        widget.model().select()
        
        # Delete columns        
        for column in columns_to_delete:
            widget.hideColumn(column) 


    def fill_tbl_document(self, widget, table_name, filter_):
        ''' Fill the table control to show documents'''
        
        # Get widgets
        doc_user = self.dialog.findChild(QComboBox, "doc_user")
        doc_type = self.dialog.findChild(QComboBox, "doc_type")
        doc_tag = self.dialog.findChild(QComboBox, "doc_tag")
        self.date_document_to = self.dialog.findChild(QDateEdit, "date_document_to")
        self.date_document_from = self.dialog.findChild(QDateEdit, "date_document_from")

        # Set signals
        doc_user.activated.connect(partial(self.set_filter_table, widget))
        doc_type.activated.connect(partial(self.set_filter_table, widget))
        doc_tag.activated.connect(partial(self.set_filter_table, widget))
        self.date_document_to.dateChanged.connect(partial(self.set_filter_table, widget))
        self.date_document_from.dateChanged.connect(partial(self.set_filter_table, widget))
        self.tbl_document.doubleClicked.connect(self.open_selected_document)

        # Fill ComboBox tagcat_id
        sql = "SELECT DISTINCT(tagcat_id)"
        sql+= " FROM "+table_name
        sql+= " ORDER BY tagcat_id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("doc_tag", rows)

        # Fill ComboBox doccat_id
        sql = "SELECT DISTINCT(doc_type)"
        sql+= " FROM "+table_name
        sql+= " ORDER BY doc_type"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("doc_type", rows)

        # Fill ComboBox doc_user
        sql = "SELECT DISTINCT(user_name)"
        sql+= " FROM "+table_name
        sql+= " ORDER BY user_name"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("doc_user", rows)

        # Set model of selected widget
        self.set_model_to_table(widget, table_name, filter_)
        

    def fill_table(self, widget, table_name, filter_): 
        ''' Fill info tab of node '''
        self.set_model_to_table(widget, table_name, filter_)                  
                
        
예제 #14
0
class Giswater(QObject):
    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
        '''
        super(Giswater, self).__init__()

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

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

        # initialize locale
        locale = QSettings().value('locale/userLocale')
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   self.plugin_name + '_{}.qm'.format(locale))
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Load local settings of the plugin
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Set controller to handle settings and database
        self.controller = DaoController(self.settings, self.plugin_name)
        self.controller.set_database_connection()
        self.dao = self.controller.getDao()

        # Declare instance attributes
        self.icon_folder = self.plugin_dir + '/icons/'
        self.actions = {}

        # {function_name, map_tool}
        self.map_tools = {}

        # Define signals
        self.set_signals()

    def set_signals(self):
        ''' Define widget and event signals '''
        self.legend.currentLayerChanged.connect(self.current_layer_changed)
        self.current_layer_changed(None)

    def tr(self, message):
        if self.controller:
            return self.controller.tr(message)

    def create_action(self,
                      index_action=None,
                      text='',
                      toolbar=None,
                      menu=None,
                      is_checkable=True,
                      function_name=None,
                      parent=None):

        if parent is None:
            parent = self.iface.mainWindow()

        icon = None
        if index_action is not None:
            icon_path = self.icon_folder + index_action + '.png'
            if os.path.exists(icon_path):
                icon = QIcon(icon_path)

        if icon is None:
            action = QAction(text, parent)
        else:
            action = QAction(icon, text, parent)

        if toolbar is not None:
            toolbar.addAction(action)

        if menu is not None:
            self.iface.addPluginToMenu(menu, action)

        if index_action is not None:
            self.actions[index_action] = action
        else:
            self.actions[text] = action

        if function_name is not None:
            try:
                action.setCheckable(is_checkable)
                if int(index_action) < 16:
                    water_soft = function_name[:2]
                    callback_function = getattr(self, water_soft + '_generic')
                    action.toggled.connect(
                        partial(callback_function, function_name))
                    #function_name = sys._getframe().f_code.co_name
                else:
                    callback_function = getattr(self, function_name)
                    action.toggled.connect(callback_function)
            except AttributeError:
                print index_action + ". Callback function not found: " + function_name
                action.setEnabled(False)
        else:
            action.setEnabled(False)

        return action

    def add_action(self, index_action, toolbar, parent):

        action = None
        text_action = self.tr(index_action + '_text')
        function_name = self.settings.value('actions/' + str(index_action) +
                                            '_function')
        # Only create action if is defined in configuration file
        if function_name:
            action = self.create_action(index_action, text_action, toolbar,
                                        None, True, function_name, parent)
            # TODO: Parametrize it
            if int(index_action) == 13:
                map_tool = LineMapTool(self.iface, self.settings, action,
                                       index_action, self.controller)
            else:
                map_tool = PointMapTool(self.iface, self.settings, action,
                                        index_action, self.controller)
            self.map_tools[function_name] = map_tool

        return action

    def initGui(self):
        ''' Create the menu entries and toolbar icons inside the QGIS GUI '''

        parent = self.iface.mainWindow()
        if self.controller is None:
            return

        # Create plugin main menu
        self.menu_name = self.tr('menu_name')

        # Create edit, epanet and swmm toolbars or not?
        self.toolbar_edit_enabled = bool(
            int(self.settings.value('status/toolbar_edit_enabled', 1)))
        self.toolbar_epanet_enabled = bool(
            int(self.settings.value('status/toolbar_epanet_enabled', 1)))
        self.toolbar_swmm_enabled = bool(
            int(self.settings.value('status/toolbar_swmm_enabled', 1)))
        if self.toolbar_swmm_enabled:
            self.toolbar_swmm_name = self.tr('toolbar_swmm_name')
            self.toolbar_swmm = self.iface.addToolBar(self.toolbar_swmm_name)
            self.toolbar_swmm.setObjectName(self.toolbar_swmm_name)
        if self.toolbar_epanet_enabled:
            self.toolbar_epanet_name = self.tr('toolbar_epanet_name')
            self.toolbar_epanet = self.iface.addToolBar(
                self.toolbar_epanet_name)
            self.toolbar_epanet.setObjectName(self.toolbar_epanet_name)
        if self.toolbar_edit_enabled:
            self.toolbar_edit_name = self.tr('toolbar_edit_name')
            self.toolbar_edit = self.iface.addToolBar(self.toolbar_edit_name)
            self.toolbar_edit.setObjectName(self.toolbar_edit_name)

        # Edit&Analysis toolbar
        if self.toolbar_edit_enabled:
            self.ag_edit = QActionGroup(parent)
            for i in range(16, 28):
                self.add_action(str(i), self.toolbar_edit, self.ag_edit)

        # Epanet toolbar
        if self.toolbar_epanet_enabled:
            self.ag_epanet = QActionGroup(parent)
            for i in range(10, 16):
                self.add_action(str(i), self.toolbar_epanet, self.ag_epanet)

        # SWMM toolbar
        if self.toolbar_swmm_enabled:
            for i in range(1, 10):
                self.ag_swmm = QActionGroup(parent)
                self.add_action(
                    str(i).zfill(2), self.toolbar_swmm, self.ag_swmm)

        # Menu entries
        self.create_action(None, self.tr('New network'), None, self.menu_name,
                           False)
        self.create_action(None, self.tr('Copy network as'), None,
                           self.menu_name, False)

        self.menu_network_configuration = QMenu(
            self.tr('Network configuration'))
        action1 = self.create_action(None, self.tr('Snapping tolerance'), None,
                                     None, False)
        action2 = self.create_action(None, self.tr('Node tolerance'), None,
                                     None, False)
        self.menu_network_configuration.addAction(action1)
        self.menu_network_configuration.addAction(action2)
        self.iface.addPluginToMenu(
            self.menu_name, self.menu_network_configuration.menuAction())

        self.menu_network_management = QMenu(self.tr('Network management'))
        action1 = self.create_action('21', self.tr('Table wizard'), None, None,
                                     False)
        action2 = self.create_action('22', self.tr('Undo wizard'), None, None,
                                     False)
        self.menu_network_management.addAction(action1)
        self.menu_network_management.addAction(action2)
        self.iface.addPluginToMenu(self.menu_name,
                                   self.menu_network_management.menuAction())

        self.menu_analysis = QMenu(self.tr('Analysis'))
        action2 = self.create_action('25', self.tr('Result selector'), None,
                                     None, False)
        action3 = self.create_action('27', self.tr('Flow trace node'), None,
                                     None, False)
        action4 = self.create_action('26', self.tr('Flow trace arc'), None,
                                     None, False)
        self.menu_analysis.addAction(action2)
        self.menu_analysis.addAction(action3)
        self.menu_analysis.addAction(action4)
        self.iface.addPluginToMenu(self.menu_name,
                                   self.menu_analysis.menuAction())

#         self.menu_go2epa = QMenu(self.tr('Go2Epa'))
#         action1 = self.create_action('23', self.tr('Giswater interface'), None, None, False)
#         action2 = self.create_action('24', self.tr('Run simulation'), None, None, False)
#         self.menu_go2epa.addAction(action1)
#         self.menu_go2epa.addAction(action2)
#         self.iface.addPluginToMenu(self.menu_name, self.menu_go2epa.menuAction())

    def unload(self):
        ''' Removes the plugin menu item and icon from QGIS GUI '''
        for action_index, action in self.actions.iteritems():
            self.iface.removePluginMenu(
                self.menu_name, self.menu_network_management.menuAction())
            self.iface.removePluginMenu(self.menu_name, action)
            self.iface.removeToolBarIcon(action)
        if self.toolbar_edit_enabled:
            del self.toolbar_edit
        if self.toolbar_epanet_enabled:
            del self.toolbar_epanet
        if self.toolbar_swmm_enabled:
            del self.toolbar_swmm

    ''' Slots '''

    def disable_actions(self):
        ''' Utility to disable all actions '''
        for i in range(1, 27):
            key = str(i)
            if key in self.actions:
                action = self.actions[key]
                action.setEnabled(False)

    def current_layer_changed(self, layer):
        ''' Manage new layer selected '''
        self.disable_actions()
        if layer is None:
            layer = self.iface.activeLayer()
        self.current_layer = layer
        try:
            list_index_action = self.settings.value(
                'layers/' + self.current_layer.name(), None)
            print list_index_action
            if list_index_action:
                if type(list_index_action) is list:
                    for index_action in list_index_action:
                        if index_action != '-1':
                            self.actions[index_action].setEnabled(True)
                elif type(list_index_action) is unicode:
                    index_action = str(list_index_action)
                    if index_action != '-1':
                        self.actions[index_action].setEnabled(True)
        except AttributeError, e:
            print "current_layer_changed: " + str(e)
예제 #15
0
class ParentDialog(object):
    def __init__(self, iface, dialog, layer, feature):
        ''' Constructor class '''
        self.iface = iface
        self.dialog = dialog
        self.layer = layer
        self.feature = feature
        self.init_config()

    def init_config(self):

        # initialize plugin directory
        user_folder = os.path.expanduser("~")
        self.plugin_name = 'giswater'
        self.plugin_dir = os.path.join(
            user_folder, '.qgis2/python/plugins/' + self.plugin_name)

        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: " + setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            self.close()
            return

        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            return

        self.schema_name = self.controller.getSchemaName()
        self.dao = self.controller.getDao()

    def translate_form(self, context_name):
        ''' Translate widgets of the form to current language '''
        # Get objects of type: QLabel
        widget_list = self.dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translate_widget(context_name, widget)

    def translate_widget(self, context_name, widget):
        ''' Translate widget text '''
        if widget:
            widget_name = widget.objectName()
            text = utils_giswater.tr(context_name, widget_name)
            if text != widget_name:
                widget.setText(text)

    def load_tab_add_info(self):
        ''' Load data from tab 'Add. info' '''
        pass

    def load_tab_analysis(self):
        ''' Load data from tab 'Analysis' '''
        pass

    def load_tab_document(self):
        ''' TODO: Load data from tab 'Document' '''
        pass

    def load_tab_picture(self):
        ''' TODO: Load data from tab 'Document' '''
        pass

    def load_tab_event(self):
        ''' TODO: Load data from tab 'Event' '''
        pass

    def load_tab_log(self):
        ''' TODO: Load data from tab 'Log' '''
        pass

    def load_tab_rtc(self):
        ''' TODO: Load data from tab 'RTC' '''
        pass

    def load_data(self):
        ''' Load data from related tables '''

        self.load_tab_add_info()
        self.load_tab_analysis()
        self.load_tab_document()
        self.load_tab_picture()
        self.load_tab_event()
        self.load_tab_log()
        self.load_tab_rtc()

    def save_tab_add_info(self):
        ''' Save tab from tab 'Add. info' '''
        pass

    def save_tab_analysis(self):
        ''' Save tab from tab 'Analysis' '''
        pass

    def save_tab_document(self):
        ''' TODO: Save tab from tab 'Document' '''
        pass

    def save_tab_picture(self):
        ''' TODO: Save tab from tab 'Document' '''
        pass

    def save_tab_event(self):
        ''' TODO: Save tab from tab 'Event' '''
        pass

    def save_tab_log(self):
        ''' TODO: Save tab from tab 'Log' '''
        pass

    def save_tab_rtc(self):
        ''' TODO: Save tab from tab 'RTC' '''
        pass

    def save_data(self):
        ''' Save data from related tables '''
        self.save_tab_add_info()
        self.save_tab_analysis()
        self.save_tab_document()
        self.save_tab_picture()
        self.save_tab_event()
        self.save_tab_log()
        self.save_tab_rtc()

    ''' Slot functions '''

    def save(self):
        ''' Save feature '''
        self.save_data()
        self.dialog.accept()
        self.layer.commitChanges()
        self.close()

    def close(self):
        ''' Close form without saving '''
        self.layer.rollBack()
        self.dialog.parent().setVisible(False)
예제 #16
0
class ParentDialog(object):   
    
    def __init__(self, iface, dialog, layer, feature):
        ''' Constructor class '''     
        self.iface = iface
        self.dialog = dialog
        self.layer = layer
        self.feature = feature
        self.init_config()             
    
        
    def init_config(self):    
        
        # initialize plugin directory
        user_folder = os.path.expanduser("~") 
        self.plugin_name = 'giswater'  
        self.plugin_dir = os.path.join(user_folder, '.qgis2/python/plugins/'+self.plugin_name)    
        
        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config', self.plugin_name+'.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: "+setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5)  
            self.close()
            return
            
        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())
        
        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()      
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING, 5) 
            return 
             
        self.schema_name = self.controller.getSchemaName()          
        self.dao = self.controller.getDao()
            
            
    def translate_form(self, context_name):
        ''' Translate widgets of the form to current language '''
        # Get objects of type: QLabel
        widget_list = self.dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translate_widget(context_name, widget)
            
            
    def translate_widget(self, context_name, widget):
        ''' Translate widget text '''
        if widget:
            widget_name = widget.objectName()
            text = utils_giswater.tr(context_name, widget_name)
            if text != widget_name:
                widget.setText(text)         
         
       
    def load_tab_add_info(self):
        ''' Load data from tab 'Add. info' '''                
        pass

    def load_tab_analysis(self):
        ''' Load data from tab 'Analysis' '''          
        pass
                
    def load_tab_document(self):
        ''' TODO: Load data from tab 'Document' '''   
        pass
                
    def load_tab_picture(self):
        ''' TODO: Load data from tab 'Document' '''   
        pass
                
    def load_tab_event(self):
        ''' TODO: Load data from tab 'Event' '''   
        pass
                
    def load_tab_log(self):
        ''' TODO: Load data from tab 'Log' '''   
        pass
        
    def load_tab_rtc(self):
        ''' TODO: Load data from tab 'RTC' '''   
        pass
    
    def load_data(self):
        ''' Load data from related tables '''
        
        self.load_tab_add_info()
        self.load_tab_analysis()
        self.load_tab_document()
        self.load_tab_picture()
        self.load_tab_event()
        self.load_tab_log()
        self.load_tab_rtc()
        

    def save_tab_add_info(self):
        ''' Save tab from tab 'Add. info' '''                
        pass

    def save_tab_analysis(self):
        ''' Save tab from tab 'Analysis' '''          
        pass
                
    def save_tab_document(self):
        ''' TODO: Save tab from tab 'Document' '''   
        pass
                
    def save_tab_picture(self):
        ''' TODO: Save tab from tab 'Document' '''   
        pass
                
    def save_tab_event(self):
        ''' TODO: Save tab from tab 'Event' '''   
        pass
                
    def save_tab_log(self):
        ''' TODO: Save tab from tab 'Log' '''   
        pass
        
    def save_tab_rtc(self):
        ''' TODO: Save tab from tab 'RTC' '''   
        pass
        
                        
    def save_data(self):
        ''' Save data from related tables '''        
        self.save_tab_add_info()
        self.save_tab_analysis()
        self.save_tab_document()
        self.save_tab_picture()
        self.save_tab_event()
        self.save_tab_log()
        self.save_tab_rtc()       
                
        
        
    ''' Slot functions '''           
               
    def save(self):
        ''' Save feature '''
        self.save_data()   
        self.dialog.accept()
        self.layer.commitChanges()    
        self.close()     
        
        
    def close(self):
        ''' Close form without saving '''
        self.layer.rollBack()   
        self.dialog.parent().setVisible(False)    
예제 #17
0
class NodeDialog():
    def __init__(self, iface, dialog, layer, feature):
        self.iface = iface
        self.dialog = dialog
        self.layer = layer
        self.feature = feature
        self.initConfig()

    def initConfig(self):

        self.node_id = utils_giswater.getStringValue2("node_id")
        self.epa_type = utils_giswater.getSelectedItem("epa_type")

        # initialize plugin directory
        user_folder = os.path.expanduser("~")
        self.plugin_name = 'giswater'
        self.plugin_dir = os.path.join(
            user_folder, '.qgis2/python/plugins/' + self.plugin_name)

        # Get config file
        setting_file = os.path.join(self.plugin_dir, 'config',
                                    self.plugin_name + '.config')
        if not os.path.isfile(setting_file):
            message = "Config file not found at: " + setting_file
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            self.close()
            return

        self.settings = QSettings(setting_file, QSettings.IniFormat)
        self.settings.setIniCodec(sys.getfilesystemencoding())

        # Get widget controls
        self.cbo_cat_nodetype_id = self.dialog.findChild(
            QComboBox, "cat_nodetype_iddd")
        self.cbo_nodecat_id = self.dialog.findChild(QComboBox, "nodecat_id")
        self.tab_analysis = self.dialog.findChild(QTabWidget, "tab_analysis")
        self.tab_event = self.dialog.findChild(QTabWidget, "tab_event")

        # Set controller to handle settings and database connection
        # TODO: Try to make only one connection
        self.controller = DaoController(self.settings, self.plugin_name)
        status = self.controller.set_database_connection()
        if not status:
            message = self.controller.getLastError()
            self.iface.messageBar().pushMessage(message, QgsMessageBar.WARNING,
                                                5)
            return

        self.schema_name = self.controller.getSchemaName()
        self.dao = self.controller.getDao()

        # Manage tab visibility
        self.setTabsVisibility()

        # Manage i18n
        self.translateForm()

        # Fill combo 'node type' from 'epa_type'
        self.fillNodeType()

        # Load data from related tables
        self.loadData()

        # Set layer in editing mode
        self.layer.startEditing()

    def translateForm(self):

        # Get objects of type: QLabel
        context_name = 'ws_node'
        widget_list = self.dialog.findChildren(QLabel)
        for widget in widget_list:
            self.translateWidget(context_name, widget)

    def translateWidget(self, context_name, widget):

        if widget:
            widget_name = widget.objectName()
            text = utils_giswater.tr(context_name, widget_name)
            if text != widget_name:
                widget.setText(text)

    def loadData(self):
        # Tab 'Add. info'
        if self.epa_type == 'TANK':
            sql = "SELECT vmax, area FROM " + self.schema_name + ".man_tank WHERE node_id = " + self.node_id
            row = self.dao.get_row(sql)
            if row:
                utils_giswater.setText("man_tank_vmax", str(row[0]))
                utils_giswater.setText("man_tank_area", str(row[1]))

    ''' Slots '''

    def fillNodeType(self):
        """ Define and execute query to populate combo 'cat_nodetype_id' """
        cat_nodetype_id = utils_giswater.getSelectedItem("cat_nodetype_id")
        sql = "SELECT id, man_table, epa_table FROM " + self.schema_name + ".arc_type WHERE epa_default = '" + self.epa_type + "' UNION "
        sql += "SELECT id, man_table, epa_table FROM " + self.schema_name + ".node_type WHERE epa_default = '" + self.epa_type + "' ORDER BY id"
        rows = self.dao.get_rows(sql)
        self.cbo_cat_nodetype_id = self.dialog.findChild(
            QComboBox, "cat_nodetype_id")
        utils_giswater.fillComboBox(self.cbo_cat_nodetype_id, rows)
        utils_giswater.setSelectedItem('cat_nodetype_id', cat_nodetype_id)

    def changeNodeType(self, index):
        """ Define and execute query to populate combo 'nodecat_id_dummy' """
        cat_nodetype_id = utils_giswater.getSelectedItem("cat_nodetype_id")
        sql = "SELECT id FROM " + self.schema_name + ".cat_arc WHERE arctype_id = '" + cat_nodetype_id + "' UNION "
        sql += "SELECT id FROM " + self.schema_name + ".cat_node WHERE nodetype_id = '" + cat_nodetype_id + "' ORDER BY id"
        rows = self.dao.get_rows(sql)
        self.cbo_nodecat_id = self.dialog.findChild(QComboBox,
                                                    "nodecat_id_dummy")
        utils_giswater.fillComboBox(self.cbo_nodecat_id, rows, False)
        self.changeNodeCat(0)

    def changeNodeCat(self, index):
        """ Just select item to 'real' combo 'nodecat_id' (that is hidden) """
        dummy = utils_giswater.getSelectedItem("nodecat_id_dummy")
        utils_giswater.setSelectedItem("nodecat_id", dummy)

    def changeEpaType(self, index):
        """ Just select item to 'real' combo 'nodecat_id' (that is hidden) """
        epa_type = utils_giswater.getSelectedItem("epa_type")
        self.save()
        self.iface.openFeatureForm(self.layer, self.feature)

    def setTabsVisibility(self):

        man_visible = False
        index_tab = 0
        if self.epa_type == 'JUNCTION':
            index_tab = 0
        if self.epa_type == 'RESERVOIR' or self.epa_type == 'HYDRANT':
            index_tab = 1
        if self.epa_type == 'TANK':
            index_tab = 2
            man_visible = True
        if self.epa_type == 'PUMP':
            index_tab = 3
        if self.epa_type == 'VALVE':
            index_tab = 4
        if self.epa_type == 'SHORTPIPE' or self.epa_type == 'FILTER':
            index_tab = 5
        if self.epa_type == 'MEASURE INSTRUMENT':
            index_tab = 6

        # Tab 'Add. info': Manage visibility of these widgets
        utils_giswater.setWidgetVisible("label_man_tank_vmax", man_visible)
        utils_giswater.setWidgetVisible("label_man_tank_area", man_visible)
        utils_giswater.setWidgetVisible("man_tank_vmax", man_visible)
        utils_giswater.setWidgetVisible("man_tank_area", man_visible)

        # Move 'visible' tab to last position and remove previous ones
        self.tab_analysis.tabBar().moveTab(index_tab, 5)
        for i in range(0, self.tab_analysis.count() - 1):
            self.tab_analysis.removeTab(0)
        self.tab_event.tabBar().moveTab(index_tab, 6)
        for i in range(0, self.tab_event.count() - 1):
            self.tab_event.removeTab(0)

    def save(self):
        if self.epa_type == 'TANK':
            vmax = utils_giswater.getStringValue2("man_tank_vmax")
            area = utils_giswater.getStringValue2("man_tank_area")
            sql = "UPDATE " + self.schema_name + ".man_tank SET vmax = " + str(
                vmax) + ", area = " + str(area)
            sql += " WHERE node_id = " + str(self.node_id)
            print sql
            self.dao.execute_sql(sql)
        self.dialog.accept()
        self.layer.commitChanges()
        self.close()

    def close(self):
        self.layer.rollBack()
        self.dialog.parent().setVisible(False)