This file is indexed.

/usr/lib/python2.7/dist-packages/guiqwt/styles.py is in python-guiqwt 3.0.3-2ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 CEA
# Pierre Raybaut
# Licensed under the terms of the CECILL License
# (see guiqwt/__init__.py for details)

# pylint: disable=C0103

"""
guiqwt.styles
-------------

The `styles` module provides set of parameters (DataSet classes) to 
configure `plot items` and `plot tools`.

.. seealso::
        
    Module :py:mod:`guiqwt.plot`
        Module providing ready-to-use curve and image plotting widgets and 
        dialog boxes
    
    Module :py:mod:`guiqwt.curve`
        Module providing curve-related plot items and plotting widgets
        
    Module :py:mod:`guiqwt.image`
        Module providing image-related plot items and plotting widgets
        
    Module :py:mod:`guiqwt.tools`
        Module providing the `plot tools`
        
Reference
~~~~~~~~~

.. autoclass:: CurveParam
   :members:
   :inherited-members:
.. autoclass:: ErrorBarParam
   :members:
   :inherited-members:
.. autoclass:: GridParam
   :members:
   :inherited-members:
.. autoclass:: ImageParam
   :members:
   :inherited-members:
.. autoclass:: TrImageParam
   :members:
   :inherited-members:
.. autoclass:: ImageFilterParam
   :members:
   :inherited-members:
.. autoclass:: HistogramParam
   :members:
   :inherited-members:
.. autoclass:: Histogram2DParam
   :members:
   :inherited-members:
.. autoclass:: AxesParam
   :members:
   :inherited-members:
.. autoclass:: ImageAxesParam
   :members:
   :inherited-members:
.. autoclass:: LabelParam
   :members:
   :inherited-members:
.. autoclass:: LegendParam
   :members:
   :inherited-members:
.. autoclass:: ShapeParam
   :members:
   :inherited-members:
.. autoclass:: AnnotationParam
   :members:
   :inherited-members:
.. autoclass:: AxesShapeParam
   :members:
   :inherited-members:
.. autoclass:: RangeShapeParam
   :members:
   :inherited-members:
.. autoclass:: MarkerParam
   :members:
   :inherited-members:
.. autoclass:: FontParam
   :members:
   :inherited-members:
.. autoclass:: SymbolParam
   :members:
   :inherited-members:
.. autoclass:: LineStyleParam
   :members:
   :inherited-members:
.. autoclass:: BrushStyleParam
   :members:
   :inherited-members:
.. autoclass:: TextStyleParam
   :members:
   :inherited-members:
"""

import numpy as np

from guidata.qt.QtGui import (QPen, QBrush, QColor, QFont, QFontDialog,
                              QTransform)
from guidata.qt.QtCore import Qt, QSizeF, QPointF

from guidata.dataset.datatypes import (DataSet, ObjectItem, BeginGroup,
                                       EndGroup, Obj, DataSetGroup,
                                       BeginTabGroup, EndTabGroup,
                                       GetAttrProp, NotProp)
from guidata.dataset.dataitems import (ChoiceItem, BoolItem, FloatItem, IntItem,
                                       ImageChoiceItem, ColorItem, StringItem,
                                       ButtonItem, FloatArrayItem, TextItem)
from guidata.dataset.qtwidgets import DataSetEditLayout
from guidata.dataset.qtitemwidgets import DataSetWidget
from guidata.utils import update_dataset
from guidata.py3compat import to_text_string

# Local imports
from guiqwt.transitional import QwtPlot, QwtPlotCurve, QwtSymbol, QwtPlotMarker
from guiqwt.config import _
from guiqwt.colormap import get_colormap_list, build_icon_from_cmap_name

class ItemParameters(object):
    """Class handling QwtPlotItem-like parameters"""
    MULTISEL_DATASETS = []
    # Customizing tab display order:
    ENDING_PARAMETERS = ("CurveParam", "ErrorBarParam",
                         "ShapeParam", "LabelParam", "LegendParam",
                         "GridParam", "AxesParam")
    
    def __init__(self, multiselection=False):
        self.multiselection = multiselection
        self.paramdict = {}
        self.items = set()
        
    @classmethod
    def register_multiselection(cls, klass, klass_ms):
        """Register a DataSet couple: (DataSet, DataSet_for_MultiSelection)"""
        # Inserting element backwards because classes have to be registered
        # from children to parent (see 'add' method to fully understand why)
        cls.MULTISEL_DATASETS.insert(0, (klass, klass_ms))
        
    def __add(self, key, item, param):
        self.paramdict[key] = param
        self.items.add(item)
        
    def add(self, key, item, param):
        if self.multiselection:
            for klass, klass_ms in self.MULTISEL_DATASETS:
                if isinstance(param, klass):
                    title = param.get_title()
                    if key in self.paramdict and not title.endswith('s'):
                        title += 's'
                    param_ms = klass_ms(title=title,
                                        comment=param.get_comment(),
                                        icon=param.get_icon())
                    update_dataset(param_ms, param)
                    self.__add(key, item, param_ms)
                    return
        self.__add(key, item, param)
        
    def get(self, key):
        from copy import deepcopy
        return deepcopy(self.paramdict.get(key))
    
    def update(self, plot):
        #XXX: removed the following workaround as the associated bug can't be 
        # reproduced anymore with guiqwt 3. However, keeping the workaround 
        # here (commented) as it could become useful eventually.
        #-----
        #FIXME: without the following workaround, ImagePlot object aspect ratio
        # is changed when pressing button "Apply"
        # (see also guiqwt.image.ImagePlot.edit_axis_parameters)
#        from guiqwt.image import ImagePlot
#        if isinstance(plot, ImagePlot):
#            ratio = plot.get_current_aspect_ratio()
        #-----
        for item in self.items:
            item.set_item_parameters(self)
        plot.replot()
        #-----
#        if isinstance(plot, ImagePlot):
#            plot.set_aspect_ratio(ratio=ratio)
#            plot.replot()
        #-----
        plot.SIG_ITEMS_CHANGED.emit(plot)
    
    def edit(self, plot, title, icon):
        paramdict = self.paramdict.copy()
        ending_parameters = []
        for key in self.ENDING_PARAMETERS:
            if key in paramdict:
                ending_parameters.append(paramdict.pop(key))
        parameters = list(paramdict.values())+ending_parameters
        dset = DataSetGroup(parameters, title=title.rstrip('.'), icon=icon)
        if dset.edit(parent=plot, apply=lambda dset: self.update(plot)):
            self.update(plot)


LINESTYLES = {
              "-": "SolidLine",
              "--": "DashLine",
              ":": "DotLine",
              "-.": "DashDotLine",
              }
COLORS = {
          "r": "red",
          "g": "green",
          "b": "blue",
          "c": "cyan",
          "m": "magenta",
          "y": "yellow",
          "k": "black",
          "w": "white",
          "G": "gray",
          }
MARKERS = {
          "+": QwtSymbol.Cross,
          "o": QwtSymbol.Ellipse,
          "*": QwtSymbol.Star1,
          ".": QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.black),
                          QPen(Qt.black), QSizeF(3, 3)),
          "x": QwtSymbol.XCross,
          "s": QwtSymbol.Rect,
          "d": QwtSymbol.Diamond,
          "^": QwtSymbol.UTriangle,
          "v": QwtSymbol.DTriangle,
          ">": QwtSymbol.RTriangle,
          "<": QwtSymbol.LTriangle,
          "h": QwtSymbol.Star2,
          }
MARKERSTYLES = {
                None: "NoLine",
                "-": "HLine",
                "|": "VLine",
                "+": "Cross",
                }


