예제 #1
0
class WebBrowseBrick(Core.BaseBrick):

    properties = {"url": Property("string", "URL", "", "urlChanged")}

    connections = {
        "login":
        Connection("Login object", [Signal("loggedIn", "loggedIn")], [],
                   "connectionToLogin")
    }

    signals = []
    slots = [Slot("setURL")]

    def __init__(self, *args, **kargs):
        Core.BaseBrick.__init__(self, *args, **kargs)

    def init(self):
        self.webViewer = QWebView()
        self.urlBlank = "about:blank"
        mainLayout = Qt.QHBoxLayout(self.brick_widget)
        mainLayout.addWidget(self.webViewer)
        self.brick_widget.setLayout(mainLayout)
        self.brick_widget.setStyleSheet("border:1px solid;")
        self.brick_widget.setSizePolicy(Qt.QSizePolicy.Expanding,
                                        Qt.QSizePolicy.Expanding)

    def urlChanged(self, url):
        self.urlConfig = url

    def setUrl(self, url):
        #TODO:DEBUG
        print "got url %s" % url
        self.urlConfig = url

# When connected to Login, then block the brick

    def connectionToLogin(self, pPeer):
        if pPeer is not None:
            self.brick_widget.setEnabled(False)
            self.webViewer.load(QUrl(self.urlBlank))

    # Logged In : True or False
    def loggedIn(self, pValue):
        self.brick_widget.setEnabled(pValue)
        if pValue:
            self.webViewer.load(QUrl(self.urlConfig))
        else:
            self.webViewer.load(QUrl(self.urlBlank))
예제 #2
0
class MotorAlignmentBrick( Core.BaseBrick ):


    properties = {"caption": Property( "string", "Caption", "", "captionChanged" ),
                  "toolTip": Property( "string", "Tool tip", "", "toolTipChanged" ),
                  "expertModeOnly": Property( "boolean", "Expert mode only", "", "expertModeOnlyChanged", False )}

    connections = {"motoralignment": Connection( "MotorAlignment object",
                                             [Signal( "motorPositionChanged", "motorPositionChanged" )],
                                            [Slot( "moveMotor" ),
                                             Slot( "getMotorPosition" ),
                                             Slot( "getMotorsList" )],
                                             "connectedToMotorAlignment" )}
    signals = [Signal( "executeTestCollect" )]
    slots = []



    def motorPositionChanged( self, pValue ):
        if self.__motorAlignmentDialog is not None:
            self.__motorAlignmentDialog.setMotorPosition( pValue )



    def expert_mode( self, expert ):
        self.__expertMode = expert
        flag = ( not self.__expertModeOnly or self.__expertMode )
        self.motorAlignmentPushButton.setEnabled( flag )
        if not flag and self.__motorAlignmentDialog is not None:
            self.__motorAlignmentDialog.close()

    def __init__( self, *args, **kargs ):
        Core.BaseBrick.__init__( self, *args, **kargs )

    def init( self ):
        self.__toolTip = ""
        self.__motorAlignmentDialog = None
        self.__expertModeOnly = False
        self.__expertMode = False

        self.brick_widget.setLayout( Qt.QVBoxLayout() )
        self.motorAlignmentPushButton = Qt.QPushButton( self.brick_widget )
        Qt.QObject.connect( self.motorAlignmentPushButton, Qt.SIGNAL( "clicked()" ), self.motorAlignmentPushButtonClicked )
        self.brick_widget.layout().addWidget( self.motorAlignmentPushButton )

    def delete( self ):
        pass


    def connectedToMotorAlignment( self, pValue ):
        pass

    def captionChanged( self, pValue ):
        self.motorAlignmentPushButton.setText( pValue )

    def toolTipChanged( self, pValue ):
        self.motorAlignmentPushButton.setToolTip( pValue )

    def expertModeOnlyChanged( self, pValue ):
        self.__expertModeOnly = pValue
        self.expert_mode( self.__expertMode )

    def motorAlignmentPushButtonClicked( self ):
        if self.__motorAlignmentDialog is not None and self.__motorAlignmentDialog.isVisible():
            self.__motorAlignmentDialog.activateWindow()
            self.__motorAlignmentDialog.raise_()
        else:
            motorsList = self.getObject( "motoralignment" ).getMotorsList()
            if motorsList is None:
                Qt.QMessageBox.information( self.brick_widget, "Info", "There are no motors specified!" )
            else:
                logger.debug( 'MotorAlignmentBrick: got motor list %s', motorsList )
                self.__motorAlignmentDialog = MotorAlignmentDialog( self, motorsList )
                self.__motorAlignmentDialog.show()
