summaryrefslogtreecommitdiff
path: root/silx/gui/plot3d/_model/items.py
blob: 7f3921a03975f6359a2f2e05d054d55f5d348469 (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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017-2019 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 base classes to implement models for 3D scene content
"""

from __future__ import absolute_import, division

__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "24/04/2018"


from collections import OrderedDict
import functools
import logging
import weakref

import numpy
import six

from ...utils.image import convertArrayToQImage
from ...colors import preferredColormaps
from ... import qt, icons
from .. import items
from ..items.volume import Isosurface, CutPlane, ComplexIsosurface
from ..Plot3DWidget import Plot3DWidget


from .core import AngleDegreeRow, BaseRow, ColorProxyRow, ProxyRow, StaticRow


_logger = logging.getLogger(__name__)


class ItemProxyRow(ProxyRow):
    """Provides a node to proxy a data accessible through functions.

    It listens on sigItemChanged to trigger the update.

    Warning: Only weak reference are kept on fget and fset.

    :param Item3D item: The item to
    :param str name: The name of this node
    :param callable fget: A callable returning the data
    :param callable fset:
        An optional callable setting the data with data as a single argument.
    :param events:
        An optional event kind or list of event kinds to react upon.
    :param callable toModelData:
        An optional callable to convert from fget
        callable to data returned by the model.
    :param callable fromModelData:
        An optional callable converting data provided to the model to
        data for fset.
    :param editorHint: Data to provide as UserRole for editor selection/setup
    """

    def __init__(self,
                 item,
                 name='',
                 fget=None,
                 fset=None,
                 events=None,
                 toModelData=None,
                 fromModelData=None,
                 editorHint=None):
        super(ItemProxyRow, self).__init__(
            name=name,
            fget=fget,
            fset=fset,
            notify=None,
            toModelData=toModelData,
            fromModelData=fromModelData,
            editorHint=editorHint)

        if isinstance(events, (items.ItemChangedType,
                               items.Item3DChangedType)):
            events = (events,)
        self.__events = events
        item.sigItemChanged.connect(self.__itemChanged)

    def __itemChanged(self, event):
        """Handle item changed

        :param Union[ItemChangedType,Item3DChangedType] event:
        """
        if self.__events is None or event in self.__events:
            self._notified()


class ItemColorProxyRow(ColorProxyRow, ItemProxyRow):
    """Combines :class:`ColorProxyRow` and :class:`ItemProxyRow`"""

    def __init__(self, *args, **kwargs):
        ItemProxyRow.__init__(self, *args, **kwargs)


class ItemAngleDegreeRow(AngleDegreeRow, ItemProxyRow):
    """Combines :class:`AngleDegreeRow` and :class:`ItemProxyRow`"""

    def __init__(self, *args, **kwargs):
        ItemProxyRow.__init__(self, *args, **kwargs)


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: int
        """
        return self._azimuth

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

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

        :rtype: int
        """
        return self._altitude

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

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

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

        :param int angle: Angle from -z axis in zy plane in degrees.
        """
        angle = int(round(angle))
        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 = int(round(numpy.degrees(numpy.arctan2(x, z))))
        altitude = int(round(numpy.degrees(numpy.pi/2. - numpy.arccos(y))))

        if azimuth != self.getAzimuthAngle():
            self.setAzimuthAngle(azimuth)

        if altitude != self.getAltitudeAngle():
            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)
        if delta == 0.:  # Avoids zenith position
            delta = 0.0001
        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 Settings(StaticRow):
    """Subtree for :class:`SceneWidget` style parameters.

    :param SceneWidget sceneWidget: The widget to control
    """

    def __init__(self, sceneWidget):
        background = ColorProxyRow(
            name='Background',
            fget=sceneWidget.getBackgroundColor,
            fset=sceneWidget.setBackgroundColor,
            notify=sceneWidget.sigStyleChanged)

        foreground = ColorProxyRow(
            name='Foreground',
            fget=sceneWidget.getForegroundColor,
            fset=sceneWidget.setForegroundColor,
            notify=sceneWidget.sigStyleChanged)

        text = ColorProxyRow(
            name='Text',
            fget=sceneWidget.getTextColor,
            fset=sceneWidget.setTextColor,
            notify=sceneWidget.sigStyleChanged)

        highlight = ColorProxyRow(
            name='Highlight',
            fget=sceneWidget.getHighlightColor,
            fset=sceneWidget.setHighlightColor,
            notify=sceneWidget.sigStyleChanged)

        axesIndicator = ProxyRow(
            name='Axes Indicator',
            fget=sceneWidget.isOrientationIndicatorVisible,
            fset=sceneWidget.setOrientationIndicatorVisible,
            notify=sceneWidget.sigStyleChanged)

        # Light direction

        self._lightProxy = _DirectionalLightProxy(sceneWidget.viewport.light)

        azimuthNode = ProxyRow(
            name='Azimuth',
            fget=self._lightProxy.getAzimuthAngle,
            fset=self._lightProxy.setAzimuthAngle,
            notify=self._lightProxy.sigAzimuthAngleChanged,
            editorHint=(-90, 90))

        altitudeNode = ProxyRow(
            name='Altitude',
            fget=self._lightProxy.getAltitudeAngle,
            fset=self._lightProxy.setAltitudeAngle,
            notify=self._lightProxy.sigAltitudeAngleChanged,
            editorHint=(-90, 90))

        lightDirection = StaticRow(('Light Direction', None),
                                   children=(azimuthNode, altitudeNode))

        # Fog
        fog = ProxyRow(
            name='Fog',
            fget=sceneWidget.getFogMode,
            fset=sceneWidget.setFogMode,
            notify=sceneWidget.sigStyleChanged,
            toModelData=lambda mode: mode is Plot3DWidget.FogMode.LINEAR,
            fromModelData=lambda mode: Plot3DWidget.FogMode.LINEAR if mode else Plot3DWidget.FogMode.NONE)

        # Settings row
        children = (background, foreground, text, highlight,
                    axesIndicator, lightDirection, fog)
        super(Settings, self).__init__(('Settings', None), children=children)


