def makeAction(self,title, method, icon = None):
   action = QAction(title,None)
   action.setIcon(QIcon(icon))
   
   # We do this magic, so that the title string from the action is used to trigger the version change
   def methodWrapper():
     method(title)
   
   action.triggered.connect( methodWrapper )
   return action     
Example #2
0
def titleStringTriggeredAction(title, method, icon=None):
    action = QAction(title, None)
    action.setIcon(QIcon(icon))

    # We do this magic, so that the title string from the action is used to set the status
    def methodWrapper():
        method(title)

    action.triggered.connect(methodWrapper)
    return action
Example #3
0
def titleStringTriggeredAction(title, method, icon = None):
  action = QAction(title,None)
  action.setIcon(QIcon(icon))
  
  # We do this magic, so that the title string from the action is used to set the status
  def methodWrapper():
    method(title)
  
  action.triggered.connect( methodWrapper )
  return action
Example #4
0
File: gui.py Project: r3/r3tagger
 def _createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered"):
     action = QAction(text, self)
     if icon is not None:
         action.setIcon(QIcon(":/{0}.png".format(icon)))
     if shortcut is not None:
         action.setShortcut(shortcut)
     if tip is not None:
         action.setToolTip(tip)
         action.setStatusTip(tip)
     if slot is not None:
         getattr(action, signal).connect(slot)
     if checkable:
         action.setCheckable(True)
     return action
Example #5
0
	def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False,
	                  signal="triggered()"):
		action = QAction(text, self)
		if icon is not None:
			action.setIcon(QIcon(icon))
		if shortcut is not None:
			action.setShortcut(shortcut)
		if tip is not None:
			action.setToolTip(tip)
			action.setStatusTip(tip)
		if slot is not None:
			self.connect(action, SIGNAL(signal), slot)
		if checkable:
			action.setCheckable(True)
		return action
Example #6
0
File: app.py Project: lite/pystut
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
#        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
#        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
#        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
#        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
#        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
#        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
#        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
#        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
#        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)       
        iconToolBar = self.addToolBar("iconBar.png")
#------------------------------------------------------
# Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")       
        action_Close.setIcon(QIcon(":/quit.png"))
#------------------------------------------------------
# Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
#------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())
 
        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
Example #7
0
File: app.py Project: lite/pystut
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
        #        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
        #        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        #        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        #        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
        #        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        #        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
        #        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
        #        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)
        iconToolBar = self.addToolBar("iconBar.png")
        #------------------------------------------------------
        # Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")
        action_Close.setIcon(QIcon(":/quit.png"))
        #------------------------------------------------------
        # Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
        #------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())

        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
class DataInspector(QMainWindow):
    """
    DataInspector main class
    """
    def __init__(self):
        super(DataInspector, self).__init__()

        self.slider_width = +300

        self.main_widget = QWidget(self)
        self.setCentralWidget(self.main_widget)
        self.render_widget = RenderWidget()

        # Create interface actions
        self.action_load_data = QAction('Load data set',
                                        self,
                                        shortcut='Ctrl+O')
        self.action_load_data.setIcon(QIcon("images/AddButton.png"))
        self.action_load_data.triggered.connect(self.load_file)
        self.action_show_simple = QAction('Switch to simple rendering',
                                          self,
                                          shortcut='Ctrl+1')
        self.action_show_simple.setText("Simple")
        self.action_show_simple.triggered.connect(self.switch_to_simple)
        self.action_show_ct = QAction('Switch to CT rendering',
                                      self,
                                      shortcut='Ctrl+2')
        self.action_show_ct.setText("CT")
        self.action_show_ct.triggered.connect(self.switch_to_ct)
        self.action_show_mip = QAction('Switch to MIP rendering',
                                       self,
                                       shortcut='Ctrl+3')
        self.action_show_mip.setText("MIP")
        self.action_show_mip.triggered.connect(self.switch_to_mip)

        # Align the dock buttons to the right with a spacer widget
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # Add buttons to container on top
        self.toolbar = self.addToolBar('Main tools')
        self.toolbar.addAction(self.action_show_simple)
        self.toolbar.addAction(self.action_show_ct)
        self.toolbar.addAction(self.action_show_mip)

        self.toolbar.addWidget(spacer)
        self.toolbar.addAction(self.action_load_data)
        self.setUnifiedTitleAndToolBarOnMac(True)

        # Slider for simple visualization
        self.sliders_simple_widget = QSlider(Qt.Horizontal)
        self.sliders_simple_widget.setMinimumWidth(self.slider_width)
        self.sliders_simple_widget.setMaximumWidth(self.slider_width)
        self.sliders_simple_widget.setMinimum(0)
        self.sliders_simple_widget.setMaximum(1000)
        self.sliders_simple_widget.valueChanged.connect(
            self.simple_slider_value_changed)
        self.sliders_simple_widget.setHidden(True)

        # Create sliders for CT transfer function
        sliders_layout = QVBoxLayout()
        sliders_layout.setContentsMargins(0, 0, 0, 0)
        sliders_layout.setSpacing(0)
        self.sliders = []
        for _ in range(0, 7):
            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(1000)
            slider.valueChanged.connect(self.ct_slider_value_changed)
            self.sliders.append(slider)
            sliders_layout.addWidget(slider)

        self.sliders_ct_widget = QWidget()
        self.sliders_ct_widget.setMinimumWidth(self.slider_width)
        self.sliders_ct_widget.setMaximumWidth(self.slider_width)
        self.sliders_ct_widget.setLayout(sliders_layout)
        self.sliders_ct_widget.setHidden(True)

        self.min_slider = QSlider(Qt.Horizontal)
        self.min_slider.setMinimum(0)
        self.min_slider.setMaximum(1000)
        self.min_slider.valueChanged.connect(self.mip_slider_value_changed)

        self.max_slider = QSlider(Qt.Horizontal)
        self.max_slider.setMinimum(0)
        self.max_slider.setMaximum(1000)
        self.max_slider.setValue(1000)
        self.max_slider.valueChanged.connect(self.mip_slider_value_changed)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.min_slider)
        layout.addWidget(self.max_slider)

        self.sliders_mip_widget = QWidget()
        self.sliders_mip_widget.setMinimumWidth(self.slider_width)
        self.sliders_mip_widget.setMaximumWidth(self.slider_width)
        self.sliders_mip_widget.setLayout(layout)
        self.sliders_mip_widget.setHidden(True)

        layout = QHBoxLayout(self.main_widget)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.render_widget)
        layout.addWidget(self.sliders_mip_widget)
        layout.addWidget(self.sliders_ct_widget)
        layout.addWidget(self.sliders_simple_widget)
        self.main_widget.setLayout(layout)

        self.resize(800, 500)

    def switch_to_simple(self):
        """
        Switch the visualization style to a simple transfer function
        """
        self.render_widget.set_render_type(RenderTypeSimple)

        self.sliders_simple_widget.setDisabled(False)
        self.sliders_ct_widget.setDisabled(True)
        self.sliders_mip_widget.setDisabled(True)

        self.sliders_simple_widget.setHidden(False)
        self.sliders_ct_widget.setHidden(True)
        self.sliders_mip_widget.setHidden(True)

    def switch_to_ct(self):
        """
        Switch to a visualization style that should work pretty ok
        for CT datasets
        """
        self.render_widget.set_render_type(RenderTypeCT)

        self.sliders_simple_widget.setDisabled(True)
        self.sliders_ct_widget.setDisabled(False)
        self.sliders_mip_widget.setDisabled(True)

        self.sliders_simple_widget.setHidden(True)
        self.sliders_ct_widget.setHidden(False)
        self.sliders_mip_widget.setHidden(True)

    def switch_to_mip(self):
        """
        Switch to Maximum intensity projection visualization type
        """
        self.render_widget.set_render_type(RenderTypeMIP)

        self.sliders_simple_widget.setDisabled(True)
        self.sliders_ct_widget.setDisabled(True)
        self.sliders_mip_widget.setDisabled(False)

        self.sliders_simple_widget.setHidden(True)
        self.sliders_ct_widget.setHidden(True)
        self.sliders_mip_widget.setHidden(False)

    def simple_slider_value_changed(self):
        """
        Callback for slider of simple visualization type
        """
        slider_value = float(self.sliders_simple_widget.value()) \
            / float(self.sliders_simple_widget.maximum())
        self.render_widget.lowerBound = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * slider_value
        self.render_widget.update()

    def mip_slider_value_changed(self):
        """
        Callback for sliders of MIP visualization
        """
        min_value = float(self.min_slider.value()) / float(
            self.min_slider.maximum())
        max_value = float(self.max_slider.value()) / float(
            self.max_slider.maximum())

        self.render_widget.mipMin = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * min_value
        self.render_widget.mipMax = self.render_widget.minimum \
            + (self.render_widget.maximum - self.render_widget.minimum) * max_value

        self.render_widget.update()

    def ct_slider_value_changed(self):
        """
        Callback for sliders of CT visualization
        """
        for (x, slider) in enumerate(self.sliders):
            # for x in range(0, len(self.sliders)):
            # slider = self.sliders[x]
            slider_value = float(slider.value()) / float(slider.maximum())
            # Use an square function for easier opacity adjustments
            converted_value = slider_value * slider_value * slider_value
            self.render_widget.sectionsOpacity[x] = converted_value

        self.render_widget.update()

    def load_file(self):
        """
        Loads a file from disk
        """
        extensions = DataReader().get_supported_extensions_as_string()
        file_name, _ = QFileDialog.getOpenFileName(
            self, "Open data set", "", "Images (" + extensions + ")")
        if not file_name:
            return

        self.render_widget.load_file(file_name)
        self.switch_to_simple()
Example #9
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(800, 480)
        self.setWindowTitle('PySide GUI')
        #self.setWindowFlags(PySide.QtCore.Qt.FramelessWindowHint)

         
        self.wgHome, self.dcHome = self.createHomePage()

        
        # serial page
        self.wgSerial = QWidget(self)
        gridLayout = QGridLayout(self.wgSerial)
        self.lb1 = QLabel('serial page')
        self.lb2 = QLabel('label 2')
        self.lb3 = QLabel('label 3')
        
        gridLayout.addWidget(self.lb1, 0, 0)
        gridLayout.addWidget(self.lb2, 1, 0)
        gridLayout.addWidget(self.lb3, 2, 0)
        

        self.sw = QStackedWidget(self)
        self.sw.addWidget(self.wgHome)
        self.sw.addWidget(self.wgSerial)
        self.setCentralWidget(self.sw)
        
        
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        menu_File = QMenu(menubar)
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)
        

        actionHome = QAction(self)
        actionHome.setIcon(QIcon("icon/Home-50.png"))
        actionHome.setStatusTip("Home content")
        actionHome.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgHome))

        actionSerial = QAction(self)
        actionSerial.setIcon(QIcon("icon/Unicast-50.png"))
        actionSerial.setStatusTip("Serial polling task status")
        actionSerial.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgSerial))

        actionLogging = QAction(self)
        actionLogging.setIcon(QIcon("icon/Database-50.png"))
        actionLogging.setStatusTip("Logging task status")
        actionLogging.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgLogging))  

        actionUpload = QAction(self)
        actionUpload.setIcon(QIcon("icon/Upload to Cloud-50.png"))
        actionUpload.setStatusTip("Uploading task status")
        actionUpload.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgLogging))  

        actionDebug = QAction(self)
        actionDebug.setIcon(QIcon("icon/Bug-50.png"))
        actionDebug.setStatusTip("debug")
        actionDebug.triggered.connect(self.debug)  


        actionAbout = QAction(self)
        actionAbout.triggered.connect(self.about)
        actionAbout.setIcon(QIcon("icon/Info-50.png"))
        actionAbout.setStatusTip("Pop up the About dialog.")

        actionSetting = QAction(self)
        actionSetting.setCheckable(False)
        actionSetting.setObjectName('action_clear')
        actionSetting.setIcon(QIcon("icon/Settings-50.png"))
        

        actionLeft = QAction(self)
        actionLeft.setIcon(QIcon("icon/Left-50.png"))
        actionLeft.setStatusTip("Left page")
        actionLeft.triggered.connect(self.switchLeftWidget)

        actionRight = QAction(self)
        actionRight.setIcon(QIcon("icon/Right-50.png"))
        actionRight.setStatusTip("Right page")
        actionRight.triggered.connect(self.switchRightWidget)
        

        actionClose = QAction(self)
        actionClose.setCheckable(False)
        actionClose.setObjectName("action_Close")        
        actionClose.setIcon(QIcon("icon/Delete-50.png"))
        actionClose.setStatusTip("Close the program.")
        actionClose.triggered.connect(self.close)        

