Ejemplo n.º 1
0
    def onClick(self):
        """Reimplemented :class:`GraphicalChoiceWidget`
        """
        # From all alternatives, extract the one with the shortest name
        # -------------------------------------------------------
        # Work around for https://bugs.kde.org/show_bug.cgi?id=345023
        # TODO: make better solution for this
        # self._chosen = str(self.sender().text())
        # it fails due to added "&"
        chosen = self.sender()._id  # <-- this was monkey-patched
        # -------------------------------------------------------

        alts = chosen.splitlines()
        alts = sorted(alts, key=lambda s: len(s.split()[0]))
        name, absname = alts[0].split()

        # Store chosen name and emit signal using name
        self._chosen = name
        self.choiceMade.emit(name)

        # show a message dialob with more info on the selected icon
        dlg = Qt.QMessageBox()
        dlg.setWindowTitle(name)
        text = 'You can access the selected icon as:\n%s\n\n' % name
        text += 'Or, by absolute name:\n%s\n\n' % absname
        if len(alts) > 1:
            text += 'Other alternative names:\n\n' + '\n\n'.join(alts[1:])
        dlg.setText(text)
        dlg.setIconPixmap(getCachedPixmap(name, size=128))
        dlg.exec_()
Ejemplo n.º 2
0
    def __init__(self, parent=None, designMode=False, choices=None, pixmaps=None, iconSize=128,
                 defaultPixmap=None, horizontalScrollBarPolicy=Qt.Qt.ScrollBarAsNeeded,
                 verticalScrollBarPolicy=Qt.Qt.ScrollBarAsNeeded):
        Qt.QScrollArea.__init__(self, parent)

        self._chosen = None
        self._iconSize = iconSize
        if defaultPixmap is None:
            defaultPixmap = Qt.QPixmap()
        self._defaultPixmap = defaultPixmap

        self.setFrameShape(Qt.QFrame.NoFrame)
        self.setWidgetResizable(True)
        self.setHorizontalScrollBarPolicy(horizontalScrollBarPolicy)
        self.setVerticalScrollBarPolicy(verticalScrollBarPolicy)

        w = Qt.QWidget()
        self.gridLayout = Qt.QGridLayout()
        w.setLayout(self.gridLayout)
        self.setWidget(w)

        if choices is not None:
            self.setChoices(choices, pixmaps)
        elif designMode:
            from taurus.qt.qtgui.icon import getCachedPixmap
            pm = getCachedPixmap('logos:taurus.png')
            self.setChoices([['choice1', 'choice2'], ['choice3', 'choice4']],
                            dict(choice1=pm, choice2=pm, choice3=pm,
                                 choice4=pm))
Ejemplo n.º 3
0
    def __init__(self, parent=None, designMode=False, choices=None, pixmaps=None, iconSize=128,
                 defaultPixmap=None, horizontalScrollBarPolicy=Qt.Qt.ScrollBarAsNeeded,
                 verticalScrollBarPolicy=Qt.Qt.ScrollBarAsNeeded):
        Qt.QScrollArea.__init__(self, parent)

        self._chosen = None
        self._iconSize = iconSize
        if defaultPixmap is None:
            defaultPixmap = Qt.QPixmap()
        self._defaultPixmap = defaultPixmap

        self.setFrameShape(Qt.QFrame.NoFrame)
        self.setWidgetResizable(True)
        self.setHorizontalScrollBarPolicy(horizontalScrollBarPolicy)
        self.setVerticalScrollBarPolicy(verticalScrollBarPolicy)

        w = Qt.QWidget()
        self.gridLayout = Qt.QGridLayout()
        w.setLayout(self.gridLayout)
        self.setWidget(w)

        if choices is not None:
            self.setChoices(choices, pixmaps)
        elif designMode:
            from taurus.qt.qtgui.icon import getCachedPixmap
            pm = getCachedPixmap('logos:taurus.png')
            self.setChoices([['choice1', 'choice2'], ['choice3', 'choice4']],
                            dict(choice1=pm, choice2=pm, choice3=pm,
                                 choice4=pm))
