Example #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))
Example #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()
Example #3
0
class ReprocessBrick( Core.BaseBrick ):


    properties = {}
    connections = {"reprocess": Connection( "Reprocess object",
                                             [Signal( "reprocessDirectoryChanged", "reprocessDirectoryChanged" ),
                                              Signal( "reprocessPrefixChanged", "reprocessPrefixChanged" ),
                                              Signal( "reprocessRunNumberChanged", "reprocessRunNumberChanged" ),
                                              Signal( "reprocessFrameFirstChanged", "reprocessFrameFirstChanged" ),
                                              Signal( "reprocessFrameLastChanged", "reprocessFrameLastChanged" ),
                                              Signal( "reprocessConcentrationChanged", "reprocessConcentrationChanged" ),
                                              Signal( "reprocessCommentsChanged", "reprocessCommentsChanged" ),
                                              Signal( "reprocessCodeChanged", "reprocessCodeChanged" ),
                                              Signal( "reprocessMaskFileChanged", "reprocessMaskFileChanged" ),
                                              Signal( "reprocessDetectorDistanceChanged", "reprocessDetectorDistanceChanged" ),
                                              Signal( "reprocessWaveLengthChanged", "reprocessWaveLengthChanged" ),
                                              Signal( "reprocessPixelSizeXChanged", "reprocessPixelSizeXChanged" ),
                                              Signal( "reprocessPixelSizeYChanged", "reprocessPixelSizeYChanged" ),
                                              Signal( "reprocessBeamCenterXChanged", "reprocessBeamCenterXChanged" ),
                                              Signal( "reprocessBeamCenterYChanged", "reprocessBeamCenterYChanged" ),
                                              Signal( "reprocessNormalisationChanged", "reprocessNormalisationChanged" ),
                                              Signal( "reprocessBeamStopDiodeChanged", "reprocessBeamStopDiodeChanged" ),
                                              Signal( "reprocessMachineCurrentChanged", "reprocessMachineCurrentChanged" ),
                                              Signal( "reprocessKeepOriginalChanged", "reprocessKeepOriginalChanged" ),
                                              Signal( "reprocessStatusChanged", "reprocessStatusChanged" )],
                                            [Slot( "reprocess" )],
                                            "connectionStatusChanged" )}



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

    def reprocessDirectoryChanged( self, pValue ):
        self.directoryLineEdit.setText( pValue )


    def reprocessPrefixChanged( self, pValue ):
        for i in range( 0, self.prefixComboBox.count() ):
            if pValue == self.prefixComboBox.itemText( i ):
                self.prefixComboBox.setCurrentIndex( i )
                break
        self.populateRunNumberListWidget()
        self.populateFrameComboBox()
        self.__validParameters[1] = self.prefixComboBox.currentIndex() > 0


    def reprocessRunNumberChanged( self, pValue ):
        pass


    def reprocessFrameFirstChanged( self, pValue ):
        pass


    def reprocessFrameLastChanged( self, pValue ):
        pass


    def reprocessConcentrationChanged( self, pValue ):
        if pValue != "":
            self.concentrationDoubleSpinBox.setValue( float( pValue ) )


    def reprocessCommentsChanged( self, pValue ):
        self.commentsLineEdit.setText( pValue )


    def reprocessCodeChanged( self, pValue ):
        self.codeLineEdit.setText( pValue )


    def reprocessMaskFileChanged( self, pValue ):
        self.maskLineEdit.setText( pValue )


    def reprocessDetectorDistanceChanged( self, pValue ):
        if pValue != "":
            self.detectorDistanceDoubleSpinBox.setValue( float( pValue ) )


    def reprocessWaveLengthChanged( self, pValue ):
        if pValue != "":
            self.waveLengthDoubleSpinBox.setValue( float( pValue ) )


    def reprocessPixelSizeXChanged( self, pValue ):
        if pValue != "":
            self.pixelSizeXDoubleSpinBox.setValue( float( pValue ) )


    def reprocessPixelSizeYChanged( self, pValue ):
        if pValue != "":
            self.pixelSizeYDoubleSpinBox.setValue( float( pValue ) )


    def reprocessBeamCenterXChanged( self, pValue ):
            self.beamCenterXSpinBox.setValue( int( pValue ) )


    def reprocessBeamCenterYChanged( self, pValue ):
        if pValue != "":
            self.beamCenterYSpinBox.setValue( int( pValue ) )


    def reprocessNormalisationChanged( self, pValue ):
        if pValue != "":
            self.normalisationDoubleSpinBox.setValue( float( pValue ) )


    def reprocessBeamStopDiodeChanged( self, pValue ):
        if pValue != "":
            self.beamStopDiodeDoubleSpinBox.setValue( float( pValue ) )


    def reprocessMachineCurrentChanged( self, pValue ):
        if pValue != "":
            self.machineCurrentDoubleSpinBox.setValue( float( pValue ) )


    def reprocessKeepOriginalChanged( self, pValue ):
        self.keepOriginalCheckBox.setChecked( pValue == "1" )


    def reprocessStatusChanged( self, pValue ):
        #TODO: Understand
        if self.__isReprocessing:
            messageList = pValue.split( ",", 3 )
            if messageList[0] == "0":   # reprocess done
                self.SPECBusyTimer.stop()
                self.__isReprocessing = False
                self.setButtonState( 0 )
                logger.info( messageList[1] )
                if self.notifyCheckBox.isChecked():
                    Qt.QMessageBox.information( self.brick_widget, "Info", "\n                       %s                                       \n" % messageList[1] )
            elif messageList[0] == "1":     # reprocess info 
                self.SPECBusyTimer.start( 25000 )
                logger.info( messageList[1] )
            elif messageList[0] == "2":     # reprocess info with item to be displayed
                self.SPECBusyTimer.start( 25000 )
                logger.info( messageList[1] )
                self.emit( "displayItemChanged", messageList[2] )
            elif messageList[0] == "3":     # reprocess warning
                logger.warning( messageList[1] )
            elif messageList[0] == "4":     # reprocess error
                self.SPECBusyTimer.stop()
                self.__isReprocessing = False
                self.setButtonState( 0 )
                logger.error( messageList[1] )


    def connectionStatusChanged( self, pPeer ):
        pass


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


    def init( self ):
        self.__expertMode = False
        self.__isReprocessing = False
        self.__validParameters = [False, False, False, False, False]

        self.brick_widget.setLayout( Qt.QVBoxLayout() )

        self.hBoxLayout2 = Qt.QHBoxLayout()
        self.directoryLabel = Qt.QLabel( "Directory", self.brick_widget )
        self.directoryLabel.setFixedWidth( 130 )
        self.hBoxLayout2.addWidget( self.directoryLabel )
        self.directoryLineEdit = Qt.QLineEdit( self.brick_widget )
        self.directoryLineEdit.setMaxLength( 100 )
        Qt.QObject.connect( self.directoryLineEdit, Qt.SIGNAL( "textChanged(const QString &)" ), self.directoryLineEditChanged )
        self.hBoxLayout2.addWidget( self.directoryLineEdit )
        self.directoryPushButton = Qt.QPushButton( "...", self.brick_widget )
        self.directoryPushButton.setFixedWidth( 25 )
        Qt.QObject.connect( self.directoryPushButton, Qt.SIGNAL( "clicked()" ), self.directoryPushButtonClicked )
        self.hBoxLayout2.addWidget( self.directoryPushButton )
        self.brick_widget.layout().addLayout( self.hBoxLayout2 )

        self.hBoxLayout3 = Qt.QHBoxLayout()
        self.directoryLabel = Qt.QLabel( "Prefix", self.brick_widget )
        self.directoryLabel.setFixedWidth( 130 )
        self.hBoxLayout3.addWidget( self.directoryLabel )
        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.runNumberListWidget = Qt.QListWidget( self.brick_widget )
        self.runNumberListWidget.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection )
        Qt.QObject.connect( self.runNumberListWidget, Qt.SIGNAL( "itemSelectionChanged()" ), self.runNumberListWidgetChanged )
        self.hBoxLayout4.addWidget( self.runNumberListWidget )
        self.brick_widget.layout().addLayout( self.hBoxLayout4 )

        self.hBoxLayout5 = Qt.QHBoxLayout()
        self.frameLabel = Qt.QLabel( "Frame (first, last)", self.brick_widget )
        self.frameLabel.setFixedWidth( 130 )
        self.hBoxLayout5.addWidget( self.frameLabel )
        self.frameFirstComboBox = Qt.QComboBox( self.brick_widget )
        Qt.QObject.connect( self.frameFirstComboBox, Qt.SIGNAL( "currentIndexChanged(int)" ), self.frameFirstComboBoxChanged )
        self.hBoxLayout5.addWidget( self.frameFirstComboBox )
        self.frameLastComboBox = Qt.QComboBox( self.brick_widget )
        Qt.QObject.connect( self.frameLastComboBox, Qt.SIGNAL( "currentIndexChanged(int)" ), self.frameLastComboBoxChanged )
        self.hBoxLayout5.addWidget( self.frameLastComboBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout5 )

        self.hBoxLayout6 = Qt.QHBoxLayout()
        self.concentrationCheckBox = Qt.QCheckBox( "Concentration", self.brick_widget )
        self.concentrationCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.concentrationCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.concentrationCheckBoxToggled )
        self.hBoxLayout6.addWidget( self.concentrationCheckBox )
        self.concentrationDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.concentrationDoubleSpinBox.setSuffix( " mg/ml" )
        self.concentrationDoubleSpinBox.setDecimals( 2 )
        self.concentrationDoubleSpinBox.setRange( 0, 100 )
        self.hBoxLayout6.addWidget( self.concentrationDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout6 )

        self.hBoxLayout7 = Qt.QHBoxLayout()
        self.commentsCheckBox = Qt.QCheckBox( "Comments", self.brick_widget )
        self.commentsCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.commentsCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.commentsCheckBoxToggled )
        self.hBoxLayout7.addWidget( self.commentsCheckBox )
        self.commentsLineEdit = Qt.QLineEdit( self.brick_widget )
        self.commentsLineEdit.setMaxLength( 100 )
        self.commentsLineEdit.setValidator( Qt.QRegExpValidator( Qt.QRegExp( "[a-zA-Z0-9\\%/()=+*^:.\-_ ]*" ), self.commentsLineEdit ) )
        self.hBoxLayout7.addWidget( self.commentsLineEdit )
        self.brick_widget.layout().addLayout( self.hBoxLayout7 )

        self.hBoxLayout8 = Qt.QHBoxLayout()
        self.codeCheckBox = Qt.QCheckBox( "Code", self.brick_widget )
        self.codeCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.codeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.codeCheckBoxToggled )
        self.hBoxLayout8.addWidget( self.codeCheckBox )
        self.codeLineEdit = Qt.QLineEdit( self.brick_widget )
        self.codeLineEdit.setMaxLength( 30 )
        self.codeLineEdit.setValidator( Qt.QRegExpValidator( Qt.QRegExp( "^[a-zA-Z][a-zA-Z0-9_]*" ), self.codeLineEdit ) )
        self.hBoxLayout8.addWidget( self.codeLineEdit )
        self.brick_widget.layout().addLayout( self.hBoxLayout8 )

        self.hBoxLayout9 = Qt.QHBoxLayout()
        self.maskCheckBox = Qt.QCheckBox( "Mask", self.brick_widget )
        self.maskCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.maskCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.maskCheckBoxToggled )
        self.hBoxLayout9.addWidget( self.maskCheckBox )
        self.maskLineEdit = Qt.QLineEdit( self.brick_widget )
        self.maskLineEdit.setMaxLength( 100 )
        Qt.QObject.connect( self.maskLineEdit, Qt.SIGNAL( "textChanged(const QString &)" ), self.maskLineEditChanged )
        self.hBoxLayout9.addWidget( self.maskLineEdit )
        self.maskDirectoryPushButton = Qt.QPushButton( "...", self.brick_widget )
        self.maskDirectoryPushButton.setFixedWidth( 25 )
        Qt.QObject.connect( self.maskDirectoryPushButton, Qt.SIGNAL( "clicked()" ), self.maskDirectoryPushButtonClicked )
        self.hBoxLayout9.addWidget( self.maskDirectoryPushButton )
        self.maskDisplayPushButton = Qt.QPushButton( "Display", self.brick_widget )
        self.maskDisplayPushButton.setFixedWidth( 55 )
        Qt.QObject.connect( self.maskDisplayPushButton, Qt.SIGNAL( "clicked()" ), self.maskDisplayPushButtonClicked )
        self.hBoxLayout9.addWidget( self.maskDisplayPushButton )
        self.brick_widget.layout().addLayout( self.hBoxLayout9 )

        self.hBoxLayout10 = Qt.QHBoxLayout()
        self.detectorDistanceCheckBox = Qt.QCheckBox( "Detector distance", self.brick_widget )
        self.detectorDistanceCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.detectorDistanceCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.detectorDistanceCheckBoxToggled )
        self.hBoxLayout10.addWidget( self.detectorDistanceCheckBox )
        self.detectorDistanceDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.detectorDistanceDoubleSpinBox.setSuffix( " m" )
        self.detectorDistanceDoubleSpinBox.setDecimals( 3 )
        self.detectorDistanceDoubleSpinBox.setRange( 0.1, 10 )
        self.hBoxLayout10.addWidget( self.detectorDistanceDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout10 )

        self.hBoxLayout11 = Qt.QHBoxLayout()
        self.waveLengthCheckBox = Qt.QCheckBox( "Wave length", self.brick_widget )
        self.waveLengthCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.waveLengthCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.waveLengthCheckBoxToggled )
        self.hBoxLayout11.addWidget( self.waveLengthCheckBox )
        self.waveLengthDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.waveLengthDoubleSpinBox.setSuffix( " nm" )
        self.waveLengthDoubleSpinBox.setDecimals( 4 )
        self.waveLengthDoubleSpinBox.setRange( 0.01, 1 )
        self.hBoxLayout11.addWidget( self.waveLengthDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout11 )

        self.hBoxLayout12 = Qt.QHBoxLayout()
        self.pixelSizeCheckBox = Qt.QCheckBox( "Pixel size (x, y)", self.brick_widget )
        self.pixelSizeCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.pixelSizeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.pixelSizeCheckBoxToggled )
        self.hBoxLayout12.addWidget( self.pixelSizeCheckBox )
        self.pixelSizeXDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.pixelSizeXDoubleSpinBox.setSuffix( " um" )
        self.pixelSizeXDoubleSpinBox.setDecimals( 1 )
        self.pixelSizeXDoubleSpinBox.setRange( 10, 500 )
        self.hBoxLayout12.addWidget( self.pixelSizeXDoubleSpinBox )
        self.pixelSizeYDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.pixelSizeYDoubleSpinBox.setSuffix( " um" )
        self.pixelSizeYDoubleSpinBox.setDecimals( 1 )
        self.pixelSizeYDoubleSpinBox.setRange( 10, 500 )
        self.hBoxLayout12.addWidget( self.pixelSizeYDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout12 )

        self.hBoxLayout13 = Qt.QHBoxLayout()
        self.beamCenterCheckBox = Qt.QCheckBox( "Beam center (x, y)", self.brick_widget )
        self.beamCenterCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.beamCenterCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.beamCenterCheckBoxToggled )
        self.hBoxLayout13.addWidget( self.beamCenterCheckBox )
        self.beamCenterXSpinBox = Qt.QSpinBox( self.brick_widget )
        self.beamCenterXSpinBox.setSuffix( " px" )
        self.beamCenterXSpinBox.setRange( 1, 9999 )
        self.hBoxLayout13.addWidget( self.beamCenterXSpinBox )
        self.beamCenterYSpinBox = Qt.QSpinBox( self.brick_widget )
        self.beamCenterYSpinBox.setSuffix( " px" )
        self.beamCenterYSpinBox.setRange( 1, 9999 )
        self.hBoxLayout13.addWidget( self.beamCenterYSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout13 )

        self.hBoxLayout14 = Qt.QHBoxLayout()
        self.normalisationCheckBox = Qt.QCheckBox( "Normalisation", self.brick_widget )
        self.normalisationCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.normalisationCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.normalisationCheckBoxToggled )
        self.hBoxLayout14.addWidget( self.normalisationCheckBox )
        self.normalisationDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.normalisationDoubleSpinBox.setDecimals( 7 )
        self.normalisationDoubleSpinBox.setRange( 0.0001, 10000 )
        self.hBoxLayout14.addWidget( self.normalisationDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout14 )

        self.hBoxLayout15 = Qt.QHBoxLayout()
        self.beamStopDiodeCheckBox = Qt.QCheckBox( "Beam stop diode", self.brick_widget )
        self.beamStopDiodeCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.beamStopDiodeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.beamStopDiodeCheckBoxToggled )
        self.hBoxLayout15.addWidget( self.beamStopDiodeCheckBox )
        self.beamStopDiodeDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.beamStopDiodeDoubleSpinBox.setDecimals( 12 )
        self.beamStopDiodeDoubleSpinBox.setRange( -1, 1 )
        self.hBoxLayout15.addWidget( self.beamStopDiodeDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout15 )

        self.hBoxLayout16 = Qt.QHBoxLayout()
        self.machineCurrentCheckBox = Qt.QCheckBox( "Machine current", self.brick_widget )
        self.machineCurrentCheckBox.setFixedWidth( 130 )
        Qt.QObject.connect( self.machineCurrentCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.machineCurrentCheckBoxToggled )
        self.hBoxLayout16.addWidget( self.machineCurrentCheckBox )
        self.machineCurrentDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget )
        self.machineCurrentDoubleSpinBox.setDecimals( 2 )
        self.machineCurrentDoubleSpinBox.setRange( 0, 350 )
        self.hBoxLayout16.addWidget( self.machineCurrentDoubleSpinBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout16 )

        self.hBoxLayout17 = Qt.QHBoxLayout()
        self.keepOriginalCheckBox = Qt.QCheckBox( "Keep original files", self.brick_widget )
        self.keepOriginalCheckBox.setChecked( True )
        self.hBoxLayout17.addWidget( self.keepOriginalCheckBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout17 )

        self.hBoxLayout18 = Qt.QHBoxLayout()
        self.notifyCheckBox = Qt.QCheckBox( "Notify when done", self.brick_widget )
        self.notifyCheckBox.setChecked( True )
        self.hBoxLayout18.addWidget( self.notifyCheckBox )
        self.brick_widget.layout().addLayout( self.hBoxLayout18 )

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

        self.hBoxLayout18 = Qt.QHBoxLayout()
        self.reprocessPushButton = Qt.QPushButton( "Reprocess", self.brick_widget )
        self.reprocessPushButton.setToolTip( "Start reprocess with the specified parameters" )
        self.hBoxLayout18.addWidget( self.reprocessPushButton )
        Qt.QObject.connect( self.reprocessPushButton, Qt.SIGNAL( "clicked()" ), self.reprocessPushButtonClicked )
        self.brick_widget.layout().addLayout( self.hBoxLayout18 )

        self.hBoxLayout19 = Qt.QHBoxLayout()
        self.abortPushButton = Qt.QPushButton( "Abort", self.brick_widget )
        self.abortPushButton.setToolTip( "Abort ongoing data reprocessing" )
        self.hBoxLayout19.addWidget( self.abortPushButton )
        Qt.QObject.connect( self.abortPushButton, Qt.SIGNAL( "clicked()" ), self.abortPushButtonClicked )
        self.brick_widget.layout().addLayout( self.hBoxLayout19 )

        self.directoryLineEditChanged( None )
        self.concentrationCheckBoxToggled( False )
        self.commentsCheckBoxToggled( False )
        self.codeCheckBoxToggled( False )
        self.maskCheckBoxToggled( False )
        self.detectorDistanceCheckBoxToggled( False )
        self.waveLengthCheckBoxToggled( False )
        self.pixelSizeCheckBoxToggled( False )
        self.beamCenterCheckBoxToggled( False )
        self.normalisationCheckBoxToggled( False )
        self.beamStopDiodeCheckBoxToggled( False )
        self.machineCurrentCheckBoxToggled( False )

        self.SPECBusyTimer = Qt.QTimer( self.brick_widget )
        Qt.QObject.connect( self.SPECBusyTimer, Qt.SIGNAL( "timeout()" ), self.SPECBusyTimerTimeOut )

        self.setButtonState( 0 )



    def delete( self ):
        pass