예제 #3
0
class BsxAttenuatorsBrick( Core.BaseBrick ):


    properties = {"maskFormat": Property( "string", "Mask format", "", "maskFormatChanged" ),
                  "suffix": Property( "string", "Suffix", "", "suffixChanged" ),
                  "maximumHistory": Property( "integer", "Maximum history", "", "maximumHistoryChanged" ),
                  "minimumValue": Property( "float", "Minimum value", "", "minimumValueChanged" ),
                  "maximumValue": Property( "float", "Maximum value", "", "maximumValueChanged" ),
                  "orientation": Property( "combo", "Orientation", description = "Layout of widgets", onchange_cb = "orientationChanged", default = "Portrait", choices = ["Portrait", "Landscape"] )}


    connections = {"attenuators": Connection( "Attenuators object",
                                            [Signal( "attenuatorsStateChanged", "attenuatorsStateChanged" ),
                                             Signal( "attenuatorsFactorChanged", "attenuatorsFactorChanged" )],
                                            [],
                                            "connectionStatusChanged" ),

                   "display": Connection( "Display object",
                                    [Signal( "displayResetChanged", "displayResetChanged" ),
                                    Signal( "displayItemChanged", "displayItemChanged" ),
                                    Signal( "transmissionChanged", "transmissionChanged" ),
                                    Signal( "grayOut", "grayOut" )],
                                    [] ),
                    "login": Connection( "Login object",
                                            [Signal( "loggedIn", "loggedIn" )],
                                             [],
                                             "connectionToLogin" )}

    signals = []
    slots = []


    def __init__( self, *args, **kargs ):
        Core.BaseBrick.__init__( self, *args, **kargs )
        self.bsxAttenuator = None

    def init( self ):
        self.__filtersDialog = None
        self.__maskFormat = ""
        self.__suffix = ""
        self.__minimumValue = 0
        self.__maximumValue = 100
        self.loginDone = False

        self.hBoxLayout = Qt.QHBoxLayout()

        self.transmissionLabel = Qt.QLabel( "Transmission (current, new)", self.brick_widget )
        self.hBoxLayout.addWidget( self.transmissionLabel )

        self.currentTransmissionLineEdit = Qt.QLineEdit( self.brick_widget )
        self.currentTransmissionLineEdit.setEnabled( True )
        self.currentTransmissionLineEdit.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding )
        self.currentTransmissionLineEdit.setToolTip( "Current transmission" )
        self.hBoxLayout.addWidget( self.currentTransmissionLineEdit )

        self.newTransmissionComboBox = Qt.QComboBox( self.brick_widget )
        self.newTransmissionComboBox.setEditable( True )
        self.newTransmissionComboBox.lineEdit().setMaxLength( 10 )
        self.newTransmissionComboBox.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding )
        self.newTransmissionComboBox.setToolTip( "New transmission" )
        Qt.QObject.connect( self.newTransmissionComboBox, Qt.SIGNAL( "editTextChanged(const QString &)" ), self.newTransmissionComboBoxChanged )
        Qt.QObject.connect( self.newTransmissionComboBox.lineEdit(), Qt.SIGNAL( "returnPressed()" ), self.newTransmissionComboBoxReturnPressed )
        self.hBoxLayout.addWidget( self.newTransmissionComboBox )

        self.filtersPushButton = Qt.QPushButton( "Filters", self.brick_widget )
        self.filtersPushButton.setToolTip( "Enable/disable transmission filters" )
        Qt.QObject.connect( self.filtersPushButton, Qt.SIGNAL( "clicked()" ), self.filtersPushButtonClicked )

        self.newTransmissionComboBoxChanged( None )

    # When connected to Login, then block the brick
    def connectionToLogin( self, pPeer ):
        if pPeer is not None:
            # Check if we were already connected first
            if not self.loginDone:
                self.brick_widget.setEnabled( False )


    # Logged In : True or False 
    def loggedIn( self, pValue ):
        self.loginDone = pValue
        self.brick_widget.setEnabled( pValue )


    def maskFormatChanged( self, pValue ):
        self.__maskFormat = pValue
        self.attenuatorsFactorChanged( self.currentTransmissionLineEdit.text() )


    def suffixChanged( self, pValue ):
        self.__suffix = pValue
        #self.attenuatorsFactorChanged(self.currentTransmissionLineEdit.text())        


    def maximumHistoryChanged( self, pValue ):
        self.newTransmissionComboBox.setMaxCount( pValue )


    def minimumValueChanged( self, pValue ):
        self.__minimumValue = pValue
        self.newTransmissionComboBox.lineEdit().setValidator( Qt.QDoubleValidator( self.__minimumValue, self.__maximumValue, 10, self.newTransmissionComboBox.lineEdit() ) )


    def maximumValueChanged( self, pValue ):
        self.__maximumValue = pValue
        self.newTransmissionComboBox.lineEdit().setValidator( Qt.QDoubleValidator( self.__minimumValue, self.__maximumValue, 10, self.newTransmissionComboBox.lineEdit() ) )


    def orientationChanged( self, pValue ):
        if self.brick_widget.layout() is not None:
            self.hBoxLayout.setParent( None )
            self.brick_widget.layout().removeWidget( self.filtersPushButton )
            sip.transferback( self.brick_widget.layout() )
        if pValue == "Landscape":
            self.brick_widget.setLayout( Qt.QHBoxLayout() )
            self.filtersPushButton.setSizePolicy( Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Expanding )
        else:
            self.brick_widget.setLayout( Qt.QVBoxLayout() )
            self.filtersPushButton.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding )
        self.brick_widget.layout().addLayout( self.hBoxLayout )
        self.brick_widget.layout().addWidget( self.filtersPushButton )


    def attenuatorsStateChanged( self, pValue ):
        if self.__filtersDialog is not None:
            self.__filtersDialog.filtersChanged( pValue )
        # Need to take the new value for Transmission
        if self.bsxAttenuator is not None:
            currentTransmission = self.bsxAttenuator.getAttenuatorsFactor()
            if currentTransmission == "":
                self.currentTransmissionLineEdit.setText( self.__suffix )
            else:
                if self.__maskFormat == "":
                    self.currentTransmissionLineEdit.setText( str( float( currentTransmission ) ) + self.__suffix )
                else:
                    self.currentTransmissionLineEdit.setText( self.__maskFormat % float( currentTransmission ) + self.__suffix )



    def attenuatorsFactorChanged( self, pValue ):
        if pValue == "":
            self.currentTransmissionLineEdit.setText( self.__suffix )
        else:
            if self.__maskFormat == "":
                self.currentTransmissionLineEdit.setText( str( float( pValue ) ) + self.__suffix )
            else:
                self.currentTransmissionLineEdit.setText( self.__maskFormat % float( pValue ) + self.__suffix )

    # connect to Display
    def displayResetChanged( self ):
        pass

    def displayItemChanged( self, _ ):
        pass

    def grayOut( self, grayout ):
        if grayout is not None:
            if grayout:
                self.newTransmissionComboBox.setEditable( False )
                self.filtersPushButton.setEnabled( False )
                self.currentTransmissionLineEdit.setEnabled( False )
            else:
                self.newTransmissionComboBox.setEditable( True )
                # Put back Signal otherwise it is lost (maybe a bug) - SO 19/9 2012
                Qt.QObject.connect( self.newTransmissionComboBox.lineEdit(), Qt.SIGNAL( "returnPressed()" ), self.newTransmissionComboBoxReturnPressed )
                self.filtersPushButton.setEnabled( True )
                self.currentTransmissionLineEdit.setEnabled( True )


    def transmissionChanged( self, pValue ):
        self.getObject( "attenuators" ).setTransmission( float( pValue ) )


    def connectionStatusChanged( self, pPeer ):
        if pPeer is not None:
            self.bsxAttenuator = pPeer
            currentTransmission = self.bsxAttenuator.getAttenuatorsFactor()
            if currentTransmission == "":
                self.currentTransmissionLineEdit.setText( self.__suffix )
            else:
                if self.__maskFormat == "":
                    self.currentTransmissionLineEdit.setText( str( float( currentTransmission ) ) + self.__suffix )
                else:
                    self.currentTransmissionLineEdit.setText( self.__maskFormat % float( currentTransmission ) + self.__suffix )



    def newTransmissionComboBoxChanged( self, pValue ):
        if pValue is None or pValue == "":
            self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) )
        else:
            if self.newTransmissionComboBox.lineEdit().hasAcceptableInput():
                self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) )
            else:
                self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) )
        self.newTransmissionComboBox.lineEdit().update()


    def newTransmissionComboBoxReturnPressed( self ):
        if self.newTransmissionComboBox.lineEdit().hasAcceptableInput():
            if self.newTransmissionComboBox.currentText() != "":
                logger.info( "Setting transmission to " + self.newTransmissionComboBox.currentText() + " %..." )
                self.bsxAttenuator.setTransmission( float( self.newTransmissionComboBox.currentText() ) )
                self.newTransmissionComboBox.clearEditText()


    def toggleFilter( self, pFilter, pChecked, pValue ):
        if pChecked:
            logger.info( "Enabling filter '" + pFilter + "'..." )
        else:
            logger.info( "Disabling filter '" + pFilter + "'..." )
        self.bsxAttenuator.toggleFilter( pValue )


    def filtersPushButtonClicked( self ):
        if self.__filtersDialog is not None and self.__filtersDialog.isVisible():
            self.__filtersDialog.activateWindow()
            self.__filtersDialog.raise_()
        else:
            attenuatorsList = self.bsxAttenuator.getAttenuatorsList()
            if attenuatorsList is None:
                Qt.QMessageBox.information( self.brick_widget, "Info", "There are no attenuators specified!" )
            else:
                self.__filtersDialog = FiltersDialog( self, attenuatorsList )
                self.__filtersDialog.filtersChanged( self.bsxAttenuator.getAttenuatorsState() )
                self.__filtersDialog.show()
