Esempio n. 1
0
class CameraBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.camera = None
        self.update_disabled = False
        self.__cameraName = None

        self.__zoomList = [1.5, 2, 2.5, 3, 3.5, 4]
        self.__initZoom = 2

        self.__fixWidth = -1
        self.__fixHeight = -1

        self.__swapRgb = True
        ####### PRINT #######
        self.__printWidget = QubPrintPreview(self)
        self.__printWidget.resize(400, 500)
        printer = qt.QPrinter()
        printer.setOutputToFile(1)
        printer.setOutputFileName('/tmp/print_file.ps')
        self.__printWidget.setPrinter(printer)
        self.__printWidget.update()

        self.__beamAction = None
        self.__scaleAction = None
        self.__chosenActions = {}
        self.__wholeActions = []
        self.__measureDialog = None

        ####### PRINT ACTION #######
        printAction = QubPrintPreviewAction(
            name="print", group="admin", withVectorMenu=True)
        printAction.previewConnect(self.__printWidget)
        self.__wholeActions.append(printAction)

        ####### SAVE IMAGE #######
        self.__saveAction = QubSaveImageAction(parent=self, label='Save falcon image',
                                               name="save", group="admin")
        self.__saveAction.setConnectCallBack(self._save_dialog_new)
        self.__wholeActions.append(self.__saveAction)
        self.__defaultSavePath = '/tmp'

        ####### UPDATE #######
        update = QubToggleAction(name="update", group="image", initState=True)
        self.connect(update, qt.PYSIGNAL("StateChanged"), self.__cameraUpdate)
        self.__wholeActions.append(update)

        ####### Start Camera ######
        startCamera = QubToggleAction(
            name="startCamera",
            group="image",
            iconName='bright-cont',
            initState=True)
        self.connect(startCamera, qt.PYSIGNAL("StateChanged"), self.__cameraStart)
        self.__wholeActions.append(startCamera)

        ####### BRIGHTNESS/CONTRAST #######
        self.__brightcount = QubOpenDialogAction(name="bright-cont",
                                                 iconName='bright-cont', group="image")
        self.__brightcount.setDialog(QubBrightnessContrastDialog(self))
        self.__wholeActions.append(self.__brightcount)

        ###### Grid TOOL ######
        self.__gridToolAction = QubOpenDialogAction(parent=self, name='grid_tool',
                                                    iconName='rectangle', label='Grid tool',
                                                    group="Tools")  # place="contextmenu")
        self.__gridDialog = GridDialog(
            self, "Grid Dialog", flags=qt.Qt.WStyle_StaysOnTop)
        self.__gridToolAction.setConnectCallBack(self._grid_dialog_connect_hdlr)
        self.__wholeActions.append(self.__gridToolAction)

        self.__previous_pos_dict = {}
        self.__beamWidth = 0
        self.__beamHeight = 0

        ####### BEAM ACTION #######
        self.__beamAction = QubBeamAction(name="beam", group="Tools")
        self.__wholeActions.append(self.__beamAction)
        self.connect(self.__beamAction, qt.PYSIGNAL("BeamSelected"),
                     self.beamSelection)

        ####### SCALE #######
        self.__scaleAction = QubScaleAction(name='scale', group='Tools')
        self.__wholeActions.append(self.__scaleAction)
        self.__wholeActions.extend(self.__creatStdActions())

        ####### ACTION INFO #######
        actionInfo = QubInfoAction(name="actionInfo", group="image", place="statusbar")
        self.__wholeActions.append(actionInfo)

        ####### CHANGE FOREGROUND COLOR #######
        self.__fcoloraction = QubForegroundColorAction(name="color", group="image")
        self.__wholeActions.append(self.__fcoloraction)

        ####### MEASURE #######
        self.__measureAction = QubOpenDialogAction(parent=self, name='measure',
                                                   iconName='measure', label='Measure',
                                                   group="Tools")
        self.__measureAction.setConnectCallBack(self._measure_dialog_new)
        self.__wholeActions.append(self.__measureAction)

        # ###### POSITION TOOL ######
        # self.__posToolAction = QubOpenDialogAction(parent=self, name='pos_tool',
        #                                            iconName='circle', label='Position tool',
        #                                            group="Tools")
        # self.__posToolAction.setConnectCallBack(self._line_dialog_new)
        # self.__wholeActions.append(self.__posToolAction)

        ####### ZOOM LIST #######
        zoomActionList = QubZoomListAction(place="toolbar",
                                           initZoom=1, zoomValList=[0.1, 0.25, 0.5, 0.75, 1, 1.5, 2],
                                           show=1, group="zoom")
        self.__wholeActions.append(zoomActionList)

        ####### ZOOM Action #######
        self.__zoomFitOrFill = QubZoomAction(place="toolbar", group="zoom")
        self.__wholeActions.append(self.__zoomFitOrFill)

        ####### LINK ZOOM ACTION #######
        self.__zoomFitOrFill.setList(zoomActionList)
        zoomActionList.setActionZoomMode(self.__zoomFitOrFill)

        ####### ZOOM WINDOW #######
        self.__zoomAction = QubZoomRectangle(
            label='Zoom Crop', place="toolbar", show=1, group="zoom")
        self.connect(self.__zoomAction, qt.PYSIGNAL("Actif"), self.__hide_show_zoom)
        self.__wholeActions.append(self.__zoomAction)

        self.__splitter = qt.QSplitter(qt.Qt.Horizontal, self)
        self.__splitter.show()

        self.__mainVideo = QubPixmapDisplayView(self.__splitter)
        self.__mainVideo.show()
        self.__mainVideo.setScrollbarMode('Auto')
        self.__mainPlug = _MainVideoPlug(self.__mainVideo, self.__zoomAction)

        actions = self.__creatStdActions()

        ####### ZOOM LIST #######
        self.__zoomActionList = QubZoomListAction(place="toolbar", keepROI=True,
                                                  initZoom=self.__initZoom, zoomValList=self.__zoomList,
                                                  show=1, group="zoom")
        actions.insert(0, self.__zoomActionList)

        ####### ZOOM Action #######
        zoomFitOrFill = QubZoomAction(place="toolbar", keepROI=True, group="zoom")
        zoomFitOrFill.setList(self.__zoomActionList)
        self.__zoomActionList.setActionZoomMode(zoomFitOrFill)
        actions.append(zoomFitOrFill)

        self.__zoomVideo = QubPixmapDisplayView(self.__splitter, None, actions)
        self.__zoomVideo.hide()
        self.__zoomPlug = _ZoomPlug(self.__zoomVideo)
        self.__zoomPlug.zoom().setZoom(2, 2)
        self.__cbk = _rectangleZoom(self.__zoomAction, self.__zoomPlug)

        layout = qt.QHBoxLayout(self, 0, 0, "layout")
        layout.addWidget(self.__splitter)

        self.__image2Pixmap = QubImage2Pixmap()
        self.__image2Pixmap.plug(self.__mainPlug)
        self.__zoomPlug.setPoller(self.__image2Pixmap)

        self.__jpegDecompress = QubStdData2Image()
        self.__jpegDecompress.setSwapRGB(True)
        self.__jpeg2image = None

        ####### PROPERTY #######
        self.addProperty('camera', 'string', '')
        self.addProperty('zoom list', 'string', ','.join(
            [str(x) for x in self.__zoomList]))
        self.addProperty('init zoom', 'integer', self.__initZoom)
        self.addProperty('swap rgb', 'boolean', True)

        self.addProperty('fix : width', 'integer', -1)
        self.addProperty('fix : height', 'integer', -1)

        self.addProperty('action : print', 'boolean', True)
        self.addProperty('action : save image', 'boolean', True)
        self.addProperty('action : update', 'boolean', True)
        self.addProperty('action : startCamera', 'boolean', True)
        self.addProperty('action : brightness contrast', 'boolean', True)
        self.addProperty('action : beam', 'boolean', True)
        self.addProperty('action : scale', 'boolean', True)
        self.addProperty('action : change foreground color', 'boolean', True)
        self.addProperty('action : measure', 'boolean', True)
        self.addProperty('action : measure (place)', 'combo',
                         ('toolbar', 'contextmenu'), 'toolbar')
        self.addProperty('action : zoom window', 'boolean', True)
        self.addProperty('action : zoom fit or fill', 'boolean', True)
        self.addProperty('action : zoom list', 'boolean', True)
        self.addProperty('action : x,y coordinates', 'boolean', True)
        self.addProperty('action : default color', 'combo',
                         ('black', 'red', 'green'), 'black')

        self.addProperty('action : save image (place)', "combo",
                         ('toolbar', 'contextmenu'), 'toolbar')
        self.addProperty('action : save image (default path)', "string", '/tmp')
        self.addProperty('action : save image (show always configure)', "boolean", True)

        self.addProperty("diffractometer", "string", "")
        self.diffractometerHwobj = None

        ####### SIGNAL #######
        self.defineSignal("BeamPositionChanged", ())

        ####### SLOT #######
        self.defineSlot("changeBeamPosition", ())
        self.defineSlot("changePixelScale", ())
        self.defineSlot('getView', ())
        self.defineSlot('getImage', ())

        ####### LINK VIEW AND SUB VIEW #######
        mainView = self.__mainVideo.view()
        zoomView = self.__zoomVideo.view()
        mainView.addEventMgrLink(zoomView,
                                 mainView.canvas(), zoomView.canvas(),
                                 mainView.matrix(), zoomView.matrix())

        self.imageReceivedConnected = None

    def safeConnect(self):
        if not self.imageReceivedConnected and self.camera is not None:
            #print "CONNECTING 0"
            self.camera.connect('imageReceived', self.__imageReceived)
            # self.connect(self.camera,qt.PYSIGNAL('imageReceived'),self.__imageReceived)
            self.imageReceivedConnected = False

    def safeDisconnect(self):
        if self.imageReceivedConnected and self.camera is not None:
            #print "DISCONNECTING 3"
            self.camera.disconnect('imageReceived', self.__imageReceived)
            # self.disconnect(self.camera,qt.PYSIGNAL('imageReceived'),self.__imageReceived)
            self.imageReceivedConnected = False

    def disable_update(self):
        # self.__imageReceived(DISABLED_JPEG,DISABLED_WIDTH,DISABLED_HEIGHT)
        self.update_disabled = True

    def enable_update(self):
        self.update_disabled = False

    def __imageReceived(self, image, width, height, force_update=False):
        if self.update_disabled:
            return

        if not force_update:
            if not self.isVisible():
                return

        if isinstance(image, qt.QImage):
            if self.__swapRgb:
                image = image.swapRGB()
            self.__jpeg2image.setImage(image, image)
        else:
            self.__jpegDecompress.putData(image, width, height)

    def propertyChanged(self, property, oldValue, newValue):
        if property == 'camera':
            # if self.camera is not None and not self.isRunning():
            #    self.safeDisconnect()
            self.safeDisconnect()
            self.camera = self.getHardwareObject(newValue)
            self.__hwoName = newValue

            if self.camera is not None:
                try:
                    self.__tangoName = self.camera.tangoname
                except BaseException:
                    self.__tangoName = ""

                try:
                    camera_role = self.camera.getDeviceByRole('camera')
                    if camera_role is not None:
                        self.camera = camera_role
                except AttributeError:
                    pass

                self.__brightcount.setCamera(self.camera)

        elif property == 'zoom list':
            zoomList = [float(x) for x in newValue.split(',')]
            if zoomList != self.__zoomList:
                self.__zoomList = zoomList
                self.__zoomActionList.changeZoomList(zoomList, self.__initZoom)
        elif property == 'init zoom':
            if newValue != self.__initZoom:
                self.__initZoom = newValue
                self.__zoomActionList.changeZoomList(self.__zoomList, newValue)
        elif property == 'swap rgb':
            self.__jpegDecompress.setSwapRGB(newValue)
            self.__swapRgb = newValue
        elif property == 'action : print':
            self.__chosenActions['print'] = newValue
        elif property == 'action : save image':
            self.__chosenActions['save'] = newValue
        elif property == 'action : update':
            self.__chosenActions['update'] = newValue
        elif property == 'action : startCamera':
            self.__chosenActions['startCamera'] = newValue
        elif property == 'action : brightness contrast':
            self.__chosenActions['bright-cont'] = newValue
        elif property == 'action : beam':
            self.__chosenActions['beam'] = newValue
        elif property == 'action : scale':
            self.__chosenActions['scale'] = newValue
        elif property == 'action : change foreground color':
            self.__chosenActions['color'] = newValue
        elif property == 'action : measure':
            self.__chosenActions['measure'] = newValue
        elif property == 'action : zoom window':
            self.__chosenActions['zoomrect'] = newValue
        elif property == 'action : zoom fit or fill':
            self.__chosenActions['Zoom tools'] = newValue
        elif property == 'action : zoom list':
            self.__chosenActions['zoomlist'] = newValue
        elif property == 'action : x,y coordinates':
            self.__chosenActions['position'] = newValue
        elif property == 'action : default color':
            self.__chosenDefaultColor = newValue
        elif property == 'action : save image (place)':
            self.__saveAction.setPlace(newValue, True)
        elif property == 'action : measure (place)':
            self.__measureAction.setPlace(newValue, True)
        elif property == 'action : save image (default path)':
            self.__defaultSavePath = newValue
        elif property == 'action : save image (show always configure)':
            self.__saveAction.setConfigureOnClick(newValue)

        elif property == 'fix : width':
            self.__fixWidth = newValue
        elif property == 'fix : height':
            self.__fixHeight = newValue
        elif property == "diffractometer":
            self.diffractometerHwobj = self.getHardwareObject(newValue)
            if self.diffractometerHwobj is not None:
                self.__previous_pos_dict = self.diffractometerHwobj.getPositions()
                self.diffractometerHwobj.connect("minidiffStateChanged",
                                                 self.diffractometerChanged)
                if self.diffractometerHwobj.zoomMotor is not None:
                    zoom = self.diffractometerHwobj.zoomMotor.getPosition()
                    xSize, ySize = self.diffractometerHwobj.getCalibrationData(zoom)
                    #xSize,ySize = self.__scaleAction.xPixelSize(), self.__scaleAction.yPixelSize()
                    self.diffractometerHwobj.getBeamInfo(self.__getBeamInfo)
                    beam_pos_x = self.diffractometerHwobj.getBeamPosX()
                    beam_pos_y = self.diffractometerHwobj.getBeamPosY()

                    self.__gridDialog.set_x_pixel_size(xSize)
                    self.__gridDialog.set_y_pixel_size(ySize)
                    self.__gridDialog.set_beam_position(beam_pos_x, beam_pos_y,
                                                        self.__beamWidth, self.__beamHeight)

    def run(self):
        chosenActions = []

        for action in self.__wholeActions:
            if self.__chosenActions.get(action.name(), True):
                chosenActions.append(action)

        self.__mainVideo.addAction(chosenActions)

        if not self.__chosenActions.get('update', False):
            self.__cameraUpdate(True)

        if not self.__chosenActions.get('startCamera', False):
            self.__cameraStart(True)

        if self.__fixWidth != -1 and self.__fixHeight != -1:
            self.__mainVideo.view().setFixedSize(self.__fixWidth + 4, self.__fixHeight + 4)

        self.__startIdle = qt.QTimer(self)
        qt.QObject.connect(self.__startIdle, qt.SIGNAL('timeout()'), self.__idleRun)
        self.__startIdle.start(0)

    def __idleRun(self):
        self.__startIdle.stop()
        self.__fcoloraction.setColor(self.__chosenDefaultColor)
        self.__mainVideo.view().setForegroundColor(qt.QColor(self.__chosenDefaultColor))

    def stop(self):
        self.safeDisconnect()

    def beamSelection(self, x, y):
        self.emit(qt.PYSIGNAL("BeamPositionChanged"), (x, y))
        self.changeBeamPosition(x, y)

    def changeBeamPosition(self, x, y, beam_width=None, beam_height=None):
        self.__beamAction.setBeamPosition(x, y)
        try:
            if not beam_width:
                beam_width = self.__beamWidth

            if not beam_height:
                beam_height = self.__beamHeight

            self.__gridDialog.set_beam_position(x, y, beam_width, beam_height)
        except BaseException:
            pass

    def changePixelScale(self, sizex, sizey):
        self.__scaleAction.setXPixelSize(sizex)
        self.__scaleAction.setYPixelSize(sizey)
        if self.__measureDialog:
            self.__measureDialog.setXPixelSize(sizex)
            self.__measureDialog.setYPixelSize(sizey)

        self.__gridDialog.set_x_pixel_size(sizex)
        self.__gridDialog.set_y_pixel_size(sizey)

    def getView(self, key):
        try:
            key['drawing'] = self.__mainVideo.view()
            key['view'] = self.__mainVideo
            key['hwname'] = self.__hwoName
            key['dsname'] = self.__tangoName
        except BaseException:
            pass

    def getImage(self, key):
        if self.__jpeg2image is not None:
            try:
                key['image'] = self.__jpeg2image.getLastImage()
            except BaseException:
                pass

    def __creatStdActions(self):
        actions = []
        ####### MOUSE POSITION #######
        posaction = QubPositionAction(name="position", group="image", place="statusbar")
        actions.append(posaction)

        return actions

    def __cameraUpdate(self, onoff):
        if onoff:
            self.__jpeg2image = _Jpeg2ImagePlug(self.__image2Pixmap)
            self.__jpegDecompress.plug(self.__jpeg2image)
            if self.camera is not None:
                imageInfo = self.camera.imageType()
            else:
                imageInfo = None
            imType = self.__jpegDecompress.STANDARD
            if imageInfo:
                if imageInfo.type() == 'bayer':
                    imType = self.__jpegDecompress.BAYER_RG
                elif imageInfo.type() == 'raw':
                    imType = self.__jpegDecompress.RAW
            self.__jpegDecompress.setImageType(imType)
            self.safeConnect()
        else:
            self.safeDisconnect()
            self.__jpeg2image.setEnd()

    def __cameraStart(self, onoff):
        if onoff:
            print "********************************************************Set the camera ON"
            if self.camera is not None:
                self.camera.setLive(True)
            else:
                print "camera is none"
        else:
            print "****************************************************Set the camera off"
            if self.camera is not None:
                print "camera :"
                print self.camera
                self.camera.setLive(False)
            else:
                print "camera is none"

    def __hide_show_zoom(self, actif):
        if actif:
            if self.__chosenActions['Zoom tools']:
                self.__zoomFitOrFill.setState(True)
            else:
                self.__mainVideo.setScrollbarMode('Fit2Screen')
            self.__zoomPlug.start()
            self.__zoomVideo.show()
            splitterWidth = self.__splitter.width()
            self.__splitter.setSizes(
                [splitterWidth / 3, splitterWidth - splitterWidth / 3])
        else:
            if self.__chosenActions['Zoom tools']:
                self.__zoomFitOrFill.setState(False)
            else:
                self.__mainVideo.setScrollbarMode('Auto')
            self.__zoomPlug.stop()
            self.__zoomVideo.hide()

    def _measure_dialog_new(self, openDialogAction, aQubImage):
        try:
            self.__measureDialog = QubMeasureListDialog(self,
                                                        canvas=aQubImage.canvas(),
                                                        matrix=aQubImage.matrix(),
                                                        eventMgr=aQubImage)
            xSize, ySize = self.__scaleAction.xPixelSize(), self.__scaleAction.yPixelSize()
            self.__measureDialog.setXPixelSize(xSize)
            self.__measureDialog.setYPixelSize(ySize)
            self.__measureDialog.connect(aQubImage, qt.PYSIGNAL("ForegroundColorChanged"),
                                         self.__measureDialog.setDefaultColor)
            openDialogAction.setDialog(self.__measureDialog)
        except BaseException:
            import traceback
            traceback.print_exc()

    def _grid_dialog_connect_hdlr(self, openDialogAction, aQubImage):
        try:
            self.__gridDialog.set_qub_event_mgr(aQubImage)
            openDialogAction.setDialog(self.__gridDialog)
        except BaseException:
            import traceback
            traceback.print_exc()

    def __getBeamInfo(self, ret):
        self.__beamWidth = float(ret["size_x"])
        self.__beamHeight = float(ret["size_y"])
        #self.__beamShape = ret["shape"]

    def _save_dialog_new(self, openDialogAction, aQubImage):
        saveDialog = QubSaveImageDialog(
            self, matrix=aQubImage.matrix(), canvas=aQubImage.canvas())
        saveDialog.setImage2Pixmap(self.__image2Pixmap)
        saveDialog.setSavePath(self.__defaultSavePath)
        openDialogAction.setDialog(saveDialog)

    def instanceMirrorChanged(self, mirror):
        #print "INSTANCEMIRRORCHANGED",mirror,BlissWidget.isInstanceMirrorAllow()
        return
        if BlissWidget.isInstanceModeSlave():
            if BlissWidget.isInstanceMirrorAllow():
                self.safeConnect()
            else:
                self.safeDisconnect()

    def diffractometerChanged(self, *args):
        """
        Handles diffractometer change events, connected to the signal
        minidiffStateChanged of the diffractometer hardware object.
        """

        if self.diffractometerHwobj.isReady():
            pos_dict = self.diffractometerHwobj.getPositions()
            p1 = self.diffractometerHwobj.motor_positions_to_screen(
                self.__previous_pos_dict)
            p2 = (self.diffractometerHwobj.getBeamPosX(),
                  self.diffractometerHwobj.getBeamPosY())

            dx = p2[0] - p1[0]
            dy = p2[1] - p1[1]

            if dy != 0:
                self.__gridDialog.move_grid_ver(-dy)

            if dx != 0:
                self.__gridDialog.move_grid_hor(-dx)

            #print dx, dy

            self.__previous_pos_dict = pos_dict