class Item3DRow(BaseRow):
    """Represents an :class:`Item3D` with checkable visibility

    :param Item3D item: The scene item to represent.
    :param str name: The optional name of the item
    """

    _EVENTS = items.ItemChangedType.VISIBLE, items.Item3DChangedType.LABEL
    """Events for which to update the first column in the tree"""

    def __init__(self, item, name=None):
        self.__name = None if name is None else six.text_type(name)
        super(Item3DRow, self).__init__()

        self.setFlags(
            self.flags(0) | qt.Qt.ItemIsUserCheckable | qt.Qt.ItemIsSelectable,
            0)
        self.setFlags(self.flags(1) | qt.Qt.ItemIsSelectable, 1)

        self._item = weakref.ref(item)
        item.sigItemChanged.connect(self._itemChanged)

    def _itemChanged(self, event):
        """Handle model update upon change"""
        if event in self._EVENTS:
            model = self.model()
            if model is not None:
                index = self.index(column=0)
                model.dataChanged.emit(index, index)

    def item(self):
        """Returns the :class:`Item3D` item or None"""
        return self._item()

    def data(self, column, role):
        if column == 0:
            if role == qt.Qt.CheckStateRole:
                item = self.item()
                if item is not None and item.isVisible():
                    return qt.Qt.Checked
                else:
                    return qt.Qt.Unchecked

            elif role == qt.Qt.DecorationRole:
                return icons.getQIcon('item-3dim')

            elif role == qt.Qt.DisplayRole:
                if self.__name is None:
                    item = self.item()
                    return '' if item is None else item.getLabel()
                else:
                    return self.__name

        return super(Item3DRow, self).data(column, role)

    def setData(self, column, value, role):
        if column == 0 and role == qt.Qt.CheckStateRole:
            item = self.item()
            if item is not None:
                item.setVisible(value == qt.Qt.Checked)
                return True
            else:
                return False
        return super(Item3DRow, self).setData(column, value, role)

    def columnCount(self):
        return 2


class DataItem3DBoundingBoxRow(ItemProxyRow):
    """Represents :class:`DataItem3D` bounding box visibility

    :param DataItem3D item: The item for which to display/control bounding box
    """

    def __init__(self, item):
        super(DataItem3DBoundingBoxRow, self).__init__(
            item=item,
            name='Bounding box',
            fget=item.isBoundingBoxVisible,
            fset=item.setBoundingBoxVisible,
            events=items.Item3DChangedType.BOUNDING_BOX_VISIBLE)


class MatrixProxyRow(ItemProxyRow):
    """Proxy for a row of a DataItem3D 3x3 matrix transform

    :param DataItem3D item:
    :param int index: Matrix row index
    """

    def __init__(self, item, index):
        self._item = weakref.ref(item)
        self._index = index

        super(MatrixProxyRow, self).__init__(
            item=item,
            name='',
            fget=self._getMatrixRow,
            fset=self._setMatrixRow,
            events=items.Item3DChangedType.TRANSFORM)

    def _getMatrixRow(self):
        """Returns the matrix row.

        :rtype: QVector3D
        """
        item = self._item()
        if item is not None:
            matrix = item.getMatrix()
            return qt.QVector3D(*matrix[self._index, :])
        else:
            return None

    def _setMatrixRow(self, row):
        """Set the row of the matrix

        :param QVector3D row: Row values to set
        """
        item = self._item()
        if item is not None:
            matrix = item.getMatrix()
            matrix[self._index, :] = row.x(), row.y(), row.z()
            item.setMatrix(matrix)

    def data(self, column, role):
        data = super(MatrixProxyRow, self).data(column, role)

        if column == 1 and role == qt.Qt.DisplayRole:
            # Convert QVector3D to text
            data = "%g; %g; %g" % (data.x(), data.y(), data.z())

        return data