예제 #4
0
class BrowseBrick(Core.BaseBrick):

    properties = {
        "enableType":
        Property("boolean", "Enable type", "", "enableTypeChanged", True)
    }
    connections = {
        "browse":
        Connection("Browse object", [], [], "connectionStatusChanged"),
        "image_proxy":
        Connection("image proxy", [], [Slot('load_files')]),
        "login":
        Connection("Login object", [Signal("loggedIn", "loggedIn")], [],
                   "connectionToLogin")
    }

    signals = [
        Signal("displayResetChanged"),
        Signal("displayItemChanged"),
        Signal("transmissionChanged"),
        Signal("grayOut", "grayOut")
    ]
    slots = []

    def __init__(self, *args, **kargs):
        Core.BaseBrick.__init__(self, *args, **kargs)

    def init(self):
        self.__expertMode = False
        self.__formats = [["All", ""], ["Raw EDF  (*.edf)", "edf"],
                          ["Normalised EDF  (*.edf)", "edf"],
                          ["Bruker  (*.gfrm)", "gfrm"],
                          ["ADSC  (*.img)", "img"],
                          ["Mar CCD  (*.mccd)", "mccd"],
                          ["SPEC  (*.dat)", "dat"]]

        self.brick_widget.setLayout(Qt.QVBoxLayout())
        self.brick_widget.layout().setAlignment(QtCore.Qt.AlignTop)
        self.brick_widget.setSizePolicy(Qt.QSizePolicy.Expanding,
                                        Qt.QSizePolicy.Expanding)

        self.hBoxLayout0 = Qt.QHBoxLayout()
        self.typeLabel = Qt.QLabel("Type", self.brick_widget)
        self.typeLabel.setFixedWidth(130)
        self.hBoxLayout0.addWidget(self.typeLabel)
        self.typeComboBox = Qt.QComboBox(self.brick_widget)
        self.typeComboBox.addItems(["Normal", "HDF"])
        Qt.QObject.connect(self.typeComboBox,
                           Qt.SIGNAL("currentIndexChanged(int)"),
                           self.typeComboBoxChanged)
        self.hBoxLayout0.addWidget(self.typeComboBox)
        self.brick_widget.layout().addLayout(self.hBoxLayout0)

        self.hBoxLayout1 = Qt.QHBoxLayout()
        self.locationLabel = Qt.QLabel(self.brick_widget)
        self.locationLabel.setFixedWidth(130)
        self.hBoxLayout1.addWidget(self.locationLabel)
        self.locationLineEdit = Qt.QLineEdit(self.brick_widget)
        self.locationLineEdit.setMaxLength(100)
        Qt.QObject.connect(self.locationLineEdit,
                           Qt.SIGNAL("textChanged(const QString &)"),
                           self.locationLineEditChanged)
        self.hBoxLayout1.addWidget(self.locationLineEdit)
        self.locationPushButton = Qt.QPushButton("...", self.brick_widget)
        self.locationPushButton.setFixedWidth(25)
        Qt.QObject.connect(self.locationPushButton, Qt.SIGNAL("clicked()"),
                           self.locationPushButtonClicked)
        self.hBoxLayout1.addWidget(self.locationPushButton)
        self.brick_widget.layout().addLayout(self.hBoxLayout1)

        self.hBoxLayout2 = Qt.QHBoxLayout()
        self.formatLabel = Qt.QLabel("Format", self.brick_widget)
        self.formatLabel.setFixedWidth(130)
        self.hBoxLayout2.addWidget(self.formatLabel)
        self.formatComboBox = Qt.QComboBox(self.brick_widget)
        Qt.QObject.connect(self.formatComboBox,
                           Qt.SIGNAL("currentIndexChanged(int)"),
                           self.formatComboBoxChanged)
        self.hBoxLayout2.addWidget(self.formatComboBox)
        self.brick_widget.layout().addLayout(self.hBoxLayout2)

        self.hBoxLayout3 = Qt.QHBoxLayout()
        self.prefixLabel = Qt.QLabel("Prefix", self.brick_widget)
        self.prefixLabel.setFixedWidth(130)
        self.hBoxLayout3.addWidget(self.prefixLabel)
        self.prefixComboBox = Qt.QComboBox(self.brick_widget)
        Qt.QObject.connect(self.prefixComboBox,
                           Qt.SIGNAL("currentIndexChanged(int)"),
                           self.prefixComboBoxChanged)
        self.hBoxLayout3.addWidget(self.prefixComboBox)
        self.brick_widget.layout().addLayout(self.hBoxLayout3)

        self.hBoxLayout4 = Qt.QHBoxLayout()
        self.runNumberLabel = Qt.QLabel("Run #", self.brick_widget)
        self.runNumberLabel.setFixedWidth(130)
        self.hBoxLayout4.addWidget(self.runNumberLabel)
        self.runNumberComboBox = Qt.QComboBox(self.brick_widget)
        Qt.QObject.connect(self.runNumberComboBox,
                           Qt.SIGNAL("currentIndexChanged(int)"),
                           self.runNumberComboBoxChanged)
        self.hBoxLayout4.addWidget(self.runNumberComboBox)
        self.brick_widget.layout().addLayout(self.hBoxLayout4)

        self.hBoxLayout5 = Qt.QHBoxLayout()
        self.extraLabel = Qt.QLabel("Extra", self.brick_widget)
        self.extraLabel.setFixedWidth(130)
        self.hBoxLayout5.addWidget(self.extraLabel)
        self.extraComboBox = Qt.QComboBox(self.brick_widget)
        Qt.QObject.connect(self.extraComboBox,
                           Qt.SIGNAL("currentIndexChanged(int)"),
                           self.extraComboBoxChanged)
        self.hBoxLayout5.addWidget(self.extraComboBox)
        self.brick_widget.layout().addLayout(self.hBoxLayout5)

        self.hBoxLayout6 = Qt.QHBoxLayout()
        self.itemsLabel = Qt.QLabel("Items (0)", self.brick_widget)
        self.itemsLabel.setFixedWidth(130)
        self.hBoxLayout6.addWidget(self.itemsLabel)
        self.itemsListWidget = Qt.QListWidget(self.brick_widget)
        Qt.QObject.connect(self.itemsListWidget,
                           Qt.SIGNAL("itemSelectionChanged()"),
                           self.itemsListWidgetChanged)
        self.hBoxLayout6.addWidget(self.itemsListWidget)
        self.brick_widget.layout().addLayout(self.hBoxLayout6)

        self.vBoxLayout0 = Qt.QVBoxLayout()
        self.vBoxLayout0.addSpacing(20)
        self.brick_widget.layout().addLayout(self.vBoxLayout0)

        self.hBoxLayout7 = Qt.QHBoxLayout()
        self.refreshPushButton = Qt.QPushButton("Refresh", self.brick_widget)
        self.refreshPushButton.setToolTip(
            "Refresh item list with the specified parameters")
        self.hBoxLayout7.addWidget(self.refreshPushButton)
        Qt.QObject.connect(self.refreshPushButton, Qt.SIGNAL("clicked()"),
                           self.refreshPushButtonClicked)
        self.brick_widget.layout().addLayout(self.hBoxLayout7)

        self.typeComboBoxChanged(self.typeComboBox.currentIndex())
        self.locationLineEditChanged(None)