#TODO: replace
#    def detectorComboBoxChanged(self, pValue):
#        if not self.__isReprocessing:
#            self.populatePrefixComboBox()
#            self.populateRunNumberListWidget()
#            self.populateFrameComboBox()



#TODO: replace
#    def operationComboBoxChanged(self, pValue):
#        if not self.__isReprocessing:
#            self.concentrationCheckBox.setEnabled(pValue in (1, 3))
#            self.concentrationDoubleSpinBox.setEnabled(pValue in (1, 3) and self.concentrationCheckBox.isChecked())
#            self.commentsCheckBox.setEnabled(pValue in (1, 3))
#            self.commentsLineEdit.setEnabled(pValue in (1, 3) and self.commentsCheckBox.isChecked())
#            self.codeCheckBox.setEnabled(pValue in (1, 3))
#            self.codeLineEdit.setEnabled(pValue in (1, 3) and self.codeCheckBox.isChecked())
#            self.maskCheckBox.setEnabled(pValue in (1, 3))
#            self.maskLineEdit.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked())
#            self.maskDirectoryPushButton.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked())
#            self.maskDisplayPushButton.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked())
#            self.detectorDistanceCheckBox.setEnabled(pValue in (1, 3))
#            self.detectorDistanceDoubleSpinBox.setEnabled(pValue in (1, 3) and self.detectorDistanceCheckBox.isChecked())
#            self.waveLengthCheckBox.setEnabled(pValue in (1, 3))
#            self.waveLengthDoubleSpinBox.setEnabled(pValue in (1, 3) and self.waveLengthCheckBox.isChecked())
#            self.pixelSizeCheckBox.setEnabled(pValue in (1, 3))
#            self.pixelSizeXDoubleSpinBox.setEnabled(pValue in (1, 3) and self.pixelSizeCheckBox.isChecked())
#            self.pixelSizeYDoubleSpinBox.setEnabled(pValue in (1, 3) and self.pixelSizeCheckBox.isChecked())
#            self.beamCenterCheckBox.setEnabled(pValue in (1, 3))
#            self.beamCenterXSpinBox.setEnabled(pValue in (1, 3) and self.beamCenterCheckBox.isChecked())
#            self.beamCenterYSpinBox.setEnabled(pValue in (1, 3) and self.beamCenterCheckBox.isChecked())
#            self.normalisationCheckBox.setEnabled(pValue in (0, 3))
#            self.normalisationDoubleSpinBox.setEnabled(pValue in (0, 3) and self.normalisationCheckBox.isChecked())
#            self.beamStopDiodeCheckBox.setEnabled(pValue in (0, 3))
#            self.beamStopDiodeDoubleSpinBox.setEnabled(pValue in (0, 3) and self.beamStopDiodeCheckBox.isChecked())
#            self.machineCurrentCheckBox.setEnabled(pValue in (1, 3))
#            self.machineCurrentDoubleSpinBox.setEnabled(pValue in (1, 3) and self.machineCurrentCheckBox.isChecked())



    def directoryLineEditChanged( self, pValue ):
        if not self.__isReprocessing:
            self.__validParameters[0] = pValue is not None and os.path.exists( pValue ) and not os.path.isfile( pValue )
            if self.__validParameters[0]:
                if str( pValue ).find( " " ) == -1:
                    self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) )
                else:
                    self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) )
            else:
                self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) )
            self.populatePrefixComboBox()
            self.populateRunNumberListWidget()
            self.populateFrameComboBox()
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def directoryPushButtonClicked( self ):
        directory = QtGui.QFileDialog.getExistingDirectory( self.brick_widget, "Choose a directory", self.directoryLineEdit.text() )
        if directory != "":
            self.directoryLineEdit.setText( directory )


    def prefixComboBoxChanged( self, pValue ):
        if not self.__isReprocessing:
            self.__validParameters[1] = pValue > 0
            self.populateRunNumberListWidget()
            self.populateFrameComboBox()
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def runNumberListWidgetChanged( self ):
        if not self.__isReprocessing:
            selectedItemsCount = len( self.runNumberListWidget.selectedItems() )
            self.populateFrameComboBox()
            self.__validParameters[2] = ( selectedItemsCount > 0 )
            self.__validParameters[3] = ( selectedItemsCount > 1 )
            self.frameFirstComboBox.setEnabled( selectedItemsCount < 2 )
            self.frameLastComboBox.setEnabled( selectedItemsCount < 2 )
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def frameFirstComboBoxChanged( self, pValue ):
        if not self.__isReprocessing:
            self.__validParameters[3] = ( pValue > 0 and self.frameLastComboBox.currentIndex() > 0 and int( self.frameFirstComboBox.currentText() ) <= int( self.frameLastComboBox.currentText() ) )
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def frameLastComboBoxChanged( self, pValue ):
        if not self.__isReprocessing:
            self.__validParameters[3] = ( self.frameFirstComboBox.currentIndex() > 0 and pValue > 0 and int( self.frameFirstComboBox.currentText() ) <= int( self.frameLastComboBox.currentText() ) )
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def concentrationCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.concentrationDoubleSpinBox.setEnabled( pValue )


    def commentsCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.commentsLineEdit.setEnabled( pValue )


    def codeCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.codeLineEdit.setEnabled( pValue )


    def maskCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.maskLineEdit.setEnabled( pValue )
            self.maskDirectoryPushButton.setEnabled( pValue )
            self.maskDisplayPushButton.setEnabled( pValue )


    def detectorDistanceCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.detectorDistanceDoubleSpinBox.setEnabled( pValue )


    def waveLengthCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.waveLengthDoubleSpinBox.setEnabled( pValue )


    def pixelSizeCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.pixelSizeXDoubleSpinBox.setEnabled( pValue )
            self.pixelSizeYDoubleSpinBox.setEnabled( pValue )


    def beamCenterCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.beamCenterXSpinBox.setEnabled( pValue )
            self.beamCenterYSpinBox.setEnabled( pValue )


    def normalisationCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.normalisationDoubleSpinBox.setEnabled( pValue )


    def beamStopDiodeCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.beamStopDiodeDoubleSpinBox.setEnabled( pValue )


    def machineCurrentCheckBoxToggled( self, pValue ):
        if not self.__isReprocessing:
            self.machineCurrentDoubleSpinBox.setEnabled( pValue )



    def maskLineEditChanged( self, pValue ):
        if not self.__isReprocessing:
            if pValue is not None:
                pValue = str( pValue )
                if os.path.isfile( pValue ):
                    i = pValue.rfind( "." )
                    if i != -1 and pValue[i - 4:i] == "_msk" and pValue[i + 1:] == "edf" and pValue.find( " " ) == -1:
                        flag = 0
                    else:
                        flag = 1
                else:
                    flag = 2
            else:
                flag = 2
            if flag == 0:
                self.__validParameters[4] = True
                self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) )
            elif flag == 1:
                self.__validParameters[4] = True
                self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) )
            else:
                self.__validParameters[4] = False
                self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) )
            self.maskDisplayPushButton.setEnabled( self.__validParameters[4] and self.maskCheckBox.isChecked() )
            self.reprocessPushButton.setEnabled( False not in self.__validParameters )



    def maskDirectoryPushButtonClicked( self ):
        qFileDialog = QtGui.QFileDialog( self.brick_widget, "Choose a mask file", self.maskLineEdit.text() )
        qFileDialog.setAcceptMode( QtGui.QFileDialog.AcceptOpen )
        qFileDialog.setFilters( ["ESRF Data Format (*.edf)"] )
        if qFileDialog.exec_():
            self.maskLineEdit.setText( str( qFileDialog.selectedFiles()[0] ) )



    def maskDisplayPushButtonClicked( self ):
        self.emit( "displayItemChanged", str( self.maskLineEdit.text() ) )



    def reprocessPushButtonClicked( self ):
        if Qt.QMessageBox.question( self.brick_widget, "Warning", "Are you sure that you want to reprocess data collection '" + str( self.prefixComboBox.currentText() ) + "'?", Qt.QMessageBox.Yes, Qt.QMessageBox.No, Qt.QMessageBox.NoButton ) == Qt.QMessageBox.Yes:
            self.setButtonState( 1 )
            self.SPECBusyTimer.start( 20000 )
            logger.info( "Start reprocessing..." )
            self.emit( "displayResetChanged" )
            self.__isReprocessing = True

            runNumber = ""
            for item in self.runNumberListWidget.selectedItems():
                if runNumber == "":
                    runNumber = str( item.text() )
                else:
                    runNumber += "," + str( item.text() )

            if len( self.runNumberListWidget.selectedItems() ) == 1:
                frameFirst = str( self.frameFirstComboBox.currentText() )
                frameLast = str( self.frameLastComboBox.currentText() )
            else:
                frameFirst = None
                frameLast = None

            if self.concentrationCheckBox.isEnabled() and self.concentrationCheckBox.isChecked():
                concentration = self.concentrationDoubleSpinBox.value()
            else:
                concentration = None

            if self.commentsCheckBox.isEnabled() and self.commentsCheckBox.isChecked():
                comments = self.commentsLineEdit.text()
            else:
                comments = None

            if self.codeCheckBox.isEnabled() and self.codeCheckBox.isChecked():
                code = self.codeLineEdit.text()
            else:
                code = None

            if self.maskCheckBox.isEnabled() and self.maskCheckBox.isChecked():
                mask = self.maskLineEdit.text()
            else:
                mask = None

            if self.detectorDistanceCheckBox.isEnabled() and self.detectorDistanceCheckBox.isChecked():
                detectorDistance = self.detectorDistanceDoubleSpinBox.value()
            else:
                detectorDistance = None

            if self.waveLengthCheckBox.isEnabled() and self.waveLengthCheckBox.isChecked():
                waveLength = self.waveLengthDoubleSpinBox.value()
            else:
                waveLength = None

            if self.pixelSizeCheckBox.isEnabled() and self.pixelSizeCheckBox.isChecked():
                pixelSizeX = self.pixelSizeXDoubleSpinBox.value()
                pixelSizeY = self.pixelSizeYDoubleSpinBox.value()
            else:
                pixelSizeX = None
                pixelSizeY = None

            if self.beamCenterCheckBox.isEnabled() and self.beamCenterCheckBox.isChecked():
                beamCenterX = self.beamCenterXSpinBox.value()
                beamCenterY = self.beamCenterYSpinBox.value()
            else:
                beamCenterX = None
                beamCenterY = None

            if self.normalisationCheckBox.isEnabled() and self.normalisationCheckBox.isChecked():
                normalisation = self.normalisationDoubleSpinBox.value()
            else:
                normalisation = None

            if self.beamStopDiodeCheckBox.isEnabled() and self.beamStopDiodeCheckBox.isChecked():
                beamStopDiode = self.beamStopDiodeDoubleSpinBox.value()
            else:
                beamStopDiode = None

            if self.machineCurrentCheckBox.isEnabled() and self.machineCurrentCheckBox.isChecked():
                machineCurrent = self.machineCurrentDoubleSpinBox.value()
            else:
                machineCurrent = None

            if self.keepOriginalCheckBox.isChecked():
                keepOriginal = "1"
            else:
                keepOriginal = "0"

            self.getObject( "reprocess" ).reprocess( self.directoryLineEdit.text(),
                                                  self.prefixComboBox.currentText(),
                                                  runNumber,
                                                  frameFirst,
                                                  frameLast,
                                                  concentration,
                                                  comments,
                                                  code,
                                                  mask,
                                                  detectorDistance,
                                                  waveLength,
                                                  pixelSizeX,
                                                  pixelSizeY,
                                                  beamCenterX,
                                                  beamCenterY,
                                                  normalisation,
                                                  beamStopDiode,
                                                  machineCurrent,
                                                  keepOriginal,
                                                  "20",
                                                  "1" )



    def abortPushButtonClicked( self ):
        self.SPECBusyTimer.stop()
        self.__isReprocessing = False
        self.setButtonState( 0 )
        logger.info( "Aborting data reprocess!" )
        self.getObject( "reprocess" ).reprocessAbort()



    def setButtonState( self, pOption ):
        if pOption == 0:     # normal
            self.keepOriginalCheckBox.setEnabled( True )
            self.notifyCheckBox.setEnabled( True )
            self.reprocessPushButton.setEnabled( True )
            self.abortPushButton.setEnabled( False )
        elif pOption == 1:   # reprocessing
            self.keepOriginalCheckBox.setEnabled( False )
            self.notifyCheckBox.setEnabled( False )
            self.reprocessPushButton.setEnabled( False )
            self.abortPushButton.setEnabled( True )
        elif pOption == 2:   # invalid parameters
            self.keepOriginalCheckBox.setEnabled( True )
            self.notifyCheckBox.setEnabled( True )
            self.reprocessPushButton.setEnabled( False )
            self.abortPushButton.setEnabled( False )
        if self.abortPushButton.isEnabled():
            self.abortPushButton.palette().setColor( QtGui.QPalette.Button, QtGui.QColor( 255, 0, 0 ) )
        else:
            self.abortPushButton.palette().setColor( QtGui.QPalette.Button, QtGui.QColor( 235, 235, 235 ) )




    def SPECBusyTimerTimeOut( self ):
        self.SPECBusyTimer.stop()
        self.__isReprocessing = False
        self.setButtonState( 0 )
        logger.warning( "The frame (or 1D curve) was not reprocessed or didn't appear on time!" )




    def populatePrefixComboBox( self ):
        if os.path.exists( self.directoryLineEdit.text() + "/raw/" ):
            directory = self.directoryLineEdit.text() + "/raw/"
        else:
            directory = self.directoryLineEdit.text() + "/"
        items = []
        if os.path.isdir( directory ):
            try:
                for filename in os.listdir( directory ):
                    #TODO: Why is this check needed ? SO 14/3 12 
                    if os.path.isfile( directory + filename ):
                        prefix, run, frame, extra, extension = self.getFilenameDetails( filename )
                        if frame != "":
                            if self.detectorComboBox.currentIndex() == 0 and extension == "edf" or self.detectorComboBox.currentIndex() == 1 and extension == "gfrm":
                                try:
                                    items.index( prefix )
                                except ValueError:
                                    items.append( prefix )
            except Exception, e:
                logger.error( "Full Exception: " + str( e ) )
        items.sort()
        items.insert( 0, "Select" )
        currentText = self.prefixComboBox.currentText()
        self.prefixComboBox.clear()
        self.prefixComboBox.addItems( items )
        try:
            self.prefixComboBox.setCurrentIndex( items.index( currentText ) )
        except ValueError:
            self.prefixComboBox.setCurrentIndex( 0 )