#------------------------------------------------------
        menu_File.addAction(actionHome)
        menu_File.addAction(actionAbout)
        menu_File.addAction(actionClose)
        menu_File.addAction(actionSetting)
        menubar.addAction(menu_File.menuAction())


        iconToolBar = self.addToolBar("iconBar.png")
        iconToolBar.addAction(actionHome)
        
        iconToolBar.addAction(actionSerial)
        iconToolBar.addAction(actionLogging)
        iconToolBar.addAction(actionUpload)

        iconToolBar.addAction(actionDebug)
        
        iconToolBar.addAction(actionAbout)
        iconToolBar.addAction(actionSetting)
        iconToolBar.addAction(actionLeft)
        iconToolBar.addAction(actionRight)
        iconToolBar.addAction(actionClose)
Example #10
0
    def create_actions(self):
        # File menu
        self.open_action = QAction("&Open...",
                                   self,
                                   shortcut=QtGui.QKeySequence.Open,
                                   triggered=self.open_file,
                                   icon=self.style().standardIcon(
                                       QtGui.QStyle.SP_DialogOpenButton))
        self.save_action = QAction("&Save",
                                   self,
                                   shortcut=QtGui.QKeySequence.Save,
                                   triggered=self.save_document,
                                   icon=self.style().standardIcon(
                                       QtGui.QStyle.SP_DialogSaveButton))
        self.save_crops_action = QAction("&Save crops",
                                         self,
                                         triggered=self.save_crops)
        self.export_csv_action = QAction("&Export CSV",
                                         self,
                                         triggered=self.export_csv)
        self.close_action = QAction("&Close",
                                    self,
                                    shortcut=QtGui.QKeySequence.Close,
                                    triggered=self.close_document)
        self.exit_action = QAction("E&xit",
                                   self,
                                   shortcut=QtGui.QKeySequence.Quit,
                                   triggered=self.close)

        # Edit menu
        self.select_all_action = QAction("Select &All",
                                         self,
                                         shortcut=QtGui.QKeySequence.SelectAll,
                                         triggered=self.select_all)
        # QT does not provide a 'select none' key sequence
        self.select_none_action = QAction("Select &None",
                                          self,
                                          shortcut="ctrl+D",
                                          triggered=self.select_none)
        self.next_box_action = QAction("Next box",
                                       self,
                                       shortcut="N",
                                       triggered=partial(self.select_next_prev,
                                                         next=True))
        self.previous_box_action = QAction("Previous box",
                                           self,
                                           shortcut="P",
                                           triggered=partial(
                                               self.select_next_prev,
                                               next=False))

        # TODO LH Does CMD + Backspace work on a mac?
        self.delete_action = QAction("&Delete selected",
                                     self,
                                     shortcut=QtGui.QKeySequence.Delete,
                                     triggered=self.delete_selected)
        self.rotate_clockwise_action = QAction("Rotate clockwise",
                                               self,
                                               shortcut="R",
                                               triggered=partial(
                                                   self.rotate90,
                                                   clockwise=True))
        self.rotate_counter_clockwise_action = QAction(
            "Rotate counter-clockwise",
            self,
            shortcut="L",
            triggered=partial(self.rotate90, clockwise=False))

        # Plugins
        # Plugin shortcuts start at F5
        shortcut_offset = 5
        for index, plugin in enumerate(self.plugins):
            action = QAction(plugin.name(),
                             self,
                             triggered=partial(self.run_plugin, index))
            shortcut_fkey = index + shortcut_offset
            if shortcut_fkey < 13:
                # Keyboards typically have 12 function keys
                action.setShortcut('f{0}'.format(shortcut_fkey))
            icon = plugin.icon()
            if icon:
                action.setIcon(icon)
            self.plugin_actions[index] = action

        # View menu
        # The obvious approach is to set the trigger to
        # partial(self.tabs.setCurrentIndex, 0) but this causes a segfault when
        # the application exits on linux.
        self.boxes_view_action = QAction("&Boxes",
                                         self,
                                         checkable=True,
                                         triggered=partial(self.show_tab, 0))
        self.metadata_view_action = QAction("&Specimens",
                                            self,
                                            checkable=True,
                                            triggered=partial(
                                                self.show_tab, 1))

        # FullScreen added in Qt 5.something
        # https://qt.gitorious.org/qt/qtbase-miniak/commit/1ef8a6d
        if not hasattr(QtGui.QKeySequence, 'FullScreen'):
            if 'darwin' == sys.platform:
                KeySequenceFullScreen = 'shift+ctrl+f'
            else:
                KeySequenceFullScreen = 'f11'
        else:
            KeySequenceFullScreen = QtGui.QKeySequence.FullScreen
        self.full_screen_action = QAction("&Full screen",
                                          self,
                                          shortcut=KeySequenceFullScreen,
                                          triggered=self.toggle_full_screen)

        self.zoom_in_action = QAction("Zoom &In",
                                      self,
                                      shortcut=QtGui.QKeySequence.ZoomIn,
                                      triggered=self.zoom_in,
                                      icon=self.style().standardIcon(
                                          QtGui.QStyle.SP_ArrowUp))
        self.zoom_out_action = QAction("Zoom &Out",
                                       self,
                                       shortcut=QtGui.QKeySequence.ZoomOut,
                                       triggered=self.zoom_out,
                                       icon=self.style().standardIcon(
                                           QtGui.QStyle.SP_ArrowDown))
        self.toogle_zoom_action = QAction("&Toogle Zoom",
                                          self,
                                          shortcut='Z',
                                          triggered=self.toggle_zoom)
        self.zoom_home_action = QAction(
            "Fit To Window",
            self,
            shortcut=QtGui.QKeySequence.MoveToStartOfDocument,
            triggered=self.zoom_home)
        # TODO LH Is F3 (normally meaning 'find next') really the right
        # shortcut for the 'toggle plugin image' action?
        self.toggle_plugin_image_action = QAction(
            "&Display plugin image",
            self,
            shortcut="f3",
            triggered=self.toggle_plugin_image,
            statusTip="Display plugin image",
            checkable=True)

        self.show_specimen_grid_action = QAction('Show grid',
                                                 self,
                                                 shortcut='g',
                                                 triggered=self.show_grid)
        self.show_specimen_expanded_action = QAction(
            'Show expanded', self, shortcut='e', triggered=self.show_expanded)

        # Help menu
        self.about_action = QAction("&About", self, triggered=self.about)
        self.help_action = QAction("&Help",
                                   self,
                                   shortcut=QtGui.QKeySequence.HelpContents,
                                   triggered=self.help)
