summaryrefslogtreecommitdiff
path: root/taurus/lib/taurus/qt/qtgui/display/taurusvaluelabel.py
blob: 325d621093a9e09b6d3f460113bd9bc01ea3a8d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/env python

#############################################################################
##
## This file is part of Taurus
## 
## http://taurus-scada.org
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
## 
## Taurus is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## Taurus is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
## 
## You should have received a copy of the GNU Lesser General Public License
## along with Taurus.  If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################

"""This module provides a set of basic Taurus widgets based on QLabel"""

__all__ = ["TaurusStateLabel", "TaurusValueLabel"]

__docformat__ = 'restructuredtext'

from taurus.external.qt import Qt

import taurus.core
from taurus.qt.qtgui.util import QT_ATTRIBUTE_QUALITY_PALETTE, QT_DEVICE_STATE_PALETTE
from taurus.qt.qtgui.base import TaurusBaseWidget

 
class TaurusValueLabel(Qt.QLabel, TaurusBaseWidget):
    """
    A widget that represents the read value of an attribute.

    .. deprecated::
        Use :class:`taurus.qt.qtgui.display.TaurusLabel` instead.

    The following features are present:
    
        * The background color changes with the attribute quality according to the :ref:`color-guide`
        * The attribute value is displayed according to the attribute format
        * Supports all data types and formats (although it is designed mainly for SCALAR format)
        * A tooltip is automatically generated displaying additional attribute information
        * If the size of the widget is too small to display the entire value, the text changes to
          a symbolic link that opens a dialog with the attribute value when clicked
    
    This widget emits the following signals (excluding signals of the super classes):
    
    **modelChanged**:
        - *Signature*: ``modelChanged(const QString &) -> None``
        - *Description*: the signal is emmited when the model for this widget 
          changes either by direct model manipulation, change of the useParentModel 
          and change of the parent model (if useParentModel is set to True)
    
    Example::
    
        import sys
        from taurus.external.qt import Qt
        from taurus.qt.qtgui.display import TaurusValueLabel

        app = Qt.QApplication(sys.argv)

        w = TaurusValueLabel()
        w.model = 'sys/taurustest/1/position'

        w.setVisible(True)
        sys.exit(app.exec_())

    .. image:: /_static/label01.png
        :align: center

    """
    
    __pyqtSignals__ = ("modelChanged(const QString &)",)
    
    def __init__(self, parent = None, designMode = False, background = 'quality'):
        name = self.__class__.__name__

        self.call__init__wo_kw(Qt.QLabel, parent)
        self.call__init__(TaurusBaseWidget, name, designMode=designMode)

        self.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Preferred)
        self.setTextInteractionFlags (Qt.Qt.TextSelectableByMouse|Qt.Qt.LinksAccessibleByMouse)
        self.setAlignment(Qt.Qt.AlignRight|Qt.Qt.AlignTrailing|Qt.Qt.AlignVCenter)
        self._charWidth = self.font().pointSize()
        self._showState = False
        self._showValueStateAsBackground = False
        self.defineBackground(background)
        self.connect(self, Qt.SIGNAL("linkActivated (const QString&)"), self.showFullValueDialog)
        self._text = ''
    
    def defineBackground(self, background):
        background = str(background).lower()
        self.setShowQuality(background == 'quality')
        self.setShowState(background == 'state')
        self.setShowValueStateAsBackground(background == 'value_state')
        self.__background = background;
        
    # The minimum size of the widget (a limit for the user)
    def minimumSizeHint(self):
        return Qt.QSize(20, 20)
        