class DataItem3DTransformRow(StaticRow):
    """Represents :class:`DataItem3D` transform parameters

    :param DataItem3D item: The item for which to display/control transform
    """

    _ROTATION_CENTER_OPTIONS = 'Origin', 'Lower', 'Center', 'Upper'

    def __init__(self, item):
        super(DataItem3DTransformRow, self).__init__(('Transform', None))
        self._item = weakref.ref(item)

        translation = ItemProxyRow(
            item=item,
            name='Translation',
            fget=item.getTranslation,
            fset=self._setTranslation,
            events=items.Item3DChangedType.TRANSFORM,
            toModelData=lambda data: qt.QVector3D(*data))
        self.addRow(translation)

        # Here to keep a reference
        self._xSetCenter = functools.partial(self._setCenter, index=0)
        self._ySetCenter = functools.partial(self._setCenter, index=1)
        self._zSetCenter = functools.partial(self._setCenter, index=2)

        rotateCenter = StaticRow(
            ('Center', None),
            children=(
                ItemProxyRow(item=item,
                             name='X axis',
                             fget=item.getRotationCenter,
                             fset=self._xSetCenter,
                             events=items.Item3DChangedType.TRANSFORM,
                             toModelData=functools.partial(
                                 self._centerToModelData, index=0),
                             editorHint=self._ROTATION_CENTER_OPTIONS),
                ItemProxyRow(item=item,
                             name='Y axis',
                             fget=item.getRotationCenter,
                             fset=self._ySetCenter,
                             events=items.Item3DChangedType.TRANSFORM,
                             toModelData=functools.partial(
                                 self._centerToModelData, index=1),
                             editorHint=self._ROTATION_CENTER_OPTIONS),
                ItemProxyRow(item=item,
                             name='Z axis',
                             fget=item.getRotationCenter,
                             fset=self._zSetCenter,
                             events=items.Item3DChangedType.TRANSFORM,
                             toModelData=functools.partial(
                                 self._centerToModelData, index=2),
                             editorHint=self._ROTATION_CENTER_OPTIONS),
            ))

        rotate = StaticRow(
            ('Rotation', None),
            children=(
                ItemAngleDegreeRow(
                    item=item,
                    name='Angle',
                    fget=item.getRotation,
                    fset=self._setAngle,
                    events=items.Item3DChangedType.TRANSFORM,
                    toModelData=lambda data: data[0]),
                ItemProxyRow(
                    item=item,
                    name='Axis',
                    fget=item.getRotation,
                    fset=self._setAxis,
                    events=items.Item3DChangedType.TRANSFORM,
                    toModelData=lambda data: qt.QVector3D(*data[1])),
                rotateCenter
            ))
        self.addRow(rotate)

        scale = ItemProxyRow(
            item=item,
            name='Scale',
            fget=item.getScale,
            fset=self._setScale,
            events=items.Item3DChangedType.TRANSFORM,
            toModelData=lambda data: qt.QVector3D(*data))
        self.addRow(scale)

        matrix = StaticRow(
            ('Matrix', None),
            children=(MatrixProxyRow(item, 0),
                      MatrixProxyRow(item, 1),
                      MatrixProxyRow(item, 2)))
        self.addRow(matrix)

    def item(self):
        """Returns the :class:`Item3D` item or None"""
        return self._item()

    @staticmethod
    def _centerToModelData(center, index):
        """Convert rotation center information from scene to model.

        :param center: The center info from the scene
        :param int index: dimension to convert
        """
        value = center[index]
        if isinstance(value, six.string_types):
            return value.title()
        elif value == 0.:
            return 'Origin'
        else:
            return six.text_type(value)

    def _setCenter(self, value, index):
        """Set one dimension of the rotation center.

        :param value: Value received through the model.
        :param int index: dimension to set
        """
        item = self.item()
        if item is not None:
            if value == 'Origin':
                value = 0.
            elif value not in self._ROTATION_CENTER_OPTIONS:
                value = float(value)
            else:
                value = value.lower()

            center = list(item.getRotationCenter())
            center[index] = value
            item.setRotationCenter(*center)

    def _setAngle(self, angle):
        """Set rotation angle.

        :param float angle:
        """
        item = self.item()
        if item is not None:
            _, axis = item.getRotation()
            item.setRotation(angle, axis)

    def _setAxis(self, axis):
        """Set rotation axis.

        :param QVector3D axis:
        """
        item = self.item()
        if item is not None:
            angle, _ = item.getRotation()
            item.setRotation(angle, (axis.x(), axis.y(), axis.z()))

    def _setTranslation(self, translation):
        """Set translation transform.

        :param QVector3D translation:
        """
        item = self.item()
        if item is not None:
            item.setTranslation(translation.x(), translation.y(), translation.z())

    def _setScale(self, scale):
        """Set scale transform.

        :param QVector3D scale:
        """
        item = self.item()
        if item is not None:
            sx, sy, sz = scale.x(), scale.y(), scale.z()
            if sx == 0. or sy == 0. or sz == 0.:
                _logger.warning('Cannot set scale to 0: ignored')
            else:
                item.setScale(scale.x(), scale.y(), scale.z())


class GroupItemRow(Item3DRow):
    """Represents a :class:`GroupItem` with transforms and children

    :param GroupItem item: The scene group to represent.
    :param str name: The optional name of the group
    """

    _CHILDREN_ROW_OFFSET = 2
    """Number of rows for group parameters. Children are added after"""

    def __init__(self, item, name=None):
        super(GroupItemRow, self).__init__(item, name)
        self.addRow(DataItem3DBoundingBoxRow(item))
        self.addRow(DataItem3DTransformRow(item))

        item.sigItemAdded.connect(self._itemAdded)
        item.sigItemRemoved.connect(self._itemRemoved)

        for child in item.getItems():
            self.addRow(nodeFromItem(child))

    def _itemAdded(self, item):
        """Handle item addition to the group and add it to the model.

        :param Item3D item: added item
        """
        group = self.item()
        if group is None:
            return

        row = group.getItems().index(item)
        self.addRow(nodeFromItem(item), row + self._CHILDREN_ROW_OFFSET)

    def _itemRemoved(self, item):
        """Handle item removal from the group and remove it from the model.

        :param Item3D item: removed item
        """
        group = self.item()
        if group is None:
            return

        # Find item
        for row in self.children():
            if isinstance(row, Item3DRow) and row.item() is item:
                self.removeRow(row)
                break  # Got it
        else:
            raise RuntimeError("Model does not correspond to scene content")


class InterpolationRow(ItemProxyRow):
    """Represents :class:`InterpolationMixIn` property.

    :param Item3D item: Scene item with interpolation property
    """

    def __init__(self, item):
        modes = [mode.title() for mode in item.INTERPOLATION_MODES]
        super(InterpolationRow, self).__init__(
            item=item,
            name='Interpolation',
            fget=item.getInterpolation,
            fset=item.setInterpolation,
            events=items.Item3DChangedType.INTERPOLATION,
            toModelData=lambda mode: mode.title(),
            fromModelData=lambda mode: mode.lower(),
            editorHint=modes)