# When connected to Login, then block the brick

    def connectionToLogin(self, pPeer):
        if pPeer is not None:
            self.brick_widget.setEnabled(False)

    # Logged In : True or False
    def loggedIn(self, pValue):
        self.brick_widget.setEnabled(pValue)

    def connectionStatusChanged(self, pPeer):
        pass

    def delete(self):
        pass

    def enableTypeChanged(self, pValue):
        self.typeComboBox.setVisible(pValue)
        self.typeLabel.setVisible(pValue)
        self.typeComboBox.setCurrentIndex(0)

    def typeComboBoxChanged(self, pValue):
        self.formatComboBox.clear()
        if pValue == 0:
            self.locationLabel.setText("Directory")
            for description, self.__ignore in self.__formats:
                self.formatComboBox.addItem(description)
        else:
            self.locationLabel.setText("File")
            self.formatComboBox.addItems([
                "Raw EDF  (frame)", "Normalised EDF  (frame)", "SPEC  (curve)"
            ])
        self.locationChanged(self.locationLineEdit.text(), pValue)

    def locationLineEditChanged(self, pValue):
        self.locationChanged(pValue, self.typeComboBox.currentIndex())

    def locationChanged(self, pValue, pType):
        if pType == 0:  # directory
            if pValue is not None and os.path.exists(
                    pValue) and not os.path.isfile(pValue):
                if str(pValue).find(" ") == -1:
                    self.locationLineEdit.palette().setColor(
                        QtGui.QPalette.Base, QtGui.QColor(255, 255, 255))
                else:
                    self.locationLineEdit.palette().setColor(
                        QtGui.QPalette.Base, QtGui.QColor(255, 255, 0))
            else:
                self.locationLineEdit.palette().setColor(
                    QtGui.QPalette.Base, QtGui.QColor(255, 0, 0))
        else:  # HDF file
            if pValue is not None and os.path.exists(
                    pValue) and os.path.isfile(pValue):
                self.locationLineEdit.palette().setColor(
                    QtGui.QPalette.Base, QtGui.QColor(255, 255, 255))
            else:
                self.locationLineEdit.palette().setColor(
                    QtGui.QPalette.Base, QtGui.QColor(255, 0, 0))
        self.locationLineEdit.update()
        self.populatePrefixComboBox()
        self.populateRunNumberComboBox()
        self.populateExtraComboBox()
        self.populateItemsListWidget()

    def locationPushButtonClicked(self):
        if self.typeComboBox.currentIndex() == 0:
            qFileDialog = QtGui.QFileDialog(self.brick_widget,
                                            "Choose a directory",
                                            self.locationLineEdit.text())
            qFileDialog.setFileMode(QtGui.QFileDialog.DirectoryOnly)
        else:
            qFileDialog = QtGui.QFileDialog(self.brick_widget,
                                            "Choose a HDF file",
                                            self.locationLineEdit.text())
            qFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
            qFileDialog.setFilters(["Hierarchical Data Format (*.h5; *.hdf5)"])
        if qFileDialog.exec_():
            self.locationLineEdit.setText(str(qFileDialog.selectedFiles()[0]))

    def formatComboBoxChanged(self, pValue):
        if pValue is not None:
            if self.typeComboBox.currentIndex() == 0:
                directory = ("", "raw", "2d", "raw", "raw", "raw",
                             "1d")[self.formatComboBox.currentIndex()]
                if directory != "":
                    directoryList = str(
                        self.locationLineEdit.text()).split("/")
                    for i in range(len(directoryList) - 1, -1, -1):
                        if directoryList[i] != "":
                            if directoryList[i] in ("raw", "1d", "2d"):
                                directoryList[i] = directory
                            else:
                                directoryList.insert(i + 1, directory)
                            break
                    directory = ""
                    for i in range(0, len(directoryList)):
                        if directoryList[i] != "":
                            directory += "/" + directoryList[i]
                    if os.path.exists(directory):
                        self.locationLineEdit.setText(directory)

                if self.formatComboBox.currentIndex() == 6:
                    self.itemsListWidget.setSelectionMode(
                        QtGui.QAbstractItemView.ExtendedSelection)
                else:
                    self.itemsListWidget.setSelectionMode(
                        QtGui.QAbstractItemView.SingleSelection)
            else:
                pass  # implement HDF

            self.populatePrefixComboBox()
            self.populateRunNumberComboBox()
            self.populateExtraComboBox()
            self.populateItemsListWidget()

    def prefixComboBoxChanged(self, pValue):
        if pValue is not None:
            self.populateRunNumberComboBox()
            self.populateExtraComboBox()
            self.populateItemsListWidget()

    def runNumberComboBoxChanged(self, pValue):
        if pValue is not None:
            self.populateExtraComboBox()
            self.populateItemsListWidget()

    def extraComboBoxChanged(self, pValue):
        if pValue is not None:
            self.populateItemsListWidget()

    def itemsListWidgetChanged(self):
        if str(self.locationLineEdit.text()).endswith("/"):
            directory0 = self.locationLineEdit.text()
        else:
            directory0 = self.locationLineEdit.text() + "/"
        items = ""
        for item in self.itemsListWidget.selectedItems():
            if items == "":
                items = str(directory0 + item.text())
            else:
                items += "," + str(directory0 + item.text())
            if item.text().split(".")[-1] != "dat":
                directoryList = str(self.locationLineEdit.text()).split("/")
                for i in range(len(directoryList) - 1, -1, -1):
                    if directoryList[i] != "":
                        if directoryList[i] in ("raw"):
                            directoryList[i] = "1d"
                        else:
                            directoryList.insert(i + 1, "1d")
                        break
                directory1 = ""
                for i in range(0, len(directoryList)):
                    if directoryList[i] != "":
                        directory1 += "/" + directoryList[i]
                filename = str(directory1 + "/" + item.text().split(".")[0] +
                               ".dat")
                if os.path.exists(filename):
                    items += "," + filename
        self.emit("displayItemChanged", items)
        self.getObject('image_proxy').load_files(items.split(','))

    def refreshPushButtonClicked(self):
        self.populateItemsListWidget()

    def populatePrefixComboBox(self):
        items = []
        if self.typeComboBox.currentIndex() == 0:
            comboFormat = self.__formats[self.formatComboBox.currentIndex()][1]
            if os.path.isdir(self.locationLineEdit.text()):
                try:
                    for filename in os.listdir(self.locationLineEdit.text()):
                        if os.path.isfile(self.locationLineEdit.text() + "/" +
                                          filename):
                            prefix, self.__runIgnored, self.__frameIgnored, self.__extraIgnored, extension = self.getFilenameDetails(
                                filename)
                            flag = False
                            if self.formatComboBox.currentIndex() == 0:
                                for i in range(1, len(self.__formats)):
                                    if extension == self.__formats[i][1]:
                                        flag = True
                                        break
                            else:
                                flag = (extension == comboFormat)
                            if flag:
                                try:
                                    items.index(prefix)
                                except ValueError:
                                    items.append(prefix)
                except Exception, e:
                    logger.error("Full Exception: " + str(e))
        else:
