summaryrefslogtreecommitdiff
path: root/lib/taurus/qt/qtgui/table/taurusvaluestable.py
blob: d5eabdadbd8c1448dde031fa97379f64119be02a (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
#!/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/>.
#
# ###########################################################################

from taurus.external.qt import Qt
from taurus.core.units import Quantity

import numpy

import taurus.core
from taurus.core.taurusbasetypes import (
    DataFormat,
    DataType,
    TaurusEventType,
    TaurusElementType,
)
from taurus.qt.qtgui.util import PintValidator
from taurus.qt.qtgui.display import TaurusLabel
from taurus.qt.qtgui.container import TaurusWidget
from taurus.core.util.enumeration import Enumeration


__all__ = ["TaurusValuesTable"]

__docformat__ = "restructuredtext"


def _value2Quantity(value, units):
    """
    Creates a Quantity from value and forces units if the vaule is unitless

    :param value: a number or a string from which a quantity can be created
    :type value: int, float or str
    :param units: Units to use if the value is unitless
    :type units: str or Pint units
    :return:
    :rtype: Quantity
    """
    q = Quantity(value)
    if q.unitless:
        q = Quantity(q, units)
    return q


class TaurusValuesIOTableModel(Qt.QAbstractTableModel):
    typeCastingMap = {
        "f": float,
        "b": bool,
        "u": int,
        "i": int,
        "S": str,
        "U": str,
    }
    # Need to have an array

    dataChanged = Qt.pyqtSignal("QModelIndex", "QModelIndex")

    def __init__(self, size, parent=None):
        Qt.QAbstractTableModel.__init__(self, parent)
        self._parent = parent
        self._rtabledata = []
        self._wtabledata = []
        self._rowCount = size[0]
        self._columnCount = size[1]
        self._modifiedDict = {}
        self._attr = None
        self.editedIndex = None
        self._editable = False
        self._writeMode = False

    def isDirty(self):
        """returns True if there are user changes. False Otherwise"""
        return bool(self._modifiedDict)

    # To be implemented -----
    def rowCount(self, index=Qt.QModelIndex()):
        """see :meth:`Qt.QAbstractTableModel.rowCount`"""
        if self._rowCount == 0:
            self._rowCount = 1
        return self._rowCount

    def columnCount(self, index=Qt.QModelIndex()):
        """see :meth:`Qt.QAbstractTableModel.columnCount`"""
        if self._columnCount == 0:
            self._columnCount = 1
        return self._columnCount

    def data(self, index, role=Qt.Qt.DisplayRole):
        """see :meth:`Qt.QAbstractTableModel.data`"""
        if self._writeMode is False:
            tabledata = self._rtabledata
        else:
            tabledata = self._wtabledata
        if not index.isValid() or not (0 <= index.row() < len(tabledata)):
            return None
        elif role == Qt.Qt.DisplayRole:
            value = None
            rc = (index.row(), index.column())
            if self._writeMode and rc in self._modifiedDict:
                if self.getAttr().type in [DataType.Integer, DataType.Float]:
                    return str(self._modifiedDict[rc])
                else:
                    return self._modifiedDict[rc]
            else:
                value = tabledata[rc]
                if isinstance(value, Quantity):
                    value = value.magnitude
            # cast the value to a standard python type
            value = self.typeCastingMap[tabledata.dtype.kind](value)
            return value
        elif role == Qt.Qt.DecorationRole:
            if (
                index.row(),
                index.column(),
            ) in self._modifiedDict and self._writeMode:
                if self.getAttr().type in [DataType.Integer, DataType.Float]:
                    value = self._modifiedDict[(index.row(), index.column())]
                    if not self.inAlarmRange(value):
                        icon = Qt.QIcon.fromTheme("document-save")
                    else:
                        icon = Qt.QIcon.fromTheme("emblem-important")
                else:
                    icon = Qt.QIcon.fromTheme("document-save")
                return icon
        elif role == Qt.Qt.EditRole:
            value = None
            if (
                index.row(),
                index.column(),
            ) in self._modifiedDict and self._writeMode:
                value = self._modifiedDict[(index.row(), index.column())]
            else:
                value = tabledata[index.row(), index.column()]
                if tabledata.dtype == bool:
                    value = bool(value)
            return value
        elif role == Qt.Qt.BackgroundRole:
            if self._writeMode:
                return Qt.QColor(22, 223, 21, 50)
            else:
                return Qt.QColor("white")
        elif role == Qt.Qt.ForegroundRole:
            if (
                index.row(),
                index.column(),
            ) in self._modifiedDict and self._writeMode:
                if self.getAttr().type in [DataType.Integer, DataType.Float]:
                    value = self._modifiedDict[(index.row(), index.column())]
                    if not self.inAlarmRange(value):
                        return Qt.QColor("blue")
                    else:
                        return Qt.QColor("orange")
                else:
                    return Qt.QColor("blue")
            return Qt.QColor("black")
        elif role == Qt.Qt.FontRole:
            if (
                index.row(),
                index.column(),
            ) in self._modifiedDict and self._writeMode:
                return Qt.QFont("Arial", 10, Qt.QFont.Bold)
        elif role == Qt.Qt.ToolTipRole:
            if (
                index.row(),
                index.column(),
            ) in self._modifiedDict and self._writeMode:
                value = str(self._modifiedDict[(index.row(), index.column())])
                msg = (
                    "Original value: %s.\nNew value that will be saved: %s"
                    % (str(tabledata[index.row(), index.column()]), value)
                )
                return msg
        return None

    def getAttr(self):
        return self._attr

    def setAttr(self, attr):
        """
        Updated the internal table data from an attribute value

        :param attr:
        :type attr: DeviceAttribute
        """
        self._attr = attr
        rvalue = attr.rvalue
        if attr.type not in [DataType.Float, DataType.Integer]:
            rvalue = numpy.array(attr.rvalue)
        # reshape the table
        if attr.data_format == DataFormat._1D:
            rows, columns = len(rvalue), 1
        elif attr.data_format == DataFormat._2D:
            rows, columns = numpy.shape(rvalue)
        else:
            raise TypeError(
                'Unsupported data format "%s"' % repr(attr.data_format)
            )

        if (self._rowCount != rows) or (self._columnCount != columns):
            self.beginResetModel()
            self.endResetModel()

        self._rowCount = rows
        self._columnCount = columns
        rvalue = rvalue.reshape(rows, columns)
        if attr.type in [DataType.Integer, DataType.Float]:
            units = self._parent.getCurrentUnits()
            rvalue = rvalue.to(units)
        self._rtabledata = rvalue
        self._editable = False
        self.dataChanged.emit(
            self.createIndex(0, 0), self.createIndex(rows - 1, columns - 1)
        )

    def getStatus(self, index):
        """
        Returns Status of the variable

        :return:
        :rtype: taurus.core.taurusbasetypes.AttrQuality
        """
        return self._attr.quality

    def getType(self):
        """
        Returns the table data type.

        :return:
        :rtype: numpy.dtype
        """
        return self._rtabledata.dtype

    def addValue(self, index, value):
        """adds a value to the dictionary of modified cell values

        :param index: table index
        :type index: QModelIndex
        :param value:
        :type value: object
        """
        rtable_value = self._rtabledata[index.row()][index.column()]
        if self._attr.getType() in [DataType.Float, DataType.Integer]:
            units = self._parent.getCurrentUnits()
            value = _value2Quantity(value, units)
            equals = numpy.allclose(rtable_value, value.to(units))
        else:
            equals = bool(rtable_value == value)
        if not equals:
            self._modifiedDict[(index.row(), index.column())] = value
        else:
            self.removeValue(index)

    def removeValue(self, index):
        """
        Removes index from dictionary

        :param index: table index
        :type index: QModelIndex
        """
        if (index.row(), index.column()) in self._modifiedDict:
            self._modifiedDict.pop((index.row(), index.column()))

    def flags(self, index):
        """see :meth:`Qt.QAbstractTableModel`"""
        if not index.isValid():
            return Qt.Qt.ItemIsEnabled
        if self._editable:
            return Qt.Qt.ItemFlags(
                Qt.Qt.ItemIsEnabled
                | Qt.Qt.ItemIsEditable
                | Qt.Qt.ItemIsSelectable
            )
        else:
            return Qt.Qt.ItemFlags(
                Qt.Qt.ItemIsEnabled | Qt.Qt.ItemIsSelectable
            )

    def getModifiedWriteData(self):
        """returns an array for the write data that includes the user
        modifications

        :return: The write values including user modifications.
        :rtype: numpy.array
        """
        table = self._wtabledata
        kind = table.dtype.kind
        if kind in "SU":
            # we want to allow the strings to be larger than the original ones
            table = table.tolist()
            for (r, c), v in self._modifiedDict.items():
                table[r][c] = v
            table = numpy.array(table, dtype=str)
        else:
            for k, v in self._modifiedDict.items():
                if kind in ["f", "i", "u"]:
                    units = self._parent.getCurrentUnits()
                    q = _value2Quantity(v, units)
                    table[k] = q
                elif kind == "b":
                    if str(v) == "true":
                        table[k] = True
                    else:
                        table[k] = False
                else:
                    raise TypeError('Unknown data type "%s"' % kind)
        # reshape if needed
        if self._attr.data_format == DataFormat._1D:
            table = table.flatten()
        return table

    def clearChanges(self):
        """clears the dictionary of changed values"""
        self._modifiedDict.clear()
        self.dataChanged.emit(
            self.createIndex(0, 0),
            self.createIndex(self.rowCount() - 1, self.columnCount() - 1),
        )

    def inAlarmRange(self, value):
        """
        Checkes if value is in alarm range.

        :param value: Quantity value
        :return: True if value in alarm range, False if valid
        :rtype: bool
        """
        try:
            min_alarm, max_alarm = self._attr.alarms
            if min_alarm >= value or value >= max_alarm:
                return True
            else:
                return False
        except Exception:
            return True

    def inRange(self, value):
        """
        Checks if value is in range.

        :param value: Quantity value
        :return: True if value in range, False if valid
        :rtype: bool
        """
        try:
            min_range, max_range = self._attr.range
            if min_range <= value <= max_range:
                return True
            else:
                return False
        except Exception:
            return True

    def setWriteMode(self, isWrite):
        """Changes the write state

        :param isWrite:
        :type isWrite: bool
        """
        self._writeMode = isWrite
        if isWrite and not self.isDirty() and self._attr is not None:
            # refresh the write data (unless it is dirty)
            wvalue = self._attr.wvalue

            # reshape the table
            if self._attr.type == DataType.String:
                wvalue = numpy.array(wvalue)
            elif self._attr.type in [DataType.Integer, DataType.Float]:
                units = self._parent.getCurrentUnits()
                wvalue = wvalue.to(units)
            if self._attr.data_format == DataFormat._1D:
                rows, columns = numpy.shape(wvalue)[0], 1
                if rows == 0:
                    # TODO: Ask to the user for a default shape
                    rows = 3
            elif self._attr.data_format == DataFormat._2D:
                try:
                    rows, columns = numpy.shape(wvalue)
                except ValueError:
                    # TODO: Ask to the user for a default shape
                    rows = 3
                    columns = 3
                    wvalue = numpy.array((rows, columns))
            else:
                self.warning(
                    "unsupported data format %s" % str(wvalue.data_format)
                )
            wvalue = wvalue.reshape(rows, columns)
            # In version 4.6 of Qt when whole table is updated it is
            # recommended to use beginReset()
            self._wtabledata = wvalue
        self.dataChanged.emit(
            self.createIndex(0, 0),
            self.createIndex(self.rowCount() - 1, self.columnCount() - 1),
        )

    def getModifiedDict(self):
        """
        Returns dictionary.

        :return: dictionary containing modified indexes and values
        :rtype: dictionary
        """
        return self._modifiedDict

    def getReadValue(self, index):
        """
        Returns read value for a given index.

        :param index: table model index
        :type index: QModelIndex
        :return: read table value for a given cell
        :rtype: string/int/float/bool
        """
        return self._rtabledata[index.row(), index.column()]


class TaurusValuesIOTable(Qt.QTableView):
    def __init__(self, parent=None):
        self._parent = parent
        name = self.__class__.__name__
        Qt.QTableView.__init__(self, parent)
        self._showQuality = True
        self._attr = None
        self._value = None
        self.setSelectionMode(Qt.QAbstractItemView.SingleSelection)
        itemDelegate = TaurusValuesIOTableDelegate(self)
        self.setItemDelegate(itemDelegate)

    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    # TaurusBaseWidget overwriting
    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

    def setModel(self, shape):
        """
        Creates an instance of QTableModel and sets a QT model.

        :param shape: shape of the model table to be set
        :type shape: tuple<int>
        """
        qmodel = TaurusValuesIOTableModel(shape, parent=self)
        Qt.QTableView.setModel(self, qmodel)

    def cancelChanges(self):
        """
        Cancels all table modifications.
        """
        self.model().clearChanges()

    def removeChange(self):
        """
        If the cell was modified it restores the original write value.
        """
        self.model().removeValue(self.selectedIndexes()[0])

    def showHelp(self):
        """
        Shows QMessageBox help window. It contains explanations of used icons.
        """
        buttonBox = Qt.QMessageBox(self)
        buttonBox.setLayout(Qt.QGridLayout(self))
        icon = Qt.QIcon.fromTheme("document-save").pixmap(48, 48)
        l = Qt.QLabel()
        l.setPixmap(icon)
        buttonBox.layout().addWidget(l, 0, 0)
        lb = "- value is valid. It will be saved if changes are accepted"
        buttonBox.layout().addWidget(Qt.QLabel(lb), 0, 1)
        icon = Qt.QIcon.fromTheme("ddialog-warning").pixmap(48, 48)
        l = Qt.QLabel()
        l.setPixmap(icon)
        buttonBox.layout().addWidget(l, 1, 0)
        lb = "- value in alarm range. It will be saved if changes are accepted"
        buttonBox.layout().addWidget(Qt.QLabel(lb), 1, 1)
        buttonBox.exec_()

    def getCurrentUnits(self):
        try:
            return str(self._parent._units.currentText())
        except Exception:
            return ""


class TaurusValuesIOTableDelegate(Qt.QStyledItemDelegate):

    editorCreated = Qt.pyqtSignal()

    def __init__(self, parent=None):
        Qt.QStyledItemDelegate.__init__(self, parent)
        self._parent = parent
        self._initialText = ""

    def createEditor(self, parent, option, index):
        """
        Creates a custom editor for a table delagate.

        see :meth:`Qt.QStyledItemDelegate.createEditor`
        """
        if index.model().getType() == bool:
            editor = Qt.QComboBox(parent)
        else:
            editor = TableInlineEdit(parent)
            editor._updateValidator(index.model().getAttr())
        self.editorCreated.emit()
        return editor

    def setEditorData(self, editor, index):
        """
        see :meth:`Qt.QStyledItemDelegate.setEditorData`
        """
        if index.model().editedIndex == (index.row(), index.column()):
            return
        index.model().editedIndex = (index.row(), index.column())
        self._initialText = None
        if index.model().getType() == bool:
            editor.addItems(["true", "false"])
            a = str(index.data()).lower()
            self._initialText = a

            editor.setCurrentIndex(editor.findText(a))
        else:
            data = index.model().data(index, Qt.Qt.EditRole)
            self._initialText = data
            editor.setText(str(self._initialText))

    def setModelData(self, editor, model, index):
        """
        see :meth:`Qt.QStyledItemDelegate.setModelData`
        """
        # if editor text changed, then don't mark as updated.
        isNumeric = False
        if self._parent._attr.type in [DataType.Integer, DataType.Float]:
            units = self._parent.getCurrentUnits()
            q = _value2Quantity(editor.text(), units)
            isNumeric = True
            if not model.inRange(q):
                return
        if index.model().getType() == bool:
            text = editor.currentText()
        else:
            if isNumeric:
                text = q
            else:
                text = editor.text()
            text = str(text)
        if (text != self._initialText) & (text != ""):
            model.addValue(index, text)
            hh = self.parent().horizontalHeader()
            if hh.length() > 0:
                hh.setSectionResizeMode(hh.Fixed)
            vh = self.parent().verticalHeader()
            if vh.length() > 0:
                vh.setSectionResizeMode(vh.Fixed)

        index.model().editedIndex = None


class TableInlineEdit(Qt.QLineEdit):
    """TableInLineEdit is used to validate the content of the new value, also
    to paint the text: blue - valid, orange - in alarm, grey - invalid.
    """

    def __init__(self, parent=None):
        super(Qt.QLineEdit, self).__init__(parent)
        self.textEdited.connect(self.onTextEdited)
        self.setValidator(None)
        self._min_range = None
        self._max_range = None
        self._min_alarm = None
        self._max_alarm = None
        self._default_unit = None

    def onTextEdited(self):
        """
        Paints the text while typing.

        Slot for the `Qt.QLineEdit.textEdited` signal
        """
        # default case: the value is in normal range with no pending changes
        color, weight = "gray", "normal"
        try:
            value = self.displayText()
            q = _value2Quantity(value, self._default_unit)
        except Exception:
            q = 0.0
        try:
            if self._min_alarm < q < self._max_alarm:
                color = "blue"
            elif self._min_range <= q <= self._max_range:
                # the value is valid but in alarm range...
                color = "orange"
            else:
                # the value is invalid and can't be applied
                color = "gray"
        except Exception:
            color = "gray"

        weight = "bold"
        self.setStyleSheet(
            "TableInlineEdit {color: %s; font-weight: %s}" % (color, weight)
        )

    def _updateValidator(self, attr):
        """This method sets a validator depending on the data type

        :param attr: TaurusAttribute
        """
        data_type = attr.getType()
        if data_type in [DataType.Integer, DataType.Float]:
            self._min_range, self._max_range = attr.range
            self._min_alarm, self._max_alarm = attr.alarms
            self._default_unit = attr.wvalue.units
            validator = PintValidator()
            validator.setBottom(self._min_range)
            validator.setTop(self._max_range)
            validator.setUnits(self._default_unit)
            self.setValidator(validator)
        else:
            self.setValidator(None)

    def __decimalDigits(self, fmt):
        """returns the number of decimal digits from a format string
        (or None if they are not defined)
        """
        try:
            if fmt[-1].lower() in ["f", "g"] and "." in fmt:
                return int(fmt[:-1].split(".")[-1])
            else:
                return None
        except Exception:
            return None


class TaurusValuesTable(TaurusWidget):
    """
    A table for displaying and/or editing 1D/2D Taurus attributes
    """

    _showQuality = False
    _writeMode = False

    def __init__(self, parent=None, designMode=False, defaultWriteMode=None):
        TaurusWidget.__init__(self, parent=parent, designMode=designMode)
        self._tableView = TaurusValuesIOTable(self)
        l = Qt.QGridLayout()
        l.addWidget(self._tableView, 1, 0)
        self._tableView.itemDelegate().editorCreated.connect(
            self._onEditorCreated
        )

        if defaultWriteMode is None:
            self.defaultWriteMode = "rw"
        else:
            self.defaultWriteMode = defaultWriteMode

        self._label = TaurusLabel()
        self._label.setBgRole("quality")
        self._label.setFgRole("quality")

        self._units = Qt.QComboBox()

        self._applyBT = Qt.QPushButton("Apply")
        self._cancelBT = Qt.QPushButton("Cancel")
        self._applyBT.clicked.connect(self.okClicked)
        self._cancelBT.clicked.connect(self.cancelClicked)

        self._rwModeCB = Qt.QCheckBox()
        self._rwModeCB.setText("Write mode")
        self._rwModeCB.toggled.connect(self.setWriteMode)

        lv = Qt.QHBoxLayout()
        lv.addWidget(self._label)
        lv.addWidget(self._units)
        l.addLayout(lv, 2, 0)
        l.addWidget(self._rwModeCB, 0, 0)
        lv = Qt.QHBoxLayout()
        lv.addWidget(self._applyBT)
        lv.addWidget(self._cancelBT)
        l.addLayout(lv, 3, 0)
        self._writeMode = False
        self.setLayout(l)
        self._initActions()

    def _initActions(self):
        """Initializes the actions for this widget (currently, the pause
        action.)"""
        self._pauseAction = Qt.QAction("&Pause", self)
        self._pauseAction.setShortcuts([Qt.Qt.Key_P, Qt.Qt.Key_Pause])
        self._pauseAction.setCheckable(True)
        self._pauseAction.setChecked(False)
        self.addAction(self._pauseAction)
        self._pauseAction.toggled.connect(self.setPaused)
        self.chooseModelAction = Qt.QAction("Choose &Model", self)
        self.chooseModelAction.setEnabled(self.isModifiableByUser())
        self.addAction(self.chooseModelAction)
        self.chooseModelAction.triggered.connect(self.chooseModel)

    def getModelClass(self):
        """see :meth:`TaurusWidget.getModelClass`"""
        return taurus.core.taurusattribute.TaurusAttribute

    def setModel(self, model):
        """Reimplemented from :meth:`TaurusWidget.setModel`"""
        TaurusWidget.setModel(self, model)
        model_obj = self.getModelObj()

        if model_obj.isWritable() and self.defaultWriteMode != "r":
            self._writeMode = True
        else:
            self.defaultWriteMode = "r"

        if model_obj is not None:
            self._tableView._attr = model_obj
            if model_obj.type in [DataType.Integer, DataType.Float]:
                if self._writeMode:
                    try:
                        default_unit = str(model_obj.wvalue.units)
                    except AttributeError:
                        default_unit = ""
                else:
                    default_unit = str(model_obj.rvalue.units)
                # TODO: fill the combobox with the compatible units
                self._units.addItem("%s" % default_unit)
                self._units.setCurrentIndex(self._units.findText(default_unit))
                self._units.setEnabled(False)
            else:
                self._units.setVisible(False)
            raiseException = False
            if model_obj.data_format == DataFormat._2D:
                try:
                    dim_x, dim_y = numpy.shape(model_obj.rvalue)
                except ValueError:
                    raiseException = True
            elif model_obj.data_format == DataFormat._1D:
                try:
                    dim_x, dim_y = len(model_obj.rvalue), 1
                except ValueError:
                    raiseException = True
            else:
                raiseException = True
            if raiseException:
                raise Exception("rvalue is invalid")
            self._tableView.setModel([dim_x, dim_y])
        self.setWriteMode(self._writeMode)
        self._label.setModel(model)

    def handleEvent(self, evt_src, evt_type, evt_value):
        """see :meth:`TaurusWidget.handleEvent`"""
        # fixme: in some situations, we may miss some config event because
        #        of the qmodel not being set. The whole handleEvent Method
        #        and setModel method should be re-thought
        model = self._tableView.model()
        if model is None:
            return
        if (
            evt_type in (TaurusEventType.Change, TaurusEventType.Periodic)
            and evt_value is not None
        ):
            attr = self.getModelObj()
            model.setAttr(attr)
            model.setWriteMode(self._writeMode)

            hh = self._tableView.horizontalHeader()
            if hh.length() > 0:
                hh.setSectionResizeMode(hh.Fixed)
            vh = self._tableView.verticalHeader()
            if vh.length() > 0:
                vh.setSectionResizeMode(vh.Fixed)
            if self.defaultWriteMode == "r":
                isWritable = False
            else:
                isWritable = True
            writable = isWritable and self._writeMode and attr.isWritable()
            self.setWriteMode(writable)
        elif evt_type == TaurusEventType.Config:
            # force a read to set an attr
            attr = self.getModelObj()
            model.setAttr(attr)

    def contextMenuEvent(self, event):
        """Reimplemented from :meth:`QWidget.contextMenuEvent`"""
        menu = Qt.QMenu()
        globalPos = event.globalPos()
        menu.addAction(self.chooseModelAction)
        menu.addAction(self._pauseAction)
        if self._writeMode:
            index = self._tableView.selectedIndexes()[0]
            if index.isValid():
                val = self._tableView.model().getReadValue(index)
                if (
                    index.row(),
                    index.column(),
                ) in self._tableView.model().getModifiedDict():
                    menu.addAction(
                        Qt.QIcon.fromTheme("edit-undo"),
                        "Reset to original value (%s) " % repr(val),
                        self._tableView.removeChange,
                    )
                    menu.addSeparator()
                menu.addAction(
                    Qt.QIcon.fromTheme("process-stop"),
                    "Reset all table",
                    self.askCancel,
                )
                menu.addSeparator()
                menu.addAction(
                    Qt.QIcon.fromTheme("help-browser"),
                    "Help",
                    self._tableView.showHelp,
                )
        menu.exec_(globalPos)
        event.accept()

    def applyChanges(self):
        """
        Writes table modifications to the device server.
        """
        tab = self._tableView.model().getModifiedWriteData()
        attr = self.getModelObj()
        if attr.type == DataType.String:
            # String arrays has to be converted to a list
            tab = tab.tolist()
        attr.write(tab)
        self._tableView.model().clearChanges()

    def okClicked(self):
        """This is a SLOT that is being triggered when ACCEPT button is
        clicked.

        .. note::
            This SLOT is called, when user wants to apply table modifications.
            When no cell was modified it will not be called. When
            modifications have been done, they will be writen to w_value
            of an attribute.
        """
        if self._tableView.model().isDirty():
            self.applyChanges()
            self.resetWriteMode()

    def cancelClicked(self):
        """This is a SLOT that is being triggered when CANCEL button is
        clicked.

        .. note:: This SLOT is called, when user does not want to apply table
                  modifications. When no cell was modified it will not be
                  called.
        """
        if self._tableView.model().isDirty():
            self.askCancel()

    def askCancel(self):
        """
        Shows a QMessageBox, asking if user wants to cancel all changes.
        Triggered when user clicks Cancel button.
        """
        result = Qt.QMessageBox.warning(
            self,
            "Your changes will be lost!",
            "Do you want to cancel changes done to the whole table?",
            Qt.QMessageBox.Ok | Qt.QMessageBox.Cancel,
        )
        if result == Qt.QMessageBox.Ok:
            self._tableView.cancelChanges()
            self.resetWriteMode()

    def _onEditorCreated(self):
        """slot called when an editor has been created"""
        self.setWriteMode(self._writeMode)

    def getWriteMode(self):
        """whether the widget is showing the read or write values

        :return:
        :rtype: bool
        """
        return self._writeMode

    def setWriteMode(self, isWrite):
        """
        Triggered when the read mode is changed to write mode.

        :param isWrite:
        :type isWrite: bool
        """
        self._applyBT.setVisible(isWrite)
        self._cancelBT.setVisible(isWrite)
        self._rwModeCB.setChecked(isWrite)
        if self.defaultWriteMode in ("rw", "wr"):
            self._rwModeCB.setVisible(True)
        else:
            self._rwModeCB.setVisible(False)

        table_view_model = self._tableView.model()
        if table_view_model is not None:
            table_view_model.setWriteMode(isWrite)
            table_view_model._editable = isWrite
        if isWrite == self._writeMode:
            return
        self._writeMode = isWrite
        valueObj = self.getModelValueObj()
        if isWrite and valueObj is not None:
            w_value = valueObj.wvalue
            value = valueObj.rvalue
            if numpy.array(w_value).shape != numpy.array(value).shape:
                ta = self.getModelObj()
                v = ta.read()
                # fixme: this is ugly! we should not be writing into the
                #     attribute without asking first...
                ta.write(v.rvalue)

    def resetWriteMode(self):
        """equivalent to self.setWriteMode(self.defaultWriteMode)"""
        if self.defaultWriteMode == "r":
            isWritable = False
        else:
            isWritable = True
        self.setWriteMode(isWritable)

    @classmethod
    def getQtDesignerPluginInfo(cls):
        """Reimplemented from :meth:`TaurusWidget.getQtDesignerPluginInfo`"""
        ret = TaurusWidget.getQtDesignerPluginInfo()
        ret["module"] = "taurus.qt.qtgui.table"
        ret["group"] = "Taurus Views"
        ret["icon"] = "designer:table.png"
        return ret

    def chooseModel(self):
        """shows a model chooser"""
        from taurus.qt.qtgui.panel import TaurusModelChooser

        selectables = [TaurusElementType.Attribute]
        models, ok = TaurusModelChooser.modelChooserDlg(
            selectables=selectables, singleModel=True
        )
        if ok and len(models) == 1:
            self.setModel(models[0])

    def setModifiableByUser(self, modifiable):
        """Reimplemented from :meth:`TaurusWidget.setModifiableByUser`"""
        self.chooseModelAction.setEnabled(modifiable)
        TaurusWidget.setModifiableByUser(self, modifiable)

    def isReadOnly(self):
        """Reimplemented from :meth:`TaurusWidget.isReadOnly`"""
        return False

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

    model = Qt.pyqtProperty(
        "QString", TaurusWidget.getModel, setModel, TaurusWidget.resetModel
    )
    writeMode = Qt.pyqtProperty(
        "bool", getWriteMode, setWriteMode, resetWriteMode
    )


def taurusTableMain():
    """A launcher for TaurusValuesTable."""

    from taurus.qt.qtgui.application import TaurusApplication
    from taurus.core.util import argparse
    import sys
    import os

    parser = argparse.get_taurus_parser()
    parser.set_usage("%prog [options] [model]]")
    parser.set_description(
        "A table for viewing and editing 1D and 2D attribute values"
    )
    app = TaurusApplication(
        cmd_line_parser=parser,
        app_name="TaurusValuesTable",
        app_version=taurus.Release.version,
    )
    args = app.get_command_line_args()

    dialog = TaurusValuesTable()
    dialog.setModifiableByUser(True)
    dialog.setWindowTitle(app.applicationName())

    # set a model list from the command line or launch the chooser
    if len(args) == 1:
        model = args[0]
        dialog.setModel(model)
    else:
        dialog.chooseModel()
        # model = 'sys/tg_test/1/boolean_spectrum'
        # model = 'sys/tg_test/1/boolean_image'
        # model = 'sys/tg_test/1/string_spectrum'
        # model = 'sys/tg_test/1/float_image'
        # model = 'sys/tg_test/1/double_image'
        # model = 'sys/tg_test/1/double_image_ro'
        # model = 'sys/tg_test/1/wave'
        # dialog.setModel(model)

    dialog.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    taurusTableMain()