class _ColormapBaseProxyRow(ProxyRow):
    """Base class for colormap model row

    This class handle synchronization and signals from the item and the colormap
    """

    _sigColormapChanged = qt.Signal()
    """Signal used internally to notify colormap (or data) update"""

    def __init__(self, item, *args, **kwargs):
        self._item = weakref.ref(item)
        self._colormap = item.getColormap()

        ProxyRow.__init__(self, *args, **kwargs)

        self._colormap.sigChanged.connect(self._colormapChanged)
        item.sigItemChanged.connect(self._itemChanged)
        self._sigColormapChanged.connect(self._modelUpdated)

    def item(self):
        """Returns the :class:`ColormapMixIn` item or None"""
        return self._item()

    def _getColormapRange(self):
        """Returns the range of the colormap for the current data.

        :return: Colormap range (min, max)
        """
        item = self.item()
        if item is not None and self._colormap is not None:
            return self._colormap.getColormapRange(item._getDataRange())
        else:
            return 1, 100  # Fallback

    def _modelUpdated(self, *args, **kwargs):
        """Emit dataChanged in the model"""
        topLeft = self.index(column=0)
        bottomRight = self.index(column=1)
        model = self.model()
        if model is not None:
            model.dataChanged.emit(topLeft, bottomRight)

    def _colormapChanged(self):
        self._sigColormapChanged.emit()

    def _itemChanged(self, event):
        """Handle change of colormap or data in the item.

        :param ItemChangedType event:
        """
        if event == items.ItemChangedType.COLORMAP:
            self._sigColormapChanged.emit()
            if self._colormap is not None:
                self._colormap.sigChanged.disconnect(self._colormapChanged)

            item = self.item()
            if item is not None:
                self._colormap = item.getColormap()
                self._colormap.sigChanged.connect(self._colormapChanged)
            else:
                self._colormap = None

        elif event == items.ItemChangedType.DATA:
            self._sigColormapChanged.emit()


class _ColormapBoundRow(_ColormapBaseProxyRow):
    """ProxyRow for colormap min or max

    :param ColormapMixIn item: The item to handle
    :param str name: Name of the raw
    :param int index: 0 for Min and 1 of Max
    """

    def __init__(self, item, name, index):
        self._index = index
        _ColormapBaseProxyRow.__init__(
            self,
            item,
            name=name,
            fget=self._getBound,
            fset=self._setBound)

        self.setToolTip('Colormap %s bound:\n'
                        'Check to set bound manually, '
                        'uncheck for autoscale' % name.lower())

    def _getRawBound(self):
        """Proxy to get raw colormap bound

        :rtype: float or None
        """
        if self._colormap is None:
            return None
        elif self._index == 0:
            return self._colormap.getVMin()
        else:  # self._index == 1
            return self._colormap.getVMax()

    def _getBound(self):
        """Proxy to get colormap effective bound value

        :rtype: float
        """
        if self._colormap is not None:
            bound = self._getRawBound()

            if bound is None:
                bound = self._getColormapRange()[self._index]
            return bound
        else:
            return 1.  # Fallback

    def _setBound(self, value):
        """Proxy to set colormap bound.

        :param float value:
        """
        if self._colormap is not None:
            if self._index == 0:
                min_ = value
                max_ = self._colormap.getVMax()
            else:  # self._index == 1
                min_ = self._colormap.getVMin()
                max_ = value

            if max_ is not None and min_ is not None and min_ > max_:
                min_, max_ = max_, min_
            self._colormap.setVRange(min_, max_)

    def flags(self, column):
        if column == 0:
            return qt.Qt.ItemIsEnabled | qt.Qt.ItemIsUserCheckable

        elif column == 1:
            if self._getRawBound() is not None:
                flags = qt.Qt.ItemIsEditable | qt.Qt.ItemIsEnabled
            else:
                flags = qt.Qt.NoItemFlags  # Disabled if autoscale
            return flags

        else:  # Never event
            return super(_ColormapBoundRow, self).flags(column)

    def data(self, column, role):
        if column == 0 and role == qt.Qt.CheckStateRole:
            if self._getRawBound() is None:
                return qt.Qt.Unchecked
            else:
                return qt.Qt.Checked

        else:
            return super(_ColormapBoundRow, self).data(column, role)

    def setData(self, column, value, role):
        if column == 0 and role == qt.Qt.CheckStateRole:
            if self._colormap is not None:
                bound = self._getBound() if value == qt.Qt.Checked else None
                self._setBound(bound)
                return True
            else:
                return False

        return super(_ColormapBoundRow, self).setData(column, value, role)


class ColormapRow(_ColormapBaseProxyRow):
    """Represents :class:`ColormapMixIn` property.

    :param Item3D item: Scene item with colormap property
    """

    def __init__(self, item):
        super(ColormapRow, self).__init__(
            item,
            name='Colormap',
            fget=self._get)

        self._colormapImage = None

        self._colormapsMapping = {}
        for cmap in preferredColormaps():
            self._colormapsMapping[cmap.title()] = cmap

        self.addRow(ProxyRow(
            name='Name',
            fget=self._getName,
            fset=self._setName,
            notify=self._sigColormapChanged,
            editorHint=list(self._colormapsMapping.keys())))

        norms = [norm.title() for norm in self._colormap.NORMALIZATIONS]
        self.addRow(ProxyRow(
            name='Normalization',
            fget=self._getNormalization,
            fset=self._setNormalization,
            notify=self._sigColormapChanged,
            editorHint=norms))

        self.addRow(_ColormapBoundRow(item, name='Min.', index=0))
        self.addRow(_ColormapBoundRow(item, name='Max.', index=1))

        self._sigColormapChanged.connect(self._updateColormapImage)

    def getColormapImage(self):
        """Returns image representing the colormap or None

        :rtype: Union[QImage,None]
        """
        if self._colormapImage is None and self._colormap is not None:
            image = numpy.zeros((16, 130, 3), dtype=numpy.uint8)
            image[1:-1, 1:-1] = self._colormap.getNColors(image.shape[1] - 2)[:, :3]
            self._colormapImage = convertArrayToQImage(image)
        return self._colormapImage

    def _get(self):
        """Getter for ProxyRow subclass"""
        return None

    def _getName(self):
        """Proxy for :meth:`Colormap.getName`"""
        if self._colormap is not None and self._colormap.getName() is not None:
            return self._colormap.getName().title()
        else:
            return ''

    def _setName(self, name):
        """Proxy for :meth:`Colormap.setName`"""
        # Convert back from titled to name if possible
        if self._colormap is not None:
            name = self._colormapsMapping.get(name, name)
            self._colormap.setName(name)

    def _getNormalization(self):
        """Proxy for :meth:`Colormap.getNormalization`"""
        if self._colormap is not None:
            return self._colormap.getNormalization().title()
        else:
            return ''

    def _setNormalization(self, normalization):
        """Proxy for :meth:`Colormap.setNormalization`"""
        if self._colormap is not None:
            return self._colormap.setNormalization(normalization.lower())

    def _updateColormapImage(self, *args, **kwargs):
        """Notify colormap update to update the image in the tree"""
        if self._colormapImage is not None:
            self._colormapImage = None
            model = self.model()
            if model is not None:
                index = self.index(column=1)
                model.dataChanged.emit(index, index)

    def data(self, column, role):
        if column == 1 and role == qt.Qt.DecorationRole:
            return self.getColormapImage()
        else:
            return super(ColormapRow, self).data(column, role)