예제 #5
0
class BsxGraphBrick(BaseBrick):

    properties = {
        "title":
        Property("string", "Title", "", "titleChanged", "untitled"),
        "lineWidth":
        Property("integer", "Line width", "", "lineWidthChanged", 1),
        "enableGrid":
        Property("boolean", "Enable grid", "", "enableGridChanged", False),
        "enableZoom":
        Property("boolean", "Enable zoom", "", "enableZoomChanged", False),
        "showPrintButton":
        Property("boolean", "Show print button", "", "showPrintButtonChanged",
                 True),
        "showScaleButton":
        Property("boolean", "Show scale button", "", "showScaleButtonChanged",
                 True),
        "showGridButton":
        Property("boolean", "Show grid button", "", "showGridButtonChanged",
                 True),
        "yAxisLabel":
        Property("string", "Y axis label", "", "yAxisLabelChanged", ""),
        "y2AxisLabel":
        Property("string", "Y2 axis label", "", "y2AxisLabelChanged", ""),
        "xAxisLabel":
        Property("string", "X axis label", "", "xAxisLabelChanged", ""),
        "titleFontSize":
        Property("combo", "Title font size", "", "titleFontSizeChanged", "14",
                 [
                     "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
                     "18", "19", "20", "21", "22", "23", "24"
                 ]),
        "axisFontSize":
        Property("combo", "Axis font size", "", "axisFontSizeChanged", "8",
                 ["6", "7", "8", "9", "10", "11", "12"]),
        "defaultScale":
        Property("combo", "Default scale", "", "defaultScaleChanged", "linear",
                 ["linear", "logarithmic"]),
        "timeOnXAxis":
        Property("boolean", "Time on X axis", "", "timeOnXAxisChanged", False),
        "timeElapsedTime":
        Property("boolean", "Elapsed time", "", "timeElapsedTimeChanged",
                 True),
        "windowSize":
        Property("integer", "Window size", "", "windowSizeChanged", "3600")
    }

    connections = {
        "y_curves":
        Connection("Y-mapped curves provider", [
            Signal('new_curves_data', 'new_curves_data'),
            Signal('erase_curve', 'erase_curve')
        ], [], 'y_curves_provider_connected'),
        'y_scan':
        Connection(
            'Y scan provider',
            [Signal('new_scan', 'new_scan'),
             Signal('new_point', 'new_value')], [],
            'y_scan_provider_connected')
    }

    def __init__(self, *args, **kargs):
        BaseBrick.__init__(self, *args, **kargs)

    def init(self):
        self.__axis_provider = dict()
        self.__curves_by_provider = dict()
        self.graphLayout = Qt.QVBoxLayout()
        self.graphSubLayout = Qt.QHBoxLayout()

        self.qtBlissGraph = QtBlissGraph()
        self.graphLayout.addWidget(self.qtBlissGraph)

        self.printPushButton = Qt.QPushButton("Print")
        self.graphSubLayout.addWidget(self.printPushButton)
        Qt.QObject.connect(self.printPushButton, Qt.SIGNAL("clicked()"),
                           self.printPushButtonClicked)

        self.current_scale = "linear"
        self.scalePushButton = Qt.QPushButton("Scale")
        self.scaleMenu = Qt.QMenu(self.scalePushButton)
        self.scaleActionGroup = Qt.QActionGroup(self.scaleMenu)
        self.scaleMenuLinear = Qt.QAction("Linear", self.scaleActionGroup)
        self.scaleMenuLinear.setCheckable(True)
        self.scaleMenu.addAction(self.scaleMenuLinear)
        self.scaleMenuLogarithmic = Qt.QAction("Logarithmic",
                                               self.scaleActionGroup)
        self.scaleMenuLogarithmic.setCheckable(True)
        self.scaleMenu.addAction(self.scaleMenuLogarithmic)
        Qt.QObject.connect(self.scaleActionGroup,
                           Qt.SIGNAL("triggered(QAction*)"),
                           self.scaleActionGroupTriggered)
        self.scalePushButton.setMenu(self.scaleMenu)
        self.graphSubLayout.addWidget(self.scalePushButton)

        self.gridPushButton = Qt.QPushButton("Grid")
        self.gridMenu = Qt.QMenu(self.gridPushButton)
        self.gridActionGroup = Qt.QActionGroup(self.gridMenu)
        self.gridMenuEnable = Qt.QAction("Enable", self.gridActionGroup)
        self.gridMenuEnable.setCheckable(True)
        self.gridMenu.addAction(self.gridMenuEnable)
        self.gridMenuDisable = Qt.QAction("Disable", self.gridActionGroup)
        self.gridMenuDisable.setCheckable(True)
        self.gridMenuDisable.setChecked(True)
        self.gridMenu.addAction(self.gridMenuDisable)
        Qt.QObject.connect(self.gridActionGroup,
                           Qt.SIGNAL("triggered(QAction*)"),
                           self.gridActionGroupTriggered)
        self.gridPushButton.setMenu(self.gridMenu)
        self.graphSubLayout.addWidget(self.gridPushButton)

        self.resetPushButton = Qt.QPushButton("Reset")
        self.graphSubLayout.addWidget(self.resetPushButton)
        Qt.QObject.connect(self.resetPushButton, Qt.SIGNAL("clicked()"),
                           self.resetPushButtonClicked)

        self.graphLayout.addLayout(self.graphSubLayout)
        self.brick_widget.setLayout(self.graphLayout)

        self.curveData = {}
        self.timeAxisX = False
        self.timeAxisElapsedTime = True
        self.windowSize = None

    def addCurve(self, pCurve):
        curveName = pCurve["name"]
        maptoy2 = pCurve.get("maptoy2", False)

        if not curveName in self.curveData:
            self.curveData[curveName] = CurveData(curveName, maptoy2=maptoy2)

        self.qtBlissGraph.newCurve(curveName,
                                   x=self.curveData[curveName].x,
                                   y=self.curveData[curveName].y,
                                   maptoy2=maptoy2)

    def addPoint(self,
                 pCurveName,
                 x=None,
                 y=None,
                 pTimeOut=False,
                 replot=True):
        if y is None:
            return
        else:
            y = float(y)

        curveData = self.curveData[pCurveName]

        if self.timeAxisX:
            if self.timeAxisElapsedTime:
                if curveData.t0 is None:
                    # 't0' is the starting time (first point added)
                    curveData.t0 = time.time()
                    curveData.t = curveData.t0
                    t = 0
                else:
                    # 't' is the time elapsed between the new point and the previous one
                    t = time.time() - curveData.t
                    curveData.t += t
            else:
                t = int(time.strftime("%S")) + int(
                    time.strftime("%H")) * 3600 + int(time.strftime("%M")) * 60
                curveData.t = t

            if self.windowSize > 0:
                x = 0
                n0 = len(curveData.x)
                curveData.x = filter(
                    None,
                    [x + self.windowSize > 0 and x - t for x in curveData.x])
                n = len(curveData.x)

                if n0 > n:
                    curveData.y = curveData.y[n0 - n:]
            else:
                if self.timeAxisElapsedTime:
                    x = curveData.t - curveData.t0
                else:
                    x = curveData.t
        elif x is not None:
            x = float(x)
        else:
            if pTimeOut:
                return

            if len(curveData.x) > 0:
                x = curveData.x[-1] + 1
            else:
                x = 0

        curveData.x.append(x)
        curveData.y.append(y)

        if self.windowSize:
            if not self.timeAxisX and len(curveData.y) == self.windowSize:
                del curveData.y[0]
                del curveData.x[0]

        if replot:
            self.qtBlissGraph.newCurve(pCurveName,
                                       curveData.x,
                                       curveData.y,
                                       maptoy2=curveData.maptoy2)
            self.qtBlissGraph.replot()

    def removeCurve(self, pCurveName):
        try:
            del self.curveData[pCurveName]
        except KeyError:
            pass
        else:
            self.qtBlissGraph.newCurve(pCurveName, [], [])

    def new_y_axis_value(self, *args, **kwargs):
        self.new_value(*args, **kwargs)

    def new_y2_axis_value(self, *args, **kwargs):
        kwargs['maptoy2'] = True
        self.new_value(*args, **kwargs)

    def new_curves_data(self, *args, **kwargs):
        self.new_value(*args, **kwargs)

    def y2_curves_data(self, *args, **kwargs):
        kwargs['maptoy2'] = True
        self.new_value(*args, **kwargs)

    def new_value(self,
                  value,
                  sender=None,
                  maptoy2=False,
                  signal=None,
                  replot=True):
        if type(value) == types.DictType:
            #dict in the form {curvename: [[values for x],[values for y]]}
            # call ourselves one time per value pair
            for curve, points in value.iteritems():
                self.erase_curve(curve)
                for (x, y) in zip(points[0], points[1]):
                    self.new_value((x, y, curve),
                                   sender=sender,
                                   maptoy2=maptoy2,
                                   replot=False)
                curveData = self.curveData[curve]
                #TODO: taking away the two next lines does a lot for speed - Need to know if hidden and see if we can unhide it
                self.qtBlissGraph.newCurve(curve,
                                           curveData.x,
                                           curveData.y,
                                           maptoy2=maptoy2)
            self.qtBlissGraph.replot()
            return

        # if value is not a dict, proceed as usual
        # it's either a tuple or a discrete value
        if type(value) == types.TupleType and len(value) == 3:
            curveName = value[2]
        else:
            curveName = sender.username()

        if sender not in self.__curves_by_provider.keys():
            self.__curves_by_provider[sender] = [curveName]
        else:
            if curveName not in self.__curves_by_provider[sender]:
                self.__curves_by_provider[sender].append(curveName)

        if value is None:
            self.removeCurve(curveName)
        else:
            if not curveName in self.curveData:
                self.addCurve({"name": curveName, 'maptoy2': maptoy2})
            if type(value) == types.TupleType:
                if len(value) >= 2:
                    self.addPoint(curveName,
                                  x=value[0],
                                  y=value[1],
                                  replot=replot)
            else:
                self.addPoint(curveName, y=value, replot=replot)

    def erase_curve(self, curve_name, sender=None):
        """If the curve_name is None or empty, erase all curves (created by objects sending data packs)"""
        #logging.debug('%s: erase_curve called with curve_name=%s and sender=%s', self, curve_name, sender)
        #logging.debug('curves by sender: %r', self.__curves_by_provider)
        if curve_name is None:
            if sender is not None:
                for curve in self.__curves_by_provider.get(sender, []):
                    #logging.debug('    removing curve %s', curve)
                    self.removeCurve(curve)
        else:
            self.removeCurve(curve_name)

    def new_scan(self, parameters, sender=None):
        self.erase_curve(None, sender)
        ylabel = parameters.get('ylabel', "")
        xlabel = parameters.get('xlabel', "")
        title = parameters.get('title', '')
        self.qtBlissGraph.setTitle(title)
        self.qtBlissGraph.xlabel(xlabel)
        if self.__axis_provider.get(sender, 'y') == 'y':
            self.qtBlissGraph.ylabel(ylabel)
        else:
            self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, ylabel)

    def y_curves_provider_connected(self, provider):
        pass

    def y_scan_provider_connected(self, provider):
        self.__axis_provider[provider] = 'y'

    def titleChanged(self, pValue):
        self.qtBlissGraph.setTitle(pValue)

    def lineWidthChanged(self, pValue):
        self.qtBlissGraph.setactivelinewidth(pValue)
        self.qtBlissGraph.linewidth = pValue
        self.qtBlissGraph.replot()

    def enableGridChanged(self, pValue):
        if pValue:
            self.gridMenuEnable.setChecked(True)
            self.qtBlissGraph.showGrid()
        else:
            self.gridMenuDisable.setChecked(True)
            self.qtBlissGraph.hideGrid()
        self.qtBlissGraph.replot()

    def enableZoomChanged(self, pValue):
        self.qtBlissGraph.enableZoom(pValue)

    def showPrintButtonChanged(self, pValue):
        if self.printPushButton is not None:
            self.printPushButton.setVisible(pValue)

    def showScaleButtonChanged(self, pValue):
        if self.scalePushButton is not None:
            self.scalePushButton.setVisible(pValue)

    def showGridButtonChanged(self, pValue):
        if self.gridPushButton is not None:
            self.gridPushButton.setVisible(pValue)

    def xAxisLabelChanged(self, pValue):
        self.qtBlissGraph.xlabel(pValue)

    def yAxisLabelChanged(self, pValue):
        self.qtBlissGraph.ylabel(pValue)

    def y2AxisLabelChanged(self, pValue):
        self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, pValue)

    def titleFontSizeChanged(self, pValue):
        title = self.qtBlissGraph.title()
        font = title.font()
        font.setPointSize(int(pValue))
        title.setFont(font)
        self.qtBlissGraph.setTitle(title)

    def axisFontSizeChanged(self, pValue):
        titleX = self.qtBlissGraph.axisTitle(qwt.QwtPlot.xBottom)
        titleY = self.qtBlissGraph.axisTitle(qwt.QwtPlot.yLeft)
        titleY2 = self.qtBlissGraph.axisTitle(qwt.QwtPlot.yRight)
        fontX = titleX.font()
        fontY = titleY.font()
        fontY2 = titleY2.font()
        size = int(pValue)
        fontX.setPointSize(size)
        fontY.setPointSize(size)
        fontY2.setPointSize(size)
        titleX.setFont(fontX)
        titleY.setFont(fontY)
        titleY2.setFont(fontY2)
        self.qtBlissGraph.setAxisFont(qwt.QwtPlot.xBottom, fontX)
        self.qtBlissGraph.setAxisFont(qwt.QwtPlot.yLeft, fontY)
        self.qtBlissGraph.setAxisFont(qwt.QwtPlot.yRight, fontY2)
        self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.xBottom, titleX)
        self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yLeft, titleY)
        self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, titleY2)

    def timeOnXAxisChanged(self, pValue):
        self.timeAxisX = pValue
        for curveData in self.curveData.itervalues():
            curveData.clear()
            self.qtBlissGraph.newCurve(str(curveData.objectName()),
                                       x=[],
                                       y=[],
                                       maptoy2=curveData.maptoy2)
        self.setXAxisScale()

    def setXAxisScale(self):
        if self.timeAxisX:
            self.qtBlissGraph.setx1timescale(True)
            if self.windowSize is not None:
                if self.windowSize <= 0:
                    self.qtBlissGraph.xAutoScale = True
                    #self.graphWidget.setAxisAutoScale(qwt.QwtPlot.xBottom)
                else:
                    self.qtBlissGraph.setX1AxisLimits(0 - int(self.windowSize),
                                                      0)
                    #self.graphWidget.setAxisScale(qwt.QwtPlot.xBottom, 0 - self.windowSize, 0)
        else:
            self.qtBlissGraph.setx1timescale(False)
            self.qtBlissGraph.xAutoScale = True
            #self.graphWidget.setAxisAutoScale(qwt.QwtPlot.xBottom)
        self.qtBlissGraph.replot()

    def timeElapsedTimeChanged(self, pValue):
        self.timeAxisElapsedTime = pValue

    def windowSizeChanged(self, pValue):
        self.windowSize = pValue
        self.setXAxisScale()

    def printPushButtonClicked(self):
        self.qtBlissGraph.printps()

    def scaleActionGroupTriggered(self, scale_action):
        if scale_action == self.scaleMenuLinear:
            if self.current_scale != "linear":
                self.current_scale = "linear"
                self.qtBlissGraph.toggleLogY()
        else:
            if self.current_scale == "linear":
                self.current_scale = "logarithmic"
                self.qtBlissGraph.toggleLogY()

    def defaultScaleChanged(self, scale):
        if scale == "linear":
            self.scaleMenuLinear.setChecked(True)
            self.scaleActionGroupTriggered(self.scaleMenuLinear)
        else:
            #logarithmic
            self.scaleMenuLogarithmic.setChecked(True)
            self.scaleActionGroupTriggered(self.scaleMenuLogarithmic)

    def gridActionGroupTriggered(self, pValue):
        self.setProperty("enableGrid", pValue == self.gridMenuEnable)

    def resetPushButtonClicked(self):
        curve_names = self.curveData.keys()
        for name in curve_names:
            self.erase_curve(name)
        self.qtBlissGraph.replot()
