Esempio n. 1
0
    def setModel(self, model):
        TaurusBaseWidget.setModel(self, model)
        plot = self.get_plot()

        if self.image is not None:
            self.disconnect(self.image.getSignaller(),
                            Qt.SIGNAL("dataChanged"),
                            self.update_cross_sections)
            plot.del_item(self.image)
            del self.image

        self.unregisterEvents()

        if model is None:
            return

        beamviewer = self.getPluginDevice('beamviewer')
        if not beamviewer:
            return

        image_attr = beamviewer.getAttribute('VideoImage')

        param = ImageParam()
        param.interpolation = 0  # None (nearest pixel)

        self.image = LimaVideoImageItem(param)
        self.image.setModel(image_attr)

        self.connect(self.image.getSignaller(), Qt.SIGNAL("dataChanged"),
                     self.update_cross_sections)

        plot.add_item(self.image)
        self.registerEvents()
Esempio n. 2
0
    def __init__(self, parent=None):
        #self.call__init__wo_kw(Qt.QToolButton, parent)
        Qt.QToolButton.__init__(self, parent)
        self.setLayout(Qt.QVBoxLayout())

        from taurus.qt.qtgui.display import TaurusLed
        self._led = TaurusLed()
        self._label = Qt.QLabel()
        self.layout().addWidget(self._led)
        self.layout().addWidget(self._label)
        self.layout().setAlignment(Qt.Qt.AlignCenter)
Esempio n. 3
0
def setup_pressure_trend(tt, log=True, length=12 * 3600):
    print '*' * 80
    print 'in setup_pressure_trend(%s,length=%s s)' % (tt, length)
    from PyQt4 import Qwt5
    try:
        #n,w = str(qtw.tabText(qtw.count()-1)),qtw.widget(qtw.count()-1)
        #qtw.insertTab(0,w,n)
        tt.setXDynScale(True)
        xMax = time.time()  #tt.axisScaleDiv(Qwt5.QwtPlot.xBottom).upperBound()
        #xMin = tt.axisScaleDiv(Qwt5.QwtPlot.xBottom).lowerBound()
        rg = length  #abs(self.str2deltatime(str(self.ui.xRangeCB.currentText())))
        xMin = xMax - rg
        tt.setAxisScale(Qwt5.QwtPlot.xBottom, xMin, xMax)
        if log:
            tt.setAxisScaleType(Qwt5.QwtPlot.yLeft,
                                Qwt5.QwtScaleTransformation.Log10)
            #tt.setAxisScale(Qwt5.QwtPlot.yLeft,1e-11,1e-2)
        tt.setUseArchiving(False)
        tt.setModelInConfig(False)
        tt.disconnect(tt.axisWidget(tt.xBottom),
                      Qt.SIGNAL("scaleDivChanged ()"), tt._scaleChangeWarning)
        #tt.setCurvesYAxis([tcs],tt.yRight)
        #: Disabling loading of configuration from file; to avoid a faulty setup to continuously crash the application.
        setattr(tt, 'applyConfig', (lambda *k, **kw: None))
    except:
        print 'Exception in set_pressure_trend(%s)' % tt
        print traceback.format_exc()
    print '*' * 80
Esempio n. 4
0
 def on_click(self, kind, name):
     """The default behavior is to mark a clicked device and to zoom to a clicked section.
     Override this function if you need something else."""
     if kind == "device":
         self.select_devices([name])
         self.emit(Qt.SIGNAL("graphicItemSelected(QString)"), name)
     elif kind == "section":
         self.zoom_to_section(name)
Esempio n. 5
0
 def setModel(self, model, action):
     #print 'DomainButton.setModel(%s,%s)'%(model,action)
     self._model = model
     self._led.setModel(model)
     if not self._label.text(): self.setLabel(model.split('/')[0])
     self._cmd = action  #action.split()
     self._action = taurus.qt.qtgui.util.ExternalAppAction(
         cmdargs=self._cmd)
     self.connect(self, Qt.SIGNAL("pressed()"), self.show)