class SymbolRow(ItemProxyRow):
    """Represents :class:`SymbolMixIn` symbol property.

    :param Item3D item: Scene item with symbol property
    """

    def __init__(self, item):
        names = [item.getSymbolName(s) for s in item.getSupportedSymbols()]
        super(SymbolRow, self).__init__(
            item=item,
            name='Marker',
            fget=item.getSymbolName,
            fset=item.setSymbol,
            events=items.ItemChangedType.SYMBOL,
            editorHint=names)


class SymbolSizeRow(ItemProxyRow):
    """Represents :class:`SymbolMixIn` symbol size property.

    :param Item3D item: Scene item with symbol size property
    """

    def __init__(self, item):
        super(SymbolSizeRow, self).__init__(
            item=item,
            name='Marker size',
            fget=item.getSymbolSize,
            fset=item.setSymbolSize,
            events=items.ItemChangedType.SYMBOL_SIZE,
            editorHint=(1, 20))  # TODO link with OpenGL max point size


class PlaneEquationRow(ItemProxyRow):
    """Represents :class:`PlaneMixIn` as plane equation.

    :param Item3D item: Scene item with plane equation property
    """

    def __init__(self, item):
        super(PlaneEquationRow, self).__init__(
            item=item,
            name='Equation',
            fget=item.getParameters,
            fset=item.setParameters,
            events=items.ItemChangedType.POSITION,
            toModelData=lambda data: qt.QVector4D(*data),
            fromModelData=lambda data: (data.x(), data.y(), data.z(), data.w()))
        self._item = weakref.ref(item)

    def data(self, column, role):
        if column == 1 and role == qt.Qt.DisplayRole:
            item = self._item()
            if item is not None:
                params = item.getParameters()
                return ('%gx %+gy %+gz %+g = 0' %
                        (params[0], params[1], params[2], params[3]))
        return super(PlaneEquationRow, self).data(column, role)


class PlaneRow(ItemProxyRow):
    """Represents :class:`PlaneMixIn` property.

    :param Item3D item: Scene item with plane equation property
    """

    _PLANES = OrderedDict((('Plane 0', (1., 0., 0.)),
                           ('Plane 1', (0., 1., 0.)),
                           ('Plane 2', (0., 0., 1.)),
                           ('-', None)))
    """Mapping of plane names to normals"""

    _PLANE_ICONS = {'Plane 0': '3d-plane-normal-x',
                    'Plane 1': '3d-plane-normal-y',
                    'Plane 2': '3d-plane-normal-z',
                    '-': '3d-plane'}
    """Mapping of plane names to normals"""

    def __init__(self, item):
        super(PlaneRow, self).__init__(
            item=item,
            name='Plane',
            fget=self.__getPlaneName,
            fset=self.__setPlaneName,
            events=items.ItemChangedType.POSITION,
            editorHint=tuple(self._PLANES.keys()))
        self._item = weakref.ref(item)
        self._lastName = None

        self.addRow(PlaneEquationRow(item))

    def _notified(self, *args, **kwargs):
        """Handle notification of modification

        Here only send if plane name actually changed
        """
        if self._lastName != self.__getPlaneName():
            super(PlaneRow, self)._notified()

    def __getPlaneName(self):
        """Returns name of plane // to axes or '-'

        :rtype: str
        """
        item = self._item()
        planeNormal = item.getNormal() if item is not None else None

        for name, normal in self._PLANES.items():
            if numpy.array_equal(planeNormal, normal):
                return name
        return '-'

    def __setPlaneName(self, data):
        """Set plane normal according to given plane name

        :param str data: Selected plane name
        """
        item = self._item()
        if item is not None:
            for name, normal in self._PLANES.items():
                if data == name and normal is not None:
                    item.setNormal(normal)

    def data(self, column, role):
        if column == 1 and role == qt.Qt.DecorationRole:
            return icons.getQIcon(self._PLANE_ICONS[self.__getPlaneName()])
        data = super(PlaneRow, self).data(column, role)
        if column == 1 and role == qt.Qt.DisplayRole:
            self._lastName = data
        return data


class ComplexModeRow(ItemProxyRow):
    """Represents :class:`items.ComplexMixIn` symbol property.

    :param Item3D item: Scene item with symbol property
    """

    def __init__(self, item, name='Mode'):
        names = [m.value.replace('_', ' ').title()
                 for m in item.supportedComplexModes()]
        super(ComplexModeRow, self).__init__(
            item=item,
            name=name,
            fget=item.getComplexMode,
            fset=item.setComplexMode,
            events=items.ItemChangedType.COMPLEX_MODE,
            toModelData=lambda data: data.value.replace('_', ' ').title(),
            fromModelData=lambda data: data.lower().replace(' ', '_'),
            editorHint=names)