예제 #6
0
class BsxShutterBrick(Core.BaseBrick):
    description = 'Simple class to display and control a shutter'

    properties = {
        "icons":
        PropertyGroup(
            "Icons", "Select icons for different elements", "set_icons", {
                "opened": Property("image", "Opened"),
                "closed": Property("image", "Closed")
            }),
        'shutter_name':
        Property(
            'string',  #type
            'Shutter name',  #label
            'The name of the shutter',  #description
            'shutterNameStateChanged',  #onchange_cb
            '')  #default value    
        ,
        'show_state':
        Property(
            'boolean',  #type
            'Show state',  #label
            '',  #description
            'showStateChanged',  #onchange_cb
            True)  #default value
        ,
        'show_button':
        Property(
            'boolean',  #type
            'Show button',  #label
            'Allow the user to manipulate the shutter\'s state',  #description
            'showButtonChanged',  #onchange_cb
            True)  #default value
        ,
        'orientation':
        Property(
            'combo',  #type
            'Orientation',  #label
            description='Layout of widgets',
            onchange_cb='orientationChanged',
            default='Portrait',
            choices=['Portrait', 'Landscape'])
    }

    connections = {
        "shutter":
        Connection("Shutter object",
                   [Signal("stateChanged", "shutter_state_changed")],
                   [Slot("open"), Slot("close")], "connectionStatusChanged"),
        "display":
        Connection("Display object", [
            Signal("displayResetChanged", "displayResetChanged"),
            Signal("displayItemChanged", "displayItemChanged"),
            Signal("transmissionChanged", "transmissionChanged"),
            Signal("grayOut", "grayOut")
        ], []),
        "login":
        Connection("Login object", [Signal("loggedIn", "loggedIn")], [],
                   "connectionToLogin")
    }

    # TACO Shutterstate
    #    shutterState = {"unknown": Qt.QColor(0x64, 0x64, 0x64),
    #                    "closed": Qt.QColor(0xff, 0x0, 0xff),
    #                    "opened": Qt.QColor(0x0, 0xff, 0x0),
    #                    "moving": Qt.QColor(0x66, 0x33, 0x0),
    #                    "automatic": Qt.QColor(0x0, 0x99, 0x0),
    #                    "fault": Qt.QColor(0x99, 0x0, 0x0),
    #                    "disabled": Qt.QColor(0xec, 0x3c, 0xdd),
    #                    "error": Qt.QColor(0xff, 0x0, 0x0)}

    # TANGO Shutterstate
    shutterState = {
        "on": Qt.QColor(0x0, 0xff, 0x0),
        "off": Qt.QColor(0xec, 0x3c, 0xdd),
        "closed": Qt.QColor(0xff, 0x0, 0xff),
        "opened": Qt.QColor(0x0, 0xff, 0x0),
        "insert": Qt.QColor(0x66, 0x33, 0x0),
        "extract": Qt.QColor(0x66, 0x33, 0x0),
        "moving": Qt.QColor(0xff, 0xa5, 0x0),
        "standby": Qt.QColor(0x66, 0x33, 0x0),
        "fault": Qt.QColor(0xff, 0x0, 0x0),
        "init": Qt.QColor(0x66, 0x33, 0x0),
        "running": Qt.QColor(0x66, 0x33, 0x0),
        "alarm": Qt.QColor(0x99, 0x0, 0x0),
        "disabled": Qt.QColor(0xec, 0x3c, 0xdd),
        "unknown": Qt.QColor(0x64, 0x64, 0x64),
        "error": Qt.QColor(0xff, 0x0, 0x0)
    }

    def __init__(self, *args, **kwargs):
        Core.BaseBrick.__init__(self, *args, **kwargs)

    def init(self):
        self.shutterName = None
        self.state = None
        self.loginDone = False
        self.shutter_state = Qt.QLabel("Unknown", self.brick_widget)
        self.shutter_state.setAutoFillBackground(True)
        self.shutter_state.palette().setColor(QtGui.QPalette.Background,
                                              self.shutterState["unknown"])
        self.shutter_state.setAlignment(Qt.Qt.AlignCenter)
        self.shutter_state.setToolTip("Current shutter state")
        self.shutter_cmd = Qt.QPushButton("Unknown", self.brick_widget)
        self.shutter_cmd.setToolTip("Unknown shutter state")
        Qt.QObject.connect(self.shutter_cmd, Qt.SIGNAL("clicked()"),
                           self.shutter_cmd_clicked)

