Exemplo n.º 1
0
class SetManagerPluginGUI(QWidget):
    
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.builder = GBuilder()
        self.create_widgets()
            
         
                
    def create_widgets(self):   
        
        ''' Widgets'''
        self.desc_label = self.builder.label(self, "<b>Decription:</b> Configure the settings for the mapping Timing - Project Sets")
        self.desc_label.setFixedHeight(25)        
        self.desc_label.setFixedWidth(400)
                        
        self.selection_cb = self.builder.combobox(self, [], self.cb_selection_changed)
        self.selection_cb.setFixedHeight(25)
        
        self.sec_label = self.builder.label(self, "<b>Use Set: </b>")
        self.sec_label.setFixedHeight(25)
        self.sec_label.setFixedWidth(50)
                
        self.open_manager = self.builder.pushbutton(self, "Setting Manager", self._open_manager_act,\
                                                    icon_path =  os.getcwd() +r'/icons/settings.png')
        self.open_manager.setFixedHeight(35)
        
        
        ''' Layout '''
        vbox = QtGui.QVBoxLayout()
        
        hl = QtGui.QHBoxLayout()
        hl.addWidget(self.desc_label)
        hl.addWidget(self.open_manager)        
        vbox.addLayout(hl)
        
        hl = QtGui.QHBoxLayout()
        hl.addWidget(self.sec_label)
        hl.addWidget(self.selection_cb)        
        vbox.addLayout(hl)
        
        self.setLayout(vbox)
        
#         self.open_manager_act()
                
    def cb_selection_changed(self):
        pass
        
    def _open_manager_act(self):        
        man =  SettingManager()
        man.exec()