def style_generator(color_keys="bgrcmykG"):
    """Cycling through curve styles"""
    while True:
        for linestyle in sorted(LINESTYLES.keys()):
            for color in color_keys:
                yield color+linestyle

def update_style_attr(style, param):
    """Parse a MATLAB-like style string and
    update the color, linestyle, marker attributes of the param
    object
    """
    for marker in list(MARKERS.keys()):
        if marker in style:
            param.symbol.update_param(MARKERS[marker])
            break
    else:
        param.symbol.update_param(QwtSymbol.NoSymbol)
    for linestyle in list(LINESTYLES.keys()):
        if linestyle in style:
            param.line.style = LINESTYLES[linestyle]
            break
    else:
        param.line.style = "NoPen"
    for color in list(COLORS.keys()):
        if color in style:
            param.line.color = COLORS[color]
            param.symbol.facecolor = COLORS[color]
            param.symbol.edgecolor = COLORS[color]
            break


def build_reverse_map(lst, obj):
    dict = {}
    for idx, _name, _icon in lst:
        val = getattr(obj, idx)
        dict[val] = idx
    return dict

LINESTYLE_CHOICES = [("SolidLine", _("Solid line"), "solid.png"),
                     ("DashLine", _("Dashed line"), "dash.png"),
                     ("DotLine", _("Dotted line"), "dot.png"),
                     ("DashDotLine", _("Dash-dot line"), "dashdot.png"),
                     ("DashDotDotLine", _("Dash-dot-dot line"), "dashdotdot.png"),
                     ("NoPen", _("No line"), "none.png"),
                     ]
MARKER_CHOICES = [("Cross", _("Cross"), "cross.png"),
                  ("Ellipse", _("Ellipse"), "ellipse.png"),
                  ("Star1", _("Star"), "star.png"),
                  ("XCross", _("X-Cross"), "xcross.png"),
                  ("Rect", _("Square"), "square.png"),
                  ("Diamond", _("Diamond"), "diamond.png"),
                  ("UTriangle", _("Triangle"), "triangle_u.png"),
                  ("DTriangle", _("Triangle"), "triangle_d.png"),
                  ("RTriangle", _("Triangle"), "triangle_r.png"),
                  ("LTriangle", _("Triangle"), "triangle_l.png"),
                  ("Star2", _("Hexagon"), "hexagon.png"),
                  ("NoSymbol", _("No symbol"), "none.png"),
                  ]
CURVESTYLE_CHOICES = [("Lines", _("Lines"), "lines.png"),
                      ("Sticks", _("Sticks"), "sticks.png"),
                      ("Steps", _("Steps"), "steps.png"),
                      ("Dots", _("Dots"), "dots.png"),
                      ("NoCurve", _("No curve"), "none.png")
                      ]

BRUSHSTYLE_CHOICES = [
    ("NoBrush", _("No brush pattern"), "nobrush.png"),
    ("SolidPattern", _("Uniform color"), "solidpattern.png"),
    ("Dense1Pattern", _("Extremely dense brush pattern"), "dense1pattern.png"),
    ("Dense2Pattern", _("Very dense brush pattern"), "dense2pattern.png"),
    ("Dense3Pattern", _("Somewhat dense brush pattern"), "dense3pattern.png"),
    ("Dense4Pattern", _("Half dense brush pattern"), "dense4pattern.png"),
    ("Dense5Pattern", _("Somewhat sparse brush pattern"), "dense5pattern.png"),
    ("Dense6Pattern", _("Very sparse brush pattern"), "dense6pattern.png"),
    ("Dense7Pattern", _("Extremely sparse brush pattern"), "dense7pattern.png"),
    ("HorPattern", _("Horizontal lines"), "horpattern.png"),
    ("VerPattern", _("Vertical lines"), "verpattern.png"),
    ("CrossPattern", _("Crossing horizontal and vertical lines"),
     "crosspattern.png"),
    ("BDiagPattern", _("Backward diagonal lines"), "bdiagpattern.png"),
    ("FDiagPattern", _("Forward diagonal lines"), "fdiagpattern.png"),
    ("DiagCrossPattern", _("Crossing diagonal lines"), "diagcrosspattern.png"),
#    ("LinearGradientPattern", _("Linear gradient (set using a dedicated QBrush constructor)"), "none.png"),
#    ("ConicalGradientPattern", _("Conical gradient (set using a dedicated QBrush constructor)"), "none.png"),
#    ("RadialGradientPattern", _("Radial gradient (set using a dedicated QBrush constructor)"), "none.png"),
#    ("TexturePattern", _("Custom pattern (see QBrush::setTexture())"), "none.png"),
]

MARKERSTYLE_CHOICES = [("NoLine", _("None"), "none.png"),
                       ("HLine",  _("Horizontal"), "horiz_marker.png"),
                       ("VLine",  _("Vertical"), "vert_marker.png"),
                       ("Cross",  _("Cross"), "cross_marker.png"),
                       ]

MARKER_NAME = build_reverse_map(MARKER_CHOICES, QwtSymbol)
CURVESTYLE_NAME = build_reverse_map(CURVESTYLE_CHOICES, QwtPlotCurve)
LINESTYLE_NAME = build_reverse_map(LINESTYLE_CHOICES, Qt)
BRUSHSTYLE_NAME = build_reverse_map(BRUSHSTYLE_CHOICES, Qt)
MARKERSTYLE_NAME = build_reverse_map(MARKERSTYLE_CHOICES, QwtPlotMarker)


# ===================================================
# Common font parameters
# ===================================================
def _font_selection(param, item, value, parent):
    font = param.build_font()
    result, valid = QFontDialog.getFont(font, parent)
    if valid:
        param.update_param( result )
    
class FontParam(DataSet):
    family = StringItem(_("Family"), default="default")
    _choose = ButtonItem(_("Choose font"), _font_selection,
                         default=None).set_pos(col=1)
    size = IntItem(_("Size in point"), default=12)
    bold = BoolItem(_("Bold"), default=False).set_pos(col=1)
    italic = BoolItem(_("Italic"), default=False).set_pos(col=2)

    def update_param(self, font):
        self.family = str(font.family())
        self.size = font.pointSize()
        self.bold = bool(font.bold())
        self.italic = bool(font.italic())

    def build_font(self):
        font = QFont(self.family)
        font.setPointSize( self.size )
        font.setBold( self.bold )
        font.setItalic( self.italic )
        return font

class FontItemWidget(DataSetWidget):
    klass = FontParam

class FontItem(ObjectItem):
    """Item holding a LineStyleParam"""
    klass = FontParam

DataSetEditLayout.register(FontItem, FontItemWidget)


# ===================================================
# Common Qwt symbol parameters
# ===================================================
class SymbolParam(DataSet):
    marker = ImageChoiceItem(_("Style"), MARKER_CHOICES,
                             default="NoSymbol")
    size = IntItem(_("Size"), default=9)
    edgecolor = ColorItem(_("Border"), default="gray")
    facecolor = ColorItem(_("Background color"), default="yellow")
    alpha = FloatItem(_("Background alpha"), default=1., min=0, max=1)

    def update_param(self, symb):
        if not isinstance(symb, QwtSymbol):
            # check if this is still needed
            #raise RuntimeError
            assert isinstance(symb, QwtSymbol.Style)
            self.marker = MARKER_NAME[symb]
            return
        self.marker = MARKER_NAME[symb.style()]
        self.size = symb.size().width()
        self.edgecolor = str(symb.pen().color().name())
        self.facecolor = str(symb.brush().color().name())

    def build_symbol(self):
        marker_type = getattr(QwtSymbol, self.marker)
        color = QColor(self.facecolor)
        color.setAlphaF(self.alpha)
        marker = QwtSymbol(marker_type, QBrush(color),
                           QPen(QColor(self.edgecolor)),
                           QSizeF(self.size, self.size))
        return marker
    
    def update_symbol(self, obj):
        obj.setSymbol(self.build_symbol())        