Example #11
0
class MainWindow(QMainWindow):
    """ Starting point of the GUI based application """
    isMyProgressTimer = False
    def __init__(self):        
        """ MainWindow Constructor Function"""
        super(MainWindow, self).__init__()
        wdgt = QWidget()
        wdgt.setWindowTitle = "ManageHD"
        self.setCentralWidget(wdgt)
        self.InitUI()
        self.GetParameterFileInfo()        
    
    def InitUI(self):        
        """ Initialize user created UI elements """
        self.qlVidsDone         = QLabel('0', self)
        self.qlVidsInProgress   = QLabel('0', self)
        self.qlStartTime        = QLabel(datetime.now().strftime("%a, %d %b %Y %H:%M:%S"), self)
        self.qlEndTime          = QLabel('', self)
        self.qlTimeLeft         = QLabel('', self)
        self.qlDestinationSpace = QLabel('', self)
        self.qlArcSpace         = QLabel('', self)
        self.qlProcessingSpeed  = QLabel('', self)
        
        self.qleSourceDir       = QLineEditDirectoriesOnly()
        self.qleArchiveDir      = QLineEditDirectoriesOnly()
        self.qleDestinationDir  = QLineEditDirectoriesOnly()
        self.qleMaxVidsCap      = QLineEditIntsOnly()
        self.qleVideoTypes      = QLineEditNoPeriodsOrCommas()
        self.qleVideoTypes.installEventFilter(self)
        
        self.qpbSourceDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForSourceDirectory)
        self.qpbArchiveDir      = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForArchiveDirectory)
        self.qpbTargetDir       = self.__CreateButton('folder.png',"", 50, self.SelectSingleFileForTargetDirectory)
        self.qpbRun             = self.__CreateButton(None,"Run", 75, self.Process)        
        
        self.setWindowTitle("Manage HD Video")
        self.videoExtensionFileFilter = "Video (*.mkv *.mp4 *.avi)"
        self.qleVideoTypes.setText("mkv mp4 avi")
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.__CreateActions()
        self.__CreateMenus()
        self.fileMenu.addAction(self.stdAction)
        self.fileMenu.addAction(self.altAction)
        if Progress.runPlatform == 'win':
            self.stdAction.setIcon(QIcon('checked.jpg'))
        self.stdAction.setChecked(True)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.fileMenu.addSeparator()
        self.helpMenu.addAction(self.aboutAction)
        self.__SetIcon()
        self.__CenterWindow()
        self.__CreateGrid()       

    def eventFilter(self, source, event): #Override
        """ Override the QMainWindow eventFilter method to add File Mask Validation. """
        if (event.type() == QEvent.FocusOut and
            source is self.qleVideoTypes):
            self.ValidateFileMask()
        return QMainWindow.eventFilter(self, source, event)
    
    def DisableGuiElements(self):
        """ Change the setEnabled property of the main GUI elements to False. """
        self.qleArchiveDir.setEnabled(False)
        self.qleDestinationDir.setEnabled(False)
        self.qleMaxVidsCap.setEnabled(False)
        self.qleSourceDir.setEnabled(False)
        self.qleVideoTypes.setEnabled(False)

        self.qpbArchiveDir.setEnabled(False)
        self.qpbSourceDir.setEnabled(False)
        self.qpbTargetDir.setEnabled(False)
        self.qpbRun.setEnabled(False)

    def EnableGuiElements(self):
        """ Change the setEnabled property of the main GUI elements to True. """
        self.qleArchiveDir.setEnabled(True)
        self.qleDestinationDir.setEnabled(True)
        self.qleMaxVidsCap.setEnabled(True)
        self.qleSourceDir.setEnabled(True)
        self.qleVideoTypes.setEnabled(True)
        
        self.qpbArchiveDir.setEnabled(True)
        self.qpbSourceDir.setEnabled(True)
        self.qpbTargetDir.setEnabled(True)
        self.qpbRun.setEnabled(True)

    def __AddGridLabel(self, grid, lblText, custFont, row, column, justification):
        sd = QLabel(lblText, self)
        sd.setFont(custFont)
        grid.addWidget(sd, row, column, alignment = justification)        

    def SelectSingleFileForSourceDirectory(self):
        self.qleSourceDir.setText( self.InvokeSingleSelectionDirectoryDialog() )
        self.ValidateFileMask()

    def SelectSingleFileForArchiveDirectory(self):
        self.qleArchiveDir.setText( self.InvokeSingleSelectionDirectoryDialog() )
    
    def SelectSingleFileForTargetDirectory(self):
        self.qleDestinationDir.setText( self.InvokeSingleSelectionDirectoryDialog() )

    def InvokeSingleSelectionFileDialog(self):
        """ Prompts the user to select a single file from a file dialog window. """
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setFilter(self.videoExtensionFileFilter)        
        ret = dialog.exec_()
        FileNames = dialog.selectedFiles()
        if len(FileNames) == 0:
            FileNames.append(None)
        return FileNames[0]
    
    def InvokeSingleSelectionDirectoryDialog(self):
        """ Prompts the user to select a single directory from a directory dialog window. """
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)        
        DirectoryName = dialog.getExistingDirectory()
        if len(DirectoryName) == 0:
            DirectoryName = None
        return DirectoryName

    def ValidateFileMask(self):
        """ Function to validate that the entered file mask is valid. """
        extensionList = ""
        if len(self.qleVideoTypes.text().split(" ")) > 0:
            for videoExtension in self.qleVideoTypes.text().split(" "):
                extensionList += ("*." + videoExtension + " ")
            extensionList = extensionList[:-1]
        self.videoExtensionFileFilter = "Video ({})".format(extensionList)        
        
    def __CreateGrid(self):
        g1 = QGridLayout()
        self.centralWidget().setLayout(g1)

        g1.setSpacing(5)

        bold = QFont()
        bold.setBold(True)
        self.__AddGridLabel(g1, 'Source Directory:', QFont(), 0, 0, -1)
        self.__AddGridLabel(g1, 'Archive Directory:', QFont(), 1, 0, -1)
        self.__AddGridLabel(g1, 'Target Directory:', QFont(), 2, 0, -1)
        self.__AddGridLabel(g1, 'Max Number of Videos:', QFont(), 3, 0, -1)
        self.__AddGridLabel(g1, 'Video File Types:', QFont(), 3, 2, -1)
        #self.__AddGridLabel(g1, 'Max Run Time in Hours:', QFont(), 4, 2, -1)

        g1.addWidget(self.qleSourceDir, 0, 1, 1, 3)
        g1.addWidget(self.qleArchiveDir, 1, 1, 1, 3)
        g1.addWidget(self.qleDestinationDir, 2, 1, 1, 3)
        g1.addWidget(self.qleMaxVidsCap, 3, 1)
        g1.addWidget(self.qleVideoTypes, 3, 3)
        #g1.addWidget(self.qleRunTimeMax, 4, 3)
        
        g1.addWidget(self.qpbRun, 10, 3, alignment = -1)
        
        g1.addWidget(QLabel('', self), 4, 0,) # Empty Column As Separator
        g1.addWidget(QLabel('', self), 5, 0,) # Empty Column As Separator
        
        self.__AddGridLabel(g1, 'Videos Completed:',   bold, 5, 0, -1)
        self.__AddGridLabel(g1, 'Start Time:',         bold, 5, 2, -1)
        self.__AddGridLabel(g1, 'Videos In Progress:', bold, 6, 0, -1)
        self.__AddGridLabel(g1, 'Time Remaining:',     bold, 7, 2, -1)
        self.__AddGridLabel(g1, 'Target Space Left:',  bold, 7, 0, -1)
        self.__AddGridLabel(g1, 'Archive Space Left:', bold, 8, 0, -1)
        self.__AddGridLabel(g1, 'End Time:',           bold, 6, 2, -1)
        self.__AddGridLabel(g1, 'Processing Speed:',   bold, 8, 2, -1)
        
        g1.addWidget(self.qlVidsDone,        5, 1,) 
        g1.addWidget(self.qlVidsInProgress,  6, 1)
        g1.addWidget(self.qlStartTime,       5, 3,) 
        g1.addWidget(self.qlEndTime,         6, 3,) 
        g1.addWidget(self.qlTimeLeft,        7, 3,) 
        g1.addWidget(self.qlDestinationSpace,     7, 1,) 
        g1.addWidget(self.qlArcSpace,        8, 1,)
        g1.addWidget(self.qlProcessingSpeed, 8, 3,)
        
        g1.addWidget(self.qpbSourceDir,      0, 4,)
        g1.addWidget(self.qpbArchiveDir,     1, 4,)
        g1.addWidget(self.qpbTargetDir,      2, 4,)        
        self.show
        
    def GetParameterFileInfo(self):
        Progress.DeterminePlatform()
        fm = FileManip()
        #params = Progress.cliParams.copy()
        params = fm.ReadSettingsFile()
        self.qlProcessingSpeed.setText(str(Progress.cliParams['ProcessingSpeedInGBperHour']))
        self.qleSourceDir.setText(params['sourceDir'])
        self.qleArchiveDir.setText(params['archiveDir'])
        self.qleDestinationDir.setText(params['destinationDir'])
        
    def GetDriveSpace(self, path):
        """ Call the GetDriveSpace() method using an instance of the FileManip class. """
        fm = FileManip() 
        return fm.GetDriveSpace(path)

    def ResetStats(self):
        """ Change statistical data displays back to their original initialized values. """
        Progress.ResetStatuses()
        self.qlVidsDone.setText( '0')
        self.qlVidsInProgress.setText('0')
        self.qlStartTime.setText(datetime.now().strftime("%a, %d %b %Y %H:%M:%S"))
        self.qlTimeLeft.setText("")
        if self.qleDestinationDir.text() != "":
            self.qlDestinationSpace.setText(str(self.GetDriveSpace(self.qleDestinationDir.text())))
        if self.qleArchiveDir.text() != "":
            self.qlArcSpace.setText(str(self.GetDriveSpace(self.qleArchiveDir.text())))
        self.qlEndTime.setText("")
        self.qlProcessingSpeed.setText("")
    
    def VerifyRequiredFieldsFilled(self):
        """ Cancels the RUN functionality and informs the user via Message Box if the required fields are not all completed. """
        if self.qleSourceDir.text() == "" or \
            self.qleVideoTypes.text() == "" or \
            self.qleDestinationDir.text() == "":
            QMessageBox.critical(self, "Required Field Error", 
                                 "You have not filled out the three required fields. "
                                 "'Source Directory', "
                                 "'Target Directory' and "
                                 "'Video File Types' "
                                 "are all required Fields.", QMessageBox.Ok)
            return 0
        return True        

    def Process(self):
        """ Batch processing of the source video files begins here. """
        result = self.VerifyRequiredFieldsFilled()
        if result != True:
            return
        self.ResetStats()
        
        Progress.statuses['ProcessingComplete'] = False
        self.DisableGuiElements()
        Params = Progress.cliParams.copy() 
        Params['sourceDir']      = self.qleSourceDir.text()
        Params['archiveDir']     = self.qleArchiveDir.text()
        Params['destinationDir'] = self.qleDestinationDir.text()

        maximumNumVids = ""
        for idx in range(0, len(self.qleMaxVidsCap.text())):
            if self.qleMaxVidsCap.text()[idx] != '.':
                maximumNumVids = maximumNumVids + self.qleMaxVidsCap.text()[idx]

        if maximumNumVids.isnumeric():
            Params['maxNumberOfVideosToProcess']  = '%1.f' % float(self.qleMaxVidsCap.text())

        if len(self.qleVideoTypes.text().split(" ")) > 0:
            extensionList = ""
            for videoExtension in self.qleVideoTypes.text().split(" "):
                extensionList += (videoExtension + ",")
        else:
            extensionList = None

        Params['videoTypes']     = extensionList
        
        #Create and instance of the processing class
        pm = ProcessMovies()

        #Disable applicable GUI elements
        self.DisableGuiElements

        #Spawn a thread to run this
        Thread(target=pm.StartWithGUI, args=(Params,)).start()

        sleep(1)
        self.qlTimeLeft.setText(Progress.CalculateTimeRemaining())
        Progress.statuses['StatusesHaveChanged'] = True
        return

    def __CreateButton(self, folderIcon, txt, pxSize, actionFunction):
        """ Function to add a button """
        if folderIcon != None:
            folderIcon = QIcon('folder.png')
            myButton = QPushButton(folderIcon, "")
        else:
            myButton = QPushButton(txt)
        myButton.setMaximumWidth(pxSize)
        myButton.clicked.connect(actionFunction)
        return myButton

    def aboutHelp(self):
        """ Displays the ABOUT box and sets its content. """
        QMessageBox.about(self, "About ManageHD",
                          "Program written in Python v3.4 \n\n"
                          "ManageHD allows you to select an entire "
                          "directory of HD video files and lower their "
                          "resolution from 1080 HD to 720 HD, in batch. "
                          "It calls the HandBrake Command Line Interface "
                          "(CLI) in order to re-encode each video. \n\nYou must "
                          "have the Handbrake CLI installed to use this "
                          "software. "
                          "The CLI (command line interface) can be downloaded at:\n\n "
                          "     http://handbrake.fr/downloads2.php \n\n"
                          "The average video file at 720 HD "
                          "is generally one fourth to one sixth the size "
                          "of its 1080 HD source file. \n\n"
                          "Coding was done by InfanteLabz. \n\n"
                          "This sofware is released under GPL v3 "
                          "licensing. \n\n Developed on Wing IDE")

    def exitFile(self):
        """ Exits the Main Window, ending the program. """
        self.close()

    def __CreateActions(self):
        """ Function to create actions for menus """
        self.stdAction = QAction(QIcon('convert.png'), 
                                'Create MKV files',
                                self, shortcut = "Ctrl+K",
                                statusTip = "File format set to MKV container",
                                triggered = self.stdConversion,
                                checkable = True)

        self.altAction = QAction(QIcon('convert.png'), 
                                'Create MP4 files',
                                self, shortcut = "Ctrl+P",
                                statusTip = "File format set to MP4 file",
                                triggered = self.altConversion,
                                checkable = True)

        self.exitAction = QAction(QIcon('exit.png'),
                                  '&Quit',
                                  self, shortcut="Ctrl+Q",
                                  statusTip = "Exit the Application",
                                  triggered=self.exitFile)

        #self.copyAction = QAction(QIcon('copy.png'), 'C&opy',
                                  #self, shortcut="Ctrl+C",
                                  #statusTip="Copy",
                                  #triggered=self.CopyFunction)

        self.aboutAction = QAction(QIcon('about.png'), 'A&bout',
                                   self, statusTip="Displays info about ManageHD",
                                   triggered=self.aboutHelp)

    def __CreateMenus(self):
        """ Function to create actual menu bar """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.helpMenu = self.menuBar().addMenu("&Help")
        
    def __CenterWindow(self):
        """ Function to center the window """
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())
    
    def __SetAboutBox(self):
        """ Function to position and wire the ABOUT box """
        self.aboutButton = QPushButton("About", self)
        self.aboutButton.move(200, 100)
        self.aboutButton.clicked.connect(self.ShowAbout)
        
    def __SetIcon(self):
        """ Function to set Icon """
        appIcon = QIcon('ManageHD_Icon.png')
        self.setWindowIcon(appIcon)

    def DisplayAbnormalTerminationStatus(self, status): # Not Implemented
        pass

    def GetArchiveDirectory(self): # Not Implemented
        pass
    
    def stdConversion(self):
        """ Called by the STANDARD menu item under FILE. Sets ManageHD to perform the standard Handbrake conversion. """
        Progress.statuses['HandbrakeOptionsString'] = str(" -i {0} -o {1} -f mkv --width 1280 --crop 0:0:0:0 --decomb -s 1 -N eng -m --large-file --encoder x264 -q 19 -E ffac3")
        Progress.statuses['OutputExtension'] = 'mkv'
        self.altAction.setChecked(False)
        if Progress.runPlatform == "win":
            self.altAction.setIcon(QIcon('convert.png'))
            self.stdAction.setIcon(QIcon('checked.jpg'))
        self.stdAction.setChecked(True)
    
    def altConversion(self):
        """ Called by the ALTERNATE menu item under FILE. Sets ManageHD to perform Handbrake conversions using an alternate series of settings. """
        Progress.statuses['HandbrakeOptionsString'] = str(" -i {0} -o {1} -f mp4 --width 1280 --crop 0:0:0:0 --decomb -s 1 -N eng -m --large-file --encoder x264 -q 19 -E ffac3")
        Progress.statuses['OutputExtension'] = 'mp4'
        self.stdAction.setChecked(False)
        if Progress.runPlatform == "win":
            self.altAction.setIcon(QIcon('checked.jpg'))
            self.stdAction.setIcon(QIcon('convert.png'))
        self.altAction.setChecked(True)

    def CopyFunction(): # Not Implemented
        pass
        
    def ValidateAndRun(self): # Not Implemented
        pass