#    # The default size of the widget
#    def sizeHint(self):
#        return Qt.QSize(60, 22)
#        #return Qt.QSize(Qt.QLabel.sizeHint(self).width(), 24)
    
    def _stateListener(self, s, t, v):
        # this method exists to force state to have at least one listener
        # when showState is set to True 
        pass
    
    @Qt.pyqtSignature("setShowState(bool)")
    def setShowState(self, showState):
        '''Whether or not to show the device state as background color.
        Note: obviously, setShowState(True) forces setShowQuality(False) !'''
        if showState == self._showState:
            return
        if showState and self.getShowQuality():
            self.setShowQuality(False)
        self._showState = showState
        
        modelObj = self.getModelObj()
        if modelObj is not None:
            s = modelObj.getParent().getStateObj()
            if showState:
                s.addListener(self._stateListener)
            else:
                s.removeListener(self._stateListener)
            
        self.updateStyle()
    
    def getShowState(self):
        """either or not to show the state as a background color"""
        return self._showState

    def resetShowState(self):
        self.setShowState(False)
    
    @Qt.pyqtSignature("setShowValueStateAsBackground(bool)")
    def setShowValueStateAsBackground(self, showState):
        '''Whether or not to show the value as background color.
        The attribute value must be a state!
        Note: obviously, forces setShowState(False) and setShowQuality(False)
    '''
        if showState:
            self.setShowQuality(False)
            self.setShowState(False)
        self._showValueStateAsBackground = showState

    def getShowValueStateAsBackground(self):
        """either or not to show the state as a background color"""
        return self._showValueStateAsBackground

    def resetShowValueStateAsBackground(self):
        self.setShowValueStateAsBackground(False)

    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    # TaurusBaseWidget overwriting
    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    
    def getModelClass(self):
        return taurus.core.taurusattribute.TaurusAttribute

    def isReadOnly(self):
        return True
    
    def updateStyle(self, extra=''):
        if self.getShowQuality():
            quality = getattr(self.getModelValueObj(), 'quality', None)
            ss = QT_ATTRIBUTE_QUALITY_PALETTE.qtStyleSheet(quality)
        elif self.getShowState():
            try: state = self.getModelObj().getParent().getState()
            except Exception:
                state = None
            ss = QT_DEVICE_STATE_PALETTE.qtStyleSheet(state)
        elif self.getShowValueStateAsBackground():
            value = getattr(self.getModelValueObj(), 'value', None)
            ss = QT_DEVICE_STATE_PALETTE.qtStyleSheet(value)
        else:
            ss = "background-color: transparent; color:black;"
        ss = """TaurusValueLabel {
            border-style: outset;
            border-width: 2px;
            border-color: rgba(255,255,255,128);
            %s %s}""" % (ss, extra)
        self.setStyleSheet(ss)
        TaurusBaseWidget.updateStyle(self)

    def validateDisplay(self):
        '''Checks that the display fits in the widget and sets it to "..." if it does not'''
        trimmedtext = "<a href='...'>...</a>"
        self._text = self.text()
        if Qt.QLabel.sizeHint(self).width() > self.size().width():
            self.setToolTip(self.getFormatedToolTip(showValue=True) )
            self._setText(trimmedtext)
            self.updateStyle()
            return False
        return True
    
    def getFormatedToolTip(self,cache=True, showValue=False):
        ret = TaurusBaseWidget.getFormatedToolTip(self,cache=cache)
        if showValue:
            ret = u"<p><b>Value:</b> %s</p><hr>%s"%(self._text, ret)
        return Qt.QString(ret)
    
    def showFullValueDialog(self,*args):
        Qt.QMessageBox.about(self,  "Full text", self._text)
    
    def handleEvent(self, evt_src, evt_type, evt_value):
        '''reimplemented to check that the display fits the size each time that the value changes'''
        TaurusBaseWidget.handleEvent(self, evt_src, evt_type, evt_value)
        self.validateDisplay()
    
    def resizeEvent(self,event):
        #We recheck the Display every time we resize
        self.updateStyle()
        self.setText(self._text) #We set the original (untrimmed) text to force a validation from scratch.
        self.validateDisplay()
        Qt.QLabel.resizeEvent(self,event)
    
    def setModel(self, m):
        oldModelObj = self.getModelObj()

        TaurusBaseWidget.setModel(self, m)

        newModelObj = self.getModelObj()
        if self.getShowState():
            if oldModelObj is not None:
                s = oldModelObj.getParent().getStateObj()
                s.removeListener(self._stateListener)
            if newModelObj is not None:
                s = newModelObj.getParent().getStateObj()
                s.addListener(self._stateListener)
        
    @classmethod
    def getQtDesignerPluginInfo(cls):
        return None