Esempio n. 6
0
def main(args):

    import sys, re, traceback, taurus
    assert len(
        args
    ) > 1, '\n\nUsage:\n\t> python panel.py [a/device/name or synoptic.jdw] [--attrs] [attr_regexps] --comms [comm_regexps]'

    model = args[1]
    taurus.setLogLevel(taurus.core.util.Logger.Debug)
    app = Qt.QApplication(args)
    form = None

    if re.match('[\w-]+/[\w-]+/[\w-]+.*', model):

        print 'loading a device panel'
        k, filters = '--attrs', fandango.defaultdict(list)
        for f in args[2:]:
            if f.startswith('--'): k = f.strip('-')
            else: filters[k].append(f)  #(f,()) if k=='comms' else f)

        form = VaccaPanel(filters=filters)  #palette=get_fullWhite_palette()
        form.setModel(model)

    elif model.lower().endswith('.jdw'):
        print 'loading a synoptic'
        form = taurus.qt.qtgui.graphic.TauJDrawSynopticsView(
            designMode=False,
            updateMode=taurus.qt.qtgui.graphic.TauJDrawSynopticsView.
            NoViewportUpdate)
        #FullViewportUpdate, : AWFUL CPU USAGE!!!!!!!!
        #MinimalViewportUpdate, : Qt Defaults
        #SmartViewportUpdate, : ?
        #BoundingRectViewportUpdate, : ?
        #NoViewportUpdate : Tau defaults
        form.setModel(model)
        models = form.get_item_list()
        for m in models:
            m = str(m)
            if m.count('/') == 2: m += '/state'
            period = 120000.
            try:
                taurus.Attribute(m).changePollingPeriod(period)
            except:
                print '(%s).changePollingPeriod(%s): Failed: %s' % (
                    m, period, traceback.format_exc())

    print 'showing ...'
    form.show()
    sys.exit(app.exec_())
Esempio n. 7
0
    def setModel(self, model):
        if not hasattr(self, '_layout'):
            self._layout = Qt.QVBoxLayout()
            self.setLayout(self._layout)

        print('In SimplePanel.setModel(%s)' % model)
        prev = self.getInnerPanel()
        print('previous was %s,%s' % (prev, prev and prev.getModel()))
        old = prev and prev.getModel()
        if prev:
            try:
                print('\t dettaching %s' % old)
                self._layout.removeWidget(prev)
                #prev.setModel(None)
            except:
                traceback.print_exc()
        self.innerPanel = TaurusDevicePanel()
        self.innerPanel.setModel(model)
        self._layout.addWidget(self.innerPanel)
Esempio n. 8
0
 def __init__(self, preffix='', suffix='', labels=False, parent=None):
     TaurusWidget.__init__(self, parent)
     self.preffix = preffix
     self.suffix = suffix
     self.labels = labels
     if preffix or suffix:
         self.setWindowTitle('%s ... %s' % (preffix, suffix))
     self.setLayout(Qt.QVBoxLayout())
     self.bar = Qt.QWidget(self)
     self.search = Qt.QLineEdit()
     self.button = Qt.QPushButton('Load')
     self.connect(self.button, Qt.SIGNAL("pressed()"), self.apply_search)
     self.bar.setLayout(Qt.QHBoxLayout())
     self.bar.layout().addWidget(self.search)
     self.bar.layout().addWidget(self.button)
     self.layout().addWidget(self.bar)
     self.form = TaurusForm(self)
     self.layout().addWidget(self.form)
Esempio n. 9
0
    def contextMenuEvent(self, event):
        action_device_panel = Qt.QAction(self)
        action_device_panel.setText('Show Device Panel')
        self.connect(action_device_panel, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().showDevicePanel)

        action_move_in = Qt.QAction(self)
        action_move_in.setText('Move In')
        self.connect(action_move_in, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().moveIn)

        action_move_out = Qt.QAction(self)
        action_move_out.setText('Move Out')
        self.connect(action_move_out, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().moveOut)

        menu = Qt.QMenu(self)
        menu.addAction(action_device_panel)
        menu.addSeparator()
        menu.addAction(action_move_in)
        menu.addAction(action_move_out)
        menu.exec_(event.globalPos())
        event.accept()