# When connected to Login, then block the brick

    def connectionToLogin(self, pPeer):
        if pPeer is not None:
            # Check if we were already connected first
            if not self.loginDone:
                self.brick_widget.setEnabled(False)

    # Logged In : True or False
    def loggedIn(self, pValue):
        self.loginDone = pValue
        self.brick_widget.setEnabled(pValue)

    # Connect to display

    def grayOut(self, grayout):
        if grayout is not None:
            if grayout:
                self.brick_widget.setEnabled(False)
            else:
                self.brick_widget.setEnabled(True)

    def displayResetChanged(self):
        pass

    def displayItemChanged(self, __):
        pass

    def transmissionChanged(self, __):
        pass

    def set_icons(self, icons):
        pass

    def shutterNameStateChanged(self, pValue):
        self.shutterName = pValue
        self.shutter_state.setToolTip("Current '%s' shutter state" %
                                      self.shutterName)
        state = self.state

        # force redisplay of state so the shutter name is displayed.
        if state is None:
            state = 'unknown'
        self.shutter_state_changed(state)

    def showStateChanged(self, pValue):
        if self.shutter_state is not None:
            self.shutter_state.setVisible(pValue)

    def showButtonChanged(self, pValue):
        if self.shutter_cmd is not None:
            self.shutter_cmd.setVisible(pValue)

    def orientationChanged(self, pValue):
        if self.brick_widget.layout() is not None:
            self.brick_widget.layout().removeWidget(self.shutter_state)
            self.brick_widget.layout().removeWidget(self.shutter_cmd)
            sip.transferback(self.brick_widget.layout())
        if pValue == "Landscape":
            self.brick_widget.setLayout(Qt.QHBoxLayout())
        else:
            self.brick_widget.setLayout(Qt.QVBoxLayout())
        self.brick_widget.layout().addWidget(self.shutter_state)
        self.brick_widget.layout().addWidget(self.shutter_cmd)

    def shutter_state_changed(self, state):
        self.state = state
        if state in ("opened", "automatic"):
            self.shutter_cmd.setText("Close")
            self.shutter_cmd.setEnabled(True)
            if self.shutterName is None:
                self.shutter_cmd.setToolTip("Close shutter")
            else:
                self.shutter_cmd.setToolTip("Close '%s' shutter" %
                                            self.shutterName)
        elif state == "unknown":
            self.shutter_cmd.setText("Unknown")
            self.shutter_cmd.setEnabled(True)
            if self.shutterName is None:
                self.shutter_cmd.setToolTip("Unknown shutter state")
            else:
                self.shutter_cmd.setToolTip("Unknown '%s' shutter state" %
                                            self.shutterName)
        else:
            self.shutter_cmd.setText("Open")
            self.shutter_cmd.setEnabled(True)
            if self.shutterName is None:
                self.shutter_cmd.setToolTip("Open shutter")
            else:
                self.shutter_cmd.setToolTip("Open '%s' shutter" %
                                            self.shutterName)
        palette = self.shutter_state.palette()
        palette.setColor(QtGui.QPalette.Background, self.shutterState[state])
        self.shutter_state.setPalette(palette)

        if self.shutterName is not None:
            state = '%s: %s' % (self.shutterName, state)

        self.shutter_state.setText(state)

    def connectionStatusChanged(self, pPeer):
        self.brick_widget.setEnabled(pPeer is not None)
        if pPeer is not None:
            pPeer.connect("ready", self.enable)

    def enable(self, arg):
        self.brick_widget.setEnabled(arg)

    def shutter_cmd_clicked(self):
        if self.shutter_cmd.text() == "Open":
            if self.shutterName is None:
                logger.info("Opening shutter...")
            else:
                logger.info("Opening '%s' shutter..." % self.shutterName)
            self.getObject('shutter').open()
        else:
            if self.shutterName is None:
                logger.info("Closing shutter...")
            else:
                logger.info("Closing '%s' shutter..." % self.shutterName)
            self.getObject('shutter').close()