#        ret = TaurusBaseWidget.getQtDesignerPluginInfo()
#        ret['module'] = 'taurus.qt.qtgui.display'
#        ret['group'] = 'Taurus Widgets [Old]'
#        ret['icon'] = ":/designer/label.png"
#        return ret

    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    # QT property definition
    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-

    #: This property holds the unique URI string representing the model name 
    #: with which this widget will get its data from. The convention used for 
    #: the string can be found :ref:`here <model-concept>`.
    #: 
    #: In case the property :attr:`useParentModel` is set to True, the model 
    #: text must start with a '/' followed by the attribute name.
    #:
    #: **Access functions:**
    #:
    #:     * :meth:`TaurusBaseWidget.getModel`
    #:     * :meth:`TaurusValueLabel.setModel`
    #:     * :meth:`TaurusBaseWidget.resetModel`
    #:
    #: .. seealso:: :ref:`model-concept`
    model = Qt.pyqtProperty("QString", TaurusBaseWidget.getModel,setModel,
                            TaurusBaseWidget.resetModel)
    
    #: This property holds whether or not this widget should search in the 
    #: widget hierarchy for a model prefix in a parent widget.
    #:
    #: **Access functions:**
    #:
    #:     * :meth:`TaurusBaseWidget.getUseParentModel`
    #:     * :meth:`TaurusBaseWidget.setUseParentModel`
    #:     * :meth:`TaurusBaseWidget.resetUseParentModel`
    #:
    #: .. seealso:: :ref:`model-concept`
    useParentModel = Qt.pyqtProperty("bool", TaurusBaseWidget.getUseParentModel, 
                                     TaurusBaseWidget.setUseParentModel,
                                     TaurusBaseWidget.resetUseParentModel)

    #: This property holds whether or not this widget should fill the background
    #: with the attribute quality/device state according to the 
    #: :ref:`color-guide`
    #:
    #: **Access functions:**
    #:
    #:     * :meth:`TaurusBaseWidget.getShowQuality`
    #:     * :meth:`TaurusBaseWidget.setShowQuality`
    #:     * :meth:`TaurusBaseWidget.resetShowQuality`
    #:
    #: .. seealso:: :ref:`color-guide`
    showQuality = Qt.pyqtProperty("bool", TaurusBaseWidget.getShowQuality,
                                  TaurusBaseWidget.setShowQuality,
                                  TaurusBaseWidget.resetShowQuality)
    
    #: This property holds whether or not this widget should display the current
    #: value of the model as text. Setting this to False is useful when you just
    #: want to represent the quality/state as background color in a small space
    #:
    #: **Access functions:**
    #:
    #:     * :meth:`TaurusBaseWidget.getShowText`
    #:     * :meth:`TaurusBaseWidget.setShowText`
    #:     * :meth:`TaurusBaseWidget.resetShowText`
    showText = Qt.pyqtProperty("bool", TaurusBaseWidget.getShowText,
                               TaurusBaseWidget.setShowText, 
                               TaurusBaseWidget.resetShowText)
    
    #: This property holds the contents of a the popup menu as an XML string.
    #:
    #: **Access functions:**
    #:
    #:     * :meth:`TaurusBaseWidget.getTaurusPopupMenu`
    #:     * :meth:`TaurusBaseWidget.setTaurusPopupMenu`
    #:     * :meth:`TaurusBaseWidget.resetTaurusPopupMenu`
    #:
    #: .. seealso:: :ref:`popupmenu-tutorial`
    taurusPopupMenu = Qt.pyqtProperty("QString", TaurusBaseWidget.getTaurusPopupMenu,
                                   TaurusBaseWidget.setTaurusPopupMenu,
                                   TaurusBaseWidget.resetTaurusPopupMenu)


class TaurusStateLabel(TaurusValueLabel):
    '''
    .. deprecated::
        Use :class:`taurus.qt.qtgui.display.TaurusLabel` instead.
    '''
    def __init__(self, parent = None, designMode = False):
        self.call__init__(TaurusValueLabel, parent=parent, designMode=designMode, background = 'value_state')
        self.setAlignment(Qt.Qt.AlignCenter)
    
    def getFormatedToolTip(self, cache=True, **notused):
        """ The tooltip should refer to the device and not the state attribute.
            That is why this method is being rewritten
        """
        if self.modelObj is None:
            return Qt.QString.fromLatin1(self.getNoneValue())
        parent = self.modelObj.getParentObj()
        if parent is None:
            return Qt.QString.fromLatin1(self.getNoneValue())
        return Qt.QString.fromLatin1(self.toolTipObjToStr( parent.getDisplayDescrObj() ))
    
    @Qt.pyqtSignature("setModel(QString)")
    def setModel(self,model):
        """ Added to allow setModel(device_name); assuming that State attribute
            is the desired model. To inherit the parent model but with a non
            'State' named attribute, use slash: '/TheAttribute'
        """
        try:
            if str(model).count('/')<3 and str(model)[0]!='/':
                model = str(model)+'/State'
        except Exception:
            pass
        TaurusBaseWidget.setModel(self,model)

    @classmethod
    def getQtDesignerPluginInfo(cls):
        return None
#        ret = TaurusValueLabel.getQtDesignerPluginInfo()
#        ret['icon'] = ":/designer/state.png"
#        return ret

    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    # QT properties 
    #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-

    model = Qt.pyqtProperty("QString", TaurusBaseWidget.getModel, setModel,
                            TaurusBaseWidget.resetModel)

def main():
    """hello"""
    import sys
    import taurus.qt.qtgui.application
    Application = taurus.qt.qtgui.application.TaurusApplication
    
    app = Application.instance()
    owns_app = app is None
    
    if owns_app:
        import taurus.core.util.argparse
        parser = taurus.core.util.argparse.get_taurus_parser()
        parser.usage = "%prog [options] <full_attribute_name(s)>"
        app = Application(sys.argv, cmd_line_parser=parser)
        
    args = app.get_command_line_args()

    if len(args) > 0:
        models = map(str.lower, args)
    else:
        models = [ 'sys/tg_test/1/%s' % a for a in ('state', 'status', 'double_scalar' ) ]

    w = Qt.QWidget()
    layout = Qt.QGridLayout()
    w.setLayout(layout)
    for model in models:
        if model.endswith('state'):
            label = TaurusStateLabel()
        else:
            label = TaurusValueLabel()
        label.model = model
        layout.addWidget(label)
    w.show()
    
    if owns_app:
        sys.exit(app.exec_())
    else:
        return w

if __name__ == '__main__':
    main()