Ejemplo n.º 4
0
Archivo: qlogo.py Proyecto: cmft/taurus
 def __init__(self, parent=None, designMode=False):
     self.__name = self.__class__.__name__
     Qt.QLabel.__init__(self, parent)
     sizePolicy = Qt.QSizePolicy(
         Qt.QSizePolicy.Policy(0), Qt.QSizePolicy.Policy(0))
     sizePolicy.setHorizontalStretch(0)
     sizePolicy.setVerticalStretch(0)
     sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
     self.setSizePolicy(sizePolicy)
     self.setScaledContents(True)
     logo = getattr(tauruscustomsettings, 'ORGANIZATION_LOGO',
                    "logos:taurus.png")
     self.setPixmap(getCachedPixmap(logo))
Ejemplo n.º 5
0
 def __init__(self, parent=None, designMode=False):
     self.__name = self.__class__.__name__
     Qt.QLabel.__init__(self, parent)
     sizePolicy = Qt.QSizePolicy(Qt.QSizePolicy.Policy(0),
                                 Qt.QSizePolicy.Policy(0))
     sizePolicy.setHorizontalStretch(0)
     sizePolicy.setVerticalStretch(0)
     sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
     self.setSizePolicy(sizePolicy)
     self.setScaledContents(True)
     logo = getattr(tauruscustomsettings, 'ORGANIZATION_LOGO',
                    "logos:taurus.png")
     self.setPixmap(getCachedPixmap(logo))
Ejemplo n.º 6
0
def main():
    import sys
    from taurus.qt.qtgui.icon import getCachedPixmap
    app = Qt.QApplication(sys.argv)

    pixmaps = {}
    choices = [['TaurusForm', 'TaurusTrend'], ['TaurusPlot', 'Qub']]
    for row in choices:
        for k in row:
            pixmaps[k] = getCachedPixmap('snapshot:%s.png' % k)

    print GraphicalChoiceDlg.getChoice(parent=None, title='Panel chooser', msg='Choose the type of Panel:', choices=choices, pixmaps=pixmaps)

    sys.exit()
Ejemplo n.º 7
0
def main():
    import sys
    from taurus.qt.qtgui.icon import getCachedPixmap
    from taurus.qt.qtgui.application import TaurusApplication

    app = TaurusApplication(sys.argv)

    pixmaps = {}
    choices = [['TaurusForm', 'TaurusTrend'], ['TaurusPlot', 'Qub']]
    for row in choices:
        for k in row:
            pixmaps[k] = getCachedPixmap('snapshot:%s.png' % k)

    print GraphicalChoiceDlg.getChoice(parent=None, title='Panel chooser', msg='Choose the type of Panel:', choices=choices, pixmaps=pixmaps)

    sys.exit()
Ejemplo n.º 8
0
    def __build_catalog(self, prefix, columns=10):
        """explores paths registered under the given prefix and selects unique
        pixmaps (performs an md5 check to discard duplicated icon files)
        """
        pixmaps_hashed = {}
        hashes = {}

        for path in Qt.QDir.searchPaths(prefix):
            if not os.path.exists(path):
                print(" %s not found. Skipping.!" % path)
                continue

            for fname in os.listdir(path):
                abs_fname = os.path.join(path, fname)
                if not os.path.isfile(abs_fname):
                    continue
                md5 = self.__md5(abs_fname)
                choice = '%s:%s' % (prefix, fname)

                if md5 in hashes:
                    hashes[md5] += '\n%s\t(%s)' % (choice, abs_fname)
                else:
                    hashes[md5] = '%s\t(%s)' % (choice, abs_fname)
                    pixmap = getCachedPixmap(choice)
                    if not pixmap.isNull():
                        pixmaps_hashed[md5] = pixmap
        pixmaps = {}
        choices = []
        row = []
        for md5, choice in hashes.items():
            try:
                pixmaps[choice] = pixmaps_hashed[md5]
            except KeyError:
                continue
            row.append(choice)
            if len(row) > columns:
                choices.append(row)
                row = []
        if len(row) > 0:
            choices.append(row)

        return choices, pixmaps