예제 #7
0
class CommandBrick(Core.BaseBrick):
    # =============================================
    #  PROPERTIES/CONNECTIONS DEFINITION
    # =============================================
    properties = {
        "caption":
        Property("string", "Caption", "", "captionChanged"),
        "parameter":
        Property("string", "Parameter", "", "parameterChanged"),
        "toolTip":
        Property("string", "Tool tip", "", "toolTipChanged"),
        "expertModeOnly":
        Property("boolean", "Expert mode only", "", "expertModeOnlyChanged",
                 False),
        "warningPopup":
        Property("boolean", "WarningPopup", "", "warningChanged", False)
    }

    connections = {
        "command":
        Connection("Command object",
                   [Signal("commandStatusChanged", "commandStatusChanged")],
                   [Slot("executeCommand")], "connectionStatusChanged")
    }

    signals = []
    slots = []

    def __init__(self, *args, **kargs):
        Core.BaseBrick.__init__(self, *args, **kargs)

    def init(self):
        self.__parameter = ""
        self.__toolTip = ""
        self.__expertModeOnly = False
        self.__expertMode = False
        self.__warning = False
        self.__caption = ""

        self.brick_widget.setLayout(Qt.QVBoxLayout())
        self.commandPushButton = Qt.QPushButton(self.brick_widget)
        Qt.QObject.connect(self.commandPushButton, Qt.SIGNAL("clicked()"),
                           self.commandPushButtonClicked)
        self.brick_widget.layout().addWidget(self.commandPushButton)

    def captionChanged(self, pValue):
        self.__caption = pValue
        self.commandPushButton.setText(pValue)

    def parameterChanged(self, pValue):
        self.__parameter = pValue

    def toolTipChanged(self, pValue):
        self.__toolTip = pValue
        self.commandPushButton.setToolTip(self.__toolTip)

    def expertModeOnlyChanged(self, pValue):
        self.__expertModeOnly = pValue
        self.expert_mode(self.__expertMode)

    def warningChanged(self, pValue):
        self.__warning = pValue

    def commandPushButtonClicked(self):
        if self.__warning:
            answer = Qt.QMessageBox.warning(
                self.brick_widget, "Warning",
                "You clicked on " + self.__caption +
                ".\nDo you really want to execute this command ?",
                Qt.QMessageBox.Ok,
                (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default))
            if answer == Qt.QMessageBox.Cancel:
                return
        self.getObject("command").executeCommand(self.__parameter)

    def commandStatusChanged(self, pValue):
        messageList = pValue.split(",", 2)
        if len(messageList) == 2:
            if messageList[0] == "0":  # command info
                logger.info(messageList[1])
            elif messageList[0] == "1":  # command warning
                logger.warning(messageList[1])
            elif messageList[0] == "2":  # command error
                logger.error(messageList[1])

    def expert_mode(self, expert):
        self.__expertMode = expert
        self.commandPushButton.setEnabled(not self.__expertModeOnly
                                          or self.__expertMode)

    def connectionStatusChanged(self, peer):
        self.calibration_object = peer
        if self.calibration_object is None:
            self.brick_widget.setEnabled(False)
        else:
            self.brick_widget.setEnabled(True)