Example #12
0
class MainWindow(QMainWindow):
    start_acq = Signal(str)
    start_rec = Signal(str)
    collect_frame = Signal(object)
    collect_threshed = Signal(object)

    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""

    #this function acts as a slot to accept 'message' signal
    @Slot(str)
    def print_message(self, message):
        ''' print stdout and stderr to terminal window '''

        #move terminal cursor to end
        self.terminal.moveCursor(QTextCursor.End)
        #write message to terminal
        self.terminal.insertPlainText(message)

    def setup_thresh_buttons(self):
        ''' set up buttons for overlay/clearing thresh view '''

        self.button_frame = QFrame(self)
        self.button_frame.setGeometry(
            QRect(self.window_width * .52,
                  self.window_height * .13 + self.video_height,
                  self.video_width * .98, 50))
        button_layout = QHBoxLayout()
        self.button_frame.setLayout(button_layout)
        self.clear_button = QPushButton('Clear')
        self.overlay_button = QPushButton('Overlay')
        button_layout.addWidget(self.clear_button)
        button_layout.addWidget(self.overlay_button)

        self.clear_button.setEnabled(False)
        self.clear_button.clicked.connect(self.clear_threshed)
        self.overlay_button.setEnabled(False)
        self.overlay_button.clicked.connect(self.overlay_threshed)

    def setup_video_frames(self):
        ''' set up spots for playing video frames '''

        filler_frame = np.zeros((360, 540, 3))
        filler_frame = qimage2ndarray.array2qimage(filler_frame)

        self.raw_frame = QFrame(self)
        self.raw_label = QLabel()
        self.raw_label.setText('raw')
        self.raw_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .15,
                  self.video_width, self.video_height))
        self.raw_frame
        raw_layout = QVBoxLayout()
        self.raw_frame.setLayout(raw_layout)
        raw_layout.addWidget(self.raw_label)

        self.threshed_frame = QFrame(self)
        self.threshed_label = QLabel()
        self.threshed_label.setText('Threshed')
        self.threshed_frame.setGeometry(
            QRect(self.window_width * .51, self.window_height * .15,
                  self.video_width, self.video_height))
        threshed_layout = QVBoxLayout()
        self.threshed_frame.setLayout(threshed_layout)
        threshed_layout.addWidget(self.threshed_label)

        self.label_frame = QFrame(self)
        self.label_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .11,
                  self.video_width * 2, 50))
        self.label_rawlabel = QLabel()
        self.label_rawlabel.setText('Raw Video')
        self.label_threshedlabel = QLabel()
        self.label_threshedlabel.setText('Threshold View')
        label_layout = QHBoxLayout()
        self.label_frame.setLayout(label_layout)
        label_layout.addWidget(self.label_rawlabel)
        label_layout.addWidget(self.label_threshedlabel)

        self.raw_label.setPixmap(QPixmap.fromImage(filler_frame))
        self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame))

    def Acquire(self):

        if self.action_Acq.isChecked():

            self.vidbuffer = []

            if self.recording:

                while 1:
                    try:
                        self.sock.send('StopRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.recording = False

            else:
                #create and start a thread to transport a worker to later
                self.workerThread = QThread(self)
                self.workerThread.start()
                #create a worker object based on Worker class and move it to our
                #worker thread
                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_acq.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.acquiring = True
                self.start_acq.connect(self.worker.acquire)
                self.start_acq.emit('start!')

            self.action_Acq.setEnabled(False)
            self.action_Record.setChecked(False)
            self.action_Record.setEnabled(True)

            record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)

    def Record(self):

        if self.action_Record.isChecked():

            if not self.acquiring:
                self.workerThread = QThread(self)
                self.workerThread.start()

                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_rec.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.start_rec.connect(self.worker.acquire)
                self.recording = True
                self.start_rec.emit('start!')

            else:

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.recording = True

            record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)
            self.action_Record.setEnabled(False)

            self.action_Acq.setChecked(False)
            self.action_Acq.setEnabled(True)

    def Stop(self):

        self.acquiring = False
        self.recording = False

        while 1:
            try:
                self.sock.send('isRecording')
                rec = self.sock.recv()
            except:
                continue
            break

        if rec == '1':
            while 1:
                try:
                    self.sock.send('StopRecord')
                    self.sock.recv()
                except:
                    continue
                break

            self.action_Record.setEnabled(True)
            self.action_Record.setChecked(False)

        while 1:
            try:
                self.sock.send('isAcquiring')
                acq = self.sock.recv_string()
            except:
                continue
            break

        if acq == '1':
            while 1:
                try:
                    self.sock.send('StopAcquisition')
                    self.sock.recv()
                except:
                    continue
                break

        self.action_Acq.setEnabled(True)
        self.action_Acq.setChecked(False)

        try:
            #open a csv file for saving tracking data
            with open(self.vt_file, 'a') as csvfile:
                #create a writer
                vidwriter = csv.writer(csvfile, dialect='excel-tab')
                #check if it's an empty file
                for row in self.vidbuffer:
                    vidwriter.writerow(row)

        except:
            pass

        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)

    def update_frame(self, image):
        self.raw_label.setPixmap(QPixmap.fromImage(image))

    def update_threshed(self, threshed_image):
        self.threshed_label.setPixmap(QPixmap.fromImage(threshed_image))

    def clear_threshed(self):
        self.green_frame = np.zeros_like(self.green_frame)
        self.red_frame = np.zeros_like(self.red_frame)

    def overlay_threshed(self):
        if self.overlay:
            self.overlay = False
        elif not self.overlay:
            self.overlay = True


#    def sort_now(self):
#
#        if self.recdir is not None:
#            os.chdir('./kilosort_control')
#            #create and show the main window
#            self.sort_frame = kilosort_control.sort_gui.MainWindow()
#            self.sort_frame.show()
#
#            #set up stream for stdout and stderr based on outputStream class
#            self.outputStream = kilosort_control.sort_gui.outputStream()
#            #when outputStream sends messages, connect to appropriate function for
#            #writing to terminal window
#            self.outputStream.message.connect(self.sort_frame.print_message)
#
#            #connect stdout and stderr to outputStream
#            sys.stdout = self.outputStream
#            sys.stderr = self.outputStream
#
#            self.sort_frame.run_now(self.recdir)
#
#            self.close()

    def get_info(self):

        self.info_window = QWidget()
        self.info_window.resize(400, 350)
        #set title
        self.info_window.setWindowTitle('Session Info')
        #give layout
        info_layout = QVBoxLayout(self.info_window)

        with open('info_fields.pickle', 'rb') as f:
            default_fields = pickle.load(f)
            f.close()

        #set label for pic_resolution setting
        experimenter_label = QLabel('Experimenter:')
        #make a QLineEdit box for displaying/editing settings
        experimenter = QComboBox(self.info_window)
        experimenter.setEditable(True)
        experimenter.addItems(default_fields['experimenter'])
        #add label and box to current window
        info_layout.addWidget(experimenter_label)
        info_layout.addWidget(experimenter)

        #set label for pic_resolution setting
        whose_animal_label = QLabel('Whose animal?')
        #make a QLineEdit box for displaying/editing settings
        whose_animal = QComboBox(self.info_window)
        whose_animal.setEditable(True)
        whose_animal.addItems(default_fields['whose_animal'])
        #add label and box to current window
        info_layout.addWidget(whose_animal_label)
        info_layout.addWidget(whose_animal)

        animal_number_label = QLabel('Animal number:')
        animal_number = QComboBox(self.info_window)
        animal_number.setEditable(True)
        animal_number.addItems(default_fields['animal_number'])
        info_layout.addWidget(animal_number_label)
        info_layout.addWidget(animal_number)

        session_number_label = QLabel('Session number:')
        session_number = QTextEdit(self.info_window)
        session_number.setText('1')
        info_layout.addWidget(session_number_label)
        info_layout.addWidget(session_number)

        session_type_label = QLabel('Session type:')
        session_type = QComboBox(self.info_window)
        session_type.setEditable(True)
        session_type.addItems(default_fields['session_type'])
        info_layout.addWidget(session_type_label)
        info_layout.addWidget(session_type)

        def save_info(self):

            info_fields = {}
            info_fields['experimenter'] = [
                experimenter.itemText(i) for i in range(experimenter.count())
            ]
            info_fields['whose_animal'] = [
                whose_animal.itemText(i) for i in range(whose_animal.count())
            ]
            info_fields['animal_number'] = [
                animal_number.itemText(i) for i in range(animal_number.count())
            ]
            info_fields['session_type'] = [
                session_type.itemText(i) for i in range(session_type.count())
            ]

            with open('info_fields.pickle', 'wb') as f:
                pickle.dump(info_fields, f, protocol=2)
                f.close()

            current_experimenter = str(experimenter.currentText())
            current_whose_animal = str(whose_animal.currentText())
            current_animal_number = str(animal_number.currentText())
            current_session_number = str(session_number.toPlainText())
            current_session_type = str(session_type.currentText())

            recdir = data_save_dir + current_whose_animal + '/' + current_animal_number

            if not os.path.exists(recdir):
                os.makedirs(recdir)

            self.experiment_info = '###### Experiment Info ######\r\n'
            self.experiment_info += 'Experimenter: %s\r\n' % current_experimenter
            self.experiment_info += 'Whose animal? %s\r\n' % current_whose_animal
            self.experiment_info += 'Animal number: %s\r\n' % current_animal_number
            self.experiment_info += 'Session number: %s\r\n' % current_session_number
            self.experiment_info += 'Session type: %s\r\n' % current_session_type

            self.experiment_info = self.experiment_info.encode()

            config_file = config_path + '/' + current_animal_number + '.xml'

            if not os.path.exists(config_file):
                shutil.copy(default_config, config_file)

            tree = et.parse(config_file)
            root = tree.getroot()
            for child in root:
                if child.tag == 'CONTROLPANEL':
                    child.attrib['recordPath'] = recdir.replace('/', '\\')
            tree.write(config_file)
            tree.write(default_config)

            self.info_window.close()
            self.noinfo = False

        ready_button = QPushButton('Ready!')
        ready_button.clicked.connect(lambda: save_info(self))
        info_layout.addWidget(ready_button)

        self.info_window.show()
Example #13
0
def createMenuAction(title, method, icon=None):
    action = QAction(title, None)
    action.triggered.connect(method)
    if icon:
        action.setIcon(icon)
    return action
Example #14
0
def createMenuAction(title, method, icon=None):
    action = QAction(title, None)
    action.triggered.connect( method )
    if icon:
    	action.setIcon(icon)
    return action