Ejemplo n.º 9
0
    def __build_catalog(self, prefix, columns=10):
        """explores paths registered under the given prefix and selects unique
        pixmaps (performs an md5 check to discard duplicated icon files)
        """
        pixmaps_hashed = {}
        hashes = {}

        for path in Qt.QDir.searchPaths(prefix):
            if not os.path.exists(path):
                print " %s not found. Skipping.!" % path
                continue

            for fname in os.listdir(path):
                abs_fname = os.path.join(path, fname)
                if not os.path.isfile(abs_fname):
                    continue
                md5 = self.__md5(abs_fname)
                choice = '%s:%s' % (prefix, fname)

                if md5 in hashes:
                    hashes[md5] += '\n%s\t(%s)' % (choice, abs_fname)
                else:
                    hashes[md5] = '%s\t(%s)' % (choice, abs_fname)
                    pixmap = getCachedPixmap(choice)
                    if not pixmap.isNull():
                        pixmaps_hashed[md5] = pixmap
        pixmaps = {}
        choices = []
        row = []
        for md5, choice in hashes.items():
            try:
                pixmaps[choice] = pixmaps_hashed[md5]
            except KeyError:
                continue
            row.append(choice)
            if len(row) > columns:
                choices.append(row)
                row = []
        if len(row) > 0:
            choices.append(row)

        return choices, pixmaps
Ejemplo n.º 10
0
    def onClick(self):
        """Reimplemented :class:`GraphicalChoiceWidget`
        """
        # From all alternatives, extract the one with the shortest name
        chosen = self.sender().text()
        alts = chosen.splitlines()
        alts = sorted(alts, key=lambda s: len(s.split()[0]))
        name, absname = alts[0].split()

        # Store chosen name and emit signal using name
        self._chosen = name
        self.choiceMade.emit(name)

        # show a message dialob with more info on the selected icon
        dlg = Qt.QMessageBox()
        dlg.setWindowTitle(name)
        text = 'You can access the selected icon as:\n%s\n\n' % name
        text += 'Or, by absolute name:\n%s\n\n' % absname
        if len(alts) > 1:
            text += 'Other alternative names:\n\n' + '\n\n'.join(alts[1:])
        dlg.setText(text)
        dlg.setIconPixmap(getCachedPixmap(name, size=128))
        dlg.exec_()
Ejemplo n.º 11
0
    def onClick(self):
        """Reimplemented :class:`GraphicalChoiceWidget`
        """
        # From all alternatives, extract the one with the shortest name
        chosen = self.sender().text()
        alts = chosen.splitlines()
        alts = sorted(alts, key=lambda s: len(s.split()[0]))
        name, absname = alts[0].split()

        # Store chosen name and emit signal using name
        self._chosen = name
        self.choiceMade.emit(name)

        # show a message dialob with more info on the selected icon
        dlg = Qt.QMessageBox()
        dlg.setWindowTitle(name)
        text = 'You can access the selected icon as:\n%s\n\n' % name
        text += 'Or, by absolute name:\n%s\n\n' % absname
        if len(alts) > 1:
            text += 'Other alternative names:\n\n' + '\n\n'.join(alts[1:])
        dlg.setText(text)
        dlg.setIconPixmap(getCachedPixmap(name, size=128))
        dlg.exec_()
Ejemplo n.º 12
0
 def changePixmap(self, name):
     self.w.pixmap = getCachedPixmap(name)
Ejemplo n.º 13
0
 def changePixmap(self, name):
     self.w.pixmap = getCachedPixmap(name)