class SymbolItemWidget(DataSetWidget):
    klass = SymbolParam

class SymbolItem(ObjectItem):
    """Item holding a SymbolParam"""
    klass = SymbolParam

DataSetEditLayout.register(SymbolItem, SymbolItemWidget)


# ===================================================
# Common line style parameters
# ===================================================
class LineStyleParam(DataSet):
    style = ImageChoiceItem(_("Style"), LINESTYLE_CHOICES, default="SolidLine")
    color = ColorItem(_("Color"), default="black")
    width = FloatItem(_("Width"), default=1., min=0)

    def update_param(self, pen):
        self.width = pen.widthF()
        self.color = str(pen.color().name())
        self.style = LINESTYLE_NAME[pen.style()]

    def build_pen(self):
        linecolor = QColor(self.color)
        style = getattr(Qt, self.style)
        pen = QPen(linecolor, self.width, style)
        return pen
        
    def set_style_from_matlab(self, linestyle):
        """Eventually convert MATLAB-like linestyle into Qt linestyle"""
        linestyle = LINESTYLES.get(linestyle, linestyle) # MATLAB-style
        if linestyle == '': # MATLAB-style
            linestyle = 'NoPen'
        self.style = linestyle

class LineStyleItemWidget(DataSetWidget):
    klass = LineStyleParam

class LineStyleItem(ObjectItem):
    """Item holding a LineStyleParam"""
    klass = LineStyleParam

DataSetEditLayout.register(LineStyleItem, LineStyleItemWidget)

# ===================================================
# Common brush style parameters
# ===================================================
class BrushStyleParam(DataSet):
    style = ImageChoiceItem(_("Style"), BRUSHSTYLE_CHOICES,
                            default="SolidPattern")
    color = ColorItem(_("Color"), default="black")
    alpha = FloatItem(_("Alpha"), default=1.0)
    angle = FloatItem(_("Angle"), default=0., min=0)
    sx = FloatItem(_("sx"), default=1., min=0)
    sy = FloatItem(_("sy"), default=1., min=0)

    def update_param(self, brush):
        from math import pi, sqrt, atan2
        tr = brush.transform()
        pt = tr.map( QPointF(1.0, 0.0) )
        self.sx = sqrt(pt.x()**2+pt.y()**2)
        self.angle = 180*atan2(pt.y(), pt.x())/pi
        pt = tr.map( QPointF(0.0, 1.0) )
        self.sy = sqrt(pt.x()**2+pt.y()**2)

        col = brush.color()
        self.color = str(col.name())
        self.alpha = col.alphaF()
        self.style = BRUSHSTYLE_NAME[brush.style()]

    def build_brush(self):
        color = QColor(self.color)
        color.setAlphaF(self.alpha)
        brush = QBrush(color, getattr(Qt, self.style))
        tr = QTransform()
        tr = tr.scale(self.sx, self.sy)
        tr = tr.rotate(self.angle)
        brush.setTransform(tr)
        return brush

class BrushStyleItemWidget(DataSetWidget):
    klass = BrushStyleParam

class BrushStyleItem(ObjectItem):
    """Item holding a LineStyleParam"""
    klass = BrushStyleParam

DataSetEditLayout.register(BrushStyleItem, BrushStyleItemWidget)


# ===================================================
# QwtText parameters
# ===================================================
class TextStyleParam(DataSet):
    font = FontItem(_("Font"))
    textcolor = ColorItem(_("Text color"), default="blue")
    background_color = ColorItem(_("Background color"), default="white")
    background_alpha = FloatItem(_("Background alpha"),
                            default=0.5, min=0, max=1)

    def update_param(self, obj):
        """obj: QwtText instance"""
        self.font.update_param( obj.font() )
        self.textcolor = obj.color().name()
        color = obj.backgroundBrush().color()
        self.background_color = color.name()
        self.background_alpha = color.alphaF()
    
    def update_text(self, obj):
        """obj: QwtText instance"""
        obj.setColor( QColor(self.textcolor) )
        color = QColor(self.background_color)
        color.setAlphaF(self.background_alpha)
        obj.setBackgroundBrush( QBrush(color) )
        font = self.font.build_font()
        obj.setFont(font)

class TextStyleItemWidget(DataSetWidget):
    klass = TextStyleParam

class TextStyleItem(ObjectItem):
    """Item holding a TextStyleParam"""
    klass = TextStyleParam

DataSetEditLayout.register(TextStyleItem, TextStyleItemWidget)


# ===================================================
# Grid parameters
# ===================================================
class GridParam(DataSet):
    background = ColorItem(_("Background color"), default="white")
    maj = BeginGroup(_("Major grid") )
    maj_xenabled = BoolItem(_("X Axis"), default=True)
    maj_yenabled = BoolItem(_("Y Axis"), default=True).set_pos(col=1)
    maj_line = LineStyleItem(_("Line"))
    _maj = EndGroup("end group")
    
    min = BeginGroup(_("Minor grid"))    
    min_xenabled = BoolItem(_("X Axis"), default=False)
    min_yenabled = BoolItem(_("Y Axis"), default=False).set_pos(col=1)
    min_line = LineStyleItem(_("Line"))
    _min = EndGroup("fin groupe")

    def update_param(self, grid):
        plot = grid.plot()
        if plot is not None:
            self.background = str(plot.canvasBackground().color().name())
        self.maj_xenabled = grid.xEnabled()
        self.maj_yenabled = grid.yEnabled()
        self.maj_line.update_param( grid.majorPen() )
        self.min_xenabled = grid.xMinEnabled()
        self.min_yenabled = grid.yMinEnabled()
        self.min_line.update_param( grid.minorPen() )

    def update_grid(self, grid):
        plot = grid.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
            plot.setCanvasBackground( QColor(self.background) )
        grid.enableX(self.maj_xenabled)
        grid.enableY(self.maj_yenabled)
        grid.setPen( self.maj_line.build_pen() )
        grid.enableXMin(self.min_xenabled)
        grid.enableYMin(self.min_yenabled)
        grid.setMinorPen( self.min_line.build_pen() )
        grid.setTitle(self.get_title())
        if plot is not None:
            plot.blockSignals(False)


# ===================================================
# Axes style parameters
# ===================================================
class AxeStyleParam(DataSet):
    title = StringItem(_("Title"), default="")
    unit = StringItem(_("Unit"), default="")
    color = ColorItem(_("Color"), default="black").set_pos(col=1)
    title_font = FontItem(_("Title font"))
    ticks_font = FontItem(_("Values font"))

    
# ===================================================
# Axes parameters
# ===================================================
class AxisParam(DataSet):
    scale = ChoiceItem(_("Scale"),
                        [("lin", _("linear")), ("log", _("logarithmic"))],
                        default="lin")
    vmin = FloatItem("Min", help=_("Lower axis limit"))
    vmax = FloatItem("Max", help=_("Upper axis limit"))

    def update_param(self, plot, axis_id):
        self.scale = plot.get_axis_scale(axis_id)
        axis = plot.axisScaleDiv(axis_id)
        self.vmin = axis.lowerBound()
        self.vmax = axis.upperBound()

    def update_axis(self, plot, axis_id):
        plot.enableAxis(axis_id, True)
        plot.set_axis_scale(axis_id, self.scale, autoscale=False)
        plot.setAxisScale(axis_id, self.vmin, self.vmax)
        plot.disable_unused_axes()