Example #15
0
File: gui.py Project: tinavas/FSERP
class Gui():
    """main gui class"""
    def __init__(self):
        self.mainwindow = QMainWindow()
        settings.get_settings()
        self.access = tuple(settings.access.items())
        self.progress = QProgressDialog("Setting up modules...", "cancel", 0,
                                        7, self.mainwindow)
        self.progress.setWindowTitle(
            QApplication.translate("MainWindow", str(settings.company), None,
                                   QApplication.UnicodeUTF8))

    def setup(self):
        """initializes the uio of the erp client"""
        self.progress.setFixedWidth(1000)
        self.progress.setCancelButton(None)
        # self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(1)
        self.mainwindow.setObjectName("MainWindow")
        self.mainwindow.resize(832, 668)
        self.mainwindow.setStyleSheet(
            "QToolBar{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "QToolBar > QWidget{\n"
            "color:white;\n"
            "}\n"
            "QToolBar > QWidget:hover {\n"
            "background:transparent;\n"
            " }\n"
            "QToolBar > QWidget:checked {\n"
            "background:transparent;\n"
            " }\n"
            "#MainWindow{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "")
        self.centralWidget = QWidget(self.mainwindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout_2 = QGridLayout(self.centralWidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.stackedWidget = QStackedWidget(self.centralWidget)
        self.stackedWidget.setStyleSheet("")
        self.stackedWidget.setObjectName("stackedWidget")
        self.shortcut = NewShortcut()
        scroll = QScrollArea()
        scroll.setWidget(self.shortcut.shortcut_setting)
        self.stackedWidget.addWidget(self.shortcut.shortcut_setting)
        self.home_page = QWidget()
        self.home_page.setObjectName("home_page")
        self.gridLayout = QGridLayout(self.home_page)
        self.gridLayout.setObjectName("gridLayout")
        self.billing_frame_2 = QFrame(self.home_page)
        self.billing_frame_2.setStyleSheet(
            "background-image:url(:/images/billing_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#6CBED2;")
        self.billing_frame_2.setFrameShape(QFrame.StyledPanel)
        self.billing_frame_2.setFrameShadow(QFrame.Raised)
        self.billing_frame_2.setObjectName("billing_frame_2")
        self.verticalLayout_4 = QVBoxLayout(self.billing_frame_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        spacerItem = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_4.addItem(spacerItem)
        self.label_10 = QLabel(self.billing_frame_2)
        self.label_10.setStyleSheet("background:transparent;")
        self.label_10.setObjectName("label_10")
        self.verticalLayout_4.addWidget(self.label_10)
        self.gridLayout.addWidget(self.billing_frame_2, 0, 1, 1, 1)
        self.employee_frame_3 = QFrame(self.home_page)
        self.employee_frame_3.setStyleSheet(
            "background-image:url(:/images/employee_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#0099CC;")
        self.employee_frame_3.setFrameShape(QFrame.StyledPanel)
        self.employee_frame_3.setFrameShadow(QFrame.Raised)
        self.employee_frame_3.setObjectName("employee_frame_3")
        self.verticalLayout_5 = QVBoxLayout(self.employee_frame_3)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        spacerItem1 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_5.addItem(spacerItem1)
        self.label_11 = QLabel(self.employee_frame_3)
        self.label_11.setStyleSheet("background:transparent;")
        self.label_11.setObjectName("label_11")
        self.verticalLayout_5.addWidget(self.label_11)
        self.gridLayout.addWidget(self.employee_frame_3, 0, 2, 1, 1)
        self.menu_frame_4 = QFrame(self.home_page)
        self.menu_frame_4.setStyleSheet(
            "background-image:url(:/images/menu_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#297ACC;")
        self.menu_frame_4.setFrameShape(QFrame.StyledPanel)
        self.menu_frame_4.setFrameShadow(QFrame.Raised)
        self.menu_frame_4.setObjectName("menu_frame_4")
        self.verticalLayout_3 = QVBoxLayout(self.menu_frame_4)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        spacerItem2 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_3.addItem(spacerItem2)
        self.label_12 = QLabel(self.menu_frame_4)
        self.label_12.setStyleSheet("background:transparent;")
        self.label_12.setObjectName("label_12")
        self.verticalLayout_3.addWidget(self.label_12)
        self.gridLayout.addWidget(self.menu_frame_4, 1, 0, 1, 1)
        self.report_frame_5 = QFrame(self.home_page)
        self.report_frame_5.setStyleSheet(
            "background-image:url(:/images/report_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#006BB2;")
        self.report_frame_5.setFrameShape(QFrame.StyledPanel)
        self.report_frame_5.setFrameShadow(QFrame.Raised)
        self.report_frame_5.setObjectName("report_frame_5")
        self.verticalLayout_6 = QVBoxLayout(self.report_frame_5)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        spacerItem3 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_6.addItem(spacerItem3)
        self.label_13 = QLabel(self.report_frame_5)
        self.label_13.setStyleSheet("background:transparent;")
        self.label_13.setObjectName("label_13")
        self.verticalLayout_6.addWidget(self.label_13)
        self.gridLayout.addWidget(self.report_frame_5, 1, 1, 1, 1)
        self.waste_frame_6 = QFrame(self.home_page)
        self.waste_frame_6.setStyleSheet(
            "background-image:url(:/images/waste_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#003D7A;")
        self.waste_frame_6.setFrameShape(QFrame.StyledPanel)
        self.waste_frame_6.setFrameShadow(QFrame.Raised)
        self.waste_frame_6.setObjectName("waste_frame_6")
        self.verticalLayout_7 = QVBoxLayout(self.waste_frame_6)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        spacerItem4 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_7.addItem(spacerItem4)
        self.label_14 = QLabel(self.waste_frame_6)
        self.label_14.setStyleSheet("background:transparent;")
        self.label_14.setObjectName("label_14")
        self.verticalLayout_7.addWidget(self.label_14)
        self.gridLayout.addWidget(self.waste_frame_6, 1, 2, 1, 1)
        self.inventory_frame_1 = QFrame(self.home_page)
        self.inventory_frame_1.setStyleSheet(
            "background-image:url(:/images/inventory_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#ADEBFF;")
        self.inventory_frame_1.setFrameShape(QFrame.StyledPanel)
        self.inventory_frame_1.setFrameShadow(QFrame.Raised)
        self.inventory_frame_1.setObjectName("inventory_frame_1")
        self.verticalLayout_2 = QVBoxLayout(self.inventory_frame_1)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        spacerItem5 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem5)
        self.label_9 = QLabel(self.inventory_frame_1)
        self.label_9.setStyleSheet("background:transparent;")
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.gridLayout.addWidget(self.inventory_frame_1, 0, 0, 1, 1)
        self.stackedWidget.addWidget(self.home_page)
        self.detail_page = QWidget()
        self.detail_page.setObjectName("detail_page")
        self.horizontalLayout_2 = QHBoxLayout(self.detail_page)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.main_tabWidget = QTabWidget(self.detail_page)
        self.main_tabWidget.setAutoFillBackground(False)
        self.main_tabWidget.setStyleSheet("")
        self.main_tabWidget.setTabPosition(QTabWidget.West)
        self.main_tabWidget.setIconSize(QSize(60, 60))
        self.main_tabWidget.setElideMode(Qt.ElideNone)
        self.main_tabWidget.setObjectName("main_tabWidget")
        ##initializes the tabs
        self.add_tabs()
        self.main_tabWidget.setFocusPolicy(Qt.StrongFocus)
        self.main_tabWidget.focusInEvent = self.change_focus
        self.main_tabWidget.currentChanged.connect(self.change_focus)
        self.stackedWidget.currentChanged.connect(self.change_focus)
        ######
        self.horizontalLayout_2.addWidget(self.main_tabWidget)
        self.stackedWidget.addWidget(self.detail_page)
        if ('Admin', True) in self.access:
            self.stackedWidget.addWidget(Admin(self.mainwindow))
        notification = NotificationTab()
        tab = notification.notificationTab_tab_4
        tab.custom_class_object = notification  # class_object is used to access the api through the
        self.stackedWidget.addWidget(tab)
        self.gridLayout_2.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.mainwindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(self.mainwindow)
        self.menuBar.setGeometry(QRect(0, 0, 832, 29))
        self.menuBar.setObjectName("menuBar")
        self.mainwindow.setMenuBar(self.menuBar)
        self.mainToolBar = QToolBar(self.mainwindow)
        self.mainToolBar.setLayoutDirection(Qt.RightToLeft)
        self.mainToolBar.setStyleSheet("")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QStatusBar(self.mainwindow)
        self.statusBar.setObjectName("statusBar")
        self.mainwindow.setStatusBar(self.statusBar)
        self.toolBar = QToolBar(self.mainwindow)
        self.toolBar.setLayoutDirection(Qt.RightToLeft)
        self.toolBar.setStyleSheet("")
        self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toolBar.setObjectName("toolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.actionNotification = QAction(self.mainwindow)
        self.actionNotification.setCheckable(True)
        self.actionNotification.setChecked(False)
        self.actionNotification.setEnabled(True)
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(":/images/notification.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionNotification.setIcon(icon6)
        self.actionNotification.setAutoRepeat(True)
        self.actionNotification.setVisible(True)
        self.actionNotification.setIconVisibleInMenu(False)
        self.actionNotification.setObjectName("actionNotification")
        self.actionNotification
        self.actionAdmin = QAction(self.mainwindow)
        # self.actionAdmin.setCheckable(True)
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(":/images/admin.png"), QIcon.Normal, QIcon.Off)
        self.actionAdmin.setIcon(icon7)
        self.actionAdmin.setObjectName("actionAdmin")
        self.actionRefresh = QAction(self.mainwindow)
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(":/images/refresh.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionRefresh.setIcon(icon8)
        self.actionRefresh.setObjectName("actionRefresh")
        self.actionHome = QAction(self.mainwindow)
        # self.actionHome.setCheckable(True)
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(":/images/home.png"), QIcon.Normal, QIcon.Off)
        self.actionHome.setIcon(icon9)
        self.actionHome.setObjectName("actionHome")
        self.actionSettings = QAction(self.mainwindow)
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(":/images/settings.png"), QIcon.Normal,
                         QIcon.Off)
        self.actionSettings.setIcon(icon10)
        self.actionSettings.setObjectName("actionRefresh")
        self.toolBar.addAction(self.actionNotification)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionAdmin)
        if ('Admin', True) in self.access:
            self.toolBar.addSeparator()
        else:
            self.actionAdmin.setVisible(False)
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionSettings)
        ##retranslates
        self.mainwindow.setWindowTitle(
            QApplication.translate("MainWindow", settings.company, None,
                                   QApplication.UnicodeUTF8))
        self.label_10.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">BILLING</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_11.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">EMPLOYEE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_12.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">MENU</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_13.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">REPORT</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_14.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">WASTE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_9.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">INVENTORY</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.inventory_frame_1.setToolTip(
            QApplication.translate("MainWindow", "Go to the Inventory Tab",
                                   None, QApplication.UnicodeUTF8))
        self.billing_frame_2.setToolTip(
            QApplication.translate("MainWindow", "Go to the Billing Tab", None,
                                   QApplication.UnicodeUTF8))
        self.employee_frame_3.setToolTip(
            QApplication.translate("MainWindow", "Go to the Employee Tab",
                                   None, QApplication.UnicodeUTF8))
        self.menu_frame_4.setToolTip(
            QApplication.translate("MainWindow", "Go to the Menu Tab", None,
                                   QApplication.UnicodeUTF8))
        self.report_frame_5.setToolTip(
            QApplication.translate("MainWindow", "Go to the Report Tab", None,
                                   QApplication.UnicodeUTF8))
        self.waste_frame_6.setToolTip(
            QApplication.translate("MainWindow", "Go to the Waste Tab", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("MainWindow", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionNotification.setText("&&Notification")
        # QApplication.translate("MainWindow", "&Notification", None, QApplication.UnicodeUTF8))
        self.actionNotification.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to see new notifications", None,
                                   QApplication.UnicodeUTF8))
        # self.actionNotification.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+N", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setText('&&Admin')
        # QApplication.translate("MainWindow", "Admin", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to go to admin interface", None,
                                   QApplication.UnicodeUTF8))
        # self.actionAdmin.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+A", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setText("&&Refresh")
        # QApplication.translate("MainWindow", "Refresh", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setToolTip(
            QApplication.translate("MainWindow",
                                   "refreshes the data from the server", None,
                                   QApplication.UnicodeUTF8))
        # self.actionRefresh.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+R", None, QApplication.UnicodeUTF8))
        self.actionHome.setText('&&Home')
        # QApplication.translate("MainWindow", "Home", None, QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("MainWindow", "Go back to the home screen",
                                   None, QApplication.UnicodeUTF8))
        self.actionSettings.setText('&&Settings')
        # QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setToolTip(
            QApplication.translate("MainWindow", "Go to the settings panel",
                                   None, QApplication.UnicodeUTF8))
        # self.actionHome.setShortcut(
        #     QApplication.translate("MainWindow", "Ctrl+Shift+H", None, QApplication.UnicodeUTF8))
        self.stackedWidget.setCurrentIndex(1)
        self.main_tabWidget.setCurrentIndex(0)

        self.ob = self.main_tabWidget.tabBar()
        # self.add_tool_tip(self.ob) todo avoided due to segmentation fault error, left for future fixes
        self.tb = EventHandlerForTabBar()
        self.ob.installEventFilter(self.tb)

        QMetaObject.connectSlotsByName(self.mainwindow)

    def add_tabs(self):
        """
        adds new tabs
        """
        global logger
        if ('Inventory', True) in self.access:
            logger.info('initiating Inventory')
            icon = QIcon()
            icon.addPixmap(QPixmap(":/images/inventory.png"), QIcon.Normal,
                           QIcon.Off)
            from inventory.inventory import Inventory

            inventory = Inventory()
            # inventory.inventory_tab_1.setToolTip("Inventory Section")
            self.main_tabWidget.addTab(inventory.inventory_tab_1, icon, "")
            inventory.inventory_detail_tabWidget.setCurrentIndex(0)
        else:
            self.inventory_frame_1.setVisible(False)
        self.progress.setLabelText('Inventory Done....')
        self.progress.setValue(2)

        if ('Billing', True) in self.access:
            logger.info('initiating Billing')
            icon1 = QIcon()
            icon1.addPixmap(QPixmap(":/images/billing.png"), QIcon.Normal,
                            QIcon.Off)
            from billing.billing import Billing

            bill = Billing()
            # bill.billing_tab_2.setToolTip("Billing Section")
            self.main_tabWidget.addTab(bill.billing_tab_2, icon1, "")
            bill.billing_detail_tabWidget.setCurrentIndex(0)
        else:
            self.billing_frame_2.setVisible(False)
        self.progress.setLabelText('Billing Done...')
        self.progress.setValue(3)

        if ('Employee', True) in self.access:
            logger.info('initiating Employee')
            icon2 = QIcon()
            icon2.addPixmap(QPixmap(":/images/employee.png"), QIcon.Normal,
                            QIcon.Off)
            from employee.employee import Employee

            employee = Employee()
            # employee.employee_tab_3.setToolTip("Employee Section")
            self.main_tabWidget.addTab(employee.employee_tab_3, icon2, "")
            employee.employee_detail_tabWidget.setCurrentIndex(0)
        else:
            self.employee_frame_3.setVisible(False)
        self.progress.setLabelText('Employee Done...')
        self.progress.setValue(4)

        if ('Menu', True) in self.access:
            logger.info('initiating Menu')
            icon3 = QIcon()
            icon3.addPixmap(QPixmap(":/images/menu.png"), QIcon.Normal,
                            QIcon.Off)
            from menu.menu import Menu

            menu = Menu()
            # menu.menu_tab_4.setToolTip("Menu Section")
            self.main_tabWidget.addTab(menu.menu_tab_4, icon3, "")
            menu.menu_detail_tabWidget.setCurrentIndex(0)
        else:
            self.menu_frame_4.setVisible(False)
        self.progress.setLabelText('Menu Done....')
        self.progress.setValue(5)

        if ('Report', True) in self.access:
            logger.info('initiating Report')
            icon4 = QIcon()
            icon4.addPixmap(QPixmap(":/images/report.png"), QIcon.Normal,
                            QIcon.Off)
            from report.report import Report

            report = Report()
            # report.report_tab_5.setToolTip("Report Section")
            self.main_tabWidget.addTab(report.report_tab_5, icon4, "")
            report.report_detail_tabWidget.setCurrentIndex(0)
        else:
            self.report_frame_5.setVisible(False)
        self.progress.setLabelText('Report Done....')
        self.progress.setValue(6)

        if ('Waste', True) in self.access:
            logger.info('initiating Waste')
            icon5 = QIcon()
            icon5.addPixmap(QPixmap(":/images/waste.png"), QIcon.Normal,
                            QIcon.Off)
            from waste.waste import Waste

            waste = Waste()
            # waste.waste_tab_6.setToolTip("Waste Section")
            self.main_tabWidget.addTab(waste.waste_tab_6, icon5, "")
            waste.waste_detail_tabWidget.setCurrentIndex(0)
        else:
            self.waste_frame_6.setVisible(False)
        self.progress.setLabelText('Waste Done....')
        self.progress.setValue(7)

    def change_focus(self, event=None):
        """
        focus method to set focus to a tab to initialize the corresponding events of the tab
        """
        wid = self.main_tabWidget.currentWidget()
        if wid:
            if wid.isVisible():
                # print wid.objectName()
                # print '1y'
                wid.setFocus()

    def add_tool_tip(
        self, ob
    ):  # todo not working causing segmentation fault, avoided calling this function
        """
        method to add tool tip to the tabs
        :param ob: Tab bar
        """
        obj = ob
        count = obj.count()
        hardcode = {
            0: 'Inventory Section',
            1: "Billing Section",
            2: "Employee Section",
            3: "Menu Section",
            4: "Report Section",
            5: "Waste Section"
        }
        for i in range(count):
            obj.setTabToolTip(i, hardcode[i])