Esempio n. 10
0
def pickPlotPoint(self,
                  pos,
                  scope=20,
                  showMarker=True,
                  targetCurveNames=None,
                  xlabels=None):
    '''Finds the pyxel-wise closest data point to the given position. The
    valid search space is constrained by the scope and targetCurveNames
    parameters.

    :param pos: (Qt.QPoint or Qt.QPolygon) the position around which to look
                for a data point. The position should be passed as a
                Qt.QPoint (if a Qt.QPolygon is given, the first point of the
                polygon is used). The position is expected in pixel units,
                with (0,0) being the top-left corner of the plot
                canvas.

    :param scope: (int) defines the area around the given position to be
                    considered when searching for data points. A data point is
                    considered within scope if its manhattan distance to
                    position (in pixels) is less than the value of the scope
                    parameter. (default=20)

    :param showMarker: (bool) If True, a marker will be put on the picked
                        data point. (default=True)

    :param targetCurveNames: (sequence<str>) the names of the curves to be
                                searched. If None passed, all curves will be
                                searched

    :return: (tuple<Qt.QPointF,str,int> or tuple<None,None,None>) if a point
                was picked within the scope, it returns a tuple containing the
                picked point (as a Qt.QPointF), the curve name and the index of
                the picked point in the curve data. If no point was found
                within the scope, it returns None,None,None
    '''
    print "pickPlotPoint(...)"
    if isinstance(pos, Qt.QPolygon):
        pos = pos.first()
    scopeRect = Qt.QRect(0, 0, scope, scope)
    scopeRect.moveCenter(pos)
    mindist = scope
    picked = None
    pickedCurveName = None
    pickedIndex = None
    self.curves_lock.acquire()
    try:
        if targetCurveNames is None:
            targetCurveNames = self.curves.keys()
        #print '%d targetCurveNames'%len(targetCurveNames)
        for name in targetCurveNames:
            curve = self.curves.get(name, None)
            if curve is None:
                #print("Curve '%s' not found"%name)
                continue
            if not curve.isVisible():
                #print("Curve '%s' not visible"%name)
                continue
            data = curve.data()
            #print("Curve '%s' has %d points"%(name,data.size()))
            for i in xrange(data.size()):
                point = Qt.QPoint(self.transform(curve.xAxis(), data.x(i)),
                                  self.transform(curve.yAxis(), data.y(i)))
                if scopeRect.contains(point):
                    #print( 'Comparing %s,%s vs %s'%(pos,scopeRect,point))
                    dist = (pos - point).manhattanLength()
                    if dist < mindist:
                        mindist = dist
                        picked = Qt.QPointF(data.x(i), data.y(i))
                        pickedCurveName = name
                        pickedIndex = i
                        pickedAxes = curve.xAxis(), curve.yAxis()
                        found = True
            #if picked: print("Curve '%s' contains %s"%(name,pos))
    finally:
        self.curves_lock.release()

    if picked is None:
        print 'pickPlotPoint(%s)> No matching point found for any curve' % pos
        return

    xlabels = xlabels or []
    print("pickPlotPoint(x=%s,y=%s,xlabels=[%s])" %
          (picked.x(), picked.y(), len(xlabels)))

    if showMarker and picked is not None:
        print 'showing pickedMarker'
        self._pickedMarker.detach()
        self._pickedMarker.setValue(picked)
        self._pickedMarker.setAxis(*pickedAxes)
        self._pickedMarker.attach(self)
        self._pickedCurveName = pickedCurveName
        self._pickedMarker.pickedIndex = pickedIndex
        self.replot()
        label = self._pickedMarker.label()
        try:
            xi, xl = ([(x[0], x[1])
                       for x in (xlabels or []) if x[0] <= picked.x()]
                      or [[-1, None]])[-1]
            c = self.curves[pickedCurveName]
            #xc = [self.transform(c.xAxis(),x) for x in c.data().xData()]
            xc = [x for x in c.data().xData()]
            xx = len([x for x in xc if x >= xi and x <= picked.x()])
            #print [x[0] for x in xlabels]
            #print 'picked point: %s'%picked.x()
            #print 'last label %s at %s'%(xl,xi)
            #print 'data point are %s'%(xc)
            #print 'data points between pick and label: %s'%xx
            index = xx
            tag = '%s-%02d' % (xl, index)
            if xl and '/ip' in pickedCurveName.lower():
                try:
                    tag = PyTango.AttributeProxy(
                        tag.replace('-', '/VC/IP-') +
                        '/Controller').read().value
                except:
                    import traceback
                    print traceback.format_exc()
        except:
            import traceback
            print traceback.format_exc()
            index, xl = (-1, None)
            tag = ''
        if xl:
            infotxt = "'%s'[%i]:\n\t (%s,%.2e)" % (
                pickedCurveName, pickedIndex, tag, picked.y())
        elif self.getXIsTime():
            infotxt = "'%s'[%i]:\n\t (x=%s,%.3g)" % (
                pickedCurveName, pickedIndex, datetime.fromtimestamp(
                    picked.x()).ctime(), picked.y())
        else:
            infotxt = "'%s'[%i]:\n\t (x=%.3g, y=%.3g)" % (
                pickedCurveName, pickedIndex, picked.x(), picked.y())
        label.setText(infotxt)
        print '\t%s' % infotxt
        fits = label.textSize().width() < self.size().width()
        if fits:
            label.setText(infotxt)
            self._pickedMarker.setLabel(Qwt5.QwtText(label))
            self._pickedMarker.alignLabel()
            self.replot()
        else:
            popup = Qt.QWidget(self, Qt.Qt.Popup)
            popup.setLayout(Qt.QVBoxLayout())
            popup.layout().addWidget(
                Qt.QLabel(infotxt)
            )  #@todo: make the widget background semitransparent green!
            popup.setWindowOpacity(self._pickedMarker.labelOpacity)
            popup.show()
            popup.move(self.pos().x() - popup.size().width(), self.pos().y())
            popup.move(self.pos())
            Qt.QTimer.singleShot(5000, popup.hide)

    return picked, pickedCurveName, pickedIndex