Example #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:
Example #5
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()
Example #6
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)
Example #7
0
class VacPumpBrick(Core.BaseBrick):

    properties = {}

    connections = {
        "pumping":
        Connection("Pumping object", [], [
            Slot("exftclose"),
            Slot("exscclose"),
            Slot("vacftclose"),
            Slot("vacscclose"),
            Slot("vacftopen"),
            Slot("vacscopen"),
            Slot("rv5open"),
            Slot("rv6open"),
            Slot("getValveThreshold"),
            Slot("getPumpThreshold"),
            Slot("getUSThreshold"),
            Slot("getFTTimeout"),
            Slot("getSCTimeout"),
            Slot("getFTVacuum"),
            Slot("getSCVacuum"),
            Slot("getUSVacuum")
        ], "connectionToPumping")
    }

    signals = []
    slots = []

    def __init__(self, *args, **kargs):
        Core.BaseBrick.__init__(self, *args, **kargs)
        self.pumpingObject = None
        self.valveThreshold = None
        self.pumpThreshold = None
        self.usThreshold = None
        self.ftTimeout = None
        self.scTimeout = None
        self.ftvacuum = 0.0
        self.scvacuum = 0.0
        self.usvacuum = 0.0

    def init(self):

        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)
        # Only in expert mode
        self.commandPushButton.setEnabled(False)
        self.commandPushButton.setToolTip(
            "Make Vacuum in Flight Tube and/or Sample Changer safely")
        self.commandPushButton.setText("Smart Vacuum")

    def getTimeToRefresh(self):
        return 0.1

    def waitForFtVacuum(self):
        # Now wait for vacuum in FT first
        time_to_wait = self.ftTimeout
        timeToRefresh = self.getTimeToRefresh()
        increaseForCountOneSec = int(1 / timeToRefresh)
        countForPrint = 0
        logger.info(
            "Waiting for flight tube vacuum to be OK. %d seconds left..." %
            time_to_wait)
        while time_to_wait > 0:
            countForPrint = countForPrint + 1
            if countForPrint == increaseForCountOneSec * 10:
                logger.info(
                    "Waiting for flight tube vacuum to be OK. %d seconds left..."
                    % time_to_wait)
                countForPrint = 0
            QtGui.qApp.processEvents()
            time.sleep(min(timeToRefresh, time_to_wait))
            self.ftvacuum = float(self.pumpingObject.getFTVacuum())
            if (self.ftvacuum < self.valveThreshold):
                return True
            time_to_wait = time_to_wait - timeToRefresh
        return False

    def waitForScVacuum(self):
        # Now wait for vacuum in SC first
        time_to_wait = self.scTimeout
        timeToRefresh = self.getTimeToRefresh()
        increaseForCountOneSec = int(1 / timeToRefresh)
        countForPrint = 0
        logger.info(
            "Waiting for sample changer vacuum to be OK. %d seconds left..." %
            time_to_wait)
        while time_to_wait > 0:
            countForPrint = countForPrint + 1
            if countForPrint == increaseForCountOneSec * 10:
                logger.info(
                    "Waiting for sample changer vacuum to be OK. %d seconds left..."
                    % time_to_wait)
                countForPrint = 0
            QtGui.qApp.processEvents()
            time.sleep(min(timeToRefresh, time_to_wait))
            self.scvacuum = float(self.pumpingObject.getSCVacuum())
            if (self.scvacuum < self.valveThreshold):
                return True
            time_to_wait = time_to_wait - timeToRefresh
        return False

    def commandPushButtonClicked(self):

        answer = Qt.QMessageBox.warning(
            self.brick_widget, "Warning",
            "You clicked on Pump Vacuum\nDo you really want to execute this command ?",
            Qt.QMessageBox.Ok,
            (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default))
        if answer == Qt.QMessageBox.Cancel:
            return
        if self.pumpingObject is None:
            logger.error("Is not connected with the CO Server. I stop")
            return
        # Logic starts here
        self.ftvacuum = float(self.pumpingObject.getFTVacuum())
        self.scvacuum = float(self.pumpingObject.getSCVacuum())
        self.usvacuum = float(self.pumpingObject.getUSVacuum())
        if (self.ftvacuum < 0 or self.scvacuum < 0 or self.usvacuum < 0):
            logging.error("Can not read vacuum gauges. I stop")
            return
        if (self.usvacuum > self.usThreshold):
            logger.error(
                "Upstream vacuum below threshold. Please contact expert")
            answer = Qt.QMessageBox.warning(
                self.brick_widget, "Warning",
                "Error in upstream vacuum\nDo you want to continue anyway ?",
                Qt.QMessageBox.Ok,
                (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default))
            if answer == Qt.QMessageBox.Cancel:
                return
        if ((self.scvacuum < self.valveThreshold)
                and (self.ftvacuum < self.valveThreshold)):
            # SC and FT vacuum OK
            #TODO: DEBUG
            print "sc vacuum %r " % self.scvacuum
            print "ft vacuum %r " % self.ftvacuum
            print "valve Threshold %r " % self.valveThreshold
            logger.info("Vacuum already OK in Sample Changer")
            logger.info("Vacuum already OK in Flight Tube")
            self.pumpingObject.rv5open()
            self.pumpingObject.rv6open()
        elif ((self.scvacuum < self.valveThreshold)
              and (self.ftvacuum < self.pumpThreshold)):
            # SC OK and FT good but not air
            logger.info("Vacuum already OK in Sample Changer")
            self.pumpingObject.rv5open()
            self.pumpingObject.exftclose()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            self.pumpingObject.vacftopen()
            # wait for vacuum
            if self.waitForFtVacuum():
                logger.info("Vacuum achieved in Flight Tube")
                self.pumpingObject.rv6open()
                self.pumpingObject.vacftclose()
                Qt.QMessageBox.information(
                    self.brick_widget, "Info",
                    "Please go into the Hutch and stop the pump")
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Flight Tube")
                self.pumpingObject.vacftclose()
        elif ((self.scvacuum < self.valveThreshold)):
            # SC OK and in FT is air - FT vacuum value from Logic - If we came here, FT is air
            logger.info("Vacuum already OK in Sample Changer")
            self.pumpingObject.rv5open()
            self.pumpingObject.exftclose()
            self.pumpingObject.vacftopen()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            # Now wait for vacuum
            if self.waitForFtVacuum():
                logger.info("Vacuum achieved in Flight Tube")
                self.pumpingObject.rv6open()
                self.pumpingObject.vacftclose()
                Qt.QMessageBox.information(
                    self.brick_widget, "Info",
                    "Please go into the Hutch and stop the pump")
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Flight Tube")
                self.pumpingObject.vacftclose()
        elif ((self.ftvacuum < self.valveThreshold)
              and (self.scvacuum < self.pumpThreshold)):
            # FT OK and SC good but not air
            logger.info("Vacuum already OK in Flight Tube")
            self.pumpingObject.exscclose()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            self.pumpingObject.vacscopen()
            # Now wait for vacuum
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                self.pumpingObject.vacscclose()
                self.pumpingObject.rv5open()
                logger.info("Check Flight Tube Vacuum again")
                self.ftvacuum = float(self.pumpingObject.getFTVacuum())
                if (self.ftvacuum >= self.valveThreshold):
                    self.pumpingObject.vacftopen()
                    # Now wait for vacuum
                    if self.waitForFtVacuum():
                        logger.info("Vacuum achieved in Flight Tube")
                        self.pumpingObject.vacftclose()
                        self.pumpingObject.rv6open()
                        Qt.QMessageBox.information(
                            self.brick_widget, "Info",
                            "Please go into the Hutch and stop the pump")
                    else:
                        logger.warning(
                            "Timeout, could not achieve vacuum in Flight Tube")
                        self.pumpingObject.vacftclose()
                else:
                    logger.info("Vacuum still OK in Flight Tube")
                    self.pumpingObject.rv6open()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.vacscclose()
        elif ((self.ftvacuum < self.valveThreshold)):
            # FT OK and in SC is air - SC vacuum value from Logic - If we came here, SC in air
            logger.info("Vacuum already OK in Flight Tube")
            self.pumpingObject.exscclose()
            self.pumpingObject.vacscopen()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            # Now wait for vacuum
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                self.pumpingObject.vacscclose()
                self.pumpingObject.rv5open()
                logger.info("Check Flight Tube Vacuum again")
                self.ftvacuum = float(self.pumpingObject.getFTVacuum())
                if (self.ftvacuum >= self.valveThreshold):
                    self.pumpingObject.vacftopen()
                    # Now wait for vacuum
                    if self.waitForFtVacuum():
                        logger.info("Vacuum achieved in Flight Tube")
                        self.pumpingObject.vacftclose()
                        self.pumpingObject.rv6open()
                        Qt.QMessageBox.information(
                            self.brick_widget, "Info",
                            "Please go into the Hutch and stop the pump")
                    else:
                        logger.warning(
                            "Timeout, could not achieve vacuum in Flight Tube")
                        self.pumpingObject.vacftclose()
                else:
                    logger.info("Vacuum still OK in Flight Tube")
                    self.pumpingObject.rv6open()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.vacscclose()
        elif ((self.ftvacuum < self.pumpThreshold)
              and (self.scvacuum < self.pumpThreshold)):
            #TODO: DEBUG
            print "sc vacuum %r " % self.scvacuum
            print "ft vacuum %r " % self.ftvacuum
            print "pump Threshold %r " % self.pumpThreshold
            # FT and SC both good and not air
            self.pumpingObject.exftclose()
            self.pumpingObject.exscclose()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            self.pumpingObject.vacscopen()
            self.pumpingObject.vacftopen()
            # Now wait for vacuum in SC first
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                # Now deal with FT
                # wait for vacuum
                if self.waitForFtVacuum():
                    logger.info("Vacuum achieved in Flight Tube")
                    self.pumpingObject.rv6open()
                    self.pumpingObject.rv5open()
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
                else:
                    logger.warning(
                        "Timeout, could not achieve vacuum in Flight Tube")
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.vacsclose()
                self.pumpingObject.vacftclose()
                # we do not try to do anything else
        elif ((self.ftvacuum < self.pumpThreshold)):
            # FT good and in SC is air - SC vacuum value from Logic - If we came here, SC in air
            self.pumpingObject.exftclose()
            self.pumpingObject.exscclose()
            self.pumpingObject.vacscopen()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            self.pumpingObject.vacftopen()
            # Now wait for vacuum in SC first
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                # Now deal with FT
                # Now wait for vacuum
                if self.waitForFtVacuum():
                    logger.info("Vacuum achieved in Flight Tube")
                    self.pumpingObject.rv6open()
                    self.pumpingObject.rv5open()
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
                else:
                    logger.warning(
                        "Timeout, could not achieve vacuum in Flight Tube")
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.vacscclose()
                self.pumpingObject.vacftclose()
        elif ((self.scvacuum < self.pumpThreshold)):
            # SC good and in FT is air - FT vacuum value from Logic - If we came here, FT in air
            self.pumpingObject.exftclose()
            self.pumpingObject.exscclose()
            self.pumpingObject.vacftopen()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            self.pumpingObject.vacscopen()
            # Now wait for vacuum in SC first
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                # Now deal with FT
                # Now wait for vacuum
                if self.waitForFtVacuum():
                    logger.info("Vacuum achieved in Flight Tube")
                    self.pumpingObject.rv6open()
                    self.pumpingObject.rv5open()
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
                else:
                    logger.warning(
                        "Timeout, could not achieve vacuum in Flight Tube")
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.exftclose()
                self.pumpingObject.vacftclose()
        else:
            # SC and FT is air - FT and SC vacuum value from Logic - If we came here, FT and SC in air
            self.pumpingObject.exftclose()
            self.pumpingObject.exscclose()
            self.pumpingObject.vacftopen()
            self.pumpingObject.vacscopen()
            Qt.QMessageBox.information(
                self.brick_widget, "Info",
                "Please go into the Hutch and start pump and ONLY when done click OK"
            )
            # Now wait for vacuum in SC first
            if self.waitForScVacuum():
                logger.info("Vacuum achieved in Sample Changer")
                # Now deal with FT
                # Now wait for vacuum
                if self.waitForFtVacuum():
                    logger.info("Vacuum achieved in Flight Tube")
                    self.pumpingObject.rv6open()
                    self.pumpingObject.rv5open()
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
                    Qt.QMessageBox.information(
                        self.brick_widget, "Info",
                        "Please go into the Hutch and stop the pump")
                else:
                    logger.warning(
                        "Timeout, could not achieve vacuum in Flight Tube")
                    self.pumpingObject.vacscclose()
                    self.pumpingObject.vacftclose()
            else:
                logger.warning(
                    "Timeout, could not achieve vacuum in Sample Changer")
                self.pumpingObject.exftclose()
                self.pumpingObject.vacftclose()

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

    def connectionToPumping(self, peer):
        if peer is not None:
            self.pumpingObject = peer
            # let us read in the static object if not already done
            if self.valveThreshold is None:
                self.valveThreshold = float(
                    self.pumpingObject.getValveThreshold())
            if self.pumpThreshold is None:
                self.pumpThreshold = float(
                    self.pumpingObject.getPumpThreshold())
            if self.usThreshold is None:
                self.usThreshold = float(self.pumpingObject.getUSThreshold())
            if self.ftTimeout is None:
                self.ftTimeout = int(self.pumpingObject.getFTTimeout())
            if self.scTimeout is None:
                self.scTimeout = int(self.pumpingObject.getSCTimeout())