class RegistrationShop(MainWindow, WindowDialog):
    """
	Main class that starts up the application.
	Creates UI and starts project/plugin managers.
	"""
    def __init__(self, args):
        """
		Sets app specific properties.
		Initializes the UI.
		"""
        super(RegistrationShop, self).__init__(args)

        self.setApplicationPath()
        # Instantiate the project controller
        ProjectController.Instance()

        # Initialize the user interface
        self.initUI()

        lastProject = RegistrationShop.settings.value("project/lastProject",
                                                      None)
        if lastProject:
            self.openProject(lastProject)

    def initialize(self):
        # Initialize the render window interactors only after calling show()
        # otherwise OpenGL errors will occur on OS X
        self.fixedDataWidget.rwi.Initialize()
        self.movingDataWidget.rwi.Initialize()
        self.multiDataWidget.rwi.Initialize()

    # UI setup methods

    def initUI(self):
        """
		Initializes the UI. Makes sure previous state of
		application is restored.
		"""
        # Create actions and elements
        self.createElements()
        self.connectElements()
        self.createActions()
        self.createMenus()
        self.createToolbar()
        self.restoreState()

        # Set some window/application properties
        self.setUnifiedTitleAndToolBarOnMac(True)
        self.setWindowTitle(APPNAME)
        self.setWindowState(Qt.WindowActive)

    def createElements(self):
        """
		Creates the widgets and docks of which the
		main window is composed.
		"""
        self.mainWindow = QMainWindow()
        projectController = ProjectController.Instance()
        self.transformTool = None

        # Render widgets
        self.fixedDataWidget = RenderWidget()
        self.movingDataWidget = RenderWidget()
        self.multiDataWidget = MultiRenderWidget()

        self.fixedRenderController = RenderController(self.fixedDataWidget,
                                                      "fixed")
        self.movingRenderController = RenderController(self.movingDataWidget,
                                                       "moving")
        self.multiRenderController = MultiRenderController(
            self.multiDataWidget)

        # Give references of the render controllers to the project controller
        projectController.fixedRenderController = self.fixedRenderController
        projectController.movingRenderController = self.movingRenderController
        projectController.multiRenderController = self.multiRenderController

        # Render properties widgets
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)

        self.fixedPropWidget = RenderPropWidget(self.fixedRenderController,
                                                parent=self)
        self.fixedPropWidget.setSizePolicy(sizePolicy)
        self.fixedPropWidget.setFileChangedSignal(
            projectController.fixedFileChanged)
        self.fixedPropWidget.setLoadDataSlot(self.loadFixedDataSetFile)

        self.movingPropWidget = RenderPropWidget(self.movingRenderController,
                                                 parent=self)
        self.movingPropWidget.setSizePolicy(sizePolicy)
        self.movingPropWidget.setFileChangedSignal(
            projectController.movingFileChanged)
        self.movingPropWidget.setLoadDataSlot(self.loadMovingDataSetFile)

        self.multiPropWidget = MultiRenderPropWidget(
            self.multiRenderController, parent=self)
        self.multiPropWidget.setSizePolicy(sizePolicy)

        self.verticalSplitter = QSplitter()
        self.verticalSplitter.setOrientation(Qt.Vertical)

        # Create the layouts

        fixedDataTitleWidget = TitleWidget("Fixed volume")
        multiDataTitleWidget = TitleWidget("Fixed + Moving")
        movingDataTitleWidget = TitleWidget("Moving volume")

        fixedLayout = QGridLayout()
        fixedLayout.setSpacing(0)
        fixedLayout.setContentsMargins(0, 0, 0, 0)
        fixedLayout.addWidget(fixedDataTitleWidget)
        fixedLayout.addWidget(self.fixedDataWidget)
        fixedWidget = QWidget()
        fixedWidget.setLayout(fixedLayout)

        multiLayout = QGridLayout()
        multiLayout.setSpacing(0)
        multiLayout.setContentsMargins(0, 0, 0, 0)
        multiLayout.addWidget(multiDataTitleWidget)
        multiLayout.addWidget(self.multiDataWidget)
        multiWidget = QWidget()
        multiWidget.setLayout(multiLayout)

        movingLayout = QGridLayout()
        movingLayout.setSpacing(0)
        movingLayout.setContentsMargins(0, 0, 0, 0)
        movingLayout.addWidget(movingDataTitleWidget)
        movingLayout.addWidget(self.movingDataWidget)
        movingWidget = QWidget()
        movingWidget.setLayout(movingLayout)

        horizontalSplitter = QSplitter()
        horizontalSplitter.setOrientation(Qt.Horizontal)
        horizontalSplitter.addWidget(fixedWidget)
        horizontalSplitter.addWidget(multiWidget)
        horizontalSplitter.addWidget(movingWidget)

        propsLayout = QHBoxLayout()
        propsLayout.setSpacing(1)
        propsLayout.setContentsMargins(0, 0, 0, 0)
        propsLayout.addWidget(self.fixedPropWidget)
        propsLayout.addWidget(self.multiPropWidget)
        propsLayout.addWidget(self.movingPropWidget)

        propsWidget = QWidget()
        propsWidget.setMinimumHeight(245)
        propsWidget.setMaximumHeight(350)
        propsWidget.setLayout(propsLayout)

        self.verticalSplitter.addWidget(horizontalSplitter)
        self.verticalSplitter.addWidget(propsWidget)
        self.verticalSplitter.setStretchFactor(0, 2)
        self.verticalSplitter.setStretchFactor(1, 1)
        self.setCentralWidget(self.verticalSplitter)

    def connectElements(self):
        """
		All the elements have to be connected because they are dependent
		on each other.
		There is the project controller, two render controllers and a multi render
		controller.
		Also there are two render widgets and a multi render widget. Together with some
		parameter widgets that show settings and with which the user can interact.
		"""
        projectController = ProjectController.Instance()
        projectController.fixedFileChanged.connect(
            self.fixedRenderController.setFile)
        projectController.fixedFileChanged.connect(
            self.multiRenderController.setFixedFile)
        projectController.movingFileChanged.connect(
            self.movingRenderController.setFile)
        projectController.movingFileChanged.connect(
            self.multiRenderController.setMovingFile)
        projectController.fixedSettingsChanged.connect(
            self.fixedRenderController.setRenderSettings)
        projectController.movingSettingsChanged.connect(
            self.movingRenderController.setRenderSettings)
        projectController.multiSettingsChanged.connect(
            self.multiRenderController.setRenderSettings)

        self.fixedRenderController.visualizationChanged.connect(
            self.multiRenderController.setFixedVisualization)
        self.fixedRenderController.visualizationUpdated.connect(
            self.multiRenderController.setFixedVisualization)
        self.movingRenderController.visualizationChanged.connect(
            self.multiRenderController.setMovingVisualization)
        self.movingRenderController.visualizationUpdated.connect(
            self.multiRenderController.setMovingVisualization)

        self.multiDataWidget.transformations.transformationChanged.connect(
            self.movingDataWidget.transformationsUpdated)

    def createActions(self):
        """
		Create actions that can be attached to buttons and menus.
		"""
        userTransformIconName = AppResources.imageNamed(
            'UserTransformButton.png')
        landmarkTransformIconName = AppResources.imageNamed(
            'LandmarkTransformButton.png')
        deformableTransformIconName = AppResources.imageNamed(
            'DeformableTransformButton.png')
        compareIconName = AppResources.imageNamed('CompareButton.png')
        helpIconName = AppResources.imageNamed('HelpButton.png')

        self.actionFreeTransformTool = QAction('Manual transform',
                                               self,
                                               shortcut='Ctrl+1')
        self.actionFreeTransformTool.setIcon(QIcon(userTransformIconName))
        self.actionFreeTransformTool.triggered.connect(self.addManualTransform)

        self.actionLandmarkTransformTool = QAction('Landmark transform',
                                                   self,
                                                   shortcut='Ctrl+2')
        self.actionLandmarkTransformTool.setIcon(
            QIcon(landmarkTransformIconName))
        self.actionLandmarkTransformTool.triggered.connect(
            self.addLandmarkTransform)

        self.actionDeformableTransformTool = QAction('Automatic transform',
                                                     self,
                                                     shortcut='Ctrl+3')
        self.actionDeformableTransformTool.setIcon(
            QIcon(deformableTransformIconName))
        self.actionDeformableTransformTool.triggered.connect(
            self.addDeformableTransform)

        self.actionLoadFixedData = QAction('Load fixed data',
                                           self,
                                           shortcut='Ctrl+Shift+F')
        self.actionLoadFixedData.triggered.connect(self.loadFixedDataSetFile)

        self.actionLoadMovingData = QAction('Load moving data',
                                            self,
                                            shortcut='Ctrl+Shift+M')
        self.actionLoadMovingData.triggered.connect(self.loadMovingDataSetFile)

        self.actionSaveProject = QAction('Save project',
                                         self,
                                         shortcut='Ctrl+S')
        self.actionSaveProject.triggered.connect(self.saveProject)

        self.actionSaveProjectAs = QAction('Save project as...',
                                           self,
                                           shortcut='Ctrl+Shift+S')
        self.actionSaveProjectAs.triggered.connect(self.saveProjectAs)

        self.actionExportDataAs = QAction('Export data...',
                                          self,
                                          shortcut='Ctrl+E')
        self.actionExportDataAs.triggered.connect(self.exportDataAs)

        self.actionOpenProject = QAction('Open project...',
                                         self,
                                         shortcut='Ctrl+O')
        self.actionOpenProject.triggered.connect(self.openProject)

        self.actionNewProject = QAction('New project', self, shortcut='Ctrl+N')
        self.actionNewProject.triggered.connect(self.newProject)

        self.actionCompare = QAction('Compare', self, shortcut='Ctrl+U')
        self.actionCompare.setIcon(QIcon(compareIconName))
        self.actionCompare.triggered.connect(self.startComparison)

        self.actionHelp = QAction('Help', self, shortcut='Ctrl+H')
        self.actionHelp.setIcon(QIcon(helpIconName))
        self.actionHelp.triggered.connect(self.showHelp)

    def createMenus(self):
        """
		Creates menus from actions.
		"""
        self.menuBar = self.menuBar()
        self.menuItemFile = self.menuBar.addMenu('&File')
        self.menuItemFile.addAction(self.actionNewProject)
        self.menuItemFile.addAction(self.actionOpenProject)
        # TODO: Open recent >
        self.menuItemFile.addAction(self.actionSaveProject)
        self.menuItemFile.addAction(self.actionSaveProjectAs)
        self.menuItemFile.addAction(self.actionExportDataAs)

        self.menuItemProject = self.menuBar.addMenu('&Project')
        self.menuItemProject.addAction(self.actionLoadFixedData)
        self.menuItemProject.addAction(self.actionLoadMovingData)
        self.menuItemProject.addSeparator()

    def createToolbar(self):
        """
		Creates the main toolbar and sets the toolbar buttons.
		"""
        # Add toolbar
        self.toolbar = self.addToolBar('Main tools')
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.toolbar.setAllowedAreas(Qt.TopToolBarArea)
        self.toolbar.setFloatable(False)
        self.toolbar.setMovable(False)

        # Create custom toolbar widget that can align items left, center and right
        self.toolbarWidget = ToolbarWidget()
        self.toolbarWidget.addActionLeft(self.actionFreeTransformTool)
        self.toolbarWidget.addActionLeft(self.actionLandmarkTransformTool)
        self.toolbarWidget.addActionLeft(self.actionDeformableTransformTool)

        statusWidget = StatusWidget.Instance()
        statusWidget.setText(
            "Welcome to RegistrationShop!\nStart your registration by loading two datasets. "
            +
            "After that you can use the transform tools to align your volume data."
        )
        self.toolbarWidget.addCenterItem(statusWidget)

        # Add help button
        self.toolbarWidget.addActionRight(self.actionCompare)
        self.toolbarWidget.addActionRight(self.actionHelp)
        self.toolbar.addWidget(self.toolbarWidget)

    # Private Functions

    def setApplicationPath(self):
        """
		Finds the path to the application. This is done so that it
		can figure out where certain resources are located.
		QCoreApplication::applicationDirPath() on OS X does not return the
		desired path to the actual application but to the python executable
		in /Library/FrameWorks. This is inconvenient because images can't be
		located that way.
		So instead os.path is used to find the location of this __file__.
		"""
        AppVars.setPath(os.path.dirname(os.path.abspath(__file__)))

    # Action callbacks
    @Slot()
    def addManualTransform(self):
        """
		What happens when manual transform is added:
		* Entry is added to the tab history
			* Translation fields
			* Rotation fields
			* Scale field(s)
		* Transform box is added to the render widget
		* Button with apply (will apply the transform to the data)

		Applying the transform to the data means:
		* Create new dataset from transformed data
		* Save this data to the project folder
		* Read in the new data and update this in the multi render widget
		* this would mean a new data model for the multi render widget
		"""
        if not self.movingDataWidget.imageData:
            statusWidget = StatusWidget.Instance()
            statusWidget.setText(
                "Please load a moving dataset before starting a manual transform."
            )
            return

        if self.transformTool is not None:
            self.transformTool.cleanUp()

        self.transformTool = UserTransformationTool()
        self.transformTool.setRenderWidgets(moving=self.movingDataWidget,
                                            multi=self.multiDataWidget)
        self.multiPropWidget.setTransformTool(self.transformTool)
        self.transformTool.toolFinished.connect(self.transformToolFinished)

    @Slot()
    def addLandmarkTransform(self):
        if not self.fixedDataWidget.imageData or not self.movingDataWidget.imageData:
            statusWidget = StatusWidget.Instance()
            statusWidget.setText(
                "Please load a fixed and a moving dataset before starting a landmark transform."
            )
            return

        # Clean up the last transform tool
        if self.transformTool is not None:
            self.transformTool.cleanUp()

        self.transformTool = LandmarkTransformationTool()
        self.transformTool.setRenderWidgets(fixed=self.fixedDataWidget,
                                            moving=self.movingDataWidget,
                                            multi=self.multiDataWidget)

        # Create a tab page under the fixed render widget
        fixedLandmarkWidget = LandmarkWidget()
        self.fixedPropWidget.addTabWidget(fixedLandmarkWidget, "Landmark")

        # Create a tab page under the moving render widget
        movingLandmarkWidget = LandmarkWidget()
        self.movingPropWidget.addTabWidget(movingLandmarkWidget, "Landmark")

        # Make sure the landmark transform tool knows of these tab widgets
        self.transformTool.setLandmarkWidgets(fixedLandmarkWidget,
                                              movingLandmarkWidget)

        # Start the transformation
        self.multiPropWidget.setTransformTool(self.transformTool)
        self.transformTool.toolFinished.connect(self.transformToolFinished)

    @Slot()
    def addDeformableTransform(self):
        if not self.fixedDataWidget.imageData or not self.movingDataWidget.imageData:
            statusWidget = StatusWidget.Instance()
            statusWidget.setText(
                "Please load a fixed and a moving dataset before starting a deformable transform."
            )
            return

        self.multiPropWidget.tabWidget.setCurrentWidget(
            self.multiPropWidget.transformParamWidget)

        if self.transformTool is not None:
            self.transformTool.cleanUp()

        statusWidget = StatusWidget.Instance()
        statusWidget.setText(
            "Choose a template for a deformable transform. After choosing "
            "a template you will be able to review and adjust the parameters.")

        dialog = ElastixMainDialog(self)
        dialog.setModal(True)
        result = dialog.exec_()
        if not result:
            return
        if not dialog.transformation:
            # load custom file
            filename, other = QFileDialog.getOpenFileName(
                self, "Open custom parameter file", "", "(*.c *.txt)")
            if len(filename) == 0:
                return
            transformation = ParameterList()
            if not transformation.loadFromFile(filename):
                transformation = None
                statusWidget = StatusWidget.Instance()
                statusWidget.setText(
                    "Warning: could not load transformation file")
        else:
            transformation = dialog.transformation

        self.transformTool = DeformableTransformationTool()
        self.transformTool.setTransformation(transformation)
        self.transformTool.startedElastix.connect(self.showProgressBar)
        self.transformTool.endedElastix.connect(self.hideProgressBar)
        self.transformTool.setRenderWidgets(fixed=self.fixedDataWidget,
                                            moving=self.movingDataWidget,
                                            multi=self.multiDataWidget)
        self.multiPropWidget.setTransformTool(self.transformTool)
        self.transformTool.toolFinished.connect(self.transformToolFinished)

    @Slot()
    def transformToolFinished(self):
        self.multiPropWidget.transformToolFinished()
        self.fixedPropWidget.removeTabWidget()
        self.movingPropWidget.removeTabWidget()

    @Slot()
    def loadFixedDataSetFile(self):
        """
		Open file dialog to search for data files. If valid data is given, it will
		pass the data file location on to the slicer and the project controller.
		"""
        dataReader = DataReader()
        extensions = dataReader.GetSupportedExtensionsAsString()
        fileName, other = QFileDialog.getOpenFileName(
            self,
            "Open fixed data set",
            "",
            "Images (" + extensions + ")",
            options=QFileDialog.Directory)
        if len(fileName) > 0:
            # If there was another dataset first, ask if the user if the
            # visualizations should be reset
            projectController = ProjectController.Instance()
            if projectController.currentProject.fixedData:
                dialog = ResetVisualizationDialog(self)
                dialog.setWindowModality(Qt.WindowModal)
                dialog.exec_()
                if dialog.result is not None:
                    projectController.loadFixedDataSet(fileName)
                    if dialog.result:
                        self.fixedRenderController.resetVisualizations()
            else:
                projectController.loadFixedDataSet(fileName)

    @Slot()
    def loadMovingDataSetFile(self):
        """
		Open file dialog to search for data files. If valid data is given, it will
		pass the data file location on to the slicer and the project controller.
		"""
        dataReader = DataReader()
        extensions = dataReader.GetSupportedExtensionsAsString()
        fileName, other = QFileDialog.getOpenFileName(
            self,
            "Open moving data set",
            "",
            "Images (" + extensions + ")",
            options=QFileDialog.Directory)
        if len(fileName) > 0:
            # If there was another dataset first, ask if the user if the
            # visualizations should be reset
            projectController = ProjectController.Instance()
            if projectController.currentProject.movingData:
                dialog = ResetVisualizationDialog(self)
                dialog.setWindowModality(Qt.WindowModal)
                dialog.exec_()
                if dialog.result is not None:
                    projectController.loadMovingDataSet(fileName)
                    if dialog.result:
                        self.movingRenderController.resetVisualizations()
            else:
                # Inserting an identity transform
                self.multiDataWidget.transformations.append(
                    Transformation(vtkTransform(), "No transform", fileName))
                projectController.loadMovingDataSet(fileName)

    @Slot()
    def saveProject(self):
        """
		Save the project to the specified name in the current project. If no name
		is specified, then 'save project as' is called.
		"""
        projCont = ProjectController.Instance()

        if projCont.currentProject.folder is not None:
            # Save that project
            saved = projCont.saveProject()
            statusWidget = StatusWidget.Instance()
            if saved:
                # Save it in the settings that this was the last opened project
                RegistrationShop.settings.setValue(
                    "project/lastProject", projCont.currentProject.folder)
                statusWidget.setText(
                    "The project was succesfully saved to disk.")
            else:
                statusWidget.setText(
                    "Something went wrong while saving the project to disk. "
                    "Please try to save the project again.")
        else:
            self.saveProjectAs()

    @Slot()
    def saveProjectAs(self):
        """
		Opens a file dialog so that the user can select a folder
		in which to save the project.
		"""
        # Open file dialog
        fileName = QFileDialog.getExistingDirectory(self,
                                                    "Select project folder",
                                                    "",
                                                    QFileDialog.ShowDirsOnly)
        if len(fileName) > 0:
            # TODO: check for existing project!

            # Set filename of project
            ProjectController.Instance().currentProject.folder = fileName
            # Call save project
            self.saveProject()

    @Slot()
    def openProject(self, folderName=None):
        """
		If no project name is supplied, it will open a file dialog so
		that the user can select a project file
		or project folder.

		:param folderName: Name of a folder with a project
		:type folderName: basestring
		"""
        fileName = ""
        if folderName:
            fileName = folderName
        else:
            fileName = QFileDialog.getExistingDirectory(
                self, "Open project", "", QFileDialog.ShowDirsOnly)

        if len(fileName) > 0:
            fullName = fileName + ProjectController.Instance().ProjectFile
            if os.path.isfile(fullName):
                self.multiDataWidget.transformations.clear()
                loaded = ProjectController.Instance().loadProject(fileName)
                if loaded:
                    RegistrationShop.settings.setValue("project/lastProject",
                                                       fileName)
                else:
                    print "Couldn't load project:", folderName
            else:
                print "Warning: Project file does not exist"
                RegistrationShop.settings.remove("project/lastProject")

    @Slot()
    def newProject(self):
        """
		Create new project by calling the project controller
		"""
        self.multiDataWidget.transformations.clear()
        ProjectController.Instance().newProject()
        # Reset the last loaded project in the settings
        RegistrationShop.settings.setValue("project/lastProject", "")

    @Slot()
    def exportDataAs(self):
        """
		Opens a file dialog so that the user can provide a filename
		for saving the transformed dataset to.
		"""
        fileType = FileTypeDialog.getFileType(self,
                                              "Choose file type for export")
        if len(fileType) == 0:
            return

        extension = "(*." + fileType + ")"
        fileName, other = QFileDialog.getSaveFileName(
            self, "Save registration result to...", "", extension)
        if len(fileName) == 0:
            return

        self.showProgressBar("Exporting data...")

        transform = self.multiDataWidget.transformations.completeTransform()
        dataReader = DataReader()
        imageData = dataReader.GetImageData(
            ProjectController.Instance().currentProject.movingData)
        transformer = DataTransformer()
        outputData = transformer.TransformImageData(imageData, transform)
        writer = DataWriter()
        writer.WriteToFile(outputData, fileName, fileType)

        self.hideProgressBar()

    @Slot()
    def startComparison(self):
        projectController = ProjectController.Instance()
        project = projectController.currentProject
        if not project or not project.fixedData or not project.movingData:
            statusWidget = StatusWidget.Instance()
            statusWidget.setText(
                "Could not start comparison. Please make a project first"
                " and make sure to load two datasets.")
            return

        if hasattr(self, "compareWidget"):
            del self.compareWidget

        transform = self.multiDataWidget.transformations.completeTransform()

        self.controller = ComparisonController()
        self.controller.setInputData(project.fixedData, project.movingData,
                                     transform)
        self.compareWidget = CompareWidget(self.controller.widgets)
        self.compareWidget.show()
        self.controller.initialize()
        self.controller.slicerChanged(self.controller.fixedImageWidget)

    @Slot()
    def showHelp(self):
        statusWidget = StatusWidget.Instance()
        statusWidget.setText("Don't panic!")