class AxisItemWidget(DataSetWidget):
    klass = AxisParam

class AxisItem(ObjectItem):
    klass = AxisParam

DataSetEditLayout.register(AxisItem, AxisItemWidget)

class AxesParam(DataSet):
    xaxis_id = ChoiceItem(_("X-axis position"),
                          [(QwtPlot.xBottom, _("bottom")),
                           (QwtPlot.xTop, _("top"))],
                          default=QwtPlot.xBottom)
    xaxis = AxisItem(_("X Axis"))
    yaxis_id = ChoiceItem(_("Y-axis position"),
                          [(QwtPlot.yLeft,  _("left")),
                           (QwtPlot.yRight, _("right"))],
                          default=QwtPlot.yLeft)
    yaxis = AxisItem(_("Y Axis"))

    def update_param(self, item):
        plot = item.plot()
        self.xaxis_id = item.xAxis()
        self.xaxis.update_param(plot, self.xaxis_id)
        self.yaxis_id = item.yAxis()
        self.yaxis.update_param(plot, self.yaxis_id)

    def update_axes(self, item):
        plot = item.plot()
        plot.grid.setAxes(self.xaxis_id, self.yaxis_id)
        item.setXAxis(self.xaxis_id)
        self.xaxis.update_axis(plot, self.xaxis_id)
        item.setYAxis(self.yaxis_id)
        self.yaxis.update_axis(plot, self.yaxis_id)

class ImageAxesParam(DataSet):
    xparams = BeginGroup(_("X Axis") )
    xmin = FloatItem("x|min", help=_("Lower x-axis limit"))
    xmax = FloatItem("x|max", help=_("Upper x-axis limit"))
    _xparams = EndGroup("end X")
    yparams = BeginGroup(_("Y Axis") )
    ymin = FloatItem("y|min", help=_("Lower y-axis limit"))
    ymax = FloatItem("y|max", help=_("Upper y-axis limit"))
    _yparams = EndGroup("end Y")
    zparams = BeginGroup(_("Z Axis") )
    zmin = FloatItem("z|min", help=_("Lower z-axis limit"))
    zmax = FloatItem("z|max", help=_("Upper z-axis limit"))
    _zparams = EndGroup("end Z")

    def update_param(self, item):
        plot = item.plot()
        xaxis = plot.axisScaleDiv(item.xAxis())
        self.xmin = xaxis.lowerBound()
        self.xmax = xaxis.upperBound()
        yaxis = plot.axisScaleDiv(item.yAxis())
        self.ymin = yaxis.lowerBound()
        self.ymax = yaxis.upperBound()
        self.zmin, self.zmax = item.min, item.max

    def update_axes(self, item):
        plot = item.plot()
        plot.set_plot_limits(self.xmin, self.xmax, self.ymin, self.ymax)
        item.set_lut_range([self.zmin, self.zmax])
        plot.update_colormap_axis(item)


# ===================================================
# Label parameters
# ===================================================
class LabelParam(DataSet):
    _multiselection = False
    _legend = False
    _no_contents = True
    label = StringItem(_("Title"), default="") \
            .set_prop("display", hide=GetAttrProp("_multiselection"))
            
    _styles = BeginTabGroup("Styles")
    #-------------------------------------------------------------- Contents tab
    ___cont = BeginGroup(_("Contents")).set_prop("display", icon="label.png",
                                             hide=GetAttrProp("_no_contents"))
    contents = TextItem("").set_prop("display",
                                     hide=GetAttrProp("_no_contents"))
    ___econt = EndGroup(_("Contents")).set_prop("display",
                                             hide=GetAttrProp("_no_contents"))
    #---------------------------------------------------------------- Symbol tab
    symbol = SymbolItem(_("Symbol")).set_prop("display", icon="diamond.png",
                                              hide=GetAttrProp("_legend"))
    #---------------------------------------------------------------- Border tab
    border = LineStyleItem(_("Border"), default=Obj(color="#cbcbcb"),
                           help=_("set width to 0 to disable")
                           ).set_prop("display", icon="dashdot.png")
    #------------------------------------------------------------------ Text tab
    ___text = BeginGroup(_("Text")).set_prop("display", icon="font.png")
    font = FontItem(_("Text font"))
    color = ColorItem(_("Text color"), default="#000000")
    bgcolor = ColorItem(_("Background color"), default="#ffffff")
    bgalpha = FloatItem(_("Background transparency"),
                        min=0.0, max=1.0, default=0.8)
    ___etext = EndGroup(_("Text"))
    #-------------------------------------------------------------- Position tab
    ___position = BeginGroup(_("Position")).set_prop("display", icon="move.png")
    _begin_anchor = BeginGroup(_("Position relative to anchor")) \
                    .set_prop("display", hide=GetAttrProp("_multiselection"))
    anchor = ChoiceItem(_("Corner"),
                        [("TL", _("Top left") ),
                         ("TR", _("Top right") ),
                         ("BL", _("Bottom left") ),
                         ("BR", _("Bottom right") ),
                         ("L", _("Left") ),
                         ("R", _("Right") ),
                         ("T", _("Top") ),
                         ("B", _("Bottom") ),
                         ("C", _("Center") ),], default="TL",
                         help=_("Label position relative to anchor point")) \
                         .set_prop("display",
                                   hide=GetAttrProp("_multiselection"))
    xc = IntItem(_("ΔX"), default=5,
                 help=_("Horizontal offset (pixels) relative to anchor point"))\
                 .set_prop("display", hide=GetAttrProp("_multiselection"))
    yc = IntItem(_("ΔY"), default=5,
                 help=_("Vertical offset (pixels) relative to anchor point")
                 ).set_pos(col=1).set_prop("display",
                                           hide=GetAttrProp("_multiselection"))
    _end_anchor = EndGroup(_("Anchor")) \
                  .set_prop("display", hide=GetAttrProp("_multiselection"))
    _begin_anchorpos = BeginGroup(_("Anchor position")) \
                       .set_prop("display", hide=GetAttrProp("_multiselection"))
    _abspos_prop = GetAttrProp("abspos")
    abspos = BoolItem(text=_("Attach to canvas"), label=_("Anchor"),
                      default=True
                      ).set_prop("display", store=_abspos_prop) \
                       .set_prop("display", hide=GetAttrProp("_multiselection"))
    xg = FloatItem(_("X"), default=0.0,
                   help=_("X-axis position in canvas coordinates")
                   ).set_prop("display", active=NotProp(_abspos_prop)) \
                    .set_prop("display", hide=GetAttrProp("_multiselection"))
    yg = FloatItem(_("Y"), default=0.0,
                   help=_("Y-axis position in canvas coordinates")
                   ).set_pos(col=1) \
                    .set_prop("display", active=NotProp(_abspos_prop)) \
                    .set_prop("display", hide=GetAttrProp("_multiselection"))
    move_anchor = ChoiceItem(_("Interact"),
                         ((True, _("moving object changes anchor position")),
                          (False, _("moving object changes label position"))),
                         default=True
                         ).set_prop("display", active=NotProp(_abspos_prop)) \
                          .set_prop("display",
                                    hide=GetAttrProp("_multiselection"))
    absg = ChoiceItem(_("Position"),
                        [("TL", _("Top left") ),
                         ("TR", _("Top right") ),
                         ("BL", _("Bottom left") ),
                         ("BR", _("Bottom right") ),
                         ("L", _("Left") ),
                         ("R", _("Right") ),
                         ("T", _("Top") ),
                         ("B", _("Bottom") ),
                         ("C", _("Center") ),], default="TL",
                         help=_("Absolute position on canvas")
                         ).set_prop("display", active=_abspos_prop) \
                          .set_prop("display",
                                    hide=GetAttrProp("_multiselection"))
    _end_anchorpos = EndGroup(_("Anchor position")) \
                     .set_prop("display", hide=GetAttrProp("_multiselection"))
    ___eposition = EndGroup(_("Position"))
    #----------------------------------------------------------------------- End
    _endstyles = EndTabGroup("Styles")

    def update_param(self, obj):
        # The following is necessary only for shape labels:
        # when shape is just created (and not yet moved), we need to update
        # these attributes
        if self.abspos:
            self.absg = obj.G
        else:
            self.xg, self.yg = obj.G
        self.xc, self.yc = obj.C

    def update_label(self, obj):
        if not self._multiselection:
            if self.abspos:
                obj.G = self.absg
            else:
                obj.G = (self.xg, self.yg)
            obj.C = self.xc, self.yc
            obj.anchor = self.anchor
            obj.move_anchor = self.move_anchor
            obj.setTitle(self.label)
        obj.marker = self.symbol.build_symbol()
        obj.border_pen = self.border.build_pen()
        obj.set_text_style(self.font.build_font(), self.color)
        color = QColor(self.bgcolor)
        color.setAlphaF(self.bgalpha)
        obj.bg_brush = QBrush(color)