class CameraMotorToolsBrick(BlissWidget):
    def __init__(self, parent, name):
        BlissWidget.__init__(self, parent, name)
        
        """
        variables
        """
        self.YBeam = None
        self.ZBeam = None
        self.YSize = None
        self.ZSize = None
        
        self.view = None
        self.firstCall = True
        self.motorArrived = 0

        self.__mosaicView,self.__mosaicDraw = None,None

        """
        property
        """
        self.addProperty("Hor. Motor", "string", "")
        self.horMotHwo = None
        
        self.addProperty("Vert. Motor", "string", "")
        self.verMotHwo = None

        #self.addProperty("Focus Motor","string","")
        #self.focusMotHwo = None

        #self.addProperty("Focus min step","float",0.05)
        #self.focusMinStep = None
        
        self.addProperty("Move To", "combo",
                         ("none", "toolbar", "popup"), "none")
        self.movetoMode = None
        self.movetoAction = None

        self.addProperty("Move to color when activate","combo",
                         ("none","blue","green","yellow","red","orange"),"none")
        self.movetoColorWhenActivate = None
        
        self.addProperty("Limits", "combo",
                         ("none", "toolbar", "popup"), "none")
        self.limitsMode = None
        self.limitsAction = None

        self.addProperty("Measure", "combo", ("none", "toolbar", "popup"), "none")
        self.measureMode = None
        self.measureAction = None

        self.addProperty("Focus","combo",
                         ("none", "toolbar", "popup"), "none")
        self.focusMode = None
        self.focusAction = None
        self.focusState = None
        self.focusDrawingRectangle = None
        self.focusPointSelected = None
        
        self.__movetoActionMosaic = None
        
        """
        Signal
        """
        self.defineSignal('getView',())
        self.defineSignal('getMosaicView',())
        self.defineSignal('getCalibration',())
        self.defineSignal('getBeamPosition',())
        self.defineSignal('getImage',())
        self.defineSignal('moveDone', ())
        self.defineSignal('mosaicImageSelected', ())
        """
        Slot
        """
        self.defineSlot('beamPositionChanged',())
        self.defineSlot('pixelCalibrationChanged',())
        self.defineSlot('setMoveToMode',())
        self.defineSlot('setLimitsDisplay',())
        self.defineSlot('setMoveToState',())

        """
        widgets - NO APPEARANCE
        """
        self.setFixedSize(0, 0)
                        
               
    def propertyChanged(self, prop, oldValue, newValue):
        if prop == "Hor. Motor":
            if self.horMotHwo is not None:
                self.disconnect(self.horMotHwo, qt.PYSIGNAL('positionChanged'),
                                self.setHorizontalPosition)
                self.disconnect(self.horMotHwo, qt.PYSIGNAL("limitsChanged"),
                                self.setHorizontalLimits)

            self.horMotHwo = self.getHardwareObject(newValue)
            
            if self.horMotHwo is not None:
                self.connect(self.horMotHwo, qt.PYSIGNAL('positionChanged'),
                             self.setHorizontalPosition)
                self.connect(self.horMotHwo, qt.PYSIGNAL("limitsChanged"),
                             self.setHorizontalLimits)

        elif prop == "Vert. Motor":
            if self.verMotHwo is not None:
                self.disconnect(self.verMotHwo, qt.PYSIGNAL('positionChanged'),
                                self.setVerticalPosition)
                self.disconnect(self.verMotHwo, qt.PYSIGNAL("limitsChanged"),
                                self.setVerticalLimits)

            self.verMotHwo = self.getHardwareObject(newValue)
            
            if self.verMotHwo is not None:
                self.connect(self.verMotHwo, qt.PYSIGNAL('positionChanged'),
                             self.setVerticalPosition)
                self.connect(self.verMotHwo, qt.PYSIGNAL("limitsChanged"),
                             self.setVerticalLimits)
        #elif prop == "Focus Motor":
        #    if self.focusMotHwo is not None:
        #        self.disconnect(self.focusMotHwo,qt.PYSIGNAL('positionChanged'),
        #                        self.setFocusPosition)
        #        self.disconnect(self.focusMotHwo,qt.PYSIGNAL('limitsChanged'),
        #                        self.setFocusLimits)

        #    self.focusMotHwo = self.getHardwareObject(newValue)
        #    self.focusState = FocusState(self,self.focusMotHwo)
            
        #    if self.focusMotHwo is not None:
        #        self.connect(self.focusMotHwo,qt.PYSIGNAL('positionChanged'),
        #                     self.setFocusPosition)
        #        self.connect(self.focusMotHwo,qt.PYSIGNAL('limitsChanged'),
        #                     self.setFocusLimits)
        #        self.connect(self.focusMotHwo, qt.PYSIGNAL("moveDone"),
        #                     self.focusMoveFinished)
        elif prop == "Move To": self.movetoMode = _enumTranslate[newValue]
        elif prop == "Limits": self.limitsMode = _enumTranslate[newValue]
        elif prop == "Focus": self.focusMode = _enumTranslate[newValue]
        elif prop == "Measure": self.measureMode = _enumTranslate[newValue]
        elif prop == "Focus min step": self.focusMinStep = newValue
        elif prop == "Move to color when activate" :
            if newValue == "none" :
                self.movetoColorWhenActivate = None
            else:
                self.movetoColorWhenActivate = newValue
        if not self.firstCall:
            self.configureAction()
            
    def run(self):
        """
        get view
        """
        view = {}
        self.emit(qt.PYSIGNAL("getView"), (view,))
        try:
            self.drawing = view["drawing"]
            self.view = view["view"]        
        except:
            print "No View"
        
        """
        get calibration
        """
        calib = {}
        self.emit(qt.PYSIGNAL("getCalibration"), (calib,))
        try:
            # in all this brick we work with pixel calibration in mm
            self.YSize = calib["ycalib"]
            self.ZSize = calib["zcalib"]
            if calib["ycalib"] is not None and calib["zcalib"] is not None:
                self.YSize = self.YSize * 1000
                self.ZSize = self.ZSize * 1000
        except:
            print "No Calibration"
            
        """
        get beam position
        """
        position = {}
        self.emit(qt.PYSIGNAL("getBeamPosition"), (position,))
        try:
            self.YBeam = position["ybeam"]
            self.ZBeam = position["zbeam"]
        except:
            print "No Beam Position"

        """
        get mosaic view
        """
        mosaicView = {}
        self.emit(qt.PYSIGNAL('getMosaicView'),(mosaicView,))
        try:
            self.__mosaicView = mosaicView['view']
            self.__mosaicDraw = mosaicView['drawing']
        except KeyError:
            self.__mosaicView,self.__mosaicDraw = None,None
            
        self.configureAction()
        
        self.firstCall = False
    
    def configureAction(self):
        """
        Move To action
        """
        if self.movetoMode is not None:
            if self.movetoAction is None:
                """
                create action
                """
                self.movetoAction = QubSelectPointAction(name='Move to Beam',
                                                         place=self.movetoMode,
                                                         actionInfo = 'Move to Beam',
                                                         group='Tools')
                self.connect(self.movetoAction,qt.PYSIGNAL("StateChanged"),self.movetoStateChanged)
                self.connect(self.movetoAction, qt.PYSIGNAL("PointSelected"),
                             self.pointSelected)
                
                if self.view is not None:
                    self.view.addAction(self.movetoAction)
                    self.oldMoveToActionColor = self.movetoAction.paletteBackgroundColor()

        else:
            if self.movetoAction is not None:
                """
                remove action
                """
                if self.view is not None:
                    self.view.delAction(self.movetoAction)
                    
                """
                del action from view
                """
                self.disconnect(self.movetoAction, qt.PYSIGNAL("PointSelected"),
                                self.pointSelected)
                self.movetoAction = None
        """
        Limits action
        """
        if self.limitsMode is not None:
            if self.limitsAction is None:
                """
                create action
                """
                self.limitsAction = QubRulerAction(name='Motor Limits',
                                                   place=self.limitsMode,
                                                   group='Tools')
                    
                if self.view is not None:
                    self.view.addAction(self.limitsAction)
                
            """
            configure action
            """
            if self.horMotHwo is not None:
                mne = self.horMotHwo.getMotorMnemonic()
                self.limitsAction.setLabel(QubRulerAction.HORIZONTAL,0,mne)

            if self.verMotHwo is not None:
                mne = self.verMotHwo.getMotorMnemonic()
                self.limitsAction.setLabel(QubRulerAction.VERTICAL,0, mne)
                
        else:
            if self.limitsAction is not None:
                """
                remove action
                """
                if self.view is not None:
                    self.view.delAction(self.limitsAction)
                    
                """
                del action from view
                """
                self.limitsAction = None

        if self.measureMode is not None:
                if self.measureAction is None:
                        self.measureAction = QubOpenDialogAction(parent=self, name='measure', iconName='measure', label='Measure', group='Tools', place=self.measureMode)
                        self.measureAction.setConnectCallBack(self._measure_dialog_new)
                        logging.getLogger().info("setting measure mode")
                        if self.view is not None:
                                logging.getLogger().info("adding action")
                                self.view.addAction(self.measureAction)
        else:
                if self.measureAction is not None:
                        if self.view is not None:
                                self.view.delAction(self.measureAction)
                        self.measureAction = None

        if self.movetoMode is not None:
            if self.__movetoActionMosaic is not None:
                self.__mosaicView.delAction(self.__movetoActionMosaic)
                self.disconnect(self.__movetoActionMosaic, qt.PYSIGNAL("PointSelected"),
                                self.__mosaicPointSelected)
                self.diconnect(self.__movetoActionMosaic,qt.PYSIGNAL("StateChanged"),
                               self.__movetoMosaicStateChanged)
                self.__movetoActionMosaic = None
                
            if self.__mosaicView is not None :
                self.__movetoActionMosaic = QubSelectPointAction(name='Move to Beam',
                                                                 place=self.movetoMode,
                                                                 actionInfo = 'Move to Beam',
                                                                 mosaicMode = True,
                                                                 residualMode = True,
                                                                 group='Tools')
                self.connect(self.__movetoActionMosaic, qt.PYSIGNAL("PointSelected"),
                             self.__mosaicPointSelected)
                self.connect(self.__movetoActionMosaic,qt.PYSIGNAL("StateChanged"),
                             self.__movetoMosaicStateChanged)

                self.__mosaicView.addAction(self.__movetoActionMosaic)
                self.__oldMoveToMosaicActionColor = self.__movetoActionMosaic.paletteBackgroundColor()

        if self.focusMode is not None:
            if self.focusAction is None:
                self.focusAction = QubToggleAction(label='Autofocus',name='autofocus',place=self.focusMode,
                                                   group='Tools',autoConnect = True)
                qt.QObject.connect(self.focusAction,qt.PYSIGNAL('StateChanged'),self.showFocusGrab)

            if self.view and self.drawing :
                self.focusDrawingRectangle,_ = QubAddDrawing(self.drawing,QubPointDrawingMgr,QubCanvasHomotheticRectangle)
                self.focusDrawingRectangle.setDrawingEvent(QubMoveNPressed1Point)
                self.focusDrawingRectangle.setKeyPressedCallBack(self.focusRawKeyPressed)

                qt.QObject.connect(self.drawing,qt.PYSIGNAL("ForegroundColorChanged"),self.focusDrawingRectangle.setColor)
                self.focusDrawingRectangle.setEndDrawCallBack(self.setFocusPointSelected)
                self.focusRectangleSize = 12
                self.focusDrawingRectangle.setWidthNHeight(self.focusRectangleSize,self.focusRectangleSize)
                self.view.addAction(self.focusAction)
                
        elif self.view is not None:
            self.view.delAction(self.focusAction)
            self.focusDrawingRectangle = None
    
    def _measure_dialog_new(self,openDialogAction,aQubImage) :
        if  self.YSize is not None and self.ZSize is not None:
            self.__measureDialog = QubMeasureListDialog(self,
                                                      canvas=aQubImage.canvas(),
                                                      matrix=aQubImage.matrix(),
                                                      eventMgr=aQubImage)
            self.__measureDialog.setXPixelSize(self.YSize/1000.0)
            self.__measureDialog.setYPixelSize(self.ZSize/1000.0)
            self.__measureDialog.connect(aQubImage, qt.PYSIGNAL("ForegroundColorChanged"),
                                       self.__measureDialog.setDefaultColor)
            openDialogAction.setDialog(self.__measureDialog)
        
    def setHorizontalPosition(self, newPosition):
        if self.limitsAction is not None:        
            self.limitsAction.setCursorPosition(QubRulerAction.HORIZONTAL, 0,
                                                newPosition)
          
    def setHorizontalLimits(self, limit):
        if self.limitsAction is not None:        
            self.limitsAction.setLimits(QubRulerAction.HORIZONTAL, 0,
                                        limit[0], limit[1])
             
    def setVerticalPosition(self, newPosition):
        if self.limitsAction is not None:        
            self.limitsAction.setCursorPosition(QubRulerAction.VERTICAL, 0,
                                                newPosition)

    def setVerticalLimits(self, limit):
        if self.limitsAction is not None:        
            self.limitsAction.setLimits(QubRulerAction.VERTICAL, 0,
                                        limit[0], limit[1])
         
    #def setFocusLimits(self,limit) :
    #    self.focusState.setLimit(limit)

    #def setFocusPosition(self,newPosition) :
    #    self.focusState.newPosition(newPosition)

    #def focusMoveFinished(self, ver, mne):
    #    self.focusState.endMovement(ver)

    #def focusRawKeyPressed(self,keyevent) :
    #    key = keyevent.key()
    #    if key == qt.Qt.Key_Plus:
    #        self.focusRectangleSize += 3
    #        if self.focusRectangleSize > 99:
    #            self.focusRectangleSize = 99
    #    elif key == qt.Qt.Key_Minus:
    #        self.focusRectangleSize -= 3
    #        if self.focusRectangleSize < 12:
    #            self.focusRectangleSize = 12
    #    else: return
    #    
    #    self.focusDrawingRectangle.setWidthNHeight(self.focusRectangleSize,self.focusRectangleSize)
    
    #def showFocusGrab(self,state) :
    #    self.focusPointSelected = None
    #    if state:
    #        self.focusDrawingRectangle.startDrawing()
    #    else:
    #        self.focusDrawingRectangle.stopDrawing()
    #        self.focusDrawingRectangle.hide()
    #        self.focusPointSelected = None
            
    #def setFocusPointSelected(self,drawingMgr) :
    #    self.focusPointSelected = drawingMgr.point()
    #    if self.focusMotHwo is not None:
    #        self.focusState.start()
            
    def beamPositionChanged(self, beamy, beamz):
        self.YBeam = beamy
        self.ZBeam = beamz
    
    def pixelCalibrationChanged(self, sizey, sizez):
        if sizey is not None:
            self.YSize = sizey * 1000
            try:
                self.__measureDialog.setXPixelSize(sizey)
            except:
                pass
        else:
            self.YSize = None
        
        if sizez is not None:
            self.ZSize = sizez * 1000
            try:
                self.__measureDialog.setYPixelSize(sizez)
            except:
                pass
        else:
            self.ZSize = None

    def setMoveToState(self,state):
        if self.movetoAction is not None:
            self.movetoAction.setState(state)

    def movetoStateChanged(self,state) :
        if self.movetoColorWhenActivate:
            if state:
                self.movetoAction.setPaletteBackgroundColor(qt.QColor(self.movetoColorWhenActivate))
            else:
                self.movetoAction.setPaletteBackgroundColor(self.oldMoveToActionColor)
        
    def pointSelected(self, drawingMgr):
        if self.horMotHwo is not None and self.verMotHwo is not None:
            if  self.YSize is not None and \
                self.ZSize is not None and \
                self.YBeam is not None and \
                self.ZBeam is not None :
                
                self.drawingMgr =  drawingMgr 
                   
                (y, z) = drawingMgr.point()
                
                self.drawingMgr.stopDrawing()

                sign = 1
                if self.horMotHwo.unit < 0:
                    sign = -1
                movetoy = - sign*(self.YBeam - y) * self.YSize

                sign = 1
                if self.verMotHwo.unit < 0:
                    sign = -1
                movetoz = - sign*(self.ZBeam - z) * self.ZSize
                
                self.motorArrived = 0
            
                self.connect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                             self.moveFinished)
                self.connect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                             self.moveFinished)

                self.horMotHwo.moveRelative(movetoy)
                self.verMotHwo.moveRelative(movetoz)
    def __movetoMosaicStateChanged(self,state):
        if self.movetoColorWhenActivate:
            if state:
                self.__movetoActionMosaic.setPaletteBackgroundColor(qt.QColor(self.movetoColorWhenActivate))
            else:
                self.__movetoActionMosaic.setPaletteBackgroundColor(self.__oldMoveToMosaicActionColor)

    def __mosaicPointSelected(self,drawingMgr) :
        point = drawingMgr.mosaicPoints()
        try:
            point = point[0]
            beamY,beamZ = point.refPoint
            YSize,ZSize = point.calibration
            horMotorPos,verMotorPos = point.absPoint
            y,z = point.point
            imageId = point.imageId
        except TypeError: return        # The click wasn't on image

        self.drawingMgr = drawingMgr
        
        drawingMgr.stopDrawing()

        sign = 1
        if self.horMotHwo.unit < 0:
            sign = -1
        movetoy = horMotorPos - sign*(beamY - y) * YSize

        sign = 1
        if self.verMotHwo.unit < 0:
            sign = -1
        movetoz = verMotorPos - sign*(beamZ - z) * ZSize

        self.motorArrived = 0
        
        self.connect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                     self.moveFinished)
        self.connect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                     self.moveFinished)

        self.horMotHwo.move(movetoy)
        self.verMotHwo.move(movetoz)

        self.emit(qt.PYSIGNAL("mosaicImageSelected"), (imageId,))


    def moveFinished(self, ver, mne):
        if mne == self.horMotHwo.getMotorMnemonic():
            self.disconnect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                            self.moveFinished)
            self.motorArrived = self.motorArrived + 1
            
        if mne == self.verMotHwo.getMotorMnemonic():
            self.disconnect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                            self.moveFinished)
            self.motorArrived = self.motorArrived + 1
                        
        if self.motorArrived == 2:
            self.drawingMgr.startDrawing()
            self.motorArrived = 0
            self.emit(qt.PYSIGNAL("moveDone"), (self.YBeam, self.ZBeam))