class RemoveIsosurfaceRow(BaseRow):
    """Class for Isosurface Delete button

    :param Isosurface isosurface: The isosurface item to attach the button to.
    """

    def __init__(self, isosurface):
        super(RemoveIsosurfaceRow, self).__init__()
        self._isosurface = weakref.ref(isosurface)

    def createEditor(self):
        """Specific editor factory provided to the model"""
        editor = qt.QWidget()
        layout = qt.QHBoxLayout(editor)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

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

        layout.addStretch(1)
        return editor

    def isosurface(self):
        """Returns the controlled isosurface

        :rtype: Isosurface
        """
        return self._isosurface()

    def data(self, column, role):
        if column == 0 and role == qt.Qt.UserRole:  # editor hint
            return self.createEditor

        return super(RemoveIsosurfaceRow, self).data(column, role)

    def flags(self, column):
        flags = super(RemoveIsosurfaceRow, self).flags(column)
        if column == 0:
            flags |= qt.Qt.ItemIsEditable
        return flags

    def _removeClicked(self):
        """Handle Delete button clicked"""
        isosurface = self.isosurface()
        if isosurface is not None:
            volume = isosurface.parent()
            if volume is not None:
                volume.removeIsosurface(isosurface)


class IsosurfaceRow(Item3DRow):
    """Represents an :class:`Isosurface` item.

    :param Isosurface item: Isosurface item
    """

    _LEVEL_SLIDER_RANGE = 0, 1000
    """Range given as editor hint"""

    _EVENTS = items.ItemChangedType.VISIBLE, items.ItemChangedType.COLOR
    """Events for which to update the first column in the tree"""

    def __init__(self, item):
        super(IsosurfaceRow, self).__init__(item, name=item.getLevel())

        self.setFlags(self.flags(1) | qt.Qt.ItemIsEditable, 1)

        item.sigItemChanged.connect(self._levelChanged)

        self.addRow(ItemProxyRow(
            item=item,
            name='Level',
            fget=self._getValueForLevelSlider,
            fset=self._setLevelFromSliderValue,
            events=items.Item3DChangedType.ISO_LEVEL,
            editorHint=self._LEVEL_SLIDER_RANGE))

        self.addRow(ItemColorProxyRow(
            item=item,
            name='Color',
            fget=self._rgbColor,
            fset=self._setRgbColor,
            events=items.ItemChangedType.COLOR))

        self.addRow(ItemProxyRow(
            item=item,
            name='Opacity',
            fget=self._opacity,
            fset=self._setOpacity,
            events=items.ItemChangedType.COLOR,
            editorHint=(0, 255)))

        self.addRow(RemoveIsosurfaceRow(item))

    def _getValueForLevelSlider(self):
        """Convert iso level to slider value.

        :rtype: int
        """
        item = self.item()
        if item is not None:
            volume = item.parent()
            if volume is not None:
                dataRange = volume.getDataRange()
                if dataRange is not None:
                    dataMin, dataMax = dataRange[0], dataRange[-1]
                    if dataMax != dataMin:
                        offset = (item.getLevel() - dataMin) / (dataMax - dataMin)
                    else:
                        offset = 0.

                    sliderMin, sliderMax = self._LEVEL_SLIDER_RANGE
                    value = sliderMin + (sliderMax - sliderMin) * offset
                    return value
        return 0

    def _setLevelFromSliderValue(self, value):
        """Convert slider value to isolevel.

        :param int value:
        """
        item = self.item()
        if item is not None:
            volume = item.parent()
            if volume is not None:
                dataRange = volume.getDataRange()
                if dataRange is not None:
                    sliderMin, sliderMax = self._LEVEL_SLIDER_RANGE
                    offset = (value - sliderMin) / (sliderMax - sliderMin)

                    dataMin, dataMax = dataRange[0], dataRange[-1]
                    level = dataMin + (dataMax - dataMin) * offset
                    item.setLevel(level)

    def _rgbColor(self):
        """Proxy to get the isosurface's RGB color without transparency

        :rtype: QColor
        """
        item = self.item()
        if item is None:
            return None
        else:
            color = item.getColor()
            color.setAlpha(255)
            return color

    def _setRgbColor(self, color):
        """Proxy to set the isosurface's RGB color without transparency

        :param QColor color:
        """
        item = self.item()
        if item is not None:
            color.setAlpha(item.getColor().alpha())
            item.setColor(color)

    def _opacity(self):
        """Proxy to get the isosurface's transparency

        :rtype: int
        """
        item = self.item()
        return 255 if item is None else item.getColor().alpha()

    def _setOpacity(self, opacity):
        """Proxy to set the isosurface's transparency.

        :param int opacity:
        """
        item = self.item()
        if item is not None:
            color = item.getColor()
            color.setAlpha(opacity)
            item.setColor(color)

    def _levelChanged(self, event):
        """Handle isosurface level changed and notify model

        :param ItemChangedType event:
        """
        if event == items.Item3DChangedType.ISO_LEVEL:
            model = self.model()
            if model is not None:
                index = self.index(column=1)
                model.dataChanged.emit(index, index)

    def data(self, column, role):
        if column == 0:  # Show color as decoration, not text
            if role == qt.Qt.DisplayRole:
                return None
            elif role == qt.Qt.DecorationRole:
                return self._rgbColor()

        elif column == 1 and role in (qt.Qt.DisplayRole, qt.Qt.EditRole):
                item = self.item()
                return None if item is None else item.getLevel()

        return super(IsosurfaceRow, self).data(column, role)

    def setData(self, column, value, role):
        if column == 1 and role == qt.Qt.EditRole:
            item = self.item()
            if item is not None:
                item.setLevel(value)
            return True

        return super(IsosurfaceRow, self).setData(column, value, role)