Esempio n. 11
0
def setup_profile_plot(tp, composer, picker=True):
    #,gauges,pumps,tcs,positions=None,labels=None):
    """ This method configures a tau plot to show pressure/temperature profiles """
    tp.info('setup_profile_plot(%s,%s)' % (composer, picker))
    #tp.setModel('BO/VC/Composer/IPAxxis|BO/VC/Composer/IPPressures')
    #tp.setModel('BO/VC/Composer/CCGAxxis|BO/VC/Composer/CCGPressures,BO/VC/Composer/IPPressures')
    #positions = [0,17,31,33,49,63,80,94,111,114,116,122]
    #labels=['Q1A','Q1B','Q1LTB','Q2A','Q2B','Q3A','Q3B','Q4A','Q4B','Q4BT','Q4C','Q4D+RF']
    gauges = '%s/CCGAxxis|%s/CCGPressures' % (composer, composer)
    pumps = '%s/IPAxxis|%s/IPPressures' % (composer, composer)
    tcs = '%s/ThermoAxxis|%s/Thermocouples' % (composer, composer)
    positions = '%s/AxxisPositions' % composer
    labels = '%s/AxxisLabels' % composer

    pumps, gauges, tcs = [str(s).lower() for s in (pumps, gauges, tcs)]
    tp.setModelInConfig(False)
    tp.setModifiableByUser(False)
    tp.setModel(pumps)
    tp.addModels([tcs])
    tcs = tcs.split('|')[-1]
    tp.setCurvesYAxis([tcs], tp.yRight)
    tp.addModels([gauges])
    gauges = gauges.split('|')[-1]
    Curves = {}
    for cname in (pumps, gauges, tcs):
        tp.info('set curve %s' % cname)
        try:
            Curves[cname] = tp.curves[cname]
        except:
            Curves[cname] = tp.curves[cname.split('|')[-1]]

    if positions and labels:
        tp.info('Setting CustomXLabels ...')
        try:
            tp._positions = list(
                int(i) for i in taurus.Attribute(positions).read().value)
            tp._labels = list(
                str(i) for i in taurus.Attribute(labels).read().value)
            tp.setAxisCustomLabels(Qwt5.QwtPlot.xBottom,
                                   zip(tp._positions, tp._labels), 60)
        except:
            print 'Unable to read pressure profile labels'
            tp._positions = []
            tp._labels = []
            #print traceback.format_exc()

    for cname, color, width in [(gauges, Qt.Qt.blue, 3),
                                (pumps, Qt.Qt.magenta, 1),
                                (tcs, Qt.Qt.red, 2)]:
        cap = Curves[cname].getAppearanceProperties()
        cap.lColor = color
        cap.lWidth = width
        tp.setCurveAppearanceProperties({Curves[cname].getCurveName(): cap})

    Curves[gauges].setSymbol(
        Qwt5.QwtSymbol(Qwt5.QwtSymbol.Diamond, Qt.QBrush(Qt.Qt.yellow),
                       Qt.QPen(Qt.Qt.green), Qt.QSize(7, 7)))
    #f1 = Qwt5.QwtSplineCurveFitter()
    #f1.setSplineSize(2000)
    #Curves[pumps].setCurveFitter(f1)
    #Curves[pumps].setCurveAttribute(Curves[pumps].Fitted,True)
    tp.enableAxis(tp.yRight)
    tp.setAxisScaleType(Qwt5.QwtPlot.yLeft, Qwt5.QwtScaleTransformation.Log10)
    #tp.setAxisScale(Qwt5.QwtPlot.yLeft,1e-11,1e-4)
    tp.setCanvasBackground(Qt.Qt.white)
    tp.toggleDataInspectorMode(True)
    tp.showMaxPeaks(True)
    Curves[pumps].showMaxPeak(False)
    tp.setAllowZoomers(False)
    tp.toggleDataInspectorMode(True)

    if picker:
        tp.info('setting Picker ...')
        tp.disconnect(tp._pointPicker, Qt.SIGNAL('selected(QwtPolygon)'),
                      tp.pickDataPoint)
        tp.connect(tp._pointPicker,
                   Qt.SIGNAL('selected(QwtPolygon)'),
                   lambda pos, s=tp: pickPlotPoint(
                       s,
                       pos,
                       xlabels=(zip(tp._positions, tp._labels)
                                if tp._positions and tp._labels else None)))

    tp._profile_loaded = True
    return tp