class LabelParam_MS(LabelParam):
    _multiselection = True
    
ItemParameters.register_multiselection(LabelParam, LabelParam_MS)

class LegendParam(LabelParam):
    _legend = True
    label = StringItem(_("Title"), default="").set_prop("display", hide=True)
    
    def update_label(self, obj):
        super(LegendParam, self).update_label(obj)
        if not self._multiselection:
            obj.setTitle(self.get_title())

class LegendParam_MS(LegendParam):
    _multiselection = True
    
ItemParameters.register_multiselection(LegendParam, LegendParam_MS)

class LabelParamWithContents(LabelParam):
    _no_contents = False
    def __init__(self, title=None, comment=None, icon=''):
        self.plain_text = None
        super(LabelParamWithContents, self).__init__(title, comment, icon)
        
    def update_param(self, obj):
        super(LabelParamWithContents, self).update_param(obj)
        self.contents = self.plain_text = obj.get_plain_text()

    def update_label(self, obj):
        super(LabelParamWithContents, self).update_label(obj)
        if self.plain_text is not None and self.contents != self.plain_text:
            text = self.contents.replace('\n', '<br>')
            obj.set_text(text)

class LabelParamWithContents_MS(LabelParamWithContents):
    _multiselection = True
    
ItemParameters.register_multiselection(LabelParamWithContents,
                                       LabelParamWithContents_MS)


# ===================================================
# Curve parameters
# ===================================================
class CurveParam(DataSet):
    _multiselection = False
    label = StringItem(_("Title"), default="").set_prop("display",
                                          hide=GetAttrProp("_multiselection"))
    line = LineStyleItem(_("Line"))
    symbol = SymbolItem(_("Symbol"))
    shade = FloatItem(_("Shadow"), default=0, min=0, max=1)
    curvestyle = ImageChoiceItem(_("Curve style"), CURVESTYLE_CHOICES,
                                 default="Lines")
    baseline = FloatItem(_("Baseline"), default=0.)

    def update_param(self, curve):
        self.label = to_text_string(curve.title().text())
        self.symbol.update_param(curve.symbol())
        self.line.update_param(curve.pen())
        self.curvestyle = CURVESTYLE_NAME[curve.style()]
        self.baseline = curve.baseline()
    
    def update_curve(self, curve):
        plot = curve.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        if not self._multiselection:
            # Non common parameters
            curve.setTitle(self.label)
        curve.setPen(self.line.build_pen())
        # Brush
        linecolor = QColor(self.line.color)
        linecolor.setAlphaF(self.shade)
        brush = QBrush(linecolor)
        if not self.shade:
            brush.setStyle(Qt.NoBrush)
        curve.setBrush(brush)
        # Symbol
        self.symbol.update_symbol( curve )
        # Curve style, type and baseline
        curve.setStyle(getattr(QwtPlotCurve, self.curvestyle))
        curve.setBaseline(self.baseline)
        if plot is not None:
            plot.blockSignals(False)

class CurveParam_MS(CurveParam):
    _multiselection = True
    
ItemParameters.register_multiselection(CurveParam, CurveParam_MS)


# ===================================================
# ErrorBar Curve parameters
# ===================================================
class ErrorBarParam(DataSet):
    mode = ChoiceItem(_("Display"), default=0,
                      choices=[_("error bars with caps (x, y)"),
                               _("error area (y)")],
                      help=_("Note: only y-axis error bars are shown in "
                             "error area mode\n(width and cap parameters "
                             "will also be ignored)"))
    color = ColorItem(_("Color"), default="darkred")
    alpha = FloatItem(_("Alpha"), default=.9, min=0, max=1,
                      help=_("Error bar transparency"))
    width = FloatItem(_("Width"), default=1.0, min=1)
    cap = IntItem(_("Cap"), default=4, min=0)
    ontop = BoolItem(_("set to foreground"), _("Visibility"), default=False)

    def update_param(self, curve):
        color = curve.errorPen.color()
        self.color = str(color.name())
        self.alpha = color.alphaF()
        self.width = curve.errorPen.widthF()
        self.cap = curve.errorCap
        self.ontop = curve.errorOnTop

    def update_curve(self, curve):
        color = QColor(self.color)
        color.setAlphaF(self.alpha)
        curve.errorPen = QPen(color, self.width)
        curve.errorBrush = QBrush(color)
        curve.errorCap = self.cap
        curve.errorOnTop = self.ontop


# ===================================================
# Image parameters
# ===================================================
def _create_choices():
    choices = []
    for cmap_name in get_colormap_list():
        choices.append((cmap_name, cmap_name, build_icon_from_cmap_name))
    return choices

class BaseImageParam(DataSet):
    _multiselection = False
    label = StringItem(_("Image title"), default=_("Image")) \
            .set_prop("display", hide=GetAttrProp("_multiselection"))
    alpha_mask = BoolItem(_("Use image level as alpha"), _("Alpha channel"),
                          default=False)
    alpha = FloatItem(_("Global alpha"), default=1.0, min=0, max=1,
                      help=_("Global alpha value"))
    _hide_colormap = False
    colormap = ImageChoiceItem(_("Colormap"), _create_choices(), default="jet"
                               ).set_prop("display",
                                      hide=GetAttrProp("_hide_colormap"))
    
    interpolation = ChoiceItem(_("Interpolation"),
                               [(0, _("None (nearest pixel)")),
                                (1, _("Linear interpolation")),
                                (2, _("2x2 antialiasing filter")),
                                (3, _("3x3 antialiasing filter")),
                                (5, _("5x5 antialiasing filter"))],
                               default=0, help=_("Image interpolation type"))

    _formats = BeginGroup(_("Statistics string formatting"))
    xformat = StringItem(_("X-Axis"), default=r'%.1f')
    yformat = StringItem(_("Y-Axis"), default=r'%.1f')
    zformat = StringItem(_("Z-Axis"), default=r'%.1f')
    _end_formats = EndGroup(_("Statistics string formatting"))
                               
    def update_param(self, image):
        self.label = to_text_string(image.title().text())
        self.colormap = image.get_color_map_name()
        interpolation = image.get_interpolation()
        mode = interpolation[0]
        from guiqwt.image import INTERP_NEAREST, INTERP_LINEAR
        if mode == INTERP_NEAREST:
            self.interpolation = 0
        elif mode == INTERP_LINEAR:
            self.interpolation = 1
        else:
            size = interpolation[1].shape[0]
            self.interpolation = size

    def update_image(self, image):
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.setTitle(self.label)
        image.set_color_map(self.colormap)
        size = self.interpolation
        from guiqwt.image import INTERP_NEAREST, INTERP_LINEAR, INTERP_AA
        if size == 0:
            mode = INTERP_NEAREST
        elif size == 1:
            mode = INTERP_LINEAR
        else:
            mode = INTERP_AA
        image.set_interpolation(mode, size)
        if plot is not None:
            plot.blockSignals(False)

