summaryrefslogtreecommitdiff
path: root/silx/gui/plot3d/SFViewParamTree.py
blob: bb81465cc9f6f01a3e7bb86a483a14c59c230852 (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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""
This module provides a tree widget to set/view parameters of a ScalarFieldView.
"""

from __future__ import absolute_import

__authors__ = ["D. N."]
__license__ = "MIT"
__date__ = "24/04/2018"

import logging
import sys
import weakref

import numpy

from silx.gui import qt
from silx.gui.icons import getQIcon
from silx.gui.colors import Colormap
from silx.gui.widgets.FloatEdit import FloatEdit

from .ScalarFieldView import Isosurface


_logger = logging.getLogger(__name__)


class ModelColumns(object):
    NameColumn, ValueColumn, ColumnMax = range(3)
    ColumnNames = ['Name', 'Value']


class SubjectItem(qt.QStandardItem):
    """
    Base class for observers items.

    Subclassing:
    ------------
    The following method can/should be reimplemented:
    - _init
    - _pullData
    - _pushData
    - _setModelData
    - _subjectChanged
    - getEditor
    - getSignals
    - leftClicked
    - queryRemove
    - setEditorData

    Also the following attributes are available:
    - editable
    - persistent

    :param subject: object that this item will be observing.
    """

    editable = False
    """ boolean: set to True to make the item editable. """

    persistent = False
    """
    boolean: set to True to make the editor persistent.
        See : Qt.QAbstractItemView.openPersistentEditor
    """

    def __init__(self, subject, *args):

        super(SubjectItem, self).__init__(*args)

        self.setEditable(self.editable)

        self.__subject = None
        self.subject = subject

    def setData(self, value, role=qt.Qt.UserRole, pushData=True):
        """
        Overloaded method from QStandardItem. The pushData keyword tells
        the item to push data to the subject if the role is equal to EditRole.
        This is useful to let this method know if the setData method was called
        internally or from the view.

        :param value: the value ti set to data
        :param role: role in the item
        :param pushData: if True push value in the existing data.
        """
        if role == qt.Qt.EditRole and pushData:
            setValue = self._pushData(value, role)
            if setValue != value:
                value = setValue
        super(SubjectItem, self).setData(value, role)

    @property
    def subject(self):
        """The subject this item is observing"""
        return None if self.__subject is None else self.__subject()

    @subject.setter
    def subject(self, subject):
        if self.__subject is not None:
            raise ValueError('Subject already set '
                             ' (subject change not supported).')
        if subject is None:
            self.__subject = None
        else:
            self.__subject = weakref.ref(subject)
        if subject is not None:
            self._init()
            self._connectSignals()

    def _connectSignals(self):
        """
        Connects the signals. Called when the subject is set.
        """

        def gen_slot(_sigIdx):
            def slotfn(*args, **kwargs):
                self._subjectChanged(signalIdx=_sigIdx,
                                     args=args,
                                     kwargs=kwargs)
            return slotfn

        if self.__subject is not None:
            self.__slots = slots = []

            signals = self.getSignals()

            if signals:
                if not isinstance(signals, (list, tuple)):
                    signals = [signals]
                for sigIdx, signal in enumerate(signals):
                    slot = gen_slot(sigIdx)
                    signal.connect(slot)
                    slots.append((signal, slot))

    def _disconnectSignals(self):
        """
        Disconnects all subject's signal
        """
        if self.__slots:
            for signal, slot in self.__slots:
                try:
                    signal.disconnect(slot)
                except TypeError:
                    pass

    def _enableRow(self, enable):
        """
        Set the enabled state for this cell, or for the whole row
        if this item has a parent.

        :param bool enable: True if we wan't to enable the cell
        """
        parent = self.parent()
        model = self.model()
        if model is None or parent is None:
            # no parent -> no siblings
            self.setEnabled(enable)
            return

        for col in range(model.columnCount()):
            sibling = parent.child(self.row(), col)
            sibling.setEnabled(enable)

    #################################################################
    # Overloadable methods
    #################################################################

    def getSignals(self):
        """
        Returns the list of this items subject's signals that
        this item will be listening to.

        :return: list.
        """
        return None

    def _subjectChanged(self, signalIdx=None, args=None, kwargs=None):
        """
        Called when one of the signals is triggered. Default implementation
        just calls _pullData, compares the result to the current value stored
        as Qt.EditRole, and stores the new value if it is different. It also
        stores its str representation as Qt.DisplayRole

        :param signalIdx: index of the triggered signal. The value passed
            is the same as the signal position in the list returned by
            SubjectItem.getSignals.
        :param args: arguments received from the signal
        :param kwargs: keyword arguments received from the signal
        """
        data = self._pullData()
        if data == self.data(qt.Qt.EditRole):
            return
        self.setData(data, role=qt.Qt.DisplayRole, pushData=False)
        self.setData(data, role=qt.Qt.EditRole, pushData=False)

    def _pullData(self):
        """
        Pulls data from the subject.

        :return: subject data
        """
        return None

    def _pushData(self, value, role=qt.Qt.UserRole):
        """
        Pushes data to the subject and returns the actual value that was stored

        :return: the value that was stored
        """
        return value

    def _init(self):
        """
        Called when the subject is set.
        :return:
        """
        self._subjectChanged()

    def getEditor(self, parent, option, index):
        """
        Returns the editor widget used to edit this item's data. The arguments
        are the one passed to the QStyledItemDelegate.createEditor method.

        :param parent: the Qt parent of the editor
        :param option:
        :param index:
        :return:
        """
        return None

    def setEditorData(self, editor):
        """
        This is called by the View's delegate just before the editor is shown,
        its purpose it to setup the editors contents. Return False to use
        the delegate's default behaviour.

        :param editor:
        :return:
        """
        return True

    def _setModelData(self, editor):
        """
        This is called by the View's delegate just before the editor is closed,
        its allows this item to update itself with data from the editor.

        :param editor:
        :return:
        """
        return False

    def queryRemove(self, view=None):
        """
        This is called by the view to ask this items if it (the view) can
        remove it. Return True to let the view know that the item can be
        removed.

        :param view:
        :return:
        """
        return False

    def leftClicked(self):
        """
        This method is called by the view when the item's cell if left clicked.

        :return:
        """
        pass


# View settings ###############################################################

class ColorItem(SubjectItem):
    """color item."""
    editable = True
    persistent = True

    def getEditor(self, parent, option, index):
        editor = QColorEditor(parent)
        editor.color = self.getColor()

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.sigColorChanged.connect(
            lambda color: self._editorSlot(color))
        return editor

    def _editorSlot(self, color):
        self.setData(color, qt.Qt.EditRole)

    def _pushData(self, value, role=qt.Qt.UserRole):
        self.setColor(value)
        return self.getColor()

    def _pullData(self):
        self.getColor()

    def setColor(self, color):
        """Override to implement actual color setter"""
        pass


class BackgroundColorItem(ColorItem):
    itemName = 'Background'

    def setColor(self, color):
        self.subject.setBackgroundColor(color)

    def getColor(self):
        return self.subject.getBackgroundColor()


class ForegroundColorItem(ColorItem):
    itemName = 'Foreground'

    def setColor(self, color):
        self.subject.setForegroundColor(color)

    def getColor(self):
        return self.subject.getForegroundColor()


class HighlightColorItem(ColorItem):
    itemName = 'Highlight'

    def setColor(self, color):
        self.subject.setHighlightColor(color)

    def getColor(self):
        return self.subject.getHighlightColor()


class _LightDirectionAngleBaseItem(SubjectItem):
    """Base class for directional light angle item."""
    editable = True
    persistent = True

    def _init(self):
        pass

    def getSignals(self):
        """Override to provide signals to listen"""
        raise NotImplementedError("MUST be implemented in subclass")

    def _pullData(self):
        """Override in subclass to get current angle"""
        raise NotImplementedError("MUST be implemented in subclass")

    def _pushData(self, value, role=qt.Qt.UserRole):
        """Override in subclass to set the angle"""
        raise NotImplementedError("MUST be implemented in subclass")

    def getEditor(self, parent, option, index):
        editor = qt.QSlider(parent)
        editor.setOrientation(qt.Qt.Horizontal)
        editor.setMinimum(-90)
        editor.setMaximum(90)
        editor.setValue(self._pullData())

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.valueChanged.connect(
            lambda value: self._pushData(value))

        return editor

    def setEditorData(self, editor):
        editor.setValue(self._pullData())
        return True

    def _setModelData(self, editor):
        value = editor.value()
        self._pushData(value)
        return True


class LightAzimuthAngleItem(_LightDirectionAngleBaseItem):
    """Light direction azimuth angle item."""

    def getSignals(self):
        return self.subject.sigAzimuthAngleChanged

    def _pullData(self):
         return self.subject.getAzimuthAngle()

    def _pushData(self, value, role=qt.Qt.UserRole):
         self.subject.setAzimuthAngle(value)


class LightAltitudeAngleItem(_LightDirectionAngleBaseItem):
    """Light direction altitude angle item."""

    def getSignals(self):
        return self.subject.sigAltitudeAngleChanged

    def _pullData(self):
         return self.subject.getAltitudeAngle()

    def _pushData(self, value, role=qt.Qt.UserRole):
         self.subject.setAltitudeAngle(value)


class _DirectionalLightProxy(qt.QObject):
    """Proxy to handle directional light with angles rather than vector.
    """

    sigAzimuthAngleChanged = qt.Signal()
    """Signal sent when the azimuth angle has changed."""

    sigAltitudeAngleChanged = qt.Signal()
    """Signal sent when altitude angle has changed."""

    def __init__(self, light):
        super(_DirectionalLightProxy, self).__init__()
        self._light = light
        light.addListener(self._directionUpdated)
        self._azimuth = 0.
        self._altitude = 0.

    def getAzimuthAngle(self):
        """Returns the signed angle in the horizontal plane.

         Unit: degrees.
        The 0 angle corresponds to the axis perpendicular to the screen.

        :rtype: float
        """
        return self._azimuth

    def getAltitudeAngle(self):
        """Returns the signed vertical angle from the horizontal plane.

        Unit: degrees.
        Range: [-90, +90]

        :rtype: float
        """
        return self._altitude

    def setAzimuthAngle(self, angle):
        """Set the horizontal angle.

        :param float angle: Angle from -z axis in zx plane in degrees.
        """
        if angle != self._azimuth:
            self._azimuth = angle
            self._updateLight()
            self.sigAzimuthAngleChanged.emit()

    def setAltitudeAngle(self, angle):
        """Set the horizontal angle.

        :param float angle: Angle from -z axis in zy plane in degrees.
        """
        if angle != self._altitude:
            self._altitude = angle
            self._updateLight()
            self.sigAltitudeAngleChanged.emit()

    def _directionUpdated(self, *args, **kwargs):
        """Handle light direction update in the scene"""
        # Invert direction to manipulate the 'source' pointing to
        # the center of the viewport
        x, y, z = - self._light.direction

        # Horizontal plane is plane xz
        azimuth = numpy.degrees(numpy.arctan2(x, z))
        altitude = numpy.degrees(numpy.pi/2. - numpy.arccos(y))

        if (abs(azimuth - self.getAzimuthAngle()) > 0.01 and
                abs(abs(altitude) - 90.) >= 0.001):  # Do not update when at zenith
            self.setAzimuthAngle(azimuth)

        if abs(altitude - self.getAltitudeAngle()) > 0.01:
            self.setAltitudeAngle(altitude)

    def _updateLight(self):
        """Update light direction in the scene"""
        azimuth = numpy.radians(self._azimuth)
        delta = numpy.pi/2. - numpy.radians(self._altitude)
        z = - numpy.sin(delta) * numpy.cos(azimuth)
        x = - numpy.sin(delta) * numpy.sin(azimuth)
        y = - numpy.cos(delta)
        self._light.direction = x, y, z


class DirectionalLightGroup(SubjectItem):
    """
    Root Item for the directional light
    """

    def __init__(self,subject, *args):
        self._light = _DirectionalLightProxy(
            subject.getPlot3DWidget().viewport.light)

        super(DirectionalLightGroup, self).__init__(subject, *args)

    def _init(self):

        nameItem = qt.QStandardItem('Azimuth')
        nameItem.setEditable(False)
        valueItem = LightAzimuthAngleItem(self._light)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Altitude')
        nameItem.setEditable(False)
        valueItem = LightAltitudeAngleItem(self._light)
        self.appendRow([nameItem, valueItem])


class BoundingBoxItem(SubjectItem):
    """Bounding box, axes labels and grid visibility item.

    Item is checkable.
    """
    itemName = 'Bounding Box'

    def _init(self):
        visible = self.subject.isBoundingBoxVisible()
        self.setCheckable(True)
        self.setCheckState(qt.Qt.Checked if visible else qt.Qt.Unchecked)

    def leftClicked(self):
        checked = (self.checkState() == qt.Qt.Checked)
        if checked != self.subject.isBoundingBoxVisible():
            self.subject.setBoundingBoxVisible(checked)


class OrientationIndicatorItem(SubjectItem):
    """Orientation indicator visibility item.

    Item is checkable.
    """
    itemName = 'Axes indicator'

    def _init(self):
        plot3d = self.subject.getPlot3DWidget()
        visible = plot3d.isOrientationIndicatorVisible()
        self.setCheckable(True)
        self.setCheckState(qt.Qt.Checked if visible else qt.Qt.Unchecked)

    def leftClicked(self):
        plot3d = self.subject.getPlot3DWidget()
        checked = (self.checkState() == qt.Qt.Checked)
        if checked != plot3d.isOrientationIndicatorVisible():
            plot3d.setOrientationIndicatorVisible(checked)


class ViewSettingsItem(qt.QStandardItem):
    """Viewport settings"""

    def __init__(self, subject, *args):

        super(ViewSettingsItem, self).__init__(*args)

        self.setEditable(False)

        classes = (BackgroundColorItem,
                   ForegroundColorItem,
                   HighlightColorItem,
                   BoundingBoxItem,
                   OrientationIndicatorItem)
        for cls in classes:
            titleItem = qt.QStandardItem(cls.itemName)
            titleItem.setEditable(False)
            self.appendRow([titleItem, cls(subject)])

        nameItem = DirectionalLightGroup(subject, 'Light Direction')
        valueItem = qt.QStandardItem()
        self.appendRow([nameItem, valueItem])


# Data information ############################################################

class DataChangedItem(SubjectItem):
    """
    Base class for items listening to ScalarFieldView.sigDataChanged
    """

    def getSignals(self):
        subject = self.subject
        if subject:
            return subject.sigDataChanged, subject.sigTransformChanged
        return None

    def _init(self):
        self._subjectChanged()


class DataTypeItem(DataChangedItem):
    itemName = 'dtype'

    def _pullData(self):
        data = self.subject.getData(copy=False)
        return ((data is not None) and str(data.dtype)) or 'N/A'


class DataShapeItem(DataChangedItem):
    itemName = 'size'

    def _pullData(self):
        data = self.subject.getData(copy=False)
        if data is None:
            return 'N/A'
        else:
            return str(list(reversed(data.shape)))


class OffsetItem(DataChangedItem):
    itemName = 'offset'

    def _pullData(self):
        offset = self.subject.getTranslation()
        return ((offset is not None) and str(offset)) or 'N/A'


class ScaleItem(DataChangedItem):
    itemName = 'scale'

    def _pullData(self):
        scale = self.subject.getScale()
        return ((scale is not None) and str(scale)) or 'N/A'


class MatrixItem(DataChangedItem):

    def __init__(self, subject, row, *args):
        self.__row = row
        super(MatrixItem, self).__init__(subject, *args)

    def _pullData(self):
        matrix = self.subject.getTransformMatrix()
        return str(matrix[self.__row])


class DataSetItem(qt.QStandardItem):

    def __init__(self, subject, *args):

        super(DataSetItem, self).__init__(*args)

        self.setEditable(False)

        klasses = [DataTypeItem, DataShapeItem, OffsetItem]
        for klass in klasses:
            titleItem = qt.QStandardItem(klass.itemName)
            titleItem.setEditable(False)
            self.appendRow([titleItem, klass(subject)])

        matrixItem = qt.QStandardItem('matrix')
        matrixItem.setEditable(False)
        valueItem = qt.QStandardItem()
        self.appendRow([matrixItem, valueItem])

        for row in range(3):
            titleItem = qt.QStandardItem()
            titleItem.setEditable(False)
            valueItem = MatrixItem(subject, row)
            matrixItem.appendRow([titleItem, valueItem])

        titleItem = qt.QStandardItem(ScaleItem.itemName)
        titleItem.setEditable(False)
        self.appendRow([titleItem, ScaleItem(subject)])


# Isosurface ##################################################################

class IsoSurfaceRootItem(SubjectItem):
    """
    Root (i.e : column index 0) Isosurface item.
    """

    def getSignals(self):
        subject = self.subject
        return [subject.sigColorChanged,
                subject.sigVisibilityChanged]

    def _subjectChanged(self, signalIdx=None, args=None, kwargs=None):
        if signalIdx == 0:
            color = self.subject.getColor()
            self.setData(color, qt.Qt.DecorationRole)
        elif signalIdx == 1:
            visible = args[0]
            self.setCheckState((visible and qt.Qt.Checked) or qt.Qt.Unchecked)

    def _init(self):
        self.setCheckable(True)

        isosurface = self.subject
        color = isosurface.getColor()
        visible = isosurface.isVisible()
        self.setData(color, qt.Qt.DecorationRole)
        self.setCheckState((visible and qt.Qt.Checked) or qt.Qt.Unchecked)

        nameItem = qt.QStandardItem('Level')
        sliderItem = IsoSurfaceLevelSlider(self.subject)
        self.appendRow([nameItem, sliderItem])

        nameItem = qt.QStandardItem('Color')
        nameItem.setEditable(False)
        valueItem = IsoSurfaceColorItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Opacity')
        nameItem.setTextAlignment(qt.Qt.AlignLeft | qt.Qt.AlignTop)
        nameItem.setEditable(False)
        valueItem = IsoSurfaceAlphaItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem()
        nameItem.setEditable(False)
        valueItem = IsoSurfaceAlphaLegendItem(self.subject)
        valueItem.setEditable(False)
        self.appendRow([nameItem, valueItem])

    def queryRemove(self, view=None):
        buttons = qt.QMessageBox.Ok | qt.QMessageBox.Cancel
        ans = qt.QMessageBox.question(view,
                                      'Remove isosurface',
                                      'Remove the selected iso-surface?',
                                      buttons=buttons)
        if ans == qt.QMessageBox.Ok:
            sfview = self.subject.parent()
            if sfview:
                sfview.removeIsosurface(self.subject)
                return False
        return False

    def leftClicked(self):
        checked = (self.checkState() == qt.Qt.Checked)
        visible = self.subject.isVisible()
        if checked != visible:
            self.subject.setVisible(checked)


class IsoSurfaceLevelItem(SubjectItem):
    """
    Base class for the isosurface level items.
    """
    editable = True

    def getSignals(self):
        subject = self.subject
        return [subject.sigLevelChanged,
                subject.sigVisibilityChanged]

    def getEditor(self, parent, option, index):
        return FloatEdit(parent)

    def setEditorData(self, editor):
        editor.setValue(self._pullData())
        return False

    def _setModelData(self, editor):
        self._pushData(editor.value())
        return True

    def _pullData(self):
        return self.subject.getLevel()

    def _pushData(self, value, role=qt.Qt.UserRole):
        self.subject.setLevel(value)
        return self.subject.getLevel()


class _IsoLevelSlider(qt.QSlider):
    """QSlider used for iso-surface level"""

    def __init__(self, parent, subject):
        super(_IsoLevelSlider, self).__init__(parent=parent)
        self.subject = subject

        self.sliderReleased.connect(self.__sliderReleased)

        self.subject.sigLevelChanged.connect(self.setLevel)
        self.subject.parent().sigDataChanged.connect(self.__dataChanged)

    def setLevel(self, level):
        """Set slider from iso-surface level"""
        dataRange = self.subject.parent().getDataRange()

        if dataRange is not None:
            width = dataRange[-1] - dataRange[0]
            if width > 0:
                sliderWidth = self.maximum() - self.minimum()
                sliderPosition = sliderWidth * (level - dataRange[0]) / width
                self.setValue(sliderPosition)

    def __dataChanged(self):
        """Handles data update to refresh slider range if needed"""
        self.setLevel(self.subject.getLevel())

    def __sliderReleased(self):
        value = self.value()
        dataRange = self.subject.parent().getDataRange()
        if dataRange is not None:
            min_, _, max_ = dataRange
            width = max_ - min_
            sliderWidth = self.maximum() - self.minimum()
            level = min_ + width * value / sliderWidth
            self.subject.setLevel(level)


class IsoSurfaceLevelSlider(IsoSurfaceLevelItem):
    """
    Isosurface level item with a slider editor.
    """
    nTicks = 1000
    persistent = True

    def getEditor(self, parent, option, index):
        editor = _IsoLevelSlider(parent, self.subject)
        editor.setOrientation(qt.Qt.Horizontal)
        editor.setMinimum(0)
        editor.setMaximum(self.nTicks)

        editor.setSingleStep(1)

        editor.setLevel(self.subject.getLevel())
        return editor

    def setEditorData(self, editor):
        return True

    def _setModelData(self, editor):
        return True


class IsoSurfaceColorItem(SubjectItem):
    """
    Isosurface color item.
    """
    editable = True
    persistent = True

    def getSignals(self):
        return self.subject.sigColorChanged

    def getEditor(self, parent, option, index):
        editor = QColorEditor(parent)
        color = self.subject.getColor()
        color.setAlpha(255)
        editor.color = color
        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.sigColorChanged.connect(
            lambda color: self.__editorChanged(color))
        return editor

    def __editorChanged(self, color):
        color.setAlpha(self.subject.getColor().alpha())
        self.subject.setColor(color)

    def _pushData(self, value, role=qt.Qt.UserRole):
        self.subject.setColor(value)
        return self.subject.getColor()


class QColorEditor(qt.QWidget):
    """
    QColor editor.
    """
    sigColorChanged = qt.Signal(object)

    color = property(lambda self: qt.QColor(self.__color))

    @color.setter
    def color(self, color):
        self._setColor(color)
        self.__previousColor = color

    def __init__(self, *args, **kwargs):
        super(QColorEditor, self).__init__(*args, **kwargs)
        layout = qt.QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        button = qt.QToolButton()
        icon = qt.QIcon(qt.QPixmap(32, 32))
        button.setIcon(icon)
        layout.addWidget(button)
        button.clicked.connect(self.__showColorDialog)
        layout.addStretch(1)

        self.__color = None
        self.__previousColor = None

    def sizeHint(self):
        return qt.QSize(0, 0)

    def _setColor(self, qColor):
        button = self.findChild(qt.QToolButton)
        pixmap = qt.QPixmap(32, 32)
        pixmap.fill(qColor)
        button.setIcon(qt.QIcon(pixmap))
        self.__color = qColor

    def __showColorDialog(self):
        dialog = qt.QColorDialog(parent=self)
        if sys.platform == 'darwin':
            # Use of native color dialog on macos might cause problems
            dialog.setOption(qt.QColorDialog.DontUseNativeDialog, True)

        self.__previousColor = self.__color
        dialog.setAttribute(qt.Qt.WA_DeleteOnClose)
        dialog.setModal(True)
        dialog.currentColorChanged.connect(self.__colorChanged)
        dialog.finished.connect(self.__dialogClosed)
        dialog.show()

    def __colorChanged(self, color):
        self.__color = color
        self._setColor(color)
        self.sigColorChanged.emit(color)

    def __dialogClosed(self, result):
        if result == qt.QDialog.Rejected:
            self.__colorChanged(self.__previousColor)
        self.__previousColor = None


class IsoSurfaceAlphaItem(SubjectItem):
    """
    Isosurface alpha item.
    """
    editable = True
    persistent = True

    def _init(self):
        pass

    def getSignals(self):
        return self.subject.sigColorChanged

    def getEditor(self, parent, option, index):
        editor = qt.QSlider(parent)
        editor.setOrientation(qt.Qt.Horizontal)
        editor.setMinimum(0)
        editor.setMaximum(255)

        color = self.subject.getColor()
        editor.setValue(color.alpha())

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.valueChanged.connect(
            lambda value: self.__editorChanged(value))

        return editor

    def __editorChanged(self, value):
        color = self.subject.getColor()
        color.setAlpha(value)
        self.subject.setColor(color)

    def setEditorData(self, editor):
        return True

    def _setModelData(self, editor):
        return True


class IsoSurfaceAlphaLegendItem(SubjectItem):
    """Legend to place under opacity slider"""

    editable = False
    persistent = True

    def getEditor(self, parent, option, index):
        layout = qt.QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(qt.QLabel('0'))
        layout.addStretch(1)
        layout.addWidget(qt.QLabel('1'))

        editor = qt.QWidget(parent)
        editor.setLayout(layout)
        return editor


class IsoSurfaceCount(SubjectItem):
    """
    Item displaying the number of isosurfaces.
    """

    def getSignals(self):
        subject = self.subject
        return [subject.sigIsosurfaceAdded, subject.sigIsosurfaceRemoved]

    def _pullData(self):
        return len(self.subject.getIsosurfaces())


class IsoSurfaceAddRemoveWidget(qt.QWidget):

    sigViewTask = qt.Signal(str)
    """Signal for the tree view to perform some task"""

    def __init__(self, parent, item):
        super(IsoSurfaceAddRemoveWidget, self).__init__(parent)
        self._item = item
        layout = qt.QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        addBtn = qt.QToolButton(self)
        addBtn.setText('+')
        addBtn.setToolButtonStyle(qt.Qt.ToolButtonTextOnly)
        layout.addWidget(addBtn)
        addBtn.clicked.connect(self.__addClicked)

        removeBtn = qt.QToolButton(self)
        removeBtn.setText('-')
        removeBtn.setToolButtonStyle(qt.Qt.ToolButtonTextOnly)
        layout.addWidget(removeBtn)
        removeBtn.clicked.connect(self.__removeClicked)

        layout.addStretch(1)

    def __addClicked(self):
        sfview = self._item.subject
        if not sfview:
            return
        dataRange = sfview.getDataRange()
        if dataRange is None:
            dataRange = [0, 1]

        sfview.addIsosurface(
            numpy.mean((dataRange[0], dataRange[-1])), '#0000FF')

    def __removeClicked(self):
        self.sigViewTask.emit('remove_iso')


class IsoSurfaceAddRemoveItem(SubjectItem):
    """
    Item displaying a simple QToolButton allowing to add an isosurface.
    """
    persistent = True

    def getEditor(self, parent, option, index):
        return IsoSurfaceAddRemoveWidget(parent, self)


class IsoSurfaceGroup(SubjectItem):
    """
    Root item for the list of isosurface items.
    """
    def getSignals(self):
        subject = self.subject
        return [subject.sigIsosurfaceAdded, subject.sigIsosurfaceRemoved]

    def _subjectChanged(self, signalIdx=None, args=None, kwargs=None):
        if signalIdx == 0:
            if len(args) >= 1:
                isosurface = args[0]
                if not isinstance(isosurface, Isosurface):
                    raise ValueError('Expected an isosurface instance.')
                self.__addIsosurface(isosurface)
            else:
                raise ValueError('Expected an isosurface instance.')
        elif signalIdx == 1:
            if len(args) >= 1:
                isosurface = args[0]
                if not isinstance(isosurface, Isosurface):
                    raise ValueError('Expected an isosurface instance.')
                self.__removeIsosurface(isosurface)
            else:
                raise ValueError('Expected an isosurface instance.')

    def __addIsosurface(self, isosurface):
        valueItem = IsoSurfaceRootItem(subject=isosurface)
        nameItem = IsoSurfaceLevelItem(subject=isosurface)
        self.insertRow(max(0, self.rowCount() - 1), [valueItem, nameItem])

    def __removeIsosurface(self, isosurface):
        for row in range(self.rowCount()):
            child = self.child(row)
            subject = getattr(child, 'subject', None)
            if subject == isosurface:
                self.takeRow(row)
                break

    def _init(self):
        nameItem = IsoSurfaceAddRemoveItem(self.subject)
        valueItem = qt.QStandardItem()
        valueItem.setEditable(False)
        self.appendRow([nameItem, valueItem])

        subject = self.subject
        isosurfaces = subject.getIsosurfaces()
        for isosurface in isosurfaces:
            self.__addIsosurface(isosurface)


# Cutting Plane ###############################################################

class ColormapBase(SubjectItem):
    """
    Mixin class for colormap items.
    """

    def getSignals(self):
        return [self.subject.getCutPlanes()[0].sigColormapChanged]


class PlaneMinRangeItem(ColormapBase):
    """
    colormap minVal item.
    Editor is a QLineEdit with a QDoubleValidator
    """
    editable = True

    def _pullData(self):
        colormap = self.subject.getCutPlanes()[0].getColormap()
        auto = colormap.isAutoscale()
        if auto == self.isEnabled():
            self._enableRow(not auto)
        return colormap.getVMin()

    def _pushData(self, value, role=qt.Qt.UserRole):
        self._setVMin(value)

    def _setVMin(self, value):
        colormap = self.subject.getCutPlanes()[0].getColormap()
        vMin = value
        vMax = colormap.getVMax()

        if vMax is not None and value > vMax:
            vMin = vMax
            vMax = value
        colormap.setVRange(vMin, vMax)

    def getEditor(self, parent, option, index):
        return FloatEdit(parent)

    def setEditorData(self, editor):
        editor.setValue(self._pullData())
        return True

    def _setModelData(self, editor):
        value = editor.value()
        self._setVMin(value)
        return True


class PlaneMaxRangeItem(ColormapBase):
    """
    colormap maxVal item.
    Editor is a QLineEdit with a QDoubleValidator
    """
    editable = True

    def _pullData(self):
        colormap = self.subject.getCutPlanes()[0].getColormap()
        auto = colormap.isAutoscale()
        if auto == self.isEnabled():
            self._enableRow(not auto)
        return self.subject.getCutPlanes()[0].getColormap().getVMax()

    def _setVMax(self, value):
        colormap = self.subject.getCutPlanes()[0].getColormap()
        vMin = colormap.getVMin()
        vMax = value
        if vMin is not None and value < vMin:
            vMax = vMin
            vMin = value
        colormap.setVRange(vMin, vMax)

    def getEditor(self, parent, option, index):
        return FloatEdit(parent)

    def setEditorData(self, editor):
        editor.setText(str(self._pullData()))
        return True

    def _setModelData(self, editor):
        value = editor.value()
        self._setVMax(value)
        return True


class PlaneOrientationItem(SubjectItem):
    """
    Plane orientation item.
    Editor is a QComboBox.
    """
    editable = True

    _PLANE_ACTIONS = (
        ('3d-plane-normal-x', 'Plane 0',
         'Set plane perpendicular to red axis', (1., 0., 0.)),
        ('3d-plane-normal-y', 'Plane 1',
         'Set plane perpendicular to green axis', (0., 1., 0.)),
        ('3d-plane-normal-z', 'Plane 2',
         'Set plane perpendicular to blue axis', (0., 0., 1.)),
    )

    def getSignals(self):
        return [self.subject.getCutPlanes()[0].sigPlaneChanged]

    def _pullData(self):
        currentNormal = self.subject.getCutPlanes()[0].getNormal(
            coordinates='scene')
        for _, text, _, normal in self._PLANE_ACTIONS:
            if numpy.allclose(normal, currentNormal):
                return text
        return ''

    def getEditor(self, parent, option, index):
        editor = qt.QComboBox(parent)
        for iconName, text, tooltip, normal in self._PLANE_ACTIONS:
            editor.addItem(getQIcon(iconName), text)

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.currentIndexChanged[int].connect(
            lambda index: self.__editorChanged(index))
        return editor

    def __editorChanged(self, index):
        normal = self._PLANE_ACTIONS[index][3]
        plane = self.subject.getCutPlanes()[0]
        plane.setNormal(normal, coordinates='scene')
        plane.moveToCenter()

    def setEditorData(self, editor):
        currentText = self._pullData()
        index = 0
        for normIdx, (_, text, _, _) in enumerate(self._PLANE_ACTIONS):
            if text == currentText:
                index = normIdx
                break
        editor.setCurrentIndex(index)
        return True

    def _setModelData(self, editor):
        return True


class PlaneInterpolationItem(SubjectItem):
    """Toggle cut plane interpolation method: nearest or linear.

    Item is checkable
    """

    def _init(self):
        interpolation = self.subject.getCutPlanes()[0].getInterpolation()
        self.setCheckable(True)
        self.setCheckState(
            qt.Qt.Checked if interpolation == 'linear' else qt.Qt.Unchecked)
        self.setData(self._pullData(), role=qt.Qt.DisplayRole, pushData=False)

    def getSignals(self):
        return [self.subject.getCutPlanes()[0].sigInterpolationChanged]

    def leftClicked(self):
        checked = self.checkState() == qt.Qt.Checked
        self._setInterpolation('linear' if checked else 'nearest')

    def _pullData(self):
        interpolation = self.subject.getCutPlanes()[0].getInterpolation()
        self._setInterpolation(interpolation)
        return interpolation[0].upper() + interpolation[1:]

    def _setInterpolation(self, interpolation):
        self.subject.getCutPlanes()[0].setInterpolation(interpolation)


class PlaneDisplayBelowMinItem(SubjectItem):
    """Toggle whether to display or not values <= colormap min of the cut plane

    Item is checkable
    """

    def _init(self):
        display = self.subject.getCutPlanes()[0].getDisplayValuesBelowMin()
        self.setCheckable(True)
        self.setCheckState(
            qt.Qt.Checked if display else qt.Qt.Unchecked)
        self.setData(self._pullData(), role=qt.Qt.DisplayRole, pushData=False)

    def getSignals(self):
        return [self.subject.getCutPlanes()[0].sigTransparencyChanged]

    def leftClicked(self):
        checked = self.checkState() == qt.Qt.Checked
        self._setDisplayValuesBelowMin(checked)

    def _pullData(self):
        display = self.subject.getCutPlanes()[0].getDisplayValuesBelowMin()
        self._setDisplayValuesBelowMin(display)
        return "Displayed" if display else "Hidden"

    def _setDisplayValuesBelowMin(self, display):
        self.subject.getCutPlanes()[0].setDisplayValuesBelowMin(display)


class PlaneColormapItem(ColormapBase):
    """
    colormap name item.
    Editor is a QComboBox
    """
    editable = True

    listValues = ['gray', 'reversed gray',
                  'temperature', 'red',
                  'green', 'blue',
                  'viridis', 'magma', 'inferno', 'plasma']

    def getEditor(self, parent, option, index):
        editor = qt.QComboBox(parent)
        editor.addItems(self.listValues)

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.currentIndexChanged[int].connect(
            lambda index: self.__editorChanged(index))

        return editor

    def __editorChanged(self, index):
        colormapName = self.listValues[index]
        colormap = self.subject.getCutPlanes()[0].getColormap()
        colormap.setName(colormapName)

    def setEditorData(self, editor):
        colormapName = self.subject.getCutPlanes()[0].getColormap().getName()
        try:
            index = self.listValues.index(colormapName)
        except ValueError:
            _logger.error('Unsupported colormap: %s', colormapName)
        else:
            editor.setCurrentIndex(index)
        return True

    def _setModelData(self, editor):
        self.__editorChanged(editor.currentIndex())
        return True

    def _pullData(self):
        return self.subject.getCutPlanes()[0].getColormap().getName()


class PlaneAutoScaleItem(ColormapBase):
    """
    colormap autoscale item.
    Item is checkable.
    """

    def _init(self):
        colorMap = self.subject.getCutPlanes()[0].getColormap()
        self.setCheckable(True)
        self.setCheckState((colorMap.isAutoscale() and qt.Qt.Checked)
                           or qt.Qt.Unchecked)
        self.setData(self._pullData(), role=qt.Qt.DisplayRole, pushData=False)

    def leftClicked(self):
        checked = (self.checkState() == qt.Qt.Checked)
        self._setAutoScale(checked)

    def _setAutoScale(self, auto):
        view3d = self.subject
        colormap = view3d.getCutPlanes()[0].getColormap()

        if auto != colormap.isAutoscale():
            if auto:
                vMin = vMax = None
            else:
                dataRange = view3d.getDataRange()
                if dataRange is None:
                    vMin = vMax = None
                else:
                    vMin, vMax = dataRange[0], dataRange[-1]
            colormap.setVRange(vMin, vMax)

    def _pullData(self):
        auto = self.subject.getCutPlanes()[0].getColormap().isAutoscale()
        self._setAutoScale(auto)
        if auto:
            data = 'Auto'
        else:
            data = 'User'
        return data


class NormalizationNode(ColormapBase):
    """
    colormap normalization item.
    Item is a QComboBox.
    """
    editable = True
    listValues = list(Colormap.NORMALIZATIONS)

    def getEditor(self, parent, option, index):
        editor = qt.QComboBox(parent)
        editor.addItems(self.listValues)

        # Wrapping call in lambda is a workaround for PySide with Python 3
        editor.currentIndexChanged[int].connect(
            lambda index: self.__editorChanged(index))

        return editor

    def __editorChanged(self, index):
        colorMap = self.subject.getCutPlanes()[0].getColormap()
        normalization = self.listValues[index]
        self.subject.getCutPlanes()[0].setColormap(name=colorMap.getName(),
                                                   norm=normalization,
                                                   vmin=colorMap.getVMin(),
                                                   vmax=colorMap.getVMax())

    def setEditorData(self, editor):
        normalization = self.subject.getCutPlanes()[0].getColormap().getNormalization()
        index = self.listValues.index(normalization)
        editor.setCurrentIndex(index)
        return True

    def _setModelData(self, editor):
        self.__editorChanged(editor.currentIndex())
        return True

    def _pullData(self):
        return self.subject.getCutPlanes()[0].getColormap().getNormalization()


class PlaneGroup(SubjectItem):
    """
    Root Item for the plane items.
    """
    def _init(self):
        valueItem = qt.QStandardItem()
        valueItem.setEditable(False)
        nameItem = PlaneVisibleItem(self.subject, 'Visible')
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Colormap')
        nameItem.setEditable(False)
        valueItem = PlaneColormapItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Normalization')
        nameItem.setEditable(False)
        valueItem = NormalizationNode(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Orientation')
        nameItem.setEditable(False)
        valueItem = PlaneOrientationItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Interpolation')
        nameItem.setEditable(False)
        valueItem = PlaneInterpolationItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Autoscale')
        nameItem.setEditable(False)
        valueItem = PlaneAutoScaleItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Min')
        nameItem.setEditable(False)
        valueItem = PlaneMinRangeItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Max')
        nameItem.setEditable(False)
        valueItem = PlaneMaxRangeItem(self.subject)
        self.appendRow([nameItem, valueItem])

        nameItem = qt.QStandardItem('Values<=Min')
        nameItem.setEditable(False)
        valueItem = PlaneDisplayBelowMinItem(self.subject)
        self.appendRow([nameItem, valueItem])


class PlaneVisibleItem(SubjectItem):
    """
    Plane visibility item.
    Item is checkable.
    """
    def _init(self):
        plane = self.subject.getCutPlanes()[0]
        self.setCheckable(True)
        self.setCheckState((plane.isVisible() and qt.Qt.Checked)
                           or qt.Qt.Unchecked)

    def leftClicked(self):
        plane = self.subject.getCutPlanes()[0]
        checked = (self.checkState() == qt.Qt.Checked)
        if checked != plane.isVisible():
            plane.setVisible(checked)
            if plane.isVisible():
                plane.moveToCenter()


# Tree ########################################################################

class ItemDelegate(qt.QStyledItemDelegate):
    """
    Delegate for the QTreeView filled with SubjectItems.
    """

    sigDelegateEvent = qt.Signal(str)

    def __init__(self, parent=None):
        super(ItemDelegate, self).__init__(parent)

    def createEditor(self, parent, option, index):
        item = index.model().itemFromIndex(index)
        if item:
            if isinstance(item, SubjectItem):
                editor = item.getEditor(parent, option, index)
                if editor:
                    editor.setAutoFillBackground(True)
                    if hasattr(editor, 'sigViewTask'):
                        editor.sigViewTask.connect(self.__viewTask)
                    return editor

        editor = super(ItemDelegate, self).createEditor(parent,
                                                        option,
                                                        index)
        return editor

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def setEditorData(self, editor, index):
        item = index.model().itemFromIndex(index)
        if item:
            if isinstance(item, SubjectItem) and item.setEditorData(editor):
                return
        super(ItemDelegate, self).setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        item = index.model().itemFromIndex(index)
        if isinstance(item, SubjectItem) and item._setModelData(editor):
            return
        super(ItemDelegate, self).setModelData(editor, model, index)

    def __viewTask(self, task):
        self.sigDelegateEvent.emit(task)


class TreeView(qt.QTreeView):
    """
    TreeView displaying the SubjectItems for the ScalarFieldView.
    """

    def __init__(self, parent=None):
        super(TreeView, self).__init__(parent)
        self.__openedIndex = None

        self.setIconSize(qt.QSize(16, 16))

        header = self.header()
        if hasattr(header, 'setSectionResizeMode'):  # Qt5
            header.setSectionResizeMode(qt.QHeaderView.ResizeToContents)
        else:  # Qt4
            header.setResizeMode(qt.QHeaderView.ResizeToContents)

        delegate = ItemDelegate()
        self.setItemDelegate(delegate)
        delegate.sigDelegateEvent.connect(self.__delegateEvent)
        self.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self.setSelectionMode(qt.QAbstractItemView.SingleSelection)

        self.clicked.connect(self.__clicked)

    def setSfView(self, sfView):
        """
        Sets the ScalarFieldView this view is controlling.

        :param sfView: A `ScalarFieldView`
        """
        model = qt.QStandardItemModel()
        model.setColumnCount(ModelColumns.ColumnMax)
        model.setHorizontalHeaderLabels(['Name', 'Value'])

        item = qt.QStandardItem()
        item.setEditable(False)
        model.appendRow([ViewSettingsItem(sfView, 'Style'), item])

        item = qt.QStandardItem()
        item.setEditable(False)
        model.appendRow([DataSetItem(sfView, 'Data'), item])

        item = IsoSurfaceCount(sfView)
        item.setEditable(False)
        model.appendRow([IsoSurfaceGroup(sfView, 'Isosurfaces'), item])

        item = qt.QStandardItem()
        item.setEditable(False)
        model.appendRow([PlaneGroup(sfView, 'Cutting Plane'), item])

        self.setModel(model)

    def setModel(self, model):
        """
        Reimplementation of the QTreeView.setModel method. It connects the
        rowsRemoved signal and opens the persistent editors.

        :param qt.QStandardItemModel model: the model
        """

        prevModel = self.model()
        if prevModel:
            self.__openPersistentEditors(qt.QModelIndex(), False)
            try:
                prevModel.rowsRemoved.disconnect(self.rowsRemoved)
            except TypeError:
                pass

        super(TreeView, self).setModel(model)
        model.rowsRemoved.connect(self.rowsRemoved)
        self.__openPersistentEditors(qt.QModelIndex())

    def __openPersistentEditors(self, parent=None, openEditor=True):
        """
        Opens or closes the items persistent editors.

        :param qt.QModelIndex parent: starting index, or None if the whole tree
            is to be considered.
        :param bool openEditor: True to open the editors, False to close them.
        """
        model = self.model()

        if not model:
            return

        if not parent or not parent.isValid():
            parent = self.model().invisibleRootItem().index()

        if openEditor:
            meth = self.openPersistentEditor
        else:
            meth = self.closePersistentEditor

        curParent = parent
        children = [model.index(row, 0, curParent)
                    for row in range(model.rowCount(curParent))]

        columnCount = model.columnCount()

        while len(children) > 0:
            curParent = children.pop(-1)

            children.extend([model.index(row, 0, curParent)
                             for row in range(model.rowCount(curParent))])

            for colIdx in range(columnCount):
                sibling = model.sibling(curParent.row(),
                                        colIdx,
                                        curParent)
                item = model.itemFromIndex(sibling)
                if isinstance(item, SubjectItem) and item.persistent:
                    meth(sibling)

    def rowsAboutToBeRemoved(self, parent, start, end):
        """
        Reimplementation of the QTreeView.rowsAboutToBeRemoved. Closes all
        persistent editors under parent.

        :param qt.QModelIndex parent: Parent index
        :param int start: Start index from parent index (inclusive)
        :param int end: End index from parent index (inclusive)
        """
        self.__openPersistentEditors(parent, False)
        super(TreeView, self).rowsAboutToBeRemoved(parent, start, end)

    def rowsRemoved(self, parent, start, end):
        """
        Called when QTreeView.rowsRemoved is emitted. Opens all persistent
        editors under parent.

        :param qt.QModelIndex parent: Parent index
        :param int start: Start index from parent index (inclusive)
        :param int end: End index from parent index (inclusive)
        """
        super(TreeView, self).rowsRemoved(parent, start, end)
        self.__openPersistentEditors(parent, True)

    def rowsInserted(self, parent, start, end):
        """
        Reimplementation of the QTreeView.rowsInserted. Opens all persistent
        editors under parent.

        :param qt.QModelIndex parent: Parent index
        :param int start: Start index from parent index
        :param int end: End index from parent index
        """
        self.__openPersistentEditors(parent, False)
        super(TreeView, self).rowsInserted(parent, start, end)
        self.__openPersistentEditors(parent)

    def keyReleaseEvent(self, event):
        """
        Reimplementation of the QTreeView.keyReleaseEvent.
        At the moment only Key_Delete is handled. It calls the selected item's
        queryRemove method, and deleted the item if needed.

        :param qt.QKeyEvent event: A key event
        """

        # TODO : better filtering
        key = event.key()
        modifiers = event.modifiers()

        if key == qt.Qt.Key_Delete and modifiers == qt.Qt.NoModifier:
            self.__removeIsosurfaces()

        super(TreeView, self).keyReleaseEvent(event)

    def __removeIsosurfaces(self):
        model = self.model()
        selected = self.selectedIndexes()
        items = []
        # WARNING : the selection mode is set to single, so we re not
        # supposed to have more than one item here.
        # Multiple selection deletion has not been tested.
        # Watch out for index invalidation
        for index in selected:
            leftIndex = model.sibling(index.row(), 0, index)
            leftItem = model.itemFromIndex(leftIndex)
            if isinstance(leftItem, SubjectItem) and leftItem not in items:
                items.append(leftItem)

        isos = [item for item in items if isinstance(item, IsoSurfaceRootItem)]
        if isos:
            for iso in isos:
                if iso.queryRemove(self):
                    parentItem = iso.parent()
                    parentItem.removeRow(iso.row())
        else:
            qt.QMessageBox.information(
                self,
                'Remove isosurface',
                'Select an iso-surface to remove it')

    def __clicked(self, index):
        """
        Called when the QTreeView.clicked signal is emitted. Calls the item's
        leftClick method.

        :param qt.QIndex index: An index
        """
        item = self.model().itemFromIndex(index)
        if isinstance(item, SubjectItem):
            item.leftClicked()

    def __delegateEvent(self, task):
        if task == 'remove_iso':
            self.__removeIsosurfaces()