class ComplexIsosurfaceRow(IsosurfaceRow):
    """Represents an :class:`ComplexIsosurface` item.

    :param ComplexIsosurface item:
    """

    _EVENTS = (items.ItemChangedType.VISIBLE,
               items.ItemChangedType.COLOR,
               items.ItemChangedType.COMPLEX_MODE)
    """Events for which to update the first column in the tree"""

    def __init__(self, item):
        super(ComplexIsosurfaceRow, self).__init__(item)

        self.addRow(ComplexModeRow(item, "Color Complex Mode"), index=1)
        for row in self.children():
            if isinstance(row, ColorProxyRow):
                self._colorRow = row
                break
        else:
            raise RuntimeError("Cannot retrieve Color tree row")
        self._colormapRow = ColormapRow(item)

        self.__updateRowsForItem(item)
        item.sigItemChanged.connect(self.__itemChanged)

    def __itemChanged(self, event):
        """Update enabled/disabled rows"""
        if event == items.ItemChangedType.COMPLEX_MODE:
            item = self.sender()
            self.__updateRowsForItem(item)

    def __updateRowsForItem(self, item):
        """Update rows for item

        :param item:
        """
        if not isinstance(item, ComplexIsosurface):
            return

        if item.getComplexMode() == items.ComplexMixIn.ComplexMode.NONE:
            removed = self._colormapRow
            added = self._colorRow
        else:
            removed = self._colorRow
            added = self._colormapRow

        # Remove unwanted rows
        if removed in self.children():
            self.removeRow(removed)

        # Add required rows
        if added not in self.children():
            self.addRow(added, index=2)

    def data(self, column, role):
        if column == 0 and role == qt.Qt.DecorationRole:
            item = self.item()
            if (item is not None and
                    item.getComplexMode() != items.ComplexMixIn.ComplexMode.NONE):
                return self._colormapRow.getColormapImage()

        return super(ComplexIsosurfaceRow, self).data(column, role)


class AddIsosurfaceRow(BaseRow):
    """Class for Isosurface create button

    :param Union[ScalarField3D,ComplexField3D] volume:
        The volume item to attach the button to.
    """

    def __init__(self, volume):
        super(AddIsosurfaceRow, self).__init__()
        self._volume = weakref.ref(volume)

    def createEditor(self):
        """Specific editor factory provided to the model"""
        editor = qt.QWidget()
        layout = qt.QHBoxLayout(editor)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

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

        layout.addStretch(1)
        return editor

    def volume(self):
        """Returns the controlled volume item

        :rtype: Union[ScalarField3D,ComplexField3D]
        """
        return self._volume()

    def data(self, column, role):
        if column == 0 and role == qt.Qt.UserRole:  # editor hint
            return self.createEditor

        return super(AddIsosurfaceRow, self).data(column, role)

    def flags(self, column):
        flags = super(AddIsosurfaceRow, self).flags(column)
        if column == 0:
            flags |= qt.Qt.ItemIsEditable
        return flags

    def _addClicked(self):
        """Handle Delete button clicked"""
        volume = self.volume()
        if volume is not None:
            dataRange = volume.getDataRange()
            if dataRange is None:
                dataRange = 0., 1.

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


class VolumeIsoSurfacesRow(StaticRow):
    """Represents  :class:`ScalarFieldView`'s isosurfaces

    :param Union[ScalarField3D,ComplexField3D] volume:
        Volume item to control
    """

    def __init__(self, volume):
        super(VolumeIsoSurfacesRow, self).__init__(
            ('Isosurfaces', None))
        self._volume = weakref.ref(volume)

        volume.sigIsosurfaceAdded.connect(self._isosurfaceAdded)
        volume.sigIsosurfaceRemoved.connect(self._isosurfaceRemoved)

        if isinstance(volume, items.ComplexMixIn):
            self.addRow(ComplexModeRow(volume, "Complex Mode"))

        for item in volume.getIsosurfaces():
            self.addRow(nodeFromItem(item))

        self.addRow(AddIsosurfaceRow(volume))

    def volume(self):
        """Returns the controlled volume item

        :rtype: Union[ScalarField3D,ComplexField3D]
        """
        return self._volume()

    def _isosurfaceAdded(self, item):
        """Handle isosurface addition

        :param Isosurface item: added isosurface
        """
        volume = self.volume()
        if volume is None:
            return

        row = volume.getIsosurfaces().index(item)
        if isinstance(volume, items.ComplexMixIn):
            row += 1  # Offset for the ComplexModeRow
        self.addRow(nodeFromItem(item), row)

    def _isosurfaceRemoved(self, item):
        """Handle isosurface removal

        :param Isosurface item: removed isosurface
        """
        volume = self.volume()
        if volume is None:
            return

        # Find item
        for row in self.children():
            if isinstance(row, IsosurfaceRow) and row.item() is item:
                self.removeRow(row)
                break  # Got it
        else:
            raise RuntimeError("Model does not correspond to scene content")


class Scatter2DPropertyMixInRow(object):
    """Mix-in class that enable/disable row according to Scatter2D mode.

    :param Scatter2D item:
    :param str propertyName: Name of the Scatter2D property of this row
    """

    def __init__(self, item, propertyName):
        assert propertyName in ('lineWidth', 'symbol', 'symbolSize')
        self.__propertyName = propertyName

        self.__isEnabled = item.isPropertyEnabled(propertyName)
        self.__updateFlags()

        item.sigItemChanged.connect(self.__itemChanged)

    def data(self, column, role):
        if column == 1 and not self.__isEnabled:
            # Discard data and editorHint if disabled
            return None
        else:
            return super(Scatter2DPropertyMixInRow, self).data(column, role)

    def __updateFlags(self):
        """Update model flags"""
        if self.__isEnabled:
            self.setFlags(qt.Qt.ItemIsEnabled, 0)
            self.setFlags(qt.Qt.ItemIsEnabled | qt.Qt.ItemIsEditable, 1)
        else:
            self.setFlags(qt.Qt.NoItemFlags)

    def __itemChanged(self, event):
        """Set flags to enable/disable the row"""
        if event == items.ItemChangedType.VISUALIZATION_MODE:
            item = self.sender()
            if item is not None:  # This occurs with PySide/python2.7
                self.__isEnabled = item.isPropertyEnabled(self.__propertyName)
                self.__updateFlags()

            # Notify model
            model = self.model()
            if model is not None:
                begin = self.index(column=0)
                end = self.index(column=1)
                model.dataChanged.emit(begin, end)