Esempio n. 3
0
class CameraMotorToolsBrick(BlissWidget):
    def __init__(self, parent, name):
        BlissWidget.__init__(self, parent, name)
        """
        variables
        """
        self.YBeam = None
        self.ZBeam = None
        self.YSize = None
        self.ZSize = None

        self.view = None
        self.firstCall = True
        self.motorArrived = 0

        self.__mosaicView, self.__mosaicDraw = None, None
        """
        property
        """
        self.addProperty("Hor. Motor", "string", "")
        self.horMotHwo = None

        self.addProperty("Vert. Motor", "string", "")
        self.verMotHwo = None

        #self.addProperty("Focus Motor","string","")
        #self.focusMotHwo = None

        #self.addProperty("Focus min step","float",0.05)
        #self.focusMinStep = None

        self.addProperty("Move To", "combo", ("none", "toolbar", "popup"),
                         "none")
        self.movetoMode = None
        self.movetoAction = None

        self.addProperty("Move to color when activate", "combo",
                         ("none", "blue", "green", "yellow", "red", "orange"),
                         "none")
        self.movetoColorWhenActivate = None

        self.addProperty("Limits", "combo", ("none", "toolbar", "popup"),
                         "none")
        self.limitsMode = None
        self.limitsAction = None

        self.addProperty("Measure", "combo", ("none", "toolbar", "popup"),
                         "none")
        self.measureMode = None
        self.measureAction = None

        self.addProperty("Focus", "combo", ("none", "toolbar", "popup"),
                         "none")
        self.focusMode = None
        self.focusAction = None
        self.focusState = None
        self.focusDrawingRectangle = None
        self.focusPointSelected = None

        self.__movetoActionMosaic = None
        """
        Signal
        """
        self.defineSignal('getView', ())
        self.defineSignal('getMosaicView', ())
        self.defineSignal('getCalibration', ())
        self.defineSignal('getBeamPosition', ())
        self.defineSignal('getImage', ())
        self.defineSignal('moveDone', ())
        self.defineSignal('mosaicImageSelected', ())
        """
        Slot
        """
        self.defineSlot('beamPositionChanged', ())
        self.defineSlot('pixelCalibrationChanged', ())
        self.defineSlot('setMoveToMode', ())
        self.defineSlot('setLimitsDisplay', ())
        self.defineSlot('setMoveToState', ())
        """
        widgets - NO APPEARANCE
        """
        self.setFixedSize(0, 0)

    def propertyChanged(self, prop, oldValue, newValue):
        if prop == "Hor. Motor":
            if self.horMotHwo is not None:
                self.disconnect(self.horMotHwo, qt.PYSIGNAL('positionChanged'),
                                self.setHorizontalPosition)
                self.disconnect(self.horMotHwo, qt.PYSIGNAL("limitsChanged"),
                                self.setHorizontalLimits)

            self.horMotHwo = self.getHardwareObject(newValue)

            if self.horMotHwo is not None:
                self.connect(self.horMotHwo, qt.PYSIGNAL('positionChanged'),
                             self.setHorizontalPosition)
                self.connect(self.horMotHwo, qt.PYSIGNAL("limitsChanged"),
                             self.setHorizontalLimits)

        elif prop == "Vert. Motor":
            if self.verMotHwo is not None:
                self.disconnect(self.verMotHwo, qt.PYSIGNAL('positionChanged'),
                                self.setVerticalPosition)
                self.disconnect(self.verMotHwo, qt.PYSIGNAL("limitsChanged"),
                                self.setVerticalLimits)

            self.verMotHwo = self.getHardwareObject(newValue)

            if self.verMotHwo is not None:
                self.connect(self.verMotHwo, qt.PYSIGNAL('positionChanged'),
                             self.setVerticalPosition)
                self.connect(self.verMotHwo, qt.PYSIGNAL("limitsChanged"),
                             self.setVerticalLimits)
        #elif prop == "Focus Motor":
        #    if self.focusMotHwo is not None:
        #        self.disconnect(self.focusMotHwo,qt.PYSIGNAL('positionChanged'),
        #                        self.setFocusPosition)
        #        self.disconnect(self.focusMotHwo,qt.PYSIGNAL('limitsChanged'),
        #                        self.setFocusLimits)

        #    self.focusMotHwo = self.getHardwareObject(newValue)
        #    self.focusState = FocusState(self,self.focusMotHwo)

        #    if self.focusMotHwo is not None:
        #        self.connect(self.focusMotHwo,qt.PYSIGNAL('positionChanged'),
        #                     self.setFocusPosition)
        #        self.connect(self.focusMotHwo,qt.PYSIGNAL('limitsChanged'),
        #                     self.setFocusLimits)
        #        self.connect(self.focusMotHwo, qt.PYSIGNAL("moveDone"),
        #                     self.focusMoveFinished)
        elif prop == "Move To":
            self.movetoMode = _enumTranslate[newValue]
        elif prop == "Limits":
            self.limitsMode = _enumTranslate[newValue]
        elif prop == "Focus":
            self.focusMode = _enumTranslate[newValue]
        elif prop == "Measure":
            self.measureMode = _enumTranslate[newValue]
        elif prop == "Focus min step":
            self.focusMinStep = newValue
        elif prop == "Move to color when activate":
            if newValue == "none":
                self.movetoColorWhenActivate = None
            else:
                self.movetoColorWhenActivate = newValue
        if not self.firstCall:
            self.configureAction()

    def run(self):
        """
        get view
        """
        view = {}
        self.emit(qt.PYSIGNAL("getView"), (view, ))
        try:
            self.drawing = view["drawing"]
            self.view = view["view"]
        except:
            print "No View"
        """
        get calibration
        """
        calib = {}
        self.emit(qt.PYSIGNAL("getCalibration"), (calib, ))
        try:
            # in all this brick we work with pixel calibration in mm
            self.YSize = calib["ycalib"]
            self.ZSize = calib["zcalib"]
            if calib["ycalib"] is not None and calib["zcalib"] is not None:
                self.YSize = self.YSize * 1000
                self.ZSize = self.ZSize * 1000
        except:
            print "No Calibration"
        """
        get beam position
        """
        position = {}
        self.emit(qt.PYSIGNAL("getBeamPosition"), (position, ))
        try:
            self.YBeam = position["ybeam"]
            self.ZBeam = position["zbeam"]
        except:
            print "No Beam Position"
        """
        get mosaic view
        """
        mosaicView = {}
        self.emit(qt.PYSIGNAL('getMosaicView'), (mosaicView, ))
        try:
            self.__mosaicView = mosaicView['view']
            self.__mosaicDraw = mosaicView['drawing']
        except KeyError:
            self.__mosaicView, self.__mosaicDraw = None, None

        self.configureAction()

        self.firstCall = False

    def configureAction(self):
        """
        Move To action
        """
        if self.movetoMode is not None:
            if self.movetoAction is None:
                """
                create action
                """
                self.movetoAction = QubSelectPointAction(
                    name='Move to Beam',
                    place=self.movetoMode,
                    actionInfo='Move to Beam',
                    group='Tools')
                self.connect(self.movetoAction, qt.PYSIGNAL("StateChanged"),
                             self.movetoStateChanged)
                self.connect(self.movetoAction, qt.PYSIGNAL("PointSelected"),
                             self.pointSelected)

                if self.view is not None:
                    self.view.addAction(self.movetoAction)
                    self.oldMoveToActionColor = self.movetoAction.paletteBackgroundColor(
                    )

        else:
            if self.movetoAction is not None:
                """
                remove action
                """
                if self.view is not None:
                    self.view.delAction(self.movetoAction)
                """
                del action from view
                """
                self.disconnect(self.movetoAction,
                                qt.PYSIGNAL("PointSelected"),
                                self.pointSelected)
                self.movetoAction = None
        """
        Limits action
        """
        if self.limitsMode is not None:
            if self.limitsAction is None:
                """
                create action
                """
                self.limitsAction = QubRulerAction(name='Motor Limits',
                                                   place=self.limitsMode,
                                                   group='Tools')

                if self.view is not None:
                    self.view.addAction(self.limitsAction)
            """
            configure action
            """
            if self.horMotHwo is not None:
                mne = self.horMotHwo.getMotorMnemonic()
                self.limitsAction.setLabel(QubRulerAction.HORIZONTAL, 0, mne)

            if self.verMotHwo is not None:
                mne = self.verMotHwo.getMotorMnemonic()
                self.limitsAction.setLabel(QubRulerAction.VERTICAL, 0, mne)

        else:
            if self.limitsAction is not None:
                """
                remove action
                """
                if self.view is not None:
                    self.view.delAction(self.limitsAction)
                """
                del action from view
                """
                self.limitsAction = None

        if self.measureMode is not None:
            if self.measureAction is None:
                self.measureAction = QubOpenDialogAction(
                    parent=self,
                    name='measure',
                    iconName='measure',
                    label='Measure',
                    group='Tools',
                    place=self.measureMode)
                self.measureAction.setConnectCallBack(self._measure_dialog_new)
                logging.getLogger().info("setting measure mode")
                if self.view is not None:
                    logging.getLogger().info("adding action")
                    self.view.addAction(self.measureAction)
        else:
            if self.measureAction is not None:
                if self.view is not None:
                    self.view.delAction(self.measureAction)
                self.measureAction = None

        if self.movetoMode is not None:
            if self.__movetoActionMosaic is not None:
                self.__mosaicView.delAction(self.__movetoActionMosaic)
                self.disconnect(self.__movetoActionMosaic,
                                qt.PYSIGNAL("PointSelected"),
                                self.__mosaicPointSelected)
                self.diconnect(self.__movetoActionMosaic,
                               qt.PYSIGNAL("StateChanged"),
                               self.__movetoMosaicStateChanged)
                self.__movetoActionMosaic = None

            if self.__mosaicView is not None:
                self.__movetoActionMosaic = QubSelectPointAction(
                    name='Move to Beam',
                    place=self.movetoMode,
                    actionInfo='Move to Beam',
                    mosaicMode=True,
                    residualMode=True,
                    group='Tools')
                self.connect(self.__movetoActionMosaic,
                             qt.PYSIGNAL("PointSelected"),
                             self.__mosaicPointSelected)
                self.connect(self.__movetoActionMosaic,
                             qt.PYSIGNAL("StateChanged"),
                             self.__movetoMosaicStateChanged)

                self.__mosaicView.addAction(self.__movetoActionMosaic)
                self.__oldMoveToMosaicActionColor = self.__movetoActionMosaic.paletteBackgroundColor(
                )

        if self.focusMode is not None:
            if self.focusAction is None:
                self.focusAction = QubToggleAction(label='Autofocus',
                                                   name='autofocus',
                                                   place=self.focusMode,
                                                   group='Tools',
                                                   autoConnect=True)
                qt.QObject.connect(self.focusAction,
                                   qt.PYSIGNAL('StateChanged'),
                                   self.showFocusGrab)

            if self.view and self.drawing:
                self.focusDrawingRectangle, _ = QubAddDrawing(
                    self.drawing, QubPointDrawingMgr,
                    QubCanvasHomotheticRectangle)
                self.focusDrawingRectangle.setDrawingEvent(
                    QubMoveNPressed1Point)
                self.focusDrawingRectangle.setKeyPressedCallBack(
                    self.focusRawKeyPressed)

                qt.QObject.connect(self.drawing,
                                   qt.PYSIGNAL("ForegroundColorChanged"),
                                   self.focusDrawingRectangle.setColor)
                self.focusDrawingRectangle.setEndDrawCallBack(
                    self.setFocusPointSelected)
                self.focusRectangleSize = 12
                self.focusDrawingRectangle.setWidthNHeight(
                    self.focusRectangleSize, self.focusRectangleSize)
                self.view.addAction(self.focusAction)

        elif self.view is not None:
            self.view.delAction(self.focusAction)
            self.focusDrawingRectangle = None

    def _measure_dialog_new(self, openDialogAction, aQubImage):
        if self.YSize is not None and self.ZSize is not None:
            self.__measureDialog = QubMeasureListDialog(
                self,
                canvas=aQubImage.canvas(),
                matrix=aQubImage.matrix(),
                eventMgr=aQubImage)
            self.__measureDialog.setXPixelSize(self.YSize / 1000.0)
            self.__measureDialog.setYPixelSize(self.ZSize / 1000.0)
            self.__measureDialog.connect(aQubImage,
                                         qt.PYSIGNAL("ForegroundColorChanged"),
                                         self.__measureDialog.setDefaultColor)
            openDialogAction.setDialog(self.__measureDialog)

    def setHorizontalPosition(self, newPosition):
        if self.limitsAction is not None:
            self.limitsAction.setCursorPosition(QubRulerAction.HORIZONTAL, 0,
                                                newPosition)

    def setHorizontalLimits(self, limit):
        if self.limitsAction is not None:
            self.limitsAction.setLimits(QubRulerAction.HORIZONTAL, 0, limit[0],
                                        limit[1])

    def setVerticalPosition(self, newPosition):
        if self.limitsAction is not None:
            self.limitsAction.setCursorPosition(QubRulerAction.VERTICAL, 0,
                                                newPosition)

    def setVerticalLimits(self, limit):
        if self.limitsAction is not None:
            self.limitsAction.setLimits(QubRulerAction.VERTICAL, 0, limit[0],
                                        limit[1])

    #def setFocusLimits(self,limit) :
    #    self.focusState.setLimit(limit)

    #def setFocusPosition(self,newPosition) :
    #    self.focusState.newPosition(newPosition)

    #def focusMoveFinished(self, ver, mne):
    #    self.focusState.endMovement(ver)

    #def focusRawKeyPressed(self,keyevent) :
    #    key = keyevent.key()
    #    if key == qt.Qt.Key_Plus:
    #        self.focusRectangleSize += 3
    #        if self.focusRectangleSize > 99:
    #            self.focusRectangleSize = 99
    #    elif key == qt.Qt.Key_Minus:
    #        self.focusRectangleSize -= 3
    #        if self.focusRectangleSize < 12:
    #            self.focusRectangleSize = 12
    #    else: return
    #
    #    self.focusDrawingRectangle.setWidthNHeight(self.focusRectangleSize,self.focusRectangleSize)

    #def showFocusGrab(self,state) :
    #    self.focusPointSelected = None
    #    if state:
    #        self.focusDrawingRectangle.startDrawing()
    #    else:
    #        self.focusDrawingRectangle.stopDrawing()
    #        self.focusDrawingRectangle.hide()
    #        self.focusPointSelected = None

    #def setFocusPointSelected(self,drawingMgr) :
    #    self.focusPointSelected = drawingMgr.point()
    #    if self.focusMotHwo is not None:
    #        self.focusState.start()

    def beamPositionChanged(self, beamy, beamz):
        self.YBeam = beamy
        self.ZBeam = beamz

    def pixelCalibrationChanged(self, sizey, sizez):
        if sizey is not None:
            self.YSize = sizey * 1000
            try:
                self.__measureDialog.setXPixelSize(sizey)
            except:
                pass
        else:
            self.YSize = None

        if sizez is not None:
            self.ZSize = sizez * 1000
            try:
                self.__measureDialog.setYPixelSize(sizez)
            except:
                pass
        else:
            self.ZSize = None

    def setMoveToState(self, state):
        if self.movetoAction is not None:
            self.movetoAction.setState(state)

    def movetoStateChanged(self, state):
        if self.movetoColorWhenActivate:
            if state:
                self.movetoAction.setPaletteBackgroundColor(
                    qt.QColor(self.movetoColorWhenActivate))
            else:
                self.movetoAction.setPaletteBackgroundColor(
                    self.oldMoveToActionColor)

    def pointSelected(self, drawingMgr):
        if self.horMotHwo is not None and self.verMotHwo is not None:
            if  self.YSize is not None and \
                self.ZSize is not None and \
                self.YBeam is not None and \
                self.ZBeam is not None :

                self.drawingMgr = drawingMgr

                (y, z) = drawingMgr.point()

                self.drawingMgr.stopDrawing()

                sign = 1
                if self.horMotHwo.unit < 0:
                    sign = -1
                movetoy = -sign * (self.YBeam - y) * self.YSize

                sign = 1
                if self.verMotHwo.unit < 0:
                    sign = -1
                movetoz = -sign * (self.ZBeam - z) * self.ZSize

                self.motorArrived = 0

                self.connect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                             self.moveFinished)
                self.connect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                             self.moveFinished)

                self.horMotHwo.moveRelative(movetoy)
                self.verMotHwo.moveRelative(movetoz)

    def __movetoMosaicStateChanged(self, state):
        if self.movetoColorWhenActivate:
            if state:
                self.__movetoActionMosaic.setPaletteBackgroundColor(
                    qt.QColor(self.movetoColorWhenActivate))
            else:
                self.__movetoActionMosaic.setPaletteBackgroundColor(
                    self.__oldMoveToMosaicActionColor)

    def __mosaicPointSelected(self, drawingMgr):
        point = drawingMgr.mosaicPoints()
        try:
            point = point[0]
            beamY, beamZ = point.refPoint
            YSize, ZSize = point.calibration
            horMotorPos, verMotorPos = point.absPoint
            y, z = point.point
            imageId = point.imageId
        except TypeError:
            return  # The click wasn't on image

        self.drawingMgr = drawingMgr

        drawingMgr.stopDrawing()

        sign = 1
        if self.horMotHwo.unit < 0:
            sign = -1
        movetoy = horMotorPos - sign * (beamY - y) * YSize

        sign = 1
        if self.verMotHwo.unit < 0:
            sign = -1
        movetoz = verMotorPos - sign * (beamZ - z) * ZSize

        self.motorArrived = 0

        self.connect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                     self.moveFinished)
        self.connect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                     self.moveFinished)

        self.horMotHwo.move(movetoy)
        self.verMotHwo.move(movetoz)

        self.emit(qt.PYSIGNAL("mosaicImageSelected"), (imageId, ))

    def moveFinished(self, ver, mne):
        if mne == self.horMotHwo.getMotorMnemonic():
            self.disconnect(self.horMotHwo, qt.PYSIGNAL("moveDone"),
                            self.moveFinished)
            self.motorArrived = self.motorArrived + 1

        if mne == self.verMotHwo.getMotorMnemonic():
            self.disconnect(self.verMotHwo, qt.PYSIGNAL("moveDone"),
                            self.moveFinished)
            self.motorArrived = self.motorArrived + 1

        if self.motorArrived == 2:
            self.drawingMgr.startDrawing()
            self.motorArrived = 0
            self.emit(qt.PYSIGNAL("moveDone"), (self.YBeam, self.ZBeam))