Example #17
0
    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
Example #18
0
def createAction(self, icon, toolTip, statusTip, scripted=False):
    """
    TOWRITE

    :param `icon`: TOWRITE
    :type `icon`: QString
    :param `toolTip`: TOWRITE
    :type `toolTip`: QString
    :param `statusTip`: TOWRITE
    :type `statusTip`: QString
    :param `scripted`: TOWRITE
    :type `scripted`: bool
    :rtype: `QAction`_

    .. TODO:: send the global Icon, Image, Commands Dirs in to be used.

    """
    connect = self.connect  # NOT local optimization, but for ease of the code looking similar to the C++ whash
    mdiArea = self.mdiArea  # ditto

    ACTION = QAction(
        QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() +
              "/" + icon + ".png"), toolTip, self
    )  # QAction *  # TODO: Qt4.7 wont load icons without an extension...
    ACTION.setStatusTip(statusTip)
    ACTION.setObjectName(icon)
    # TODO: Set What's This Context Help to statusTip for now so there is some infos there.
    # Make custom whats this context help popup with more descriptive help than just
    # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup
    # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip.
    ACTION.setWhatsThis(statusTip)
    # TODO: Finish All Commands ... <.<

    if icon == "donothing":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()"))
    elif icon == "new":
        ACTION.setShortcut(QKeySequence.New)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()"))
    elif icon == "open":
        ACTION.setShortcut(QKeySequence.Open)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()"))
    elif icon == "save":
        ACTION.setShortcut(QKeySequence.Save)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()"))
    elif icon == "saveas":
        ACTION.setShortcut(QKeySequence.SaveAs)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()"))
    elif icon == "print":
        ACTION.setShortcut(QKeySequence.Print)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()"))
    elif icon == "designdetails":
        ACTION.setShortcut(QKeySequence("Ctrl+D"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()"))
    elif icon == "exit":
        ACTION.setShortcut(QKeySequence("Ctrl+Q"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()"))

    elif icon == "cut":
        ACTION.setShortcut(QKeySequence.Cut)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()"))
    elif icon == "copy":
        ACTION.setShortcut(QKeySequence.Copy)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()"))
    elif icon == "paste":
        ACTION.setShortcut(QKeySequence.Paste)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()"))

    elif icon == "windowcascade":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()"))
    elif icon == "windowtile":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()"))
    elif icon == "windowclose":
        ACTION.setShortcut(QKeySequence.Close)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()"))
    elif icon == "windowcloseall":
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("closeAllSubWindows()"))
    elif icon == "windownext":
        ACTION.setShortcut(QKeySequence.NextChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("activateNextSubWindow()"))
    elif icon == "windowprevious":
        ACTION.setShortcut(QKeySequence.PreviousChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("activatePreviousSubWindow()"))

    elif icon == "help":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()"))
    elif icon == "changelog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()"))
    elif icon == "tipoftheday":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()"))
    elif icon == "about":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()"))
    elif icon == "whatsthis":
        connect(ACTION, SIGNAL("triggered()"), self,
                SLOT("whatsThisContextHelp()"))

    elif icon == "icon16":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()"))
    elif icon == "icon24":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()"))
    elif icon == "icon32":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()"))
    elif icon == "icon48":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()"))
    elif icon == "icon64":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()"))
    elif icon == "icon128":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()"))

    elif icon == "settingsdialog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()"))

    elif icon == "undo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()"))
    elif icon == "redo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()"))

    elif icon == "makelayercurrent":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()"))
    elif icon == "layers":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()"))
    elif icon == "layerprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()"))

    elif icon == "textbold":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextBold(bool)"))
    elif icon == "textitalic":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextItalic(bool)"))
    elif icon == "textunderline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextUnderline(bool)"))
    elif icon == "textstrikeout":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextStrikeOut(bool)"))
    elif icon == "textoverline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextOverline(bool)"))

    elif icon == "zoomrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()"))
    elif icon == "zoomprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()"))
    elif icon == "zoomwindow":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()"))
    elif icon == "zoomdynamic":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()"))
    elif icon == "zoomscale":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()"))
    elif icon == "zoomcenter":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()"))
    elif icon == "zoomin":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()"))
    elif icon == "zoomout":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()"))
    elif icon == "zoomselected":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()"))
    elif icon == "zoomall":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()"))
    elif icon == "zoomextents":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()"))

    elif icon == "panrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()"))
    elif icon == "panpoint":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()"))
    elif icon == "panleft":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()"))
    elif icon == "panright":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()"))
    elif icon == "panup":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()"))
    elif icon == "pandown":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()"))

    elif icon == "day":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()"))
    elif icon == "night":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()"))

    elif scripted:
        ACTION.setIcon(
            QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon +
                  ".png"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()"))

    else:
        ACTION.setEnabled(False)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()"))

    return ACTION
def createAction(self, icon, toolTip, statusTip, scripted=False):
    """
    TOWRITE

    :param `icon`: TOWRITE
    :type `icon`: QString
    :param `toolTip`: TOWRITE
    :type `toolTip`: QString
    :param `statusTip`: TOWRITE
    :type `statusTip`: QString
    :param `scripted`: TOWRITE
    :type `scripted`: bool
    :rtype: `QAction`_

    .. TODO:: send the global Icon, Image, Commands Dirs in to be used.

    """
    connect = self.connect  # NOT local optimization, but for ease of the code looking similar to the C++ whash
    mdiArea = self.mdiArea  # ditto

    ACTION = QAction(
        QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() + "/" + icon + ".png"), toolTip, self
    )  # QAction *  # TODO: Qt4.7 wont load icons without an extension...
    ACTION.setStatusTip(statusTip)
    ACTION.setObjectName(icon)
    # TODO: Set What's This Context Help to statusTip for now so there is some infos there.
    # Make custom whats this context help popup with more descriptive help than just
    # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup
    # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip.
    ACTION.setWhatsThis(statusTip)
    # TODO: Finish All Commands ... <.<

    if icon == "donothing":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()"))
    elif icon == "new":
        ACTION.setShortcut(QKeySequence.New)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()"))
    elif icon == "open":
        ACTION.setShortcut(QKeySequence.Open)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()"))
    elif icon == "save":
        ACTION.setShortcut(QKeySequence.Save)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()"))
    elif icon == "saveas":
        ACTION.setShortcut(QKeySequence.SaveAs)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()"))
    elif icon == "print":
        ACTION.setShortcut(QKeySequence.Print)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()"))
    elif icon == "designdetails":
        ACTION.setShortcut(QKeySequence("Ctrl+D"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()"))
    elif icon == "exit":
        ACTION.setShortcut(QKeySequence("Ctrl+Q"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()"))

    elif icon == "cut":
        ACTION.setShortcut(QKeySequence.Cut)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()"))
    elif icon == "copy":
        ACTION.setShortcut(QKeySequence.Copy)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()"))
    elif icon == "paste":
        ACTION.setShortcut(QKeySequence.Paste)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()"))

    elif icon == "windowcascade":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()"))
    elif icon == "windowtile":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()"))
    elif icon == "windowclose":
        ACTION.setShortcut(QKeySequence.Close)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()"))
    elif icon == "windowcloseall":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("closeAllSubWindows()"))
    elif icon == "windownext":
        ACTION.setShortcut(QKeySequence.NextChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activateNextSubWindow()"))
    elif icon == "windowprevious":
        ACTION.setShortcut(QKeySequence.PreviousChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activatePreviousSubWindow()"))

    elif icon == "help":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()"))
    elif icon == "changelog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()"))
    elif icon == "tipoftheday":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()"))
    elif icon == "about":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()"))
    elif icon == "whatsthis":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("whatsThisContextHelp()"))

    elif icon == "icon16":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()"))
    elif icon == "icon24":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()"))
    elif icon == "icon32":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()"))
    elif icon == "icon48":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()"))
    elif icon == "icon64":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()"))
    elif icon == "icon128":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()"))

    elif icon == "settingsdialog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()"))

    elif icon == "undo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()"))
    elif icon == "redo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()"))

    elif icon == "makelayercurrent":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()"))
    elif icon == "layers":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()"))
    elif icon == "layerprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()"))

    elif icon == "textbold":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextBold(bool)"))
    elif icon == "textitalic":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextItalic(bool)"))
    elif icon == "textunderline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextUnderline(bool)"))
    elif icon == "textstrikeout":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextStrikeOut(bool)"))
    elif icon == "textoverline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextOverline(bool)"))

    elif icon == "zoomrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()"))
    elif icon == "zoomprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()"))
    elif icon == "zoomwindow":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()"))
    elif icon == "zoomdynamic":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()"))
    elif icon == "zoomscale":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()"))
    elif icon == "zoomcenter":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()"))
    elif icon == "zoomin":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()"))
    elif icon == "zoomout":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()"))
    elif icon == "zoomselected":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()"))
    elif icon == "zoomall":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()"))
    elif icon == "zoomextents":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()"))

    elif icon == "panrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()"))
    elif icon == "panpoint":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()"))
    elif icon == "panleft":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()"))
    elif icon == "panright":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()"))
    elif icon == "panup":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()"))
    elif icon == "pandown":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()"))

    elif icon == "day":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()"))
    elif icon == "night":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()"))

    elif scripted:
        ACTION.setIcon(QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon + ".png"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()"))

    else:
        ACTION.setEnabled(False)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()"))

    return ACTION