Exemplo n.º 2
0
class DirectViewWindow(QtGui.QMainWindow):
    '''
    View Window that can be connected to a simulation
    '''
    def __init__(self, views, *args, **kwargs):
        QtGui.QMainWindow.__init__(self, *args, **kwargs)
        
        ''' 1. members '''
        self.builder = GBuilder()       

        ''' 2. initialize the gui factories '''
        self.view_plugins = views
        
        ''' 3. actions '''
        self.init_actions()
        self.create_widgets()
    
    @try_ex          
    def create_widgets(self):
        
        ''' 1. Main window '''
        self.setWindowTitle('TUMCreate - Automotive Simulator - Direct View')
        self.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo2.png')))
        self.builder.set_props(self, ctr_lout=True, min_sz_x=1200, min_sz_y=700)

        ''' 2. Two Group Boxes '''              
        self.groupb_info = self.builder.groupbox(self, 'Information', max_height=200, max_width=2000) 
        self.set_info_group()
        
        self.groupb_viewer = self.builder.groupbox(self, 'View')
        self.set_viewer_group()
        
        ''' 3. Init Menubar '''
        self.init_menubar();            
                
        ''' 4. Toolbar'''
        self.toolbar_gen_sets = self.builder.toolbar(self, GEnums.T_TOP, actions=self.gen_set_actions)
        
        ''' 5. Create Layout'''
        self.init_layout()
    
    @try_ex
    def init_actions(self):
        
        ''' 1. Create General Settings'''   

        self.exit_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/exit.png')), '&Exit', self)        
        self.exit_action.setShortcut('Ctrl+Q')
        self.exit_action.setStatusTip('Exit application')
        self.exit_action.triggered.connect(QtGui.qApp.quit)
        
        self.help_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/help.png')), '&Help', self)        
        self.help_action.setShortcut('F3')
        self.help_action.setStatusTip('Open Help')
        self.help_action.triggered.connect(QtGui.qApp.quit)
               
        self.clear_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/clear.png')), '&Clear all parameters', self)        
        self.clear_action.setShortcut('Ctrl+Shift+N')
        self.clear_action.setStatusTip('Open Help')
        self.clear_action.triggered.connect(QtGui.qApp.quit) 
        
        self.load_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/load.png')), '&Clear all parameters', self)        
        self.load_action.setShortcut('Ctrl+Shift+L')
        self.load_action.setStatusTip('Load file')
        self.load_action.triggered.connect(self._load_views_hit) 
        
        ''' 2. define all actions that will appear in the general Toolbar '''
        self.gen_set_actions = [self.clear_action, self.help_action, self.load_action]
    
    @try_ex
    def init_layout(self):
        ''' Sets the layout for the three main groupboxes '''
        
        main_layout = self.centralWidget().layout()
        
        h_layout = QtGui.QHBoxLayout()
        
        h_layout.addWidget(self.groupb_info)        
        
        main_layout.addLayout(h_layout)
        
        main_layout.addWidget(self.groupb_viewer)
         
    @try_ex
    def init_menubar(self):
        
        ''' 1. Create Menubar'''
        menubar = self.menuBar()
        
        ''' 2. add Menus and actions'''        
        # File
        file_menu = menubar.addMenu('&File')
        file_menu.addAction(self.exit_action)
                
        # Help        
        help_menu = menubar.addMenu('&Help')
        help_menu.addAction(self.help_action)
        
    def link_axis(self):   
        link_plot = False     
        for view in self.view_plugins:
            # check if there are link axis
            p = view.link_axis()
            if p != None:
                if link_plot:
                    p.setXLink(link_plot)
                else:
                    link_plot = p
        
    @try_ex
    def set_cb_changed_event_set(self):
        self.settings_stack.setCurrentIndex(self.settings_cbox.currentIndex())

    @try_ex
    def set_info_group(self):

        ''' 1. Logo'''
        self.space = QtGui.QLabel()
        self.info_label = QtGui.QLabel("\nTitle:          \t%s \nAuthor:          \t%s\nCompany:\t%s\nDepartement:\t%s\nVersion:          \t%s" % (__title__, __author__, __enterprise__, __departement__ , __version__))
        self.space.setFixedWidth(10)
        
        self.info_logo = self.builder.image(self.groupb_info, os.path.dirname(__file__)[:-4] + r'/icons/tumcreatelogo.png', 2.4)
        self.info_logo.setMaximumWidth(270)
        
        ''' 2. Description Text '''
        self.desc_txt = self.builder.label(self.groupb_info, "<b>Description:    </b>" + '\n\nThis application simulates an automotive environment. It offers the possibility to perform timing analyses of communication flows between a certain number of ECUs.')
                   
        ''' 3. Groupbox Layout'''
        v_layout = QtGui.QVBoxLayout(self.groupb_info)  
                      
        h_layout_one = QtGui.QHBoxLayout()
        h_layout_one.addWidget(self.space)
        h_layout_one.addWidget(self.info_label)        
        h_layout_one.addWidget(self.info_logo)

        v_layout.addLayout(h_layout_one)
        v_layout.addWidget(self.desc_txt)
    
    @try_ex
    def set_cb_changed_event_view(self, e):
        # check which items are selected and show all of them
        try:
            # clear all
            try:
                for ky in self.wid_to_idx:
                    self.wid_to_idx[ky].setParent(None)                
            except:
                ECULogger().log_traceback()
            
            # get checked items
            checked_idx = []
            for cnt in range(self.viewer_cbox.count()):
                item = self.viewer_cbox.model().item(cnt, 0)
                if item.checkState():                
                    checked_idx.append(cnt)
            
            row_nr = int(self.arrange_rows.text())
            col_nr = int(self.arrange_cols.text())
            
            if row_nr * col_nr < len(checked_idx):
                row_nr = ceil(float(len(checked_idx)) / col_nr) 
                self.arrange_rows.setText(str(row_nr))
            # arrange
            cnt = 0
            for r in range(row_nr):            
                hlay = QHBoxLayout()
                for c in range(col_nr):
                    try:
                        wid = self.wid_to_idx[checked_idx[cnt]]; cnt += 1
                        hlay.addWidget(wid)
                    except:
                        pass
                try:
                    self.main_v_layout.addLayout(hlay)
                except:
                    pass
        except:
            pass

    @try_ex
    def set_viewer_group(self):
        
        ''' 1. Load Items from viewer factory '''
        self.wid_to_idx = {}
        self.viewer_cbox = self.builder.checkable_combobox(self.groupb_viewer, [], self.set_cb_changed_event_view)
        self.save_but = self.builder.pushbutton(self.groupb_viewer, "Save", self._save_hit)
        self.save_but.setFixedWidth(100)
        
        # field to enter arrangement
        [lay_r, self.arrange_rows] = self.builder.label_text(self.groupb_viewer, "rows:", 25, 40, self.set_cb_changed_event_view)
        self.arrange_rows.setText('2')
        [lay_c, self.arrange_cols] = self.builder.label_text(self.groupb_viewer, "columns:", 40, 40, self.set_cb_changed_event_view)
        self.arrange_cols.setText('2')
        
        cnt = 0
        for view in self.view_plugins:            
            if view != None:
                self.viewer_cbox.addItem(view.get_combobox_name())
                item = self.viewer_cbox.model().item(cnt, 0)
                item.setCheckState(QtCore.Qt.Checked)
                self.wid_to_idx[cnt] = view.get_widget(self)
                cnt += 1

        ''' Layout '''
        self.main_v_layout = QVBoxLayout()
        self.viewer_cbox.setFixedHeight(25)       
        
        hl = QHBoxLayout()
        hl.addWidget(self.viewer_cbox)   
        hl.addLayout(lay_r)
        hl.addLayout(lay_c)     
        hl.addWidget(self.save_but)
        self.main_v_layout.addLayout(hl)           
              
        self.groupb_viewer.setLayout(self.main_v_layout)       
    
        self.set_cb_changed_event_view(None)
    
    def _load_views_hit(self, filename=False):
        
        if not filename:
            filename = QtGui.QFileDialog.getOpenFileName(self, 'Load', '', 'Simulation (*.tum)')
        with open(filename, 'rb') as f:
            save_vals = pickle.load(f)
        
        for view in self.view_plugins:  
            if view != None:
                try:
                    save_val = save_vals[view.get_combobox_name()]
                except:
                    logging.warn("Warning: On GUI load no saved values found for %s" % view.__class__.__name__)