class EnergyWaveLengthBrick(Core.BaseBrick):

    properties = {}

    connections = {
        "energy":
        Connection("Energy object", [Signal("energyChanged", "energyChanged")],
                   [
                       Slot("setEnergy"),
                       Slot("getEnergy"),
                       Slot("pilatusReady"),
                       Slot("pilatusReset"),
                       Slot("setPilatusFill"),
                       Slot("energyAdjustPilatus")
                   ], "connectedToEnergy"),
        "login":
        Connection("Login object", [Signal("loggedIn", "loggedIn")], [],
                   "connectionToLogin"),
        "display":
        Connection("Display object", [
            Signal("displayResetChanged", "displayResetChanged"),
            Signal("displayItemChanged", "displayItemChanged"),
            Signal("transmissionChanged", "transmissionChanged"),
            Signal("grayOut", "grayOut")
        ], []),
    }

    signals = []
    slots = []

    def __init__(self, *args, **kargs):
        Core.BaseBrick.__init__(self, *args, **kargs)
        # to keep track in case a dialog boxes is open
        self.__energyDialogOpen = False
        self.__energyDialog = None
        self.__waveLengthDialogOpen = False
        self.__waveLengthDialog = None
        self.loginDone = False

    def init(self):
        # The keV to Angstrom calc
        self.hcOverE = 12.3984

        self.vboxLayout = Qt.QVBoxLayout()
        self.hBox1Layout = Qt.QHBoxLayout()

        self.brick_widget.setLayout(self.vboxLayout)
        self.energyLabel = Qt.QLabel("Energy [keV]     ", self.brick_widget)
        self.hBox1Layout.addWidget(self.energyLabel)

        self.energyLineEdit = Qt.QLineEdit(self.brick_widget)
        self.energyLineEdit.setEnabled(False)
        self.energyLineEdit.setSizePolicy(Qt.QSizePolicy.Expanding,
                                          Qt.QSizePolicy.Expanding)
        self.energyLineEdit.setToolTip("Current Energy")
        self.hBox1Layout.addWidget(self.energyLineEdit)

        self.newEnergyPushButton = Qt.QPushButton("New Energy",
                                                  self.brick_widget)
        Qt.QObject.connect(self.newEnergyPushButton, Qt.SIGNAL("clicked()"),
                           self.newEnergyPushButtonClicked)
        self.hBox1Layout.addWidget(self.newEnergyPushButton)

        self.brick_widget.layout().addLayout(self.hBox1Layout)

        self.hBox2Layout = Qt.QHBoxLayout()

        self.wavelengthLabel = Qt.QLabel("Wavelength [A] ", self.brick_widget)
        self.hBox2Layout.addWidget(self.wavelengthLabel)

        self.waveLengthLineEdit = Qt.QLineEdit(self.brick_widget)
        self.waveLengthLineEdit.setEnabled(False)
        self.waveLengthLineEdit.setSizePolicy(Qt.QSizePolicy.Expanding,
                                              Qt.QSizePolicy.Expanding)
        self.waveLengthLineEdit.setToolTip("Current Wavelength")
        self.hBox2Layout.addWidget(self.waveLengthLineEdit)

        self.newWaveLengthPushButton = Qt.QPushButton("New Wavelength",
                                                      self.brick_widget)
        Qt.QObject.connect(self.newWaveLengthPushButton,
                           Qt.SIGNAL("clicked()"),
                           self.newWaveLengthPushButtonClicked)
        self.hBox2Layout.addWidget(self.newWaveLengthPushButton)

        self.brick_widget.layout().addLayout(self.hBox2Layout)

    # 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)

    # Connect to display

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

    def displayItemChanged(self, _):
        pass

    def displayResetChanged(self):
        pass

    def transmissionChanged(self, _):
        pass

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

    def newEnergyPushButtonClicked(self):
        # Check if pilatus is ready
        if not self.energyControlObject.pilatusReady():
            Qt.QMessageBox.critical(self.brick_widget, "Error",
                                    "Pilatus detector is busy.. Try later",
                                    Qt.QMessageBox.Ok)
            return
        if self.__energyDialogOpen:
            self.__energyDialog.activateWindow()
            self.__energyDialog.raise_()
        else:
            self.__energyDialog = EnterEnergy(self)
            self.__energyDialog.show()

    def energyDialogOpen(self):
        self.__energyDialogOpen = True

    def energyDialogClose(self):
        self.__energyDialogOpen = False

    def newWaveLengthPushButtonClicked(self):
        # Check if pilatus is ready
        if not self.energyControlObject.pilatusReady():
            Qt.QMessageBox.critical(self.brick_widget, "Error",
                                    "Pilatus detector is busy.. Try later",
                                    Qt.QMessageBox.Ok)
            return
        if self.__waveLengthDialogOpen:
            self.__waveLengthDialog.activateWindow()
            self.__waveLengthDialog.raise_()
        else:
            self.__waveLengthDialog = EnterWaveLength(self)
            self.__waveLengthDialog.show()

    def waveLengthDialogOpen(self):
        self.__waveLengthDialogOpen = True

    def waveLengthDialogClose(self):
        self.__waveLengthDialogOpen = False

    def setEnergy(self, energyStr):
        if self.energyControlObject is not None:
            # Put 30 second timeout, since Pilatus can be long
            self.energyControlObject.setEnergy(energyStr, timeout=30)
            # make sure you set gapfill as well
            self.energyControlObject.setPilatusFill()
        else:
            logging.error("Could not set Energy to " + energyStr)

    def getEnergy(self):
        if self.energyControlObject is not None:
            return self.energyControlObject.getEnergy()
        else:
            logging.error("Could not get Energy")

    def energyChanged(self, pValue):
        if pValue is not None:
            self.__energy = float(pValue)
            energyStr = "%.4f" % self.__energy
            self.energyLineEdit.setText(energyStr + " keV")
            # and calculate wavelength
            wavelength = self.hcOverE / self.__energy
            wavelengthStr = "%.4f" % wavelength
            self.waveLengthLineEdit.setText(wavelengthStr + " Angstrom")

    def connectedToEnergy(self, pPeer):
        if pPeer is not None:
            self.energyControlObject = pPeer
            # read energy when getting contact with CO Object
            self.__energy = float(self.energyControlObject.getEnergy())
            energyStr = "%.4f" % self.__energy
            self.energyLineEdit.setText(energyStr + " keV")
            # and calculate wavelength
            wavelength = self.hcOverE / self.__energy
            wavelengthStr = "%.4f" % wavelength
            self.waveLengthLineEdit.setText(wavelengthStr + " Angstrom")