class QuadGridParam(DataSet):
    _multiselection = False
    label = StringItem(_("Image title"), default=_("Image")) \
            .set_prop("display", hide=GetAttrProp("_multiselection"))
    alpha_mask = BoolItem(_("Use image level as alpha"), _("Alpha channel"),
                          default=False)
    alpha = FloatItem(_("Global alpha"), default=1.0, min=0, max=1,
                      help=_("Global alpha value"))
    _hide_colormap = False
    colormap = ImageChoiceItem(_("Colormap"), _create_choices(), default="jet"
                               ).set_prop("display",
                                      hide=GetAttrProp("_hide_colormap"))
    
    interpolation = ChoiceItem(_("Interpolation"),
                               [ (0, _("Quadrangle interpolation")),
                                 (1, _("Flat")),
                                 ],
                               default=0,
                               help=_("Image interpolation type, "
                                      "Flat mode use fixed u,v "
                                      "interpolation parameters"))
    uflat = FloatItem(_("Fixed U interpolation parameter"),
                      default=0.5, min=0., max=1., help=_("For flat mode only"))
    vflat = FloatItem(_("Fixed V interpolation parameter"),
                      default=0.5, min=0., max=1., help=_("For flat mode only"))
    grid = BoolItem(_("Show grid"), default=False)
    gridcolor = ColorItem(_("Grid lines color"), default="black")
                               
    def update_param(self, image):
        self.label = to_text_string(image.title().text())
        self.colormap = image.get_color_map_name()
        interp, uflat, vflat = image.interpolate
        self.interpolation = interp
        self.uflat = uflat
        self.vflat = vflat
        self.grid = image.grid

    def update_image(self, image):
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.setTitle(self.label)
        image.set_color_map(self.colormap)
        image.interpolate = (self.interpolation, self.uflat, self.vflat)
        image.grid = self.grid
        # TODO : gridcolor
        if plot is not None:
            plot.blockSignals(False)

class RawImageParam(BaseImageParam):
    _hide_background = False
    background = ColorItem(_("Background color"), default="#000000"
                           ).set_prop("display",
                                      hide=GetAttrProp("_hide_background"))
    
    def update_param(self, image):
        super(RawImageParam, self).update_param(image)
        self.background = str(QColor(image.bg_qcolor).name())

    def update_image(self, image):
        super(RawImageParam, self).update_image(image)
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.set_background_color(self.background)
        if plot is not None:
            plot.blockSignals(False)