class Scatter2DSymbolRow(Scatter2DPropertyMixInRow, SymbolRow):
    """Specific class for Scatter2D symbol.

    It is enabled/disabled according to visualization mode.

    :param Scatter2D item:
    """

    def __init__(self, item):
        SymbolRow.__init__(self, item)
        Scatter2DPropertyMixInRow.__init__(self, item, 'symbol')


class Scatter2DSymbolSizeRow(Scatter2DPropertyMixInRow, SymbolSizeRow):
    """Specific class for Scatter2D symbol size.

    It is enabled/disabled according to visualization mode.

    :param Scatter2D item:
    """

    def __init__(self, item):
        SymbolSizeRow.__init__(self, item)
        Scatter2DPropertyMixInRow.__init__(self, item, 'symbolSize')


class Scatter2DLineWidth(Scatter2DPropertyMixInRow, ItemProxyRow):
    """Specific class for Scatter2D symbol size.

    It is enabled/disabled according to visualization mode.

    :param Scatter2D item:
    """

    def __init__(self, item):
        # TODO link editorHint with OpenGL max line width
        ItemProxyRow.__init__(self,
                              item=item,
                              name='Line width',
                              fget=item.getLineWidth,
                              fset=item.setLineWidth,
                              events=items.ItemChangedType.LINE_WIDTH,
                              editorHint=(1, 10))
        Scatter2DPropertyMixInRow.__init__(self, item, 'lineWidth')


def initScatter2DNode(node, item):
    """Specific node init for Scatter2D to set order of parameters

    :param Item3DRow node: The model node to setup
    :param Scatter2D item: The Scatter2D the node is representing
    """
    node.addRow(ItemProxyRow(
        item=item,
        name='Mode',
        fget=item.getVisualization,
        fset=item.setVisualization,
        events=items.ItemChangedType.VISUALIZATION_MODE,
        editorHint=[m.value.title() for m in item.supportedVisualizations()],
        toModelData=lambda data: data.value.title(),
        fromModelData=lambda data: data.lower()))

    node.addRow(ItemProxyRow(
        item=item,
        name='Height map',
        fget=item.isHeightMap,
        fset=item.setHeightMap,
        events=items.Item3DChangedType.HEIGHT_MAP))

    node.addRow(ColormapRow(item))

    node.addRow(Scatter2DSymbolRow(item))
    node.addRow(Scatter2DSymbolSizeRow(item))

    node.addRow(Scatter2DLineWidth(item))


def initVolumeNode(node, item):
    """Specific node init for volume items

    :param Item3DRow node: The model node to setup
    :param Union[ScalarField3D,ComplexField3D] item:
        The volume item represented by the node
    """
    node.addRow(nodeFromItem(item.getCutPlanes()[0]))  # Add cut plane
    node.addRow(VolumeIsoSurfacesRow(item))


def initVolumeCutPlaneNode(node, item):
    """Specific node init for volume CutPlane

    :param Item3DRow node: The model node to setup
    :param CutPlane item: The CutPlane the node is representing
    """
    if isinstance(item, items.ComplexMixIn):
        node.addRow(ComplexModeRow(item))

    node.addRow(PlaneRow(item))

    node.addRow(ColormapRow(item))

    node.addRow(ItemProxyRow(
        item=item,
        name='Show <=Min',
        fget=item.getDisplayValuesBelowMin,
        fset=item.setDisplayValuesBelowMin,
        events=items.ItemChangedType.ALPHA))

    node.addRow(InterpolationRow(item))


NODE_SPECIFIC_INIT = [  # class, init(node, item)
    (items.Scatter2D, initScatter2DNode),
    (items.ScalarField3D, initVolumeNode),
    (CutPlane, initVolumeCutPlaneNode),
]
"""List of specific node init for different item class"""


def nodeFromItem(item):
    """Create :class:`Item3DRow` subclass corresponding to item

    :param Item3D item: The item fow which to create the node
    :rtype: Item3DRow
    """
    assert isinstance(item, items.Item3D)

    # Item with specific model row class
    if isinstance(item, (items.GroupItem, items.GroupWithAxesItem)):
        return GroupItemRow(item)
    elif isinstance(item, ComplexIsosurface):
        return ComplexIsosurfaceRow(item)
    elif isinstance(item, Isosurface):
        return IsosurfaceRow(item)

    # Create Item3DRow and populate it
    node = Item3DRow(item)

    if isinstance(item, items.DataItem3D):
        node.addRow(DataItem3DBoundingBoxRow(item))
        node.addRow(DataItem3DTransformRow(item))

    # Specific extra init
    for cls, specificInit in NODE_SPECIFIC_INIT:
        if isinstance(item, cls):
            specificInit(node, item)
            break

    else:  # Generic case: handle mixins
        for cls in item.__class__.__mro__:
            if cls is items.ColormapMixIn:
                node.addRow(ColormapRow(item))

            elif cls is items.InterpolationMixIn:
                node.addRow(InterpolationRow(item))

            elif cls is items.SymbolMixIn:
                node.addRow(SymbolRow(item))
                node.addRow(SymbolSizeRow(item))

            elif cls is items.PlaneMixIn:
                node.addRow(PlaneRow(item))

    return node