#                     ECULogger().log_traceback()
                    continue
                view.load(save_val)

    def _save_hit(self):
        
        save_vals = {}
        
        for view in self.view_plugins:  
            if view != None:
                try:
                    print("Call save on %s" % view)
                    save_val = view.save()
                    print("OK!")
                except:
                    ECULogger().log_traceback()
                    continue
                save_vals[view.get_combobox_name()] = save_val
        
        filename = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", ".tum")
        with open(filename, 'wb') as f:          
            pickle.dump(save_vals, f, pickle.HIGHEST_PROTOCOL)
Exemplo n.º 3
0
class MainWindow(QtGui.QMainWindow):
    '''
    Main Window of the application
    '''
    def __init__(self, *args, **kwargs):
        QtGui.QMainWindow.__init__(self, *args, **kwargs)
        
        ''' 1. members '''
        self.builder = GBuilder()
        self.monitor = Monitor()
        self.setWindowTitle('TUMCreate - Automotive Simulator')
        self.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo2.png')))
        
        ''' 2. initialize the gui factories '''
        ViewerPluginFactory().load_classes()
        SettingsPluginFactory().load_classes()
        
        ''' 3. actions '''
        self.init_actions()
        self.create_widgets()
              
    def create_widgets(self):
        
        ''' 1. Main window '''
        self.builder.set_props(self, ctr_lout=True, min_sz_x=1200, min_sz_y=700)
        
        ''' 2. Three Group Boxes '''
        self.groupb_settings = self.builder.groupbox(self, 'Settings', max_height=200)
        self.set_settings_group()
              
        self.groupb_info = self.builder.groupbox(self, 'Information', max_height=200, max_width=700) 
        self.set_info_group()
        
        self.groupb_viewer = self.builder.groupbox(self, 'View')
        self.set_viewer_group() 
        
        ''' 3. Init Menubar '''
        self.init_menubar();            
                
        ''' 4. Toolbar'''
        self.toolbar_gen_sets = self.builder.toolbar(self, GEnums.T_TOP, actions=self.gen_set_actions)

        ''' 5. Create Layout'''
        self.init_layout()
    
    def create_aut_env(self):  # Spaeter on Button Click z.B.
        ''' this method creates the simulation'''               
        
        api_log_path = os.path.join(os.path.dirname(__file__), "../logs/api.log")
        api.show_logging(logging.INFO, api_log_path, True)
        my_env = api.create_environment(2500)
        
        ecu_spec = SimpleECUSpec([], 200, 200)
        ecu_group_1 = api.set_ecus(my_env, 10, 'SecureECU', ecu_spec)
        
        ecu_spec = SimpleECUSpec(['SEC 1'], 200, 200)
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 100)
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 1000)
        
        sec_mod_group = api.set_ecus(my_env, 1, 'SecLwAuthSecurityModule', ecu_spec)
        
        bus_spec = SimpleBusSpec(['CAN_0'])
        bus_group = api.set_busses(my_env, 1, 'StdCANBus', bus_spec)
        api.connect_bus_by_obj(my_env, 'CAN_0', ecu_group_1 + sec_mod_group)
        
        api.register_ecu_groups_to_secmod(my_env, sec_mod_group[0].ecu_id, [ecu_group_1])
        
        certeros = api.create_cert_manager()
        for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]):  # UNINTENDED HACK
            api.generate_valid_ecu_cert_cfg(certeros, ecu.ecu_id, CAEnum.CA_L313, 'SEC 1', 0, float('inf'))
        api.generate_valid_sec_mod_cert_cfg(certeros, 'SEC 1', CAEnum.CA_L313, 0, float('inf'))
        api.apply_certification(my_env, certeros)
        
        
        stream_1 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_1', 'SecureECU_4', 'SecureECU_5'], 13, float('inf'), 0, float('inf'))
        stream_2 = MessageStream(my_env.get_env(), 'SecureECU_1', ['SecureECU_3', 'SecureECU_2', 'SecureECU_5'], 12, float('inf'), 0, float('inf'))
        stream_3 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_4', 'SecureECU_1', 'SecureECU_5'], 222, float('inf'), 0, float('inf'))
        stream_4 = MessageStream(my_env.get_env(), 'SecureECU_3', ['SecureECU_0', 'SecureECU_1', 'SecureECU_5'], 11, float('inf'), 0, float('inf'))
        stream_5 = MessageStream(my_env.get_env(), 'SecureECU_4', ['SecureECU_2', 'SecureECU_1', 'SecureECU_3'], 500, float('inf'), 0, float('inf'))
        api.add_allowed_stream(my_env, 'SEC 1', stream_1)
        api.add_allowed_stream(my_env, 'SEC 1', stream_2)
        api.add_allowed_stream(my_env, 'SEC 1', stream_3)
        api.add_allowed_stream(my_env, 'SEC 1', stream_4)
        api.add_allowed_stream(my_env, 'SEC 1', stream_5)
        
        t_set = TimingFunctionSet()
        ecu_func_set = StdSecurLwSecModTimingFunctions(main_library_tag='CyaSSL')
        t_set.set_mapping_from_function_set('SEC 1', ecu_func_set)
        api.apply_timing_functions_set(my_env, 'SEC 1', t_set)
          
        t_set2 = TimingFunctionSet() 
        ecu_func_set = StdSecurECUTimingFunctions(main_library_tag='CyaSSL')
        
        for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]):  # UNINTENDED HACK
            t_set2.set_mapping_from_function_set(ecu.ecu_id, ecu_func_set) 
            api.apply_timing_functions_set(my_env, ecu.ecu_id, t_set2)

        api.connect_monitor(my_env, self.monitor, 50)
        api.build_simulation(my_env)
        
        ''' start this in a new thread'''
        sim = SimulationThread(self, my_env)
        sim.start()
          
    def init_actions(self):
        
        ''' 1. Create General Settings'''   
        self.exit_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/exit.png')), '&Exit', self)    
        self.exit_action.setShortcut('Ctrl+Q')
        self.exit_action.setStatusTip('Exit application')
        self.exit_action.triggered.connect(QtGui.qApp.quit)
        
        self.help_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/help.png')), '&Help', self)        
        self.help_action.setShortcut('F3')
        self.help_action.setStatusTip('Open Help')
        self.help_action.triggered.connect(QtGui.qApp.quit)
               
        self.clear_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/clear.png')), '&Clear all parameters', self)        
        self.clear_action.setShortcut('Ctrl+Shift+N')
        self.clear_action.setStatusTip('Open Help')
        self.clear_action.triggered.connect(QtGui.qApp.quit) 
        
        ''' 2. define all actions that will appear in the general Toolbar '''
        self.gen_set_actions = [self.clear_action, self.help_action]

    def init_layout(self):
        ''' Sets the layout for the three main groupboxes '''
        
        main_layout = self.centralWidget().layout()
        
        h_layout = QtGui.QHBoxLayout()
        
        h_layout.addWidget(self.groupb_settings)
        h_layout.addWidget(self.groupb_info)        
        
        main_layout.addLayout(h_layout)
        main_layout.addWidget(self.groupb_viewer)
         
    def init_menubar(self):
        
        ''' 1. Create Menubar'''
        menubar = self.menuBar()
        
        ''' 2. add Menus and actions'''        
        # File
        file_menu = menubar.addMenu('&File')
        file_menu.addAction(self.clear_action)
        file_menu.addAction(self.exit_action)
                
        # Help        
        help_menu = menubar.addMenu('&Help')
        help_menu.addAction(self.help_action)
    
    def set_settings_group(self):
        
        ''' 1. Load Items from settings factory '''
        set_fact = SettingsPluginFactory()
        self.settings_stack = QtGui.QStackedWidget()
        
        self.settings_cbox = self.builder.combobox(self.groupb_settings, [], self.set_cb_changed_event_set)

        for setting_plugin in set_fact.createable_objects():
            setting = set_fact.make(setting_plugin)
            
            if setting != None:                                                       
                self.settings_stack.addWidget(setting.get_widget(self))
                self.settings_cbox.addItem(setting.get_combobox_name())                
                
        ''' layout '''
        v_layout = QVBoxLayout()
                
        self.settings_cbox.setFixedHeight(20)        
        v_layout.addWidget(self.settings_cbox) 
        v_layout.addWidget(self.settings_stack) 
    
        self.groupb_settings.setLayout(v_layout)
    
    def set_cb_changed_event_set(self):
        self.settings_stack.setCurrentIndex(self.settings_cbox.currentIndex())

    def set_info_group(self):

        ''' 1. Logo'''
        self.space = QtGui.QLabel()
        self.info_label = QtGui.QLabel("\nTitle:          \t%s \nAuthor:          \t%s\nCompany:\t%s\nDepartement:\t%s\nVersion:          \t%s" % (__title__, __author__, __enterprise__, __departement__ , __version__))
        self.space.setFixedWidth(10)
        
        self.info_logo = self.builder.image(self.groupb_info, os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo.png', 2.4))
        self.info_logo.setMaximumWidth(270)
        
        ''' 2. Description Text '''
        self.desc_txt = self.builder.label(self.groupb_info, "<b>Description:    </b>" + '\n\nThis application simulates an automotive environment. It offers the possibility to perform timing analyses of communication flows between a certain number of ECUs.')
                   
        ''' 3. Groupbox Layout'''
        v_layout = QtGui.QVBoxLayout(self.groupb_info)  
                      
        h_layout_one = QtGui.QHBoxLayout()
        h_layout_one.addWidget(self.space)
        h_layout_one.addWidget(self.info_label)        
        h_layout_one.addWidget(self.info_logo)

        v_layout.addLayout(h_layout_one)
        v_layout.addWidget(self.desc_txt)

    def set_cb_changed_event_view(self):
        self.viewer_stack.setCurrentIndex(self.viewer_cbox.currentIndex())

    def set_viewer_group(self):
        
        ''' 1. Load Items from viewer factory '''
        view_fact = ViewerPluginFactory()
        self.viewer_stack = QtGui.QStackedWidget()        
        self.viewer_cbox = self.builder.combobox(self.groupb_viewer, [], self.set_cb_changed_event_view)
        self.set_start_button = self.builder.pushbutton(self.groupb_viewer, 'Start Simulation', self.create_aut_env)
        self.set_start_button.setFixedWidth(200)
        self.set_start_button.setFixedHeight(25)

        for viewer_plugin in view_fact.createable_objects():
            view = view_fact.make(viewer_plugin)
            if view != None:
                view.set_monitor(self.monitor)                 
                self.viewer_stack.addWidget(view.get_widget(self))
                self.viewer_cbox.addItem(view.get_combobox_name())                

        ''' layout '''
        v_layout = QVBoxLayout()                
        self.viewer_cbox.setFixedHeight(25)       
        v_layout.addWidget(self.viewer_stack)  
        
        hl = QHBoxLayout()
        hl.addWidget(self.viewer_cbox)
        hl.addWidget(self.set_start_button)
        v_layout.addLayout(hl)           
              
        self.groupb_viewer.setLayout(v_layout)    
Exemplo n.º 4
0
class SettingManager(QDialog):
    
    def __init__(self, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
    
        self.builder = GBuilder()        
        self.setWindowIcon(QtGui.QIcon( os.getcwd() +r'/icons/tumcreatelogo2.png'))
        self.setWindowTitle("Timing Set Manager")    
        self.selected_tab_row = 0
        
        self.create_widgets()        
        
        self._load_variables()   

    def create_widgets(self):
        
        ''' Create Widgets'''
        self.builder.set_props(self, False, 1200, 740)

        self.desc_label = self.builder.label(self, "Description: \nEdit an existing Timing Mapping Parameter Set or create a new one")
        self.desc_label.setFixedHeight(50)
        
        self.set_cb = self.builder.combobox(self, [], self.set_cb_selection_changed)
        self.set_cb.setFixedHeight(22)
        
        self.set_plus_pb = self.builder.pushbutton(self, "Add", self.add_hit, os.getcwd() +r'/icons/add.png')
        self.set_plus_pb.setFixedWidth(100)
        self.set_plus_pb.setFixedHeight(30)
                
        self.elem_tab = self.builder.table(self, 0, 5, ["Affiliation", "Timing Variable", "Type", "Value", "Condition"])        
        self.elem_tab.cellDoubleClicked.connect(self._cell_double_clicked)
        
        ''' Save and Exit Buttons '''        
        self.space = self.builder.label(self, "")
#         self.space.setFixedWidth(300)
        self.ok_pb = self.builder.pushbutton(self, "Ok", self.ok_hit)
        self.ok_pb.setFixedHeight(30)
        self.ok_pb.setFixedWidth(140)
        self.apply_pb = self.builder.pushbutton(self, "Apply", self.apply_hit)
        self.apply_pb.setFixedHeight(30)
        self.apply_pb.setFixedWidth(140)
        self.cancel_pb = self.builder.pushbutton(self, "Cancel", self.cancel_hit)
        self.cancel_pb.setFixedHeight(30)
        self.cancel_pb.setFixedWidth(140)
                
        ''' Layout '''
        v_lay = QVBoxLayout()        
        v_lay.addWidget(self.desc_label)
        
        hl = QHBoxLayout()
        hl.addWidget(self.set_plus_pb)
        hl.addWidget(self.set_cb)
        v_lay.addLayout(hl)
        
        v_lay.addWidget(self.elem_tab)     
        
        hl = QHBoxLayout()
        hl.addWidget(self.space)
        hl.addWidget(self.ok_pb)
        hl.addWidget(self.cancel_pb)   
        hl.addWidget(self.apply_pb)
        v_lay.addLayout(hl)
        
        self.setLayout(v_lay)       
        
    def _load_variables(self):
        ''' Load all timing Variables that are specified in the timing.ini '''
        timing_vars = []
        self.db_lookup_dict = {}
        
        ''' 1. Load the variables '''
        for reg_tim in Registrator().reg_simple_timings.keys():
            for l in Registrator().reg_simple_timings[reg_tim]:
                dic = Registrator().reg_simple_timings[reg_tim][l]
                
                lst = list(dic.keys())
                try:                            
                    lst += Registrator().db_lookup_timings[reg_tim][l]
                    self.db_lookup_dict[l] = list(Registrator().db_lookup_timings[reg_tim][l].keys())
                except:
                    pass
    
                timing_vars.append([l, lst, reg_tim, dic])
                
        ''' 2. Set table from variables'''
        self._set_timing_tab(timing_vars)
        
    def _set_timing_tab(self, timing_vars):
                
        self.elem_tab.setRowCount(len(timing_vars))
        self.db_lookup_idx_to_info = {}
             
        self.type_cb_to_idx = {}
        self.type_idx_to_cb = {}
        self.type_item_state = {}
        self.type_to_dict = {}
                
        for i in range(len(timing_vars)):
            
            cur_var = timing_vars[i][0]
            cur_vals = timing_vars[i][1]
            cur_ass = timing_vars[i][2]
            cur_vals_dict = timing_vars[i][3]            
                        
            ''' 1. Set Variable Name '''
            self.elem_tab.setItem(i, 0, QTableWidgetItem(cur_ass))
            self.elem_tab.setItem(i, 1, QTableWidgetItem(cur_var))
            self.elem_tab.setItem(i, 2, QTableWidgetItem())
            self.type_to_dict[cur_var] = cur_vals_dict            
            
            ''' 2. Set Setting '''
            wid = QWidget()
            vl = QVBoxLayout()
            cb = self.builder.combobox(self, cur_vals + ["new Setting ..."], self.on_type_cb_itemchanged)
            self.type_cb_to_idx[str(cb)] = i
            self.type_idx_to_cb[i] = cb
            cb.setFixedHeight(20)            
            vl.addWidget(cb)
            wid.setLayout(vl)
            self.elem_tab.setCellWidget(i, 2, wid)            
            self.type_item_state[i] = cb.currentText()
            
            ''' 3. Set value'''
            self.elem_tab.setItem(i, 3, QTableWidgetItem(str(cur_vals_dict[cb.currentText()])))
            
    def on_type_cb_itemchanged(self):
        ''' changed index if new Setting hit create new Setting'''
        
        for i in range(self.elem_tab.rowCount()):
            try:
                cb = self.type_idx_to_cb[i]
                if(cb.currentText() == "new Setting ..."):
                    idx = cb.findText(self.type_item_state[i])
                    cb.setCurrentIndex(idx)                    
                    self.new_setting(i)
                    continue
                
                if cb.currentText() != self.type_item_state[i] and cb.currentText() != 'CUSTOMIZED':
                    ''' load values '''#                     
                    itm = self.elem_tab.item(i, 1)
                    txt = itm.text()
                    cor_dic = self.type_to_dict[txt]
                    try:
                        val = cor_dic[cb.currentText()]                    
                        self.elem_tab.setItem(i, 3, QTableWidgetItem(str(val)))
                    except:
                        pass
                    
                    self.db_lookup_dict[txt]
                    
                    itm1 = self.elem_tab.item(i, 0)
                    itm2 = self.elem_tab.item(i, 1)
                    
                    ''' if DB Lookup show request -> double click opens window: edit request and edit the condition '''
                    [request, spec] = TimingDBMap().lookup_from_spec(itm1.text(), itm2.text(), cb.currentText())
                    [condition, spec] = TimingDBMap().conditions_from_spec(itm1.text(), itm2.text(), cb.currentText())                    
                    itm = QTableWidgetItem(request)                    
                    self.elem_tab.setItem(i, 4, itm)
                    itm.setToolTip("Conditions: \n%s" % self._pretty_str_cond(condition))
                    self.db_lookup_idx_to_info[i] = [condition, request, spec]
                        
                self.type_item_state[i] = cb.currentText()
            except:
                pass
            
        
    def _pretty_str_cond(self, conditions):
        out_str = ""
        
        for el in conditions:
            out_str += "\nName:\t\t"
            out_str += el['name']
            out_str += "\nConfig:\t\t"
            out_str += str(el['config'])
            out_str += "\nValue:\t\t"
            out_str += str(el['value'])
            out_str += "\n"
            
        return out_str
            
    def _cell_double_clicked(self, row, col):
        print("DOUBLE CLICKED row %s" % row)
        try:
            [condition, request, spec] = self.db_lookup_idx_to_info[row]
            DBElemEditor(condition, request, spec, self.elem_tab.item(row, 4))

        except:
            pass

    def new_setting(self, row):
        print("Create new setting in row %s" % row)
        
    
    def add_hit(self):
        print("asd")
    
    def ok_hit(self):
        print("ok")
    
    def apply_hit(self):
        print("Apply")
    
    def cancel_hit(self):
        self.close()
    
    def set_cb_selection_changed(self):
        pass
Exemplo n.º 5
0
class DBElemEditor(QDialog):
    
    def __init__(self, condition, request, spec, q_tab_item):
        QWidget.__init__(self)
        
        self.builder = GBuilder()
        
        self.edited_item = q_tab_item
        self.condition = condition
        self.request = request
        self.spec_node = spec
        
        self._create_widget()
        
        self._fill_widgets()
        
        self.exec()
        
    def _create_widget(self):
        
        self.builder.set_props(self, False, 820, 300)
        self.setWindowIcon(QtGui.QIcon( os.getcwd() +r'/icons/tumcreatelogo2.png'))
        
        self.tit_label = self.builder.label(self, "Description: \nEdit the Database request and the conditions")
            
        self.left_label = self.builder.label(self, "Database request:")    
        
        self.db_textbox = QtGui.QTextEdit()
    
    
        self.cond_label = self.builder.label(self, "Conditions for Database with ID:") 
        self.condition_tab = self.builder.table(self, len(self.condition), 6, ["ID", 'Lookup DB', "Var Name", "Var Config", "Type", "Value"], False)
        self.condition_tab.verticalHeader().hide()
        self.condition_tab.setColumnWidth(2, 250)
        
        
        self.add_pb = self.builder.pushbutton(self, "Add Item", self.add_hit, icon_path = os.getcwd() +r'/icons/add.png')
        self.add_pb.setFixedHeight(30)
        self.add_pb.setFixedWidth(200)
        self.del_pb = self.builder.pushbutton(self, "Delete Item", self.delete_hit, icon_path = os.getcwd() +r'/icons/delete.png')
        self.del_pb.setFixedHeight(30)
        self.del_pb.setFixedWidth(200)
        
        
        self.space = self.builder.label(self, "")
        self.ok_pb = self.builder.pushbutton(self, "Ok", self.ok_hit)
        self.ok_pb.setFixedHeight(30)
        self.ok_pb.setFixedWidth(140)
        self.cancel_pb = self.builder.pushbutton(self, "Cancel", self.cancel_hit)
        self.cancel_pb.setFixedHeight(30)
        self.cancel_pb.setFixedWidth(140)
                
    
        ''' Layout '''
        v_lay = QVBoxLayout()
        
        v_lay.addWidget(self.tit_label)
        
        v_lay.addWidget(self.left_label)
    
        v_lay.addWidget(self.db_textbox)
        v_lay.addWidget(self.cond_label)
        v_lay.addWidget(self.condition_tab)
    
        hl = QHBoxLayout()
        hl.addWidget(self.add_pb)
        hl.addWidget(self.del_pb) 
        
        hl.addWidget(self.space)
        hl.addWidget(self.ok_pb)
        hl.addWidget(self.cancel_pb)   
        v_lay.addLayout(hl)
    
        self.setLayout(v_lay)
    
    def _fill_widgets(self):
        
        self.db_textbox.setText(self.request)
        
        db_path = self.spec_node.attrib['dbpath']
        spec_id = self.spec_node.attrib['id']
        found_vars = self.spec_node.findall('{http://www.tum-create.edu.sg/timingSchema}variable')
        if found_vars == None: return
        
        i = 0
        for var in found_vars:
            var_name = var.attrib['name']
            var_config = var.attrib['config']
            var_type = var.attrib['type']
        
            val = var.find('{http://www.tum-create.edu.sg/timingSchema}value')
            if val == None: return
            var_value = val.text

            self.condition_tab.setItem(i, 0, QTableWidgetItem(spec_id))
            self.condition_tab.setItem(i, 1, QTableWidgetItem(db_path))
            self.condition_tab.setItem(i, 2, QTableWidgetItem(var_name))
            self.condition_tab.setItem(i, 3, QTableWidgetItem(var_config))
            self.condition_tab.setItem(i, 4, QTableWidgetItem(var_type))
            self.condition_tab.setItem(i, 5, QTableWidgetItem(var_value))
    
            i += 1
    
    def add_hit(self):                
        self.condition_tab.setRowCount(self.condition_tab.rowCount() + 1)
        
    def delete_hit(self):                
        cur_row = self.condition_tab.currentRow()
        self.condition_tab.removeRow(cur_row)
        
    
    def ok_hit(self):
#         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '''
        CONTINUE HERE:
            TODO: 
                Read out changes from the table and write it back to the timing Mapping file and save it (but only after Editor closed)
  
        '''
        for i in range(self.condition_tab.rowCount()): 
            for j in range(self.condition_tab.columnCount()):            
                itm = self.condition_tab.item(i, j)
                if j == 0: k = 1
            
        
        
        
        
        
        print("ok")
        
    def cancel_hit(self):
        self.close()