Esempio n. 4
0
class CameraBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.camera       = None
        self.update_disabled = False
        self.__cameraName = None

        self.__zoomList = [1.5,2,2.5,3,3.5,4]
        self.__initZoom = 2

        self.__fixWidth  = -1
        self.__fixHeight = -1

        self.__swapRgb = True
                        ####### PRINT #######
        self.__printWidget = QubPrintPreview(self)
        self.__printWidget.resize(400,500)
        printer = qt.QPrinter()
        printer.setOutputToFile(1)
        printer.setOutputFileName('/tmp/print_file.ps')
        self.__printWidget.setPrinter(printer)
        self.__printWidget.update()

        self.__beamAction    = None
        self.__scaleAction   = None
        self.__chosenActions = {}
        self.__wholeActions  = []
        self.__measureDialog = None

        ####### PRINT ACTION #######
        printAction = QubPrintPreviewAction(name="print",group="admin",withVectorMenu=True)
        printAction.previewConnect(self.__printWidget)
        self.__wholeActions.append(printAction)

        ####### SAVE IMAGE #######
        self.__saveAction = QubSaveImageAction(parent=self, label='Save falcon image',
                                               name="save", group="admin")
        self.__saveAction.setConnectCallBack(self._save_dialog_new)
        self.__wholeActions.append(self.__saveAction)
        self.__defaultSavePath = '/tmp'

        ####### UPDATE #######
        update = QubToggleAction(name="update",group="image",initState=True)
        self.connect(update,qt.PYSIGNAL("StateChanged"),self.__cameraUpdate)
        self.__wholeActions.append(update)

        ####### Start Camera ######
        startCamera = QubToggleAction(name="startCamera", group="image", iconName = 'bright-cont', initState=True)
        self.connect(startCamera, qt.PYSIGNAL("StateChanged"), self.__cameraStart)
        self.__wholeActions.append(startCamera)


        ####### BRIGHTNESS/CONTRAST #######
        self.__brightcount = QubOpenDialogAction(name="bright-cont",
                                                 iconName = 'bright-cont', group="image")
        self.__brightcount.setDialog(QubBrightnessContrastDialog(self))
        self.__wholeActions.append(self.__brightcount)

        ###### Grid TOOL ######
        self.__gridToolAction = QubOpenDialogAction(parent=self, name='grid_tool',
                                                    iconName='rectangle', label='Grid tool',
                                                    group="Tools") #place="contextmenu")
        self.__gridDialog = GridDialog(self, "Grid Dialog", flags = qt.Qt.WStyle_StaysOnTop)
        self.__gridToolAction.setConnectCallBack(self._grid_dialog_connect_hdlr)
        self.__wholeActions.append(self.__gridToolAction)

        self.__previous_pos_dict = {}
        self.__beamWidth = 0
        self.__beamHeight = 0

        ####### BEAM ACTION #######
        self.__beamAction = QubBeamAction(name="beam", group="Tools")
        self.__wholeActions.append(self.__beamAction)
        self.connect(self.__beamAction,qt.PYSIGNAL("BeamSelected"),
                     self.beamSelection)

        ####### SCALE #######
        self.__scaleAction = QubScaleAction(name='scale',group='Tools')
        self.__wholeActions.append(self.__scaleAction)
        self.__wholeActions.extend(self.__creatStdActions())

        ####### ACTION INFO #######
        actionInfo = QubInfoAction(name="actionInfo", group="image",place="statusbar")
        self.__wholeActions.append(actionInfo)

        ####### CHANGE FOREGROUND COLOR #######
        self.__fcoloraction = QubForegroundColorAction(name="color", group="image")
        self.__wholeActions.append(self.__fcoloraction)

        ####### MEASURE #######
        self.__measureAction = QubOpenDialogAction(parent=self, name='measure',
                                            iconName='measure', label='Measure',
                                            group="Tools")
        self.__measureAction.setConnectCallBack(self._measure_dialog_new)
        self.__wholeActions.append(self.__measureAction)

        # ###### POSITION TOOL ######
        # self.__posToolAction = QubOpenDialogAction(parent=self, name='pos_tool',
        #                                            iconName='circle', label='Position tool',
        #                                            group="Tools")
        # self.__posToolAction.setConnectCallBack(self._line_dialog_new)
        # self.__wholeActions.append(self.__posToolAction)

        ####### ZOOM LIST #######
        zoomActionList = QubZoomListAction(place = "toolbar",
                                           initZoom = 1,zoomValList = [0.1,0.25,0.5,0.75,1,1.5,2],
                                           show = 1,group = "zoom")
        self.__wholeActions.append(zoomActionList)

        ####### ZOOM Action #######
        self.__zoomFitOrFill = QubZoomAction(place = "toolbar",group = "zoom")
        self.__wholeActions.append(self.__zoomFitOrFill)

        ####### LINK ZOOM ACTION #######
        self.__zoomFitOrFill.setList(zoomActionList)
        zoomActionList.setActionZoomMode(self.__zoomFitOrFill)

        ####### ZOOM WINDOW #######
        self.__zoomAction = QubZoomRectangle(label='Zoom Crop',place="toolbar", show=1, group="zoom")
        self.connect(self.__zoomAction,qt.PYSIGNAL("Actif"),self.__hide_show_zoom)
        self.__wholeActions.append(self.__zoomAction)

        self.__splitter = qt.QSplitter(qt.Qt.Horizontal,self)
        self.__splitter.show()

        self.__mainVideo = QubPixmapDisplayView(self.__splitter)
        self.__mainVideo.show()
        self.__mainVideo.setScrollbarMode('Auto')
        self.__mainPlug = _MainVideoPlug(self.__mainVideo,self.__zoomAction)

        actions = self.__creatStdActions()

        ####### ZOOM LIST #######
        self.__zoomActionList = QubZoomListAction(place = "toolbar",keepROI = True,
                                                  initZoom = self.__initZoom,zoomValList = self.__zoomList,
                                                  show = 1,group = "zoom")
        actions.insert(0,self.__zoomActionList)

        ####### ZOOM Action #######
        zoomFitOrFill = QubZoomAction(place = "toolbar",keepROI = True,group = "zoom")
        zoomFitOrFill.setList(self.__zoomActionList)
        self.__zoomActionList.setActionZoomMode(zoomFitOrFill)
        actions.append(zoomFitOrFill)

        self.__zoomVideo = QubPixmapDisplayView(self.__splitter,None,actions)
        self.__zoomVideo.hide()
        self.__zoomPlug = _ZoomPlug(self.__zoomVideo)
        self.__zoomPlug.zoom().setZoom(2,2)
        self.__cbk = _rectangleZoom(self.__zoomAction,self.__zoomPlug)

        layout = qt.QHBoxLayout(self,0,0,"layout")
        layout.addWidget(self.__splitter)

        self.__image2Pixmap = QubImage2Pixmap()
        self.__image2Pixmap.plug(self.__mainPlug)
        self.__zoomPlug.setPoller(self.__image2Pixmap)

        self.__jpegDecompress = QubStdData2Image()
        self.__jpegDecompress.setSwapRGB(True)
        self.__jpeg2image = None

        ####### PROPERTY #######
        self.addProperty('camera','string','')
        self.addProperty('zoom list','string',','.join([str(x) for x in self.__zoomList]))
        self.addProperty('init zoom','integer',self.__initZoom)
        self.addProperty('swap rgb','boolean',True)

        self.addProperty('fix : width','integer',-1)
        self.addProperty('fix : height','integer',-1)

        self.addProperty('action : print','boolean',True)
        self.addProperty('action : save image','boolean',True)
        self.addProperty('action : update','boolean',True)
        self.addProperty('action : startCamera','boolean',True)
        self.addProperty('action : brightness contrast','boolean',True)
        self.addProperty('action : beam','boolean',True)
        self.addProperty('action : scale','boolean',True)
        self.addProperty('action : change foreground color','boolean',True)
        self.addProperty('action : measure','boolean',True)
        self.addProperty('action : measure (place)', 'combo', ('toolbar','contextmenu'),'toolbar')
        self.addProperty('action : zoom window','boolean',True)
        self.addProperty('action : zoom fit or fill','boolean',True)
        self.addProperty('action : zoom list','boolean',True)
        self.addProperty('action : x,y coordinates','boolean',True)
        self.addProperty('action : default color','combo',('black','red','green'),'black')

        self.addProperty('action : save image (place)',"combo",('toolbar','contextmenu'),'toolbar')
        self.addProperty('action : save image (default path)',"string",'/tmp')
        self.addProperty('action : save image (show always configure)',"boolean",True)

        self.addProperty("diffractometer", "string", "")
        self.diffractometerHwobj = None


        ####### SIGNAL #######
        self.defineSignal("BeamPositionChanged", ())

        ####### SLOT #######
        self.defineSlot("changeBeamPosition", ())
        self.defineSlot("changePixelScale",())
        self.defineSlot('getView',())
        self.defineSlot('getImage',())

        ####### LINK VIEW AND SUB VIEW #######
        mainView = self.__mainVideo.view()
        zoomView = self.__zoomVideo.view()
        mainView.addEventMgrLink(zoomView,
                                 mainView.canvas(),zoomView.canvas(),
                                 mainView.matrix(),zoomView.matrix())

        self.imageReceivedConnected = None

    def safeConnect(self):
        if not self.imageReceivedConnected and self.camera is not None:
            #print "CONNECTING 0"
            self.camera.connect('imageReceived', self.__imageReceived)
            #self.connect(self.camera,qt.PYSIGNAL('imageReceived'),self.__imageReceived)
            self.imageReceivedConnected = False

    def safeDisconnect(self):
        if self.imageReceivedConnected and self.camera is not None:
            #print "DISCONNECTING 3"
            self.camera.disconnect('imageReceived', self.__imageReceived)
            #self.disconnect(self.camera,qt.PYSIGNAL('imageReceived'),self.__imageReceived)
            self.imageReceivedConnected = False

    def disable_update(self):
        #self.__imageReceived(DISABLED_JPEG,DISABLED_WIDTH,DISABLED_HEIGHT)
        self.update_disabled = True

    def enable_update(self):
        self.update_disabled = False

    def __imageReceived(self,image,width,height,force_update=False):
        if self.update_disabled:
            return

        if not force_update:
            if not self.isVisible():
                return
        
        if isinstance(image,qt.QImage):
            if self.__swapRgb:
                image = image.swapRGB()
            self.__jpeg2image.setImage(image,image)
        else:
            self.__jpegDecompress.putData(image,width,height)

    def propertyChanged(self,property,oldValue,newValue):
        if property=='camera':
            #if self.camera is not None and not self.isRunning():
            #    self.safeDisconnect()
            self.safeDisconnect()
            self.camera      = self.getHardwareObject(newValue)
            self.__hwoName   = newValue

            if self.camera is not None:
		try:
                    self.__tangoName = self.camera.tangoname
		except:
		    self.__tangoName = ""

                try:
                    camera_role=self.camera.getDeviceByRole('camera')
                    if camera_role is not None:
                        self.camera=camera_role
                except AttributeError:
                    pass

                self.__brightcount.setCamera(self.camera)

        elif property == 'zoom list' :
            zoomList = [float(x) for x in newValue.split(',')]
            if zoomList != self.__zoomList :
                self.__zoomList = zoomList
                self.__zoomActionList.changeZoomList(zoomList,self.__initZoom)
        elif property == 'init zoom' :
            if newValue != self.__initZoom :
                self.__initZoom = newValue
                self.__zoomActionList.changeZoomList(self.__zoomList,newValue)
        elif property == 'swap rgb' :
            self.__jpegDecompress.setSwapRGB(newValue)
            self.__swapRgb = newValue
        elif property == 'action : print' : self.__chosenActions['print'] = newValue
        elif property == 'action : save image' : self.__chosenActions['save'] = newValue
        elif property == 'action : update' : self.__chosenActions['update'] = newValue
        elif property == 'action : startCamera' : self.__chosenActions['startCamera'] = newValue
        elif property == 'action : brightness contrast' : self.__chosenActions['bright-cont'] = newValue
        elif property == 'action : beam' : self.__chosenActions['beam'] = newValue
        elif property == 'action : scale' : self.__chosenActions['scale'] = newValue
        elif property == 'action : change foreground color' : self.__chosenActions['color'] = newValue
        elif property == 'action : measure' : self.__chosenActions['measure'] = newValue
        elif property == 'action : zoom window' : self.__chosenActions['zoomrect'] = newValue
        elif property == 'action : zoom fit or fill' : self.__chosenActions['Zoom tools'] = newValue
        elif property == 'action : zoom list' : self.__chosenActions['zoomlist'] = newValue
        elif property == 'action : x,y coordinates' : self.__chosenActions['position'] = newValue
        elif property == 'action : default color' : self.__chosenDefaultColor = newValue
        elif property == 'action : save image (place)' :
            self.__saveAction.setPlace(newValue,True)
        elif property == 'action : measure (place)':
            self.__measureAction.setPlace(newValue, True)
        elif property == 'action : save image (default path)' :
            self.__defaultSavePath = newValue
        elif property == 'action : save image (show always configure)' :
            self.__saveAction.setConfigureOnClick(newValue)

        elif property == 'fix : width' : self.__fixWidth = newValue
        elif property == 'fix : height': self.__fixHeight = newValue
        elif property == "diffractometer":
            self.diffractometerHwobj = self.getHardwareObject(newValue)
            if self.diffractometerHwobj is not None:
                self.__previous_pos_dict = self.diffractometerHwobj.getPositions()
                self.diffractometerHwobj.connect("minidiffStateChanged",
                                                 self.diffractometerChanged)
                if self.diffractometerHwobj.zoomMotor is not None:    
                    zoom = self.diffractometerHwobj.zoomMotor.getPosition()
                    xSize,ySize = self.diffractometerHwobj.getCalibrationData(zoom)
                    #xSize,ySize = self.__scaleAction.xPixelSize(), self.__scaleAction.yPixelSize()
                    self.diffractometerHwobj.getBeamInfo(self.__getBeamInfo)
                    beam_pos_x = self.diffractometerHwobj.getBeamPosX()
                    beam_pos_y = self.diffractometerHwobj.getBeamPosY()


                    self.__gridDialog.set_x_pixel_size(xSize)
                    self.__gridDialog.set_y_pixel_size(ySize)
                    self.__gridDialog.set_beam_position(beam_pos_x, beam_pos_y,
                                                 self.__beamWidth, self.__beamHeight)

    def run(self) :
        chosenActions = []

        for action in self.__wholeActions :
            if self.__chosenActions.get(action.name(), True) :
                chosenActions.append(action)

        self.__mainVideo.addAction(chosenActions)

        if not self.__chosenActions.get('update', False) :
            self.__cameraUpdate(True)

        if not self.__chosenActions.get('startCamera', False) :
            self.__cameraStart(True)

        if self.__fixWidth != -1 and self.__fixHeight != -1 :
            self.__mainVideo.view().setFixedSize(self.__fixWidth + 4,self.__fixHeight + 4)

        self.__startIdle = qt.QTimer(self)
        qt.QObject.connect(self.__startIdle,qt.SIGNAL('timeout()'),self.__idleRun)
        self.__startIdle.start(0)

    def __idleRun(self) :
        self.__startIdle.stop()
        self.__fcoloraction.setColor(self.__chosenDefaultColor)
        self.__mainVideo.view().setForegroundColor(qt.QColor(self.__chosenDefaultColor))

    def stop(self) :
        self.safeDisconnect()

    def beamSelection(self,x,y) :
        self.emit(qt.PYSIGNAL("BeamPositionChanged"), (x,y))
        self.changeBeamPosition(x,y)

    def changeBeamPosition(self, x, y, beam_width=None, beam_height=None):
        self.__beamAction.setBeamPosition(x, y)
        try:
            if not beam_width:
                beam_width = self.__beamWidth

            if not beam_height:
                beam_height = self.__beamHeight

            self.__gridDialog.set_beam_position(x, y, beam_width, beam_height)
        except:
            pass

    def changePixelScale(self,sizex,sizey) :
        self.__scaleAction.setXPixelSize(sizex)
        self.__scaleAction.setYPixelSize(sizey)
        if self.__measureDialog :
            self.__measureDialog.setXPixelSize(sizex)
            self.__measureDialog.setYPixelSize(sizey)

        self.__gridDialog.set_x_pixel_size(sizex)
        self.__gridDialog.set_y_pixel_size(sizey)

    def getView(self,key):
        try:
            key['drawing'] = self.__mainVideo.view()
            key['view']    = self.__mainVideo
            key['hwname']  = self.__hwoName
            key['dsname']  = self.__tangoName
        except:
            pass

    def getImage(self,key) :
        if self.__jpeg2image is not None :
            try:
                key['image'] = self.__jpeg2image.getLastImage()
            except:
                pass

    def __creatStdActions(self) :
        actions = []
        ####### MOUSE POSITION #######
        posaction = QubPositionAction(name="position", group="image",place="statusbar")
        actions.append(posaction)

        return actions

    def __cameraUpdate(self,onoff) :
        if onoff :
            self.__jpeg2image = _Jpeg2ImagePlug(self.__image2Pixmap)
            self.__jpegDecompress.plug(self.__jpeg2image)
            if self.camera is not None:
                imageInfo = self.camera.imageType()
            else:
                imageInfo = None
            imType    = self.__jpegDecompress.STANDARD
            if imageInfo :
                if imageInfo.type() == 'bayer': imType = self.__jpegDecompress.BAYER_RG
                elif imageInfo.type() == 'raw': imType = self.__jpegDecompress.RAW
            self.__jpegDecompress.setImageType(imType)
            self.safeConnect()
        else:
            self.safeDisconnect()
            self.__jpeg2image.setEnd()

    def __cameraStart(self, onoff) :
        if onoff :
            print "********************************************************Set the camera ON"
            if self.camera is not None:
                self.camera.setLive(True)
            else:
                print "camera is none"
        else:
            print "****************************************************Set the camera off"
            if self.camera is not None:
                print "camera :"
                print self.camera
                self.camera.setLive(False)
            else:
                print "camera is none"

    def __hide_show_zoom(self,actif) :
        if actif :
            if self.__chosenActions['Zoom tools'] :
                self.__zoomFitOrFill.setState(True)
            else:
                self.__mainVideo.setScrollbarMode('Fit2Screen')
            self.__zoomPlug.start()
            self.__zoomVideo.show()
            splitterWidth = self.__splitter.width()
            self.__splitter.setSizes([splitterWidth/3,splitterWidth - splitterWidth/3])
        else:
            if self.__chosenActions['Zoom tools'] :
                self.__zoomFitOrFill.setState(False)
            else:
                self.__mainVideo.setScrollbarMode('Auto')
            self.__zoomPlug.stop()
            self.__zoomVideo.hide()

    def _measure_dialog_new(self,openDialogAction,aQubImage) :
        try :
            self.__measureDialog = QubMeasureListDialog(self,
                                                        canvas=aQubImage.canvas(),
                                                        matrix=aQubImage.matrix(),
                                                        eventMgr=aQubImage)
            xSize,ySize = self.__scaleAction.xPixelSize(),self.__scaleAction.yPixelSize()
            self.__measureDialog.setXPixelSize(xSize)
            self.__measureDialog.setYPixelSize(ySize)
            self.__measureDialog.connect(aQubImage, qt.PYSIGNAL("ForegroundColorChanged"),
                                         self.__measureDialog.setDefaultColor)
            openDialogAction.setDialog(self.__measureDialog)
        except:
            import traceback
            traceback.print_exc()

    def _grid_dialog_connect_hdlr(self,openDialogAction, aQubImage) :
        try :
            self.__gridDialog.set_qub_event_mgr(aQubImage)
            openDialogAction.setDialog(self.__gridDialog)
        except:
            import traceback
            traceback.print_exc()

    def __getBeamInfo(self, ret):
        self.__beamWidth = float(ret["size_x"])
        self.__beamHeight = float(ret["size_y"])
        #self.__beamShape = ret["shape"]

    def _save_dialog_new(self,openDialogAction,aQubImage) :
        saveDialog = QubSaveImageDialog(self,matrix=aQubImage.matrix(),canvas=aQubImage.canvas())
        saveDialog.setImage2Pixmap(self.__image2Pixmap)
        saveDialog.setSavePath(self.__defaultSavePath)
        openDialogAction.setDialog(saveDialog)

    def instanceMirrorChanged(self,mirror):
        #print "INSTANCEMIRRORCHANGED",mirror,BlissWidget.isInstanceMirrorAllow()
        return
        if BlissWidget.isInstanceModeSlave():
            if BlissWidget.isInstanceMirrorAllow():
                self.safeConnect()
            else:
                self.safeDisconnect()

    def diffractometerChanged(self, *args):
        """
        Handles diffractometer change events, connected to the signal 
        minidiffStateChanged of the diffractometer hardware object.
        """
        
        if self.diffractometerHwobj.isReady():
            pos_dict = self.diffractometerHwobj.getPositions()
            p1 = self.diffractometerHwobj.motor_positions_to_screen(self.__previous_pos_dict)
            p2 = (self.diffractometerHwobj.getBeamPosX(), self.diffractometerHwobj.getBeamPosY())

            dx = p2[0] - p1[0]
            dy = p2[1] - p1[1]

            if dy != 0:
                self.__gridDialog.move_grid_ver(-dy)

            if dx != 0:
                self.__gridDialog.move_grid_hor(-dx)

            #print dx, dy

            self.__previous_pos_dict = pos_dict