class RawImageParam_MS(RawImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(RawImageParam, RawImageParam_MS)


class XYImageParam(RawImageParam):
    pass

class XYImageParam_MS(XYImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(XYImageParam, XYImageParam_MS)


class ImageParam(RawImageParam):
    _xdata = BeginGroup(_("Image placement along X-axis"))
    xmin = FloatItem(_("x|min"), default=None)
    xmax = FloatItem(_("x|max"), default=None)
    _end_xdata = EndGroup(_("Image placement along X-axis"))
    _ydata = BeginGroup(_("Image placement along Y-axis"))
    ymin = FloatItem(_("y|min"), default=None)
    ymax = FloatItem(_("y|max"), default=None)
    _end_ydata = EndGroup(_("Image placement along Y-axis"))
    
    def update_param(self, image):
        super(ImageParam, self).update_param(image)
        self.xmin = image.xmin
        if self.xmin is None:
            self.xmin = 0.
        self.ymin = image.ymin
        if self.ymin is None:
            self.ymin = 0.
        if image.is_empty():
            shape = (0, 0)
        else:
            shape = image.data.shape
        self.xmax = image.xmax
        if self.xmax is None:
            self.xmax = float(shape[1])
        self.ymax = image.ymax
        if self.ymax is None:
            self.ymax = float(shape[0])

    def update_image(self, image):
        super(ImageParam, self).update_image(image)
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.xmin = self.xmin
        image.xmax = self.xmax
        image.ymin = self.ymin
        image.ymax = self.ymax
        image.update_bounds()
        image.update_border()
        if plot is not None:
            plot.blockSignals(False)

class ImageParam_MS(ImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(ImageParam, ImageParam_MS)


class RGBImageParam(ImageParam):
    _hide_background = True
    _hide_colormap = True

    def update_image(self, image):
        super(RGBImageParam, self).update_image(image)
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.recompute_alpha_channel()
        if plot is not None:
            plot.blockSignals(False)

class RGBImageParam_MS(RGBImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(RGBImageParam, RGBImageParam_MS)


class MaskedImageParam(ImageParam):
    g_mask = BeginGroup(_("Mask"))
    filling_value = FloatItem(_("Filling value"))
    show_mask = BoolItem(_("Show image mask"), default=False)
    alpha_masked = FloatItem(_("Masked area alpha"),
                             default=.7, min=0, max=1)
    alpha_unmasked = FloatItem(_("Unmasked area alpha"),
                               default=0., min=0, max=1)
    _g_mask = EndGroup(_("Mask"))
    
    def update_image(self, image):
        super(MaskedImageParam, self).update_image(image)
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.update_mask()
        if plot is not None:
            plot.blockSignals(False)
                         
class MaskedImageParam_MS(MaskedImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(MaskedImageParam, MaskedImageParam_MS)


class ImageFilterParam(BaseImageParam):
    label = StringItem(_("Title"), default=_("Filter"))
    g1 = BeginGroup(_("Bounds"))
    xmin = FloatItem(_("x|min"))
    xmax = FloatItem(_("x|max"))
    ymin = FloatItem(_("y|min"))
    ymax = FloatItem(_("y|max"))
    _g1 = EndGroup("sub-group")
    use_source_cmap = BoolItem(_("Use image colormap and level"),
                               _("Color map"), default=True)
    
    def update_param(self, obj):
        self.xmin, self.ymin, self.xmax, self.ymax = obj.border_rect.get_rect()
        self.use_source_cmap = obj.use_source_cmap
        super(ImageFilterParam, self).update_param(obj)
    
    def update_imagefilter(self, imagefilter):
        m, M = imagefilter.get_lut_range()
        set_range = False
        if not self.use_source_cmap and imagefilter.use_source_cmap:
            set_range = True
        imagefilter.use_source_cmap = self.use_source_cmap
        if set_range:
            imagefilter.set_lut_range([m, M])
        self.update_image(imagefilter)
        imagefilter.border_rect.set_rect(self.xmin, self.ymin,
                                         self.xmax, self.ymax)


class TrImageParam(RawImageParam):
    _crop = BeginGroup(_("Crop")
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    crop_left = IntItem(_("Left"), default=0)
    crop_right = IntItem(_("Right"), default=0)
    crop_top = IntItem(_("Top"), default=0)
    crop_bottom = IntItem(_("Bottom"), default=0)
    _end_crop = EndGroup(_("Cropping")
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    _ps = BeginGroup(_("Pixel size")
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    dx = FloatItem(_("Width (dx)"), default=1.0)
    dy = FloatItem(_("Height (dy)"), default=1.0)
    _end_ps = EndGroup(_("Pixel size")
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    _pos = BeginGroup(_("Translate, rotate and flip"))
    pos_x0 = FloatItem(_("x<sub>CENTER</sub>"), default=0.0
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    hflip = BoolItem(_("Flip horizontally"), default=False
                     ).set_prop("display", col=1)
    pos_y0 = FloatItem(_("y<sub>CENTER</sub>"), default=0.0
                    ).set_prop("display", hide=GetAttrProp("_multiselection"))
    vflip = BoolItem(_("Flip vertically"), default=False
                     ).set_prop("display", col=1)
    pos_angle = FloatItem(_("θ (°)"), default=0.0).set_prop("display", col=0)
    _end_pos = EndGroup(_("Translate, rotate and flip"))

    def update_param(self, image):
        super(TrImageParam, self).update_param(image)
        # we don't get crop info from the image because
        # its not easy to extract from the transform
        # and TrImageItem keeps it's crop information
        # directly in this DataSet

    def update_image(self, image):
        RawImageParam.update_image(self, image)
        plot = image.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        image.set_transform(*self.get_transform())
        if plot is not None:
            plot.blockSignals(False)

    def get_transform(self):
        return (self.pos_x0, self.pos_y0, self.pos_angle*np.pi/180,
                self.dx, self.dy, self.hflip, self.vflip)

    def set_transform(self, x0, y0, angle, dx=1.0, dy=1.0,
                      hflip=False, vflip=False):
        self.pos_x0 = x0
        self.pos_y0 = y0
        self.pos_angle = angle*180/np.pi
        self.dx = dx
        self.dy = dy
        self.hflip = hflip
        self.vflip = vflip

    def set_crop(self, left, top, right, bottom):
        self.crop_left = left
        self.crop_right = right
        self.crop_top = top
        self.crop_bottom = bottom

    def get_crop(self):
        return (self.crop_left, self.crop_top,
                self.crop_right, self.crop_bottom)
    
class TrImageParam_MS(TrImageParam):
    _multiselection = True
    
ItemParameters.register_multiselection(TrImageParam, TrImageParam_MS)


# ===================================================
# Histogram parameters
# ===================================================
class HistogramParam(DataSet):
    n_bins = IntItem(_("Bins"), default=100, min=1, help=_("Number of bins"))
    logscale = BoolItem(_("logarithmic"), _("Y-axis scale"), default=False)

    def update_param(self, obj):
        self.n_bins = obj.get_bins()
        self.logscale = obj.get_logscale()

    def update_hist(self, hist):
        hist.set_bins(self.n_bins)
        hist.set_logscale(self.logscale)


# ===================================================
# Histogram 2D parameters
# ===================================================
class Histogram2DParam(BaseImageParam):
    """Histogram"""
    _multiselection = False
    label = StringItem(_("Title"), default=_("Histogram")) \
            .set_prop("display", hide=GetAttrProp("_multiselection"))
    nx_bins = IntItem(_("X-axis bins"), default=100, min=1,
                      help=_("Number of bins along x-axis"))
    ny_bins = IntItem(_("Y-axis bins"), default=100, min=1,
                      help=_("Number of bins along y-axis"))
    logscale = BoolItem(_("logarithmic"), _("Z-axis scale"), default=False)
    
    computation = ChoiceItem(_("Computation"),
                         [(-1, _("Bin count")),
                          (0, _("Maximum value")),
                          (1, _("Mininum value")),
                          (2, _("Sum")),
                          (3, _("Product")),
                          (4, _("Average")),
                          ],
                   default=-1,
                   help=_("Bin count : counts the number of points per bin,\n"
                          "For max, min, sum, product, average, compute the "
                          "function of a third parameter (one by default)"))
    auto_lut = BoolItem(_("Automatic LUT range"), default=True,
                        help=_("Automatically adapt color scale "
                               "when panning, zooming"))
    background = ColorItem(_("Background color"), default="transparent",
                           help=_("Background color when no data is present"))

    def update_param(self, obj):
        super(Histogram2DParam, self).update_param(obj)
        self.logscale = obj.logscale
        self.nx_bins, self.ny_bins = obj.nx_bins, obj.ny_bins

    def update_histogram(self, histogram):
        histogram.logscale = int(self.logscale)
        histogram.set_background_color(self.background)
        histogram.set_bins(self.nx_bins, self.ny_bins)
        self.update_image(histogram)

class Histogram2DParam_MS(Histogram2DParam):
    _multiselection = True

ItemParameters.register_multiselection(Histogram2DParam, Histogram2DParam_MS)
    

# ===================================================
# Shape parameters
# ===================================================
class MarkerParam(DataSet):
    _styles = BeginTabGroup("Styles")
    #------------------------------------------------------------------ Line tab
    ___line = BeginGroup(_("Line")).set_prop("display", icon="dashdot.png")
    line = LineStyleItem(_("Line (not selected)"))
    sel_line = LineStyleItem(_("Line (selected)"))
    ___eline = EndGroup(_("Line"))
    #---------------------------------------------------------------- Symbol tab
    ___sym = BeginGroup(_("Symbol")).set_prop("display", icon="diamond.png")
    symbol = SymbolItem(_("Symbol (not selected)"))
    sel_symbol = SymbolItem(_("Symbol (selected)"))
    ___esym = EndGroup(_("Symbol"))
    #------------------------------------------------------------------ Text tab
    ___text = BeginGroup(_("Text")).set_prop("display", icon="font.png")
    text = TextStyleItem(_("Text (not selected)"))
    sel_text = TextStyleItem(_("Text (selected)"))
    ___etext = EndGroup(_("Text"))
    #----------------------------------------------------------------------- End
    _endstyles = EndTabGroup("Styles")
    markerstyle = ImageChoiceItem(_("Line style"), MARKERSTYLE_CHOICES,
                                  default="NoLine")
    spacing = IntItem(_("Spacing"), default=10, min=0)
    
    def update_param(self, obj):
        self.symbol.update_param(obj.symbol())
        self.text.update_param(obj.label())
        self.line.update_param(obj.linePen())
        self.markerstyle = MARKERSTYLE_NAME[obj.lineStyle()]
        self.spacing = obj.spacing()

    def update_marker(self, obj):
        if obj.selected:
            line = self.sel_line
            symb = self.sel_symbol
            text = self.sel_text
        else:
            line = self.line
            symb = self.symbol
            text = self.text
        symb.update_symbol(obj)
        label = obj.label()
        text.update_text(label)
        obj.setLabel(label)
        obj.setLinePen(line.build_pen())
        obj.setLineStyle(getattr(QwtPlotMarker, self.markerstyle))
        obj.setSpacing(self.spacing)
        obj.update_label()
        
    def set_markerstyle(self, style):
        """
        Set marker line style

        style:
            
            * convenient values: '+', '-', '|' or None
            * `QwtPlotMarker.NoLine`, `QwtPlotMarker.Vertical`, ...
        """
        self.markerstyle = MARKERSTYLES.get(style, style)

class ShapeParam(DataSet):
    label = StringItem(_("Title"), default="")
    _styles = BeginTabGroup("Styles")
    #------------------------------------------------------------------ Line tab
    ___line = BeginGroup(_("Line")).set_prop("display", icon="dashdot.png")
    line = LineStyleItem(_("Line (not selected)"))
    sel_line = LineStyleItem(_("Line (selected)"))
    ___eline = EndGroup(_("Line"))
    #---------------------------------------------------------------- Symbol tab
    ___sym = BeginGroup(_("Symbol")).set_prop("display", icon="diamond.png")
    symbol = SymbolItem(_("Symbol (not selected)"))
    sel_symbol = SymbolItem(_("Symbol (selected)"))
    ___esym = EndGroup(_("Symbol"))
    #------------------------------------------------------------------ Fill tab
    ___fill = BeginGroup(_("Fill pattern")).set_prop("display",
                                                     icon="dense6pattern.png")
    fill = BrushStyleItem(_("Fill pattern (not selected)"))
    sel_fill = BrushStyleItem(_("Fill pattern (selected)"))
    ___efill = EndGroup(_("Fill pattern"))
    #----------------------------------------------------------------------- End
    _endstyles = EndTabGroup("Styles")
    readonly = BoolItem(_("Read-only shape"), default=False,
                        help=_("Read-only shapes can't be removed from "
                               "the item list panel"))
    private = BoolItem(_("Private shape"), default=False,
                        help=_("Private shapes are not shown in "
                               "the item list panel")).set_pos(col=1)
    
    def update_param(self, obj):
        self.label = to_text_string(obj.title().text())
        self.line.update_param(obj.pen)
        self.symbol.update_param(obj.symbol)
        self.fill.update_param(obj.brush)
        self.sel_line.update_param(obj.sel_pen)
        self.sel_symbol.update_param(obj.sel_symbol)
        self.sel_fill.update_param(obj.sel_brush)
        self.readonly = obj.is_readonly()
        self.private = obj.is_private()
        
    def update_shape(self, obj):
        plot = obj.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        obj.setTitle(self.label)
        obj.pen = self.line.build_pen()
        obj.symbol = self.symbol.build_symbol()
        obj.brush = self.fill.build_brush()
        obj.sel_pen = self.sel_line.build_pen()
        obj.sel_symbol = self.sel_symbol.build_symbol()
        obj.sel_brush = self.sel_fill.build_brush()
        obj.set_readonly(self.readonly)
        obj.set_private(self.private)
        if plot is not None:
            plot.blockSignals(False)

class AxesShapeParam(DataSet):
    arrow_angle = FloatItem(_("Arrow angle (°)"), min=0, max=90, nonzero=True)
    arrow_size = FloatItem(_("Arrow size (%)"), min=0, max=100, nonzero=True)
    _styles = BeginTabGroup("Styles")
    #------------------------------------------------------------------ Line tab
    ___line = BeginGroup(_("Line")).set_prop("display", icon="dashdot.png")
    xarrow_pen = LineStyleItem(_("Line (X-Axis)"))
    yarrow_pen = LineStyleItem(_("Line (Y-Axis)"))
    ___eline = EndGroup(_("Line"))
    #------------------------------------------------------------------ Fill tab
    ___fill = BeginGroup(_("Fill pattern")).set_prop("display",
                                                     icon="dense6pattern.png")
    xarrow_brush = BrushStyleItem(_("Fill pattern (X-Axis)"))
    yarrow_brush = BrushStyleItem(_("Fill pattern (Y-Axis)"))
    ___efill = EndGroup(_("Fill pattern"))
    #----------------------------------------------------------------------- End
    _endstyles = EndTabGroup("Styles")
    
    def update_param(self, obj):
        self.arrow_angle = obj.arrow_angle
        self.arrow_size = obj.arrow_size
        self.xarrow_pen.update_param(obj.x_pen)
        self.yarrow_pen.update_param(obj.y_pen)
        self.xarrow_brush.update_param(obj.x_brush)
        self.yarrow_brush.update_param(obj.y_brush)
        
    def update_axes(self, obj):
        obj.arrow_angle = self.arrow_angle
        obj.arrow_size = self.arrow_size
        obj.x_pen = self.xarrow_pen.build_pen()
        obj.x_brush = self.xarrow_brush.build_brush()
        obj.y_pen = self.yarrow_pen.build_pen()
        obj.y_brush = self.yarrow_brush.build_brush()

class AnnotationParam(DataSet):
    show_label = BoolItem(_("Show annotation"), default=True)
    show_computations = BoolItem(_("Show informations on area "
                                   "covered by this shape"), default=True)
    title = StringItem(_("Title"), default="")
    subtitle = StringItem(_("Subtitle"), default="")
    format = StringItem(_("String formatting"), default="%.1f")
    uncertainty = FloatItem(_("Uncertainty"), default=0., min=0., max=1.,
                            help=_("Measurement relative uncertainty")
                            ).set_pos(col=1)
    transform_matrix = FloatArrayItem(_("Transform matrix"),
                                      default=np.eye(3, dtype=float))
    readonly = BoolItem(_("Read-only shape"), default=False,
                        help=_("Read-only shapes can't be removed from "
                               "the item list panel"))
    private = BoolItem(_("Private shape"), default=False,
                        help=_("Private shapes are not shown in "
                               "the item list panel")).set_pos(col=1)
    
    def update_param(self, obj):
        self.show_label = obj.is_label_visible()
        self.show_computations = obj.area_computations_visible
        self.title = to_text_string(obj.title().text())
        self.readonly = obj.is_readonly()
        self.private = obj.is_private()
        
    def update_annotation(self, obj):
        plot = obj.plot()
        if plot is not None:
            plot.blockSignals(True)  # Avoid unwanted calls of update_param 
                                     # triggered by the setter methods below
        obj.setTitle(self.title)
        obj.set_label_visible(self.show_label)
        obj.area_computations_visible = self.show_computations
        obj.update_label()
        obj.set_readonly(self.readonly)
        obj.set_private(self.private)
        if plot is not None:
            plot.blockSignals(False)


# ===================================================
# Range selection parameters
# ===================================================
class RangeShapeParam(DataSet):
    _styles = BeginTabGroup("Styles")
    #------------------------------------------------------------------ Line tab
    ___line = BeginGroup(_("Line")).set_prop("display", icon="dashdot.png")
    line = LineStyleItem(_("Line (not selected)"))
    sel_line = LineStyleItem(_("Line (selected)"))
    ___eline = EndGroup(_("Line"))
    #---------------------------------------------------------------- Symbol tab
    ___symbol = BeginGroup(_("Symbol")).set_prop("display", icon="diamond.png")
    symbol = SymbolItem(_("Symbol (not selected)"))
    sel_symbol = SymbolItem(_("Symbol (selected)"))
    ___esymbol = EndGroup(_("Symbol"))
    #------------------------------------------------------------------ Fill tab
    ___fill = BeginGroup(_("Fill")).set_prop("display",
                                             icon="dense6pattern.png")
    fill = ColorItem(_("Fill color"))
    shade = FloatItem(_("Shade"), default = .05, min=0, max=1)
    ___efill = EndGroup(_("Fill"))
    #----------------------------------------------------------------------- End
    _endstyles = EndTabGroup("Styles")
    
    def update_param(self, range):
        self.line.update_param(range.pen)
        self.sel_line.update_param(range.sel_pen)
        self.fill = range.brush.color().name()
        self.shade = range.brush.color().alphaF()
        self.symbol.update_param(range.symbol)
        self.sel_symbol.update_param(range.sel_symbol)
        
    def update_range(self, range):
        range.pen = self.line.build_pen()
        range.sel_pen = self.sel_line.build_pen()
        col = QColor(self.fill)
        col.setAlphaF(self.shade)
        range.brush = QBrush(col)
        range.symbol = self.symbol.build_symbol()
        range.sel_symbol = self.sel_symbol.build_symbol()