Ejemplo n.º 14
0
    def setModel(self, model, pixmap=None):
        model, modelclass, raw = str(model).strip(), '', model
        if model:
            model = model and model.split()[0] or ''
            modelclass = taurus.Factory().findObjectClass(model)
        self.trace('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]  # TODO: Tango-centric
        elif not issubclass(modelclass, TaurusDevice):
            self.warning('TaurusDevicePanel accepts only Device models')
            return
        try:
            taurus.Device(model).ping()  # TODO: Tango-centric
            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():
                for k, v in self.getIconMap().items():
                    if searchCl(k, model):
                        pixmap = v
            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:
                logo = getattr(tauruscustomsettings, 'ORGANIZATION_LOGO',
                               "logos:taurus.png")
                qpixmap = getCachedPixmap(logo)

            self._image.setPixmap(qpixmap)
            if hasattr(self, '_statelabel'):
                self._statelabel.setModel(model +
                                          '/state')  # TODO: Tango-centric
            self._status.setModel(model + '/status')  # TODO: Tango-centric
            try:
                self._attrsframe.clear()
                filters = get_regexp_dict(TaurusDevicePanel._attribute_filter,
                                          model, ['.*'])
                if hasattr(filters, 'keys'):
                    filters = filters.items()  # Dictionary!
                if filters and isinstance(filters[0],
                                          (list, tuple)):  # Mapping
                    self._attrs = []
                    for tab, attrs in filters:
                        self._attrs.append(
                            self.get_attrs_form(device=model,
                                                filters=attrs,
                                                parent=self))
                        self._attrsframe.addTab(self._attrs[-1], tab)
                else:
                    if self._attrs and isinstance(self._attrs, list):
                        self._attrs = self._attrs[0]
                    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 SPLIT_SIZES:
                    self._splitter.setSizes(SPLIT_SIZES)
            except:
                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()
        except:
            self.warning(traceback.format_exc())
            qmsg = Qt.QMessageBox(Qt.QMessageBox.Critical, '%s Error' % model,
                                  '%s not available' % model,
                                  Qt.QMessageBox.Ok, self)
            qmsg.show()
        self.setWindowTitle(self.getModel())
        return
Ejemplo n.º 15
0
    def setModel(self, model, pixmap=None):
        model, modelclass, raw = str(model).strip(), '', model
        if model:
            model = model and model.split()[0] or ''
            modelclass = taurus.Factory().findObjectClass(model)
        self.trace('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]  # TODO: Tango-centric
        elif not issubclass(modelclass, TaurusDevice):
            self.warning('TaurusDevicePanel accepts only Device models')
            return
        try:
            taurus.Device(model).ping()  # TODO: Tango-centric
            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():
                for k, v in self.getIconMap().items():
                    if searchCl(k, model):
                        pixmap = v
            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:
                logo = getattr(tauruscustomsettings, 'ORGANIZATION_LOGO',
                               "logos:taurus.png")
                qpixmap = getCachedPixmap(logo)

            self._image.setPixmap(qpixmap)
            self._state.setModel(model + '/state')  # TODO: Tango-centric
            if hasattr(self, '_statelabel'):
                self._statelabel.setModel(
                    model + '/state')  # TODO: Tango-centric
            self._status.setModel(model + '/status')  # TODO: Tango-centric
            try:
                self._attrsframe.clear()
                filters = get_regexp_dict(
                    TaurusDevicePanel._attribute_filter, model, ['.*'])
                if hasattr(filters, 'keys'):
                    filters = filters.items()  # Dictionary!
                if filters and isinstance(filters[0], (list, tuple)):  # Mapping
                    self._attrs = []
                    for tab, attrs in filters:
                        self._attrs.append(self.get_attrs_form(
                            device=model, filters=attrs, parent=self))
                        self._attrsframe.addTab(self._attrs[-1], tab)
                else:
                    if self._attrs and isinstance(self._attrs, list):
                        self._attrs = self._attrs[0]
                    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 SPLIT_SIZES:
                    self._splitter.setSizes(SPLIT_SIZES)
            except:
                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()
        except:
            self.warning(traceback.format_exc())
            qmsg = Qt.QMessageBox(Qt.QMessageBox.Critical, '%s Error' %
                                  model, '%s not available' % model, Qt.QMessageBox.Ok, self)
            qmsg.show()
        self.setWindowTitle(self.getModel())
        return
Ejemplo n.º 16
0
    def __init__(self, parent=None, designMode=False, extraWidgets=None):
        Qt.QWizardPage.__init__(self, parent)
        TaurusBaseWidget.__init__(self, 'WidgetPage')
        if extraWidgets:
            customWidgets, customWidgetScreenshots = list(zip(*extraWidgets))
            pixmaps = {}
            for k, s in extraWidgets:
                if s is None:
                    pixmaps[k] = None
                else:
                    try:
                        pixmaps[k] = getCachedPixmap(s)
                        if pixmaps[k].isNull():
                            raise Exception('Invalid Pixmap')
                    except:
                        self.warning('Could not create pixmap from %s' % s)
                        pixmaps[k] = None

        else:
            customWidgets, customWidgetScreenshots = [], []
            pixmaps = {}
        self.setFinalPage(True)
        self.setTitle('Panel type')
        self.setSubTitle('Choose a name and type for the new panel')
        self.setButtonText(Qt.QWizard.NextButton, 'Advanced settings...')

        self.widgetDescription = {
            'widgetname': None,
            'modulename': None,
            'classname': None
        }

        # name part
        self.nameLE = Qt.QLineEdit()
        self.registerField("panelname*", self.nameLE)
        self.diagnosticLabel = Qt.QLabel('')
        nameLayout = Qt.QHBoxLayout()
        nameLayout.addWidget(Qt.QLabel("Panel Name"))
        nameLayout.addWidget(self.nameLE)
        nameLayout.addWidget(self.diagnosticLabel)

        # contents
        available = TaurusWidgetFactory().getWidgetClassNames()
        choices = []
        row = []
        for cname in self.defaultCandidates + list(customWidgets):
            if cname in available or '.' in cname:
                row.append(cname)
                if cname not in pixmaps:
                    pixmaps[cname] = getCachedPixmap('snapshot:%s.png' % cname)
                if len(row) == 3:
                    choices.append(row)
                    row = []
        row.append(self.OTHER_TXT)
        choices.append(row)

        # defaultPixmap=getPixmap('logos:taurus.png')
        self.choiceWidget = GraphicalChoiceWidget(choices=choices,
                                                  pixmaps=pixmaps)

        self.widgetTypeLB = Qt.QLabel("<b>Widget Type:</b>")

        self.choiceWidget.choiceMade.connect(self.onChoiceMade)

        layout = Qt.QVBoxLayout()
        layout.addLayout(nameLayout)
        layout.addWidget(self.choiceWidget)
        layout.addWidget(self.widgetTypeLB)
        self.setLayout(layout)
Ejemplo n.º 17
0
Archivo: qled.py Proyecto: cmft/taurus
 def _refresh(self):
     """internal usage only"""
     self._ledName = self.toLedName()
     pixmap = getCachedPixmap(self._ledName)
     self.setPixmap(pixmap)
     return self.update()
Ejemplo n.º 18
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._status.setFixedHeight(2000)
        self._status.setFixedWidth(7000)
        #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 = fandango.qt.Dropable(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._label.checkDropSupport()
        self._label.setSupportedMimeTypes([
            self.TAURUS_DEV_MIME_TYPE, self.TEXT_MIME_TYPE,
            self.TAURUS_MODEL_MIME_TYPE
        ])
        self._label.setDropEventCallback(self.setModelHook)

        #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(str(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))
            self.checkDropSupport(
            )  #<< Needed to reapply drop support overriden by taurusgui.ini
            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:
            try:
                taurus.Device(model).getDeviceProxy().ping()  #T4
            except:
                taurus.Device(model).getHWObj().ping()  #T3
            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 = getCachedPixmap(':/logo.png')

            self._image.setPixmap(qpixmap)
            if hasattr(self, '_state'): self._state.setModel(model + '/state')
            if hasattr(self, '_statelabel'):
                try:
                    self._statelabel.setBgRole('value')
                    from taurus.qt.qtgui.base.taurusbase import defaultFormatter
                    self._statelabel.setFormat(defaultFormatter)
                    self._statelabel.setModel(model + '/state')
                except:
                    print('no taurus formatter for 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 = [
                        #('Status',['Status']),
                        ('Search 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
Ejemplo n.º 19
0
 def _refresh(self):
     """internal usage only"""
     self._ledName = self.toLedName()
     pixmap = getCachedPixmap(self._ledName)
     self.setPixmap(pixmap)
     return self.update()