Esempio n. 12
0
 def __init__(self, timeout=10000):
     self._pixmap = Qt.QPixmap(wdir('image/icons/alba-entry.JPG'))
     Qt.QSplashScreen.__init__(self, self._pixmap)
     self.showMessage('initializing application...')
     self._timer = Qt.QTimer.singleShot(timeout, self.close)
     self.show()
Esempio n. 13
0
class VaccaPanel(fandango.qt.Dropable(taurus.qt.qtgui.panel.TaurusDevicePanel)
                 ):
    """

    :param parent:
    :param model: a device name or an state attribute
    :param palette:
    :param bound:
    :param filters:
    :return:

    It is a class that inherits from TaurusDevicePanel and Dropable module from fandango.

    If connect=True at init, it checks if it exists any shareDataManager to
        subscribe in it. It can be done later using getPanelDescription or connectSharedSignals

    This Widget shows the device Commands and Attributes, it is listening the shareDataManager to show the device selected information.

    The title of this Widget can be draggable.

    VaccaPanel has the follow functionalities:

        * Title is draggable.
        * Is connected to shareDataManager to share information in the GUI.

    """
    def __init__(self,
                 parent=None,
                 model=None,
                 filters=[],
                 connect=False):  #,palette=None, bound=True,filters=[]):
        """
        In Init, the class VaccaPanel check if exist any shareDataManager to
        subscribe in it.

        :param parent:
        :param model: Model to start the Panel.
        :param filters: dictionary with 'attrs' and 'comms' filters as regexp or tuples lists
        :return:
        """

        self.call__init__(taurus.qt.qtgui.panel.TaurusDevicePanel, parent,
                          model)
        #self.setLogLevel(self.Info)
        self.info('init(%s,%s): connecting ...' % (model, filters))

        self._connected = []
        if connect: self.connectSharedSignals()

        if self.checkDropSupport():
            self.setSupportedMimeTypes([
                self.TAURUS_DEV_MIME_TYPE, self.TEXT_MIME_TYPE,
                self.TAURUS_MODEL_MIME_TYPE
            ])
            self.setDropEventCallback(self.setModelHook)

        self.info('init(...): layout ...')
        self._header.layout().removeWidget(self._label)
        #self._label = vacca.utils.DraggableLabel()
        self._label = fandango.qt.Draggable(Qt.QLabel)()
        self._label.font().setBold(True)
        self._label.setText('SELECT A DEVICE FROM THE TREE')
        self._header.layout().addWidget(self._label, 0, 1, Qt.Qt.AlignLeft)
        self._label.setDragEventCallback(self._label.text)
        #self.setToolTip(getattr(self,'__help__',self.__doc__))

        if filters:
            self.info('VaccaPanel(filters=%s)' % filters)
            if 'attrs' in filters:
                type(self)._attribute_filter = {'.*': filters['attrs']}
            if 'comms' in filters:
                type(self)._command_filter = {
                    '.*': [
                        c if fun.isSequence(c) else (c, ())
                        for c in filters['comms']
                    ]
                }

    def connectSharedSignals(self, read='SelectedInstrument', write=''):
        self.info('connectSharedSignals(%s,%s)' % (read, write))
        sdm = vacca.utils.get_shared_data_manager()
        if sdm and read and read not in self._connected:
            sdm.connectReader(read, self.setModelHook, readOnConnect=True)
            self._connected.append(read)
        return

    def setModelHook(self, model):
        #self.info('%s,%s'%(repr(args),repr(kwargs)))
        #l = [(str(type(a)),) for l in (args,kwargs.values()) for a in args]
        self.info('In setModelHook(%s)' % str(model))
        try:
            fandango.tango.parse_tango_model(str(model).strip())['device']
            self.setModel(model)
        except:
            self.warning('Invalid model: %s\n%s' %
                         (repr(model), traceback.format_exc()))

    @classmethod
    def getAttributeFilters(klass, dev_class=None):
        """
        TaurusDevicePanel filters are fixed to work by device name.
        But, if AttributeFilters is declared as class property, it will override them.
        
        get{Property}(klass,dev_class) will update it from Tango DB and return the matching values.
        set{Property}(dict) will update the parent TaurusDevicePanel dictionary, not the DB
        """
        if dev_class is not None and dev_class not in klass._attribute_filter:
            filters = get_class_property(dev_class,
                                         'AttributeFilters',
                                         extract=False)
            if filters:
                filters = [(l.split(':')[0], l.split(':')[-1].split(','))
                           for l in filters]
                klass._attribute_filter[dev_class] = filters
                #return {'.*':filters}

        print('getAttributeFilters(%s,%s): ...' % (klass, dev_class)
              )  #,klass._attribute_filter))
        return klass._attribute_filter

    @classmethod
    def getCommandFilters(klass, dev_class=None):
        """
        get{Property}(klass,dev_class) will update it from Tango DB and return the matching values.
        set{Property}(dict) will update the parent TaurusDevicePanel dictionary, not the DB
        """
        if dev_class is not None and dev_class not in klass._command_filter:
            filters = get_class_property(dev_class,
                                         'CommandFilters',
                                         extract=False)
            if filters:
                #filters = dict((k,eval(v)) for k,v in (l.split(':',1) for l in filters))
                filters = [(c, ()) for c in filters]
                klass._command_filter[dev_class] = filters

        print('getCommandFilters(%s,%s): ...' % (klass, dev_class)
              )  #,klass._command_filter))
        return klass._command_filter

    @classmethod
    def getIconMap(klass, dev_class=None):
        if dev_class is not None and dev_class not in klass._icon_map:
            p = get_class_property(dev_class, 'Icon', extract=True)
            if p: klass._icon_map[dev_class] = p  #Not trivial!
        print('getIconMap(%s): ...' % (klass))
        #print('getIconMap(%s): ...%s'%(klass,klass._icon_map))
        return klass._icon_map

    def setModel(self, model, pixmap=None):
        """
        Set Model is the callback used in shareDataManager to manage device
        selections.

        :param model: Model to VaccaPanel
        :param pixmap:
        :return:
        """
        try:
            #self.setLogLevel(self.Debug)
            self.info('VaccaPanel(%s).setModel(%s,%s)' %
                      (id(self), model, pixmap))
            model, modelclass, raw = str(model).strip(), '', model
            model = fandango.tango.parse_tango_model(model)
            if model is None:
                self.warning(
                    'VaccaPanel(%s).setModel(%s,%s): MODEL NOT PARSABLE!' %
                    (id(self), model, pixmap))
                return
            else:
                model = model['device']
            if model:
                model = model and model.split()[0] or ''
                modelclass = taurus.Factory().findObjectClass(model)
            self.debug('In TaurusDevicePanel.setModel(%s(%s),%s)' %
                       (raw, modelclass, pixmap))
            if model == self.getModel():
                return
            elif raw is None or not model or not modelclass:
                if self.getModel(): self.detach()
                return
            elif issubclass(modelclass, TaurusAttribute):
                #if model.lower().endswith('/state'):
                model = model.rsplit('/', 1)[0]
            elif not issubclass(modelclass, TaurusDevice):
                self.warning('TaurusDevicePanel accepts only Device models')
                return
        except Exception, e:
            traceback.print_exc()
            raise e

        try:
            taurus.Device(model).ping()
            dev_class = fandango.get_device_info(model).dev_class
            if self.getModel():
                self.detach(
                )  #Do not dettach previous model before pinging the new one (fail message will be shown at except: clause)
            TaurusWidget.setModel(self, model)
            self.setWindowTitle(str(model).upper())
            model = self.getModel()
            self._label.setText(model.upper())
            font = self._label.font()
            font.setPointSize(15)
            self._label.setFont(font)
            if pixmap is None and self.getIconMap(dev_class=dev_class):
                for k, v in self.getIconMap().items():
                    if searchCl(k, model) or searchCl(k, dev_class):
                        pixmap = v
                        break
            if pixmap is not None:
                #print 'Pixmap is %s'%pixmap
                qpixmap = Qt.QPixmap(pixmap)
                if qpixmap.height() > .9 * IMAGE_SIZE[1]:
                    qpixmap = qpixmap.scaledToHeight(.9 * IMAGE_SIZE[1])
                if qpixmap.width() > .9 * IMAGE_SIZE[0]:
                    qpixmap = qpixmap.scaledToWidth(.9 * IMAGE_SIZE[0])
            else:
                qpixmap = getPixmap(':/logo.png')

            self._image.setPixmap(qpixmap)
            self._state.setModel(model + '/state')
            if hasattr(self, '_statelabel'):
                self._statelabel.setModel(model + '/state')
            self._status.setModel(model + '/status')

            try:
                self._attrsframe.clear()
                class_filters = type(self).getAttributeFilters(
                    dev_class=dev_class)
                filters = get_regexp_dict(self._attribute_filter, model, [])
                if not filters:
                    filters = get_regexp_dict(self._attribute_filter,
                                              dev_class, ['.*'])

                search_tab = None
                if filters == [
                        '.*'
                ] and len(taurus.Device(model).get_attribute_list()) > 32:
                    filters = [('Attributes', ['.*'])]

                if hasattr(filters, 'keys'):
                    filters = filters.items()  #Dictionary!
                print('\tfilters = %s' % filters)

                #Showing multiple Tabs
                if filters and isinstance(filters[0], (list, tuple)):
                    self._attrs = []
                    for tab, attrs in filters:
                        if attrs[1:] or attrs[0] not in ('*', '.*'):
                            self.debug(
                                'VaccaPanel.setModel.get_attrs_form(%s,%s)' %
                                (model, attrs))
                            self._attrs.append(
                                self.get_attrs_form(device=model,
                                                    filters=attrs,
                                                    parent=self))
                            self._attrsframe.addTab(self._attrs[-1], tab)
                        else:
                            self.info('Embedding a Search panel')
                            search_tab = tab, VaccaSearchForm(preffix=model +
                                                              '/*',
                                                              suffix='*',
                                                              labels=True)
                #Mapping into a single form
                else:
                    if self._attrs and isinstance(self._attrs, list):
                        self._attrs = self._attrs[0]
                    if not isinstance(self._attrs, Qt.QWidget):
                        self._attrs = None
                    self._attrs = self.get_attrs_form(device=model,
                                                      form=self._attrs,
                                                      filters=filters,
                                                      parent=self)
                    if self._attrs:
                        self._attrsframe.addTab(self._attrs, 'Attributes')

                if not TaurusDevicePanel.READ_ONLY:
                    self._comms = self.get_comms_form(model, self._comms, self)
                    if self._comms:
                        self._attrsframe.addTab(self._comms, 'Commands')

                    if search_tab:
                        self._attrsframe.addTab(search_tab[1], search_tab[0])

                if SPLIT_SIZES: self._splitter.setSizes(SPLIT_SIZES)

            except Exception, e:
                self.warning('setModel(%s) failed!' % model)
                self.warning(traceback.format_exc())
                qmsg = Qt.QMessageBox(Qt.QMessageBox.Critical,
                                      '%s Error' % model,
                                      '%s not available' % model,
                                      Qt.QMessageBox.Ok, self)
                qmsg.setDetailedText(traceback.format_exc())
                qmsg.show()
                raise e

        except Exception, e:
            self.warning('setModel(%s) failed!' % model)
            self.warning(traceback.format_exc())
            qmsg = Qt.QMessageBox(Qt.QMessageBox.Critical, '%s Error' % model,
                                  '%s not available' % model,
                                  Qt.QMessageBox.Ok, self)
            qmsg.setDetailedText(traceback.format_exc())
            qmsg.show()
            raise e
Esempio n. 14
0
 def __init__(self, *args):
     Qt.QMainWindow(self, *args)
     self.setDockNestingEnabled(True)
Esempio n. 15
0
        if DEVICE and DEVICE.lower() not in DEVICES:
            DEVICES.append(DEVICE.lower())
        if DEVICES and not DEVICE:
            DEVICE = DEVICES[0]
    except:
        traceback.print_exc()

    if any((USE_DEVICE_TREE, JDRAW_FILE, len(DEVICES) > 1)):
        print('\t>>> Loading Tree panel(%s) ...' % (len(DEVICES)))
        from tree import *
        try:
            # The lastWindowClosed() signal will close all opened widgets and dialogs on application exit
            assert Qt.QApplication.instance(), 'QApplication not running!'
            panelclass = VaccaPanel  #VaccaAction(default=PANEL_COMMAND)
            Qt.QObject.connect(Qt.QApplication.instance(),
                               Qt.SIGNAL("lastWindowClosed()"),
                               panelclass.kill)
            VaccaTree.setDefaultPanelClass(panelclass)
        except:
            print("Cannot instance Device Tree")
        logger = fn.Logger()
        printf = logger.info

        def filterMatching(a, dct=AttributeFilters, p=printf):
            match = False
            if a.lower().endswith('/state'): return True
            elif a.lower().endswith('/status'): return False
            for k, l in dct.items():
                if fn.searchCl(k, a.rsplit('/', 1)[0]):
                    for t in l:  #T is every declared Tab for panel (TabName,[attrlist]); or just attrname when not using tabs
                        p((k, t))
Esempio n. 16
0
def init_qt():
    return Qt.QApplication([])
Esempio n. 17
0
    def contextMenuEvent(self, event):
        action_display_current = Qt.QAction(self)
        action_display_current.setText('Display Current')
        action_display_current.setCheckable(True)
        action_display_current.setChecked(
            self.taurusValueBuddy().getDisplayAttr() == 'current')
        slot = partial(self.taurusValueBuddy().setDisplayAttr, 'current')
        self.connect(action_display_current, Qt.SIGNAL('toggled(bool)'), slot)

        action_display_pressure = Qt.QAction(self)
        action_display_pressure.setText('Display Pressure')
        action_display_pressure.setCheckable(True)
        action_display_pressure.setChecked(
            self.taurusValueBuddy().getDisplayAttr() == 'pressure')
        slot = partial(self.taurusValueBuddy().setDisplayAttr, 'pressure')
        self.connect(action_display_pressure, Qt.SIGNAL('toggled(bool)'), slot)

        action_display_voltage = Qt.QAction(self)
        action_display_voltage.setText('Display Voltage')
        action_display_voltage.setCheckable(True)
        action_display_voltage.setChecked(
            self.taurusValueBuddy().getDisplayAttr() == 'voltage')
        slot = partial(self.taurusValueBuddy().setDisplayAttr, 'voltage')
        self.connect(action_display_voltage, Qt.SIGNAL('toggled(bool)'), slot)

        action_device_panel = Qt.QAction(self)
        action_device_panel.setText('Show Device Panel')
        self.connect(action_device_panel, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().showDevicePanel)

        action_start = Qt.QAction(self)
        action_start.setText('Start')
        self.connect(action_start, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().start)

        action_stop = Qt.QAction(self)
        action_stop.setText('Stop')
        self.connect(action_stop, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().stop)

        action_reconnect = Qt.QAction(self)
        action_reconnect.setText('Reconnect')
        self.connect(action_reconnect, Qt.SIGNAL('triggered()'),
                     self.taurusValueBuddy().reconnect)

        menu = Qt.QMenu(self)
        menu.addAction(action_device_panel)
        menu.addSeparator()
        menu.addAction(action_display_pressure)
        menu.addAction(action_display_current)
        menu.addAction(action_display_voltage)
        menu.addSeparator()
        menu.addAction(action_start)
        menu.addAction(action_stop)
        menu.addSeparator()
        menu.addAction(action_reconnect)
        menu.exec_(event.globalPos())
        event.accept()
Esempio n. 18
0
        if attrname not in self.listeners:
            print "subscribe", attrname,
            t0 = time.time()
            with self.lock:
                print "...got lock"
                listener = TaurusWebAttribute(attrname, callback)
                self.listeners[attrname] = listener
                print "...sub done", attrname, ", took %f s." % (time.time() -
                                                                 t0)

    def _unsubscribe_attribute(self, attrname):
        listener = self.listeners.pop(attrname, None)
        if listener:
            t0 = time.time()
            print "unsubscribe", attrname,
            with self.lock:
                print "...got lock"
                listener.clear()
                print "...unsub done", attrname, ", took %f s." % (
                    time.time() - t0)


if __name__ == '__main__':
    import sys
    print sys.argv[1]
    qapp = Qt.QApplication([])
    sw = SynopticWidget()
    sw.show()
    sw.setModel(sys.argv[1])
    qapp.exec_()