This file is indexed.

/usr/share/pyshared/PyMca/MaskImageWidget.py is in pymca 4.5.0-4.

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
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
#/*##########################################################################
# Copyright (C) 2004-2012 European Synchrotron Radiation Facility
#
# This file is part of the PyMCA X-ray Fluorescence Toolkit developed at
# the ESRF by the Beamline Instrumentation Software Support (BLISS) group.
#
# This toolkit is free software; you can redistribute it and/or modify it 
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option) 
# any later version.
#
# PyMCA is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# PyMCA; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307, USA.
#
# PyMCA follows the dual licensing model of Trolltech's Qt and Riverbank's PyQt
# and cannot be used as a free plugin for a non-free program. 
#
# Please contact the ESRF industrial unit (industry@esrf.fr) if this license 
# is a problem for you.
#############################################################################*/
__author__ = "V.A. Sole - ESRF BLISS Group"
import sys
import RGBCorrelatorGraph
qt = RGBCorrelatorGraph.qt
IconDict = RGBCorrelatorGraph.IconDict
QWTVERSION4 = RGBCorrelatorGraph.QtBlissGraph.QWTVERSION4
QTVERSION = qt.qVersion()
if hasattr(qt, "QString"):
    QString = qt.QString
else:
    QString = str
MATPLOTLIB = False
if QTVERSION > '4.0.0':
    try:
        import QPyMcaMatplotlibSave
        MATPLOTLIB = True
    except ImportError:
        MATPLOTLIB = False
else:
    qt.QIcon = qt.QIconSet
import numpy
import ColormapDialog
import spslut
import os
import PyMcaDirs
import ArraySave
try:
    from PyMca import ProfileScanWidget
except ImportError:
    import ProfileScanWidget
try:
    from PyMca import SpecfitFuns
except ImportError:
    import SpecfitFuns


COLORMAPLIST = [spslut.GREYSCALE, spslut.REVERSEGREY, spslut.TEMP,
                spslut.RED, spslut.GREEN, spslut.BLUE, spslut.MANY]

if QWTVERSION4:
    raise ImportError("MaskImageWidget needs Qwt5")

if QTVERSION > '4.0.0':
    import PyQt4.Qwt5 as Qwt
else:
    import Qwt5 as Qwt

try:
    import QwtPlotItems
    OVERLAY_DRAW = True
except ImportError:
    OVERLAY_DRAW = False

DEBUG = 0

if QTVERSION < '4.6.0':
    USE_PICKER = True
else:
    USE_PICKER = False
class MyPicker(Qwt.QwtPlotPicker):
    def __init__(self, *var):
        Qwt.QwtPlotPicker.__init__(self, *var)
        self.__text = Qwt.QwtText()
        self.data = None

    if USE_PICKER:
        def trackerText(self, var):
            d=self.invTransform(var)
            if self.data is None:
                self.__text.setText("%g, %g" % (d.x(), d.y()))
            else:
                limits = self.data.shape
                x = round(d.y())
                y = round(d.x())
                if x < 0: x = 0
                if y < 0: y = 0
                x = min(int(x), limits[0]-1)
                y = min(int(y), limits[1]-1)
                z = self.data[x, y]
                self.__text.setText("%d, %d, %.4g" % (y, x, z))
            return self.__text
    
class MaskImageWidget(qt.QWidget):
    def __init__(self, parent = None, rgbwidget=None, selection=True, colormap=False,
                 imageicons=True, standalonesave=True, usetab=False,
                 profileselection=False, scanwindow=None):
        qt.QWidget.__init__(self, parent)
        if QTVERSION < '4.0.0':
            self.setIcon(qt.QPixmap(IconDict['gioconda16']))
            self.setCaption("PyMca - Image Selection Tool")
            profileselection = False
        else:
            self.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict['gioconda16'])))
            self.setWindowTitle("PyMca - Image Selection Tool")
            if 0:
                screenHeight = qt.QDesktopWidget().height()
                if screenHeight > 0:
                    self.setMaximumHeight(int(0.99*screenHeight))
                    self.setMinimumHeight(int(0.5*screenHeight))
                screenWidth = qt.QDesktopWidget().width()
                if screenWidth > 0:
                    self.setMaximumWidth(int(screenWidth)-5)
                    self.setMinimumWidth(min(int(0.5*screenWidth),800))

        self._y1AxisInverted = False
        self.__selectionMask = None
        self.__imageData = None
        self.__image = None
        self.colormap = None
        self.colormapDialog = None
        self.setDefaultColormap(2, False)
        self.rgbWidget = rgbwidget

        self.__imageIconsFlag = imageicons
        self.__selectionFlag = selection
        self.__useTab = usetab
        self.mainTab = None

        self._build(standalonesave, profileselection=profileselection)
        self._profileSelectionWindow = None
        self._profileScanWindow = scanwindow

        self.__brushMenu  = None
        self.__brushMode  = False
        self.__eraseMode  = False
        self.__connected = True

        self.__setBrush2()
        
        self.outputDir   = None
        self._saveFilter = None
        
        self._buildConnections()
        self._matplotlibSaveImage = None

        #the overlay items to be drawn
        self._overlayItemsDict = {}
        #the last overlay legend used
        self.__lastOverlayLegend = None

    def _build(self, standalonesave, profileselection=False):
        self.mainLayout = qt.QVBoxLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        if self.__useTab:
            self.mainTab = qt.QTabWidget(self)
            #self.graphContainer =qt.QWidget()
            #self.graphContainer.mainLayout = qt.QVBoxLayout(self.graphContainer)
            #self.graphContainer.mainLayout.setMargin(0)
            #self.graphContainer.mainLayout.setSpacing(0)
            self.graphWidget = RGBCorrelatorGraph.RGBCorrelatorGraph(self,
                                                   selection = self.__selectionFlag,
                                                   colormap=True,
                                                   imageicons=self.__imageIconsFlag,
                                                   standalonesave=False,
                                                   standalonezoom=False,
                                                   profileselection=profileselection)
            self.mainTab.addTab(self.graphWidget, 'IMAGES')
        else:
            if QTVERSION < '4.0.0':
                self.graphWidget = RGBCorrelatorGraph.RGBCorrelatorGraph(self,
                                                   selection = self.__selectionFlag,
                                                   colormap=True,
                                                   imageicons=self.__imageIconsFlag,
                                                   standalonesave=True,
                                                   standalonezoom=False)
                standalonesave = False
            else:
                self.graphWidget = RGBCorrelatorGraph.RGBCorrelatorGraph(self,
                                                   selection =self.__selectionFlag,
                                                   colormap=True,
                                                   imageicons=self.__imageIconsFlag,
                                                   standalonesave=False,
                                                   standalonezoom=False,
                                                   profileselection=profileselection)

        #for easy compatibility with RGBCorrelatorGraph
        self.graph = self.graphWidget.graph

        if profileselection:
            self.connect(self.graphWidget,
                         qt.SIGNAL('PolygonSignal'), 
                         self._polygonSignalSlot)

        if standalonesave:
            self.buildStandaloneSaveMenu()

        self.connect(self.graphWidget.zoomResetToolButton,
                     qt.SIGNAL("clicked()"), 
                     self._zoomResetSignal)
        self.graphWidget.picker = MyPicker(Qwt.QwtPlot.xBottom,
                           Qwt.QwtPlot.yLeft,
                           Qwt.QwtPicker.NoSelection,
                           Qwt.QwtPlotPicker.CrossRubberBand,
                           Qwt.QwtPicker.AlwaysOn,
                           self.graphWidget.graph.canvas())
        self.graphWidget.picker.setTrackerPen(qt.QPen(qt.Qt.black))
        self.graphWidget.graph.enableSelection(False)
        self.graphWidget.graph.enableZoom(True)
        if self.__selectionFlag:
            if self.__imageIconsFlag:
                self.setSelectionMode(False)
            else:
                self.setSelectionMode(True)
            self._toggleSelectionMode()
        if self.__useTab:
            self.mainLayout.addWidget(self.mainTab)
        else:
            self.mainLayout.addWidget(self.graphWidget)

    def buildStandaloneSaveMenu(self):
        self.connect(self.graphWidget.saveToolButton,
                         qt.SIGNAL("clicked()"), 
                         self._saveToolButtonSignal)
        self._saveMenu = qt.QMenu()
        self._saveMenu.addAction(QString("Image Data"),
                                 self.saveImageList)
        self._saveMenu.addAction(QString("Colormap Clipped Seen Image Data"),
                                 self.saveClippedSeenImageList)
        self._saveMenu.addAction(QString("Clipped and Subtracted Seen Image Data"),
                                 self.saveClippedAndSubtractedSeenImageList)

        self._saveMenu.addAction(QString("Standard Graphics"),
                                 self.graphWidget._saveIconSignal)
        if QTVERSION > '4.0.0':
            if MATPLOTLIB:
                self._saveMenu.addAction(QString("Matplotlib") ,
                                 self._saveMatplotlibImage)

    def _buildConnections(self, widget = None):
        self.connect(self.graphWidget.hFlipToolButton,
                 qt.SIGNAL("clicked()"),
                 self._hFlipIconSignal)

        self.connect(self.graphWidget.colormapToolButton,
                     qt.SIGNAL("clicked()"),
                     self.selectColormap)

        if self.__selectionFlag:
            self.connect(self.graphWidget.selectionToolButton,
                     qt.SIGNAL("clicked()"),
                     self._toggleSelectionMode)
            text = "Toggle between Selection\nand Zoom modes"
            if QTVERSION > '4.0.0':
                self.graphWidget.selectionToolButton.setToolTip(text)

        if self.__imageIconsFlag:
            self.connect(self.graphWidget.imageToolButton,
                     qt.SIGNAL("clicked()"),
                     self._resetSelection)

            self.connect(self.graphWidget.eraseSelectionToolButton,
                     qt.SIGNAL("clicked()"),
                     self._setEraseSelectionMode)

            self.connect(self.graphWidget.rectSelectionToolButton,
                     qt.SIGNAL("clicked()"),
                     self._setRectSelectionMode)

            self.connect(self.graphWidget.brushSelectionToolButton,
                     qt.SIGNAL("clicked()"),
                     self._setBrushSelectionMode)

            self.connect(self.graphWidget.brushToolButton,
                     qt.SIGNAL("clicked()"),
                     self._setBrush)

        if QTVERSION < "4.0.0":
            self.connect(self.graphWidget.graph,
                         qt.PYSIGNAL("QtBlissGraphSignal"),
                         self._graphSignal)
        else:
            if self.__imageIconsFlag:
                self.connect(self.graphWidget.additionalSelectionToolButton,
                         qt.SIGNAL("clicked()"),
                         self._additionalSelectionMenuDialog)
                self._additionalSelectionMenu = qt.QMenu()
                self._additionalSelectionMenu.addAction(QString("Reset Selection"),
                                                        self._resetSelection)
                self._additionalSelectionMenu.addAction(QString("Invert Selection"),
                                                        self._invertSelection)
                self._additionalSelectionMenu.addAction(QString("I >= Colormap Max"),
                                                        self._selectMax)
                self._additionalSelectionMenu.addAction(QString("Colormap Min < I < Colormap Max"),
                                                        self._selectMiddle)
                self._additionalSelectionMenu.addAction(QString("I <= Colormap Min"),
                                                        self._selectMin)

            self.connect(self.graphWidget.graph,
                     qt.SIGNAL("QtBlissGraphSignal"),
                     self._graphSignal)

    def _polygonSignalSlot(self, ddict):
        if DEBUG:
            print("_polygonSignalSLot, event = %s" % ddict['event'])
            print("Received ddict = ", ddict)

        if ddict['event'] in [None, "NONE"]:
            #Nothing to be made
            return

        if ddict['event'] == "PolygonWidthChanged":
            if self.__lastOverlayLegend is not None:
                legend = self.__lastOverlayLegend
                if legend in self._overlayItemsDict:
                    info = self._overlayItemsDict[legend]['info']
                    if info['mode'] == ddict['mode']:
                        newDict = {}
                        newDict.update(info)
                        newDict['pixelwidth'] = ddict['pixelwidth']
                        self._polygonSignalSlot(newDict)
            return

        if self._profileSelectionWindow is None:
            if self._profileScanWindow is None:
                #identical to the standard scan window
                self._profileSelectionWindow = ProfileScanWidget.ProfileScanWidget(actions=False)
            else:
                self._profileSelectionWindow = ProfileScanWidget.ProfileScanWidget(actions=True)
                self.connect(self._profileSelectionWindow,
                             qt.SIGNAL('addClicked'),
                             self._profileSelectionSlot)
                self.connect(self._profileSelectionWindow,
                             qt.SIGNAL('removeClicked'),
                             self._profileSelectionSlot)
                self.connect(self._profileSelectionWindow,
                             qt.SIGNAL('replaceClicked'),
                             self._profileSelectionSlot)
            self._interpolate =  SpecfitFuns.interpol
            #if I do not return here and the user interacts with the graph while
            #the profileSelectionWindow is not shown, I get crashes under Qt 4.5.3 and MacOS X
            #when calling _getProfileCurve
            return


        self._updateProfileCurve(ddict)

    def _updateProfileCurve(self, ddict):
        curve = self._getProfileCurve(ddict)
        if curve is None:
            return
        xdata, ydata, legend, info = curve            
        replot=True
        replace=True
        self._profileSelectionWindow.addCurve(xdata, ydata,
                                              legend=legend,
                                              info=info,
                                              replot=replot,
                                              replace=replace)

    def getGraphTitle(self):
        try:
            title = self.graphWidget.graph.title().text()
            if sys.version < '3.0':
                title = str(title)
        except:
            title = ""
        return title

    def _getProfileCurve(self, ddict, image=None, overlay=OVERLAY_DRAW):
        if image is None:
            imageData = self.__imageData
        else:
            imageData = image
        if imageData is None:
            return None

        title = self.getGraphTitle()

        self._profileSelectionWindow.setTitle(title)
        if self._profileScanWindow is not None:
            self._profileSelectionWindow.label.setText(title)

        #showing the profileSelectionWindow now can make the program crash if the workaround mentioned above
        #is not implemented
        self._profileSelectionWindow.show()
        #self._profileSelectionWindow.raise_()

        if ddict['event'] == 'PolygonModeChanged':
            return

        #if I show the image here it does not crash, but it is not nice because
        #the user would get the profileSelectionWindow under his mouse
        #self._profileSelectionWindow.show()

        shape = imageData.shape
        width = ddict['pixelwidth'] - 1
        if ddict['mode'].upper() in ["HLINE", "HORIZONTAL"]:
            if width < 1:
                row = int(ddict['y'][0])
                if row < 0:
                    row = 0
                if row >= shape[0]:
                    row = shape[0] - 1
                ydata  = imageData[row, :]
                legend = "Row = %d"  % row
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([0.0, shape[1], shape[1], 0.0],
                                         [row, row, row+1, row+1],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            else:
                row0 = int(ddict['y'][0]) - 0.5 * width
                if row0 < 0:
                    row0 = 0
                    row1 = row0 + width
                else:
                    row1 = int(ddict['y'][0]) + 0.5 * width
                if row1 >= shape[0]:
                    row1 = shape[0] - 1
                    row0 = max(0, row1 - width)
                ydata = imageData[row0:int(row1+1), :].sum(axis=0)
                legend = "Row = %d to %d"  % (row0, row1)
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([0.0, 0.0, shape[1], shape[1]],
                                         [row0, row1, row1, row0],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            xdata  = numpy.arange(shape[1]).astype(numpy.float)
        elif ddict['mode'].upper() in ["VLINE", "VERTICAL"]:
            if width < 1:
                column = int(ddict['x'][0])
                if column < 0:
                    column = 0
                if column >= shape[1]:
                    column = shape[1] - 1
                ydata  = imageData[:, column]
                legend = "Column = %d"  % column
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([column, column, column+1, column+1],
                                         [0.0, shape[0], shape[0], 0.0],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            else:
                col0 = int(ddict['x'][0]) - 0.5 * width
                if col0 < 0:
                    col0 = 0
                    col1 = col0 + width
                else:
                    col1 = int(ddict['x'][0]) + 0.5 * width
                if col1 >= shape[1]:
                    col1 = shape[1] - 1
                    col0 = max(0, col1 - width)
                ydata = imageData[:, col0:int(col1+1)].sum(axis=1)
                legend = "Col = %d to %d"  % (col0, col1)
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([col0, col0, col1, col1],
                                         [0, shape[0], shape[0], 0.],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            xdata  = numpy.arange(shape[0]).astype(numpy.float)
        elif ddict['mode'].upper() in ["LINE"]:
            if len(ddict['x']) == 1:
                #only one point given
                return
            #the coordinates of the reference points
            x0 = numpy.arange(float(shape[0]))
            y0 = numpy.arange(float(shape[1]))
            #get the interpolation points
            col0, col1 = [int(x) for x in ddict['x']]
            row0, row1 = [int(x) for x in ddict['y']]
            deltaCol = abs(col0 - col1)
            deltaRow = abs(row0 - row1)
            if deltaCol > deltaRow:
                npoints = deltaCol+1
            else:    
                npoints = deltaRow+1
            if width < 1:
                x = numpy.zeros((npoints, 2), numpy.float)
                x[:, 0] = numpy.linspace(row0, row1, npoints)
                x[:, 1] = numpy.linspace(col0, col1, npoints)
                legend = "From (%.3f, %.3f) to (%.3f, %.3f)" % (col0, row0, col1, row1)
                #perform the interpolation
                ydata = self._interpolate((x0, y0), imageData, x)
                xdata = numpy.arange(float(npoints))
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([col0, col1],
                                         [row0, row1],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            elif deltaCol == 0:
                #vertical line
                col0 = int(ddict['x'][0]) - 0.5 * width
                if col0 < 0:
                    col0 = 0
                    col1 = col0 + width
                else:
                    col1 = int(ddict['x'][0]) + 0.5 * width
                if col1 >= shape[1]:
                    col1 = shape[1] - 1
                    col0 = max(0, col1 - width)
                row0 = int(ddict['y'][0])
                row1 = int(ddict['y'][1])
                if row0 > row1:
                    tmp = row0
                    row0 = row1
                    row1 = tmp
                if row0 < 0:
                    row0 = 0
                if row1 >= shape[0]:
                    row1 = shape[0] - 1                    
                ydata = imageData[row0:row1+1, col0:int(col1+1)].sum(axis=1)
                legend = "Col = %d to %d"  % (col0, col1)
                npoints = max(ydata.shape)
                xdata = numpy.arange(float(npoints))
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([col0, col0, col1, col1],
                                         [row0, row1, row1, row0],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            elif deltaRow == 0:
                #horizontal line
                row0 = int(ddict['y'][0]) - 0.5 * width
                if row0 < 0:
                    row0 = 0
                    row1 = row0 + width
                else:
                    row1 = int(ddict['y'][0]) + 0.5 * width
                if row1 >= shape[0]:
                    row1 = shape[0] - 1
                    row0 = max(0, row1 - width)
                col0 = int(ddict['x'][0])
                col1 = int(ddict['x'][1])
                if col0 > col1:
                    tmp = col0
                    col0 = col1
                    col1 = tmp
                if col0 < 0:
                    col0 = 0
                if col1 >= shape[1]:
                    col1 = shape[1] - 1                    
                ydata = imageData[row0:int(row1+1), col0:col1+1].sum(axis=0)
                legend = "Row = %d to %d"  % (row0, row1)
                npoints = max(ydata.shape)
                xdata = numpy.arange(float(npoints))
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem([col0, col0, col1, col1],
                                         [row0, row1, row1, row0],
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
            else:
                #restore original value of width
                width = ddict['pixelwidth']
                #find m and b in the line y = mx + b
                m = (row1 - row0) / float((col1 - col0))
                b = row0 - m * col0
                alpha = numpy.arctan(m)
                if deltaRow > deltaCol:
                    npoints = deltaRow + 1
                else:
                    npoints = deltaCol + 1
                #imagine the following sequence
                # - change origin to the first point
                # - clock-wise rotation to bring the line on the x axis of a new system
                # so that the points (col0, row0) and (col1, row1) become (x0, 0) (x1, 0)
                # - counter clock-wise rotation to get the points (x0, -0.5 width),
                # (x0, 0.5 width), (x1, 0.5 * width) and (x1, -0.5 * width) back to the
                # original system.
                # - restore the origin to (0, 0)
                # - if those extremes are inside the image the selection is acceptable
                cosalpha = numpy.cos(alpha)
                sinalpha = numpy.sin(alpha)
                newCol0 = 0.0
                newCol1 = (col1-col0) * cosalpha + (row1-row0) * sinalpha
                newRow0 = 0.0
                newRow1 = -(col1-col0) * sinalpha + (row1-row0) * cosalpha

                if DEBUG:
                    print("new X0 Y0 = %f, %f  " % (newCol0, newRow0))
                    print("new X1 Y1 = %f, %f  " % (newCol1, newRow1))

                tmpX   = numpy.linspace(newCol0, newCol1, npoints).astype(numpy.float)
                rotMatrix = numpy.zeros((2,2), numpy.float)
                rotMatrix[0,0] =   cosalpha
                rotMatrix[0,1] = - sinalpha
                rotMatrix[1,0] =   sinalpha
                rotMatrix[1,1] =   cosalpha
                if DEBUG:
                    #test if I recover the original points
                    testX = numpy.zeros((2, 1) , numpy.float)
                    colRow = numpy.dot(rotMatrix, testX)
                    print("Recovered X0 = %f" % (colRow[0,0] + col0))
                    print("Recovered Y0 = %f" % (colRow[1,0] + row0))
                    print("It should be = %f, %f" % (col0, row0))
                    testX[0,0] = newCol1
                    testX[1,0] = newRow1
                    colRow = numpy.dot(rotMatrix, testX)
                    print("Recovered X1 = %f" % (colRow[0,0] + col0))
                    print("Recovered Y1 = %f" % (colRow[1,0] + row0))
                    print("It should be = %f, %f" % (col1, row1))

                #find the drawing limits
                testX = numpy.zeros((2, 4) , numpy.float)
                testX[0,0] = newCol0
                testX[0,1] = newCol0
                testX[0,2] = newCol1
                testX[0,3] = newCol1
                testX[1,0] = newRow0 - 0.5 * width
                testX[1,1] = newRow0 + 0.5 * width
                testX[1,2] = newRow1 + 0.5 * width
                testX[1,3] = newRow1 - 0.5 * width
                colRow = numpy.dot(rotMatrix, testX)
                colLimits0 = colRow[0, :] + col0
                rowLimits0 = colRow[1, :] + row0

                for a in rowLimits0:
                    if (a >= shape[0]) or (a < 0):
                        print("outside row limits",a)
                        return
                for a in colLimits0:
                    if (a >= shape[1]) or (a < 0):
                        print("outside column limits",a)
                        return

                r0 = rowLimits0[0]
                r1 = rowLimits0[1]

                if r0 > r1:
                    print("r0 > r1", r0, r1)
                    raise ValueError("r0 > r1")                    

                x = numpy.zeros((2, npoints) , numpy.float)
                tmpMatrix = numpy.zeros((npoints, 2) , numpy.float)

                if 0:
                    #take only the central point
                    oversampling = 1
                    x[0, :] = tmpX
                    x[1, :] = 0.0
                    colRow = numpy.dot(rotMatrix, x)
                    colRow[0, :] += col0
                    colRow[1, :] += row0
                    tmpMatrix[:,0] = colRow[1,:]
                    tmpMatrix[:,1] = colRow[0,:]
                    ydataCentral = self._interpolate((x0, y0),\
                                    imageData, tmpMatrix)
                    #multiply by width too have the equivalent scale
                    ydata = ydataCentral
                else:
                    if ddict['event'] == "PolygonSelected":
                        #oversampling solves noise introduction issues
                        oversampling = width + 1
                        oversampling = min(oversampling, 21) 
                    else:
                        oversampling = 1
                    ncontributors = width * oversampling
                    iterValues = numpy.linspace(-0.5*width, 0.5*width, ncontributors)
                    tmpMatrix = numpy.zeros((npoints*len(iterValues), 2) , numpy.float)
                    x[0, :] = tmpX
                    offset = 0
                    for i in iterValues:
                        x[1, :] = i
                        colRow = numpy.dot(rotMatrix, x)
                        colRow[0, :] += col0
                        colRow[1, :] += row0
                        """
                        colLimits = [colRow[0, 0], colRow[0, -1]]
                        rowLimits = [colRow[1, 0], colRow[1, -1]]
                        for a in rowLimits:
                            if (a >= shape[0]) or (a < 0):
                                print("outside row limits",a)
                                return
                        for a in colLimits:
                            if (a >= shape[1]) or (a < 0):
                                print("outside column limits",a)
                                return
                        """
                        #it is much faster to make one call to the interpolating
                        #routine than making many calls
                        tmpMatrix[offset:(offset+npoints),0] = colRow[1,:]
                        tmpMatrix[offset:(offset+npoints),1] = colRow[0,:]                    
                        offset += npoints
                    ydata = self._interpolate((x0, y0),\
                                   imageData, tmpMatrix)
                    ydata.shape = len(iterValues), npoints
                    ydata = ydata.sum(axis=0)
                    #deal with the oversampling
                    ydata /= oversampling
                          
                xdata = numpy.arange(float(npoints))
                legend = "y = %f (x-%.1f) + %f ; width=%d" % (m, col0, b, width)
                if overlay:
                    #self.drawOverlayItem(x, y, legend=name, info=info, replot, replace)
                    self.drawOverlayItem(colLimits0,
                                         rowLimits0,
                                         legend=ddict['mode'],
                                         info=ddict,
                                         replace=True,
                                         replot=True)
        else:
            if DEBUG:
                print("Mode %s not supported yet" % ddict['mode'])
            return
        info = {}
        info['xlabel'] = "Point"
        info['ylabel'] = "Z"
        return xdata, ydata, legend, info

    def _profileSelectionSlot(self, ddict):
        if DEBUG:
            print(ddict)
        # the curves as [[x0, y0, legend0, info0], ...] 
        curveList = ddict['curves']
        label = ddict['label']
        n = len(curveList)
        if ddict['event'] == 'ADD':
            for i in range(n):
                x, y, legend, info = curveList[i]
                info['profilelabel'] = label
                if i == (n-1):
                    replot = True
                self._profileScanWindow.addCurve(x, y, legend=legend, info=info,
                                                 replot=replot, replace=False)
        elif ddict['event'] == 'REPLACE':
            for i in range(n):
                x, y, legend, info = curveList[i]
                info['profilelabel'] = label
                if i in [0, n-1]:
                    replace = True
                else:
                    replace = False
                if i == (n-1):
                    replot = True
                else:
                    replot = False
                self._profileScanWindow.addCurve(x, y, legend=legend, info=info,
                                                 replot=replot, replace=replace)
        elif ddict['event'] == 'REMOVE':
            curveList = self._profileScanWindow.getAllCurves()
            if curveList in [None, []]:
                return
            toDelete = []
            n = len(curveList)                
            for i in range(n):
                x, y, legend, info = curveList[i]
                curveLabel = info.get('profilelabel', None)
                if curveLabel is not None:
                    if label == curveLabel:
                        toDelete.append(legend)
            n = len(toDelete)
            for i in range(n):
                legend = toDelete[i]
                if i == (n-1):
                    replot = True
                else:
                    replot = False
                self._profileScanWindow.removeCurve(legend, replot=replot)        

    def drawOverlayItem(self, x, y, legend=None, info=None, replace=False, replot=True):
        #same call as the plot1D addCurve command
        if legend is None:
            legend="UnnamedOverlayItem"
        if legend not in self._overlayItemsDict:
            overlayItem = QwtPlotItems.PolygonItem(legend)
            overlayItem.attach(self.graphWidget.graph)
            self._overlayItemsDict[legend] = {}
            self._overlayItemsDict[legend]['item'] = overlayItem
        else:
            overlayItem = self._overlayItemsDict[legend]['item']
        if replace:
            iterKeys = list(self._overlayItemsDict.keys())
            for name in iterKeys:
                if name == legend:
                    continue
                self._overlayItemsDict[name]['item'].detach()
                delKeys = list(self._overlayItemsDict[name].keys())
                for key in delKeys:
                    del self._overlayItemsDict[name][key]
                del self._overlayItemsDict[name]
        overlayItem.setData(x, y)
        self._overlayItemsDict[legend]['x'] = x
        self._overlayItemsDict[legend]['y'] = y
        self._overlayItemsDict[legend]['info'] = info
        if replot:
            self.graphWidget.graph.replot()
        self.__lastOverlayLegend = legend

    def _hFlipIconSignal(self):
        if QWTVERSION4:
            qt.QMessageBox.information(self, "Flip Image", "Not available under PyQwt4")
            return
        if not self.graphWidget.graph.yAutoScale:
            qt.QMessageBox.information(self, "Open",
                    "Please set Y Axis to AutoScale first")
            return
        if not self.graphWidget.graph.xAutoScale:
            qt.QMessageBox.information(self, "Open",
                    "Please set X Axis to AutoScale first")
            return

        if self._y1AxisInverted:
            self._y1AxisInverted = False
        else:
            self._y1AxisInverted = True
        self.graphWidget.graph.zoomReset()
        self.graphWidget.graph.setY1AxisInverted(self._y1AxisInverted)
        self.plotImage(True)

        #inform the other widgets
        ddict = {}
        ddict['event'] = "hFlipSignal"
        ddict['current'] = self._y1AxisInverted * 1
        ddict['id'] = id(self)
        self.emitMaskImageSignal(ddict)        

    def setY1AxisInverted(self, value):
        self._y1AxisInverted = value
        self.graphWidget.graph.setY1AxisInverted(self._y1AxisInverted)

    def buildAndConnectImageButtonBox(self, replace=True):
        # The IMAGE selection
        self.imageButtonBox = qt.QWidget(self)
        buttonBox = self.imageButtonBox
        self.imageButtonBoxLayout = qt.QHBoxLayout(buttonBox)
        self.imageButtonBoxLayout.setMargin(0)
        self.imageButtonBoxLayout.setSpacing(0)
        self.addImageButton = qt.QPushButton(buttonBox)
        icon = qt.QIcon(qt.QPixmap(IconDict["rgb16"]))
        self.addImageButton.setIcon(icon)
        self.addImageButton.setText("ADD IMAGE")
        self.removeImageButton = qt.QPushButton(buttonBox)
        self.removeImageButton.setIcon(icon)
        self.removeImageButton.setText("REMOVE IMAGE")
        self.imageButtonBoxLayout.addWidget(self.addImageButton)
        self.imageButtonBoxLayout.addWidget(self.removeImageButton)

        
        self.mainLayout.addWidget(buttonBox)
        
        self.connect(self.addImageButton, qt.SIGNAL("clicked()"), 
                    self._addImageClicked)
        self.connect(self.removeImageButton, qt.SIGNAL("clicked()"), 
                    self._removeImageClicked)
        if replace:
            self.replaceImageButton = qt.QPushButton(buttonBox)
            self.replaceImageButton.setIcon(icon)
            self.replaceImageButton.setText("REPLACE IMAGE")
            self.imageButtonBoxLayout.addWidget(self.replaceImageButton)
            self.connect(self.replaceImageButton,
                         qt.SIGNAL("clicked()"), 
                         self._replaceImageClicked)
    
    def _setEraseSelectionMode(self):
        if DEBUG:
            print("_setEraseSelectionMode")
        self.__eraseMode = True
        self.__brushMode = True
        self.graphWidget.picker.setTrackerMode(Qwt.QwtPicker.ActiveOnly)
        self.graphWidget.graph.enableSelection(False)

    def _setRectSelectionMode(self):
        if DEBUG:
            print("_setRectSelectionMode")
        self.__eraseMode = False
        self.__brushMode = False
        self.graphWidget.picker.setTrackerMode(Qwt.QwtPicker.AlwaysOn)
        self.graphWidget.graph.enableSelection(True)
        
    def _setBrushSelectionMode(self):
        if DEBUG:
            print("_setBrushSelectionMode")
        self.__eraseMode = False
        self.__brushMode = True
        self.graphWidget.picker.setTrackerMode(Qwt.QwtPicker.ActiveOnly)
        self.graphWidget.graph.enableSelection(False)
        
    def _setBrush(self):
        if DEBUG:
            print("_setBrush")
        if self.__brushMenu is None:
            if QTVERSION < '4.0.0':
                self.__brushMenu = qt.QPopupMenu()
                self.__brushMenu.insertItem(QString(" 1 Image Pixel Width"),
                                            self.__setBrush1)
                self.__brushMenu.insertItem(QString(" 2 Image Pixel Width"),
                                            self.__setBrush2)
                self.__brushMenu.insertItem(QString(" 3 Image Pixel Width"),
                                            self.__setBrush3)
                self.__brushMenu.insertItem(QString(" 5 Image Pixel Width"),
                                            self.__setBrush4)
                self.__brushMenu.insertItem(QString("10 Image Pixel Width"),
                                            self.__setBrush5)
                self.__brushMenu.insertItem(QString("20 Image Pixel Width"),
                                            self.__setBrush6)
            else:
                self.__brushMenu = qt.QMenu()
                self.__brushMenu.addAction(QString(" 1 Image Pixel Width"),
                                           self.__setBrush1)
                self.__brushMenu.addAction(QString(" 2 Image Pixel Width"),
                                           self.__setBrush2)
                self.__brushMenu.addAction(QString(" 3 Image Pixel Width"),
                                           self.__setBrush3)
                self.__brushMenu.addAction(QString(" 5 Image Pixel Width"),
                                           self.__setBrush4)
                self.__brushMenu.addAction(QString("10 Image Pixel Width"),
                                           self.__setBrush5)
                self.__brushMenu.addAction(QString("20 Image Pixel Width"),
                                           self.__setBrush6)
        if QTVERSION < '4.0.0':
            self.__brushMenu.exec_loop(self.cursor().pos())
        else:
            self.__brushMenu.exec_(self.cursor().pos())

    def __setBrush1(self):
        self.__brushWidth = 1

    def __setBrush2(self):
        self.__brushWidth = 2

    def __setBrush3(self):
        self.__brushWidth = 3

    def __setBrush4(self):
        self.__brushWidth = 5

    def __setBrush5(self):
        self.__brushWidth = 10

    def __setBrush6(self):
        self.__brushWidth = 20

    def _toggleSelectionMode(self):
        if self.graphWidget.graph._selecting:
            self.setSelectionMode(False)
        else:
            self.setSelectionMode(True)

    def setSelectionMode(self, mode = None):
        #does it have sense to enable the selection without the image selection icons?
        #if not self.__imageIconsFlag:
        #    mode = False
        if mode:
            self.graphWidget.graph.enableSelection(True)
            self.__brushMode  = False
            self.graphWidget.picker.setTrackerMode(Qwt.QwtPicker.AlwaysOn)
            if QTVERSION < '4.0.0':
                self.graphWidget.selectionToolButton.setState(qt.QButton.On)
            else:
                self.graphWidget.hideProfileSelectionIcons()
                self.graphWidget.selectionToolButton.setChecked(True)
            self.graphWidget.graph.enableZoom(False)
            self.graphWidget.selectionToolButton.setDown(True)
            self.graphWidget.showImageIcons()            
        else:
            self.graphWidget.picker.setTrackerMode(Qwt.QwtPicker.AlwaysOff)
            self.graphWidget.showProfileSelectionIcons()
            self.graphWidget.graph.enableZoom(True)
            if QTVERSION < '4.0.0':
                self.graphWidget.selectionToolButton.setState(qt.QButton.Off)
            else:
                self.graphWidget.selectionToolButton.setChecked(False)
            self.graphWidget.selectionToolButton.setDown(False)
            self.graphWidget.hideImageIcons()
        if self.__imageData is None: return
        #do not reset the selection
        #self.__selectionMask = numpy.zeros(self.__imageData.shape, numpy.UInt8)

    def _additionalSelectionMenuDialog(self):
        if self.__imageData is None:
            return
        self._additionalSelectionMenu.exec_(self.cursor().pos())

    def _getSelectionMinMax(self):
        if self.colormap is None:
            goodData = self.__imageData[numpy.isfinite(self.__imageData)]
            maxValue = goodData.max()
            minValue = goodData.min()
        else:
            minValue = self.colormap[2]
            maxValue = self.colormap[3]

        return minValue, maxValue

    def _selectMax(self):
        selectionMask = numpy.zeros(self.__imageData.shape,
                                             numpy.uint8)
        minValue, maxValue = self._getSelectionMinMax()
        tmpData = numpy.array(self.__imageData, copy=True)
        tmpData[numpy.isfinite(self.__imageData)] = minValue
        selectionMask[tmpData >= maxValue] = 1
        self.setSelectionMask(selectionMask, plot=False)
        self.plotImage(update=False)
        self._emitMaskChangedSignal()
        
    def _selectMiddle(self):
        selectionMask = numpy.zeros(self.__imageData.shape,
                                             numpy.uint8)
        minValue, maxValue = self._getSelectionMinMax()
        tmpData = numpy.array(self.__imageData, copy=True)
        tmpData[numpy.isfinite(self.__imageData)] = maxValue
        selectionMask[tmpData >= maxValue] = 0
        selectionMask[tmpData <= minValue] = 0
        self.setSelectionMask(selectionMask, plot=False)
        self.plotImage(update=False)
        self._emitMaskChangedSignal()        

    def _selectMin(self):
        selectionMask = numpy.zeros(self.__imageData.shape,
                                             numpy.uint8)
        minValue, maxValue = self._getSelectionMinMax()
        tmpData = numpy.array(self.__imageData, copy=True)
        tmpData[numpy.isfinite(self.__imageData)] = maxValue
        selectionMask[tmpData <= minValue] = 1
        self.setSelectionMask(selectionMask, plot=False)
        self.plotImage(update=False)
        self._emitMaskChangedSignal()
        
    def _invertSelection(self):
        if self.__imageData is None:
            return
        mask = numpy.ones(self.__imageData.shape,
                                             numpy.uint8)
        if self.__selectionMask is not None:
            mask[self.__selectionMask > 0] = 0

        self.setSelectionMask(mask, plot=True)
        self._emitMaskChangedSignal()
        
    def _resetSelection(self, owncall=True):
        if DEBUG:
            print("_resetSelection")
        self.__selectionMask = None
        if self.__imageData is None:
            return
        #self.__selectionMask = numpy.zeros(self.__imageData.shape, numpy.uint8)
        self.plotImage(update = True)

        #inform the others
        if owncall:
            ddict = {}
            ddict['event'] = "resetSelection"
            ddict['id'] = id(self)
            self.emitMaskImageSignal(ddict)
            
    def setSelectionMask(self, mask, plot=True):
        if mask is not None:
            if self.__imageData is not None:
                mask *=  numpy.isfinite(self.__imageData)
        self.__selectionMask = mask
        if plot:
            self.plotImage(update=False)

    def getSelectionMask(self):
        if self.__imageData is None:
            return None
        if self.__selectionMask is None:
            return numpy.zeros(self.__imageData.shape, numpy.uint8)
        return self.__selectionMask

    def setImageData(self, data, clearmask=False):
        self.__image = None
        if data is None:
            self.__imageData = data
            self.__selectionMask = None
            self.plotImage(update = True)
            return
        else:
            self.__imageData = data
        if clearmask:
            self.__selectionMask = None
        if self.colormapDialog is not None:
            goodData = self.__imageData[numpy.isfinite(self.__imageData)]
            minData = goodData.min()
            maxData = goodData.max()
            if self.colormapDialog.autoscale:
                self.colormapDialog.setDisplayedMinValue(minData) 
                self.colormapDialog.setDisplayedMaxValue(maxData) 
            self.colormapDialog.setDataMinMax(minData, maxData, update=True)
        else:
            self.plotImage(update = True)

    def getImageData(self):
        return self.__imageData

    def getQImage(self):
        return self.__image

    def setQImage(self, qimage, width, height, clearmask=False, data=None):
        #This is just to get it different than None
        if (qimage.width() != width) or (qimage.height() != height):
            if 1 or (qimage.width() > width) or (qimage.height() > height):
                transformation = qt.Qt.SmoothTransformation
            else:
                transformation = qt.Qt.FastTransformation
            self.__image = qimage.scaled(qt.QSize(width, height),
                                     qt.Qt.IgnoreAspectRatio,
                                     transformation)
        else:
            self.__image = qimage

        if self.__image.format() == qt.QImage.Format_Indexed8:
            pixmap0 = numpy.fromstring(qimage.bits().asstring(width * height),
                                 dtype = numpy.uint8)
            pixmap = numpy.zeros((height * width, 4), numpy.uint8)
            pixmap[:,0] = pixmap0[:]
            pixmap[:,1] = pixmap0[:]
            pixmap[:,2] = pixmap0[:]
            pixmap[:,3] = 255
            pixmap.shape = height, width, 4
        else:
            self.__image = self.__image.convertToFormat(qt.QImage.Format_ARGB32) 
            pixmap = numpy.fromstring(self.__image.bits().asstring(width * height * 4),
                                 dtype = numpy.uint8)
        pixmap.shape = height, width,-1
        if data is None:
            self.__imageData = numpy.zeros((height, width), numpy.float)
            self.__imageData = pixmap[:,:,0] * 0.114 +\
                               pixmap[:,:,1] * 0.587 +\
                               pixmap[:,:,2] * 0.299
        else:
            self.__imageData = data
            self.__imageData.shape = height, width
        self.__pixmap0 = pixmap
        if clearmask:
            self.__selectionMask = None
        self.plotImage(update = True)
        
    def plotImage(self, update=True):
        if self.__imageData is None:
            self.graphWidget.graph.clear()
            self.graphWidget.picker.data = None
            return

        if update:
            self.getPixmapFromData()
            self.__pixmap0 = self.__pixmap.copy()
            self.graphWidget.picker.data = self.__imageData
            if self.colormap is None:
                if self.__defaultColormap < 2:
                    self.graphWidget.picker.setTrackerPen(qt.QPen(qt.Qt.green))
                else:
                    self.graphWidget.picker.setTrackerPen(qt.QPen(qt.Qt.black))
            elif int(str(self.colormap[0])) > 1:     #color
                self.graphWidget.picker.setTrackerPen(qt.QPen(qt.Qt.black))
            else:
                self.graphWidget.picker.setTrackerPen(qt.QPen(qt.Qt.green))
        self.__applyMaskToImage()
        if not self.graphWidget.graph.yAutoScale:
            ylimits = self.graphWidget.graph.getY1AxisLimits()
        if not self.graphWidget.graph.xAutoScale:
            xlimits = self.graphWidget.graph.getX1AxisLimits()
        self.graphWidget.graph.pixmapPlot(self.__pixmap.tostring(),
            (self.__imageData.shape[1], self.__imageData.shape[0]),
                                        xmirror = 0,
                                        ymirror = not self._y1AxisInverted)

        if not self.graphWidget.graph.yAutoScale:
            self.graphWidget.graph.setY1AxisLimits(ylimits[0], ylimits[1],
                                                   replot=False)
        if not self.graphWidget.graph.xAutoScale:
            self.graphWidget.graph.setX1AxisLimits(xlimits[0], xlimits[1],
                                                   replot=False)
        self.graphWidget.graph.replot()

    def getPixmapFromData(self):
        colormap = self.colormap
        if self.__image is not None:
            self.__pixmap = self.__pixmap0.copy()
            return

        tmpData = numpy.isfinite(self.__imageData)
        goodData = tmpData.min()
        
        if self.colormapDialog is not None:
            minData = self.colormapDialog.dataMin
            maxData = self.colormapDialog.dataMax
        else:
            if goodData:
                minData = self.__imageData.min()
                maxData = self.__imageData.max()
            else:
                tmpData = self.__imageData[tmpData]
                minData = tmpData.min()
                maxData = tmpData.max()
        tmpData = None
                
        if colormap is None:
            (self.__pixmap,size,minmax)= spslut.transform(\
                                self.__imageData,
                                (1,0),
                                (self.__defaultColormapType,3.0),
                                "BGRX",
                                self.__defaultColormap,
                                0,
                                (minData,maxData),
                                (0, 255), 1)
        else:
            if len(colormap) < 7:
                colormap.append(spslut.LINEAR)
            if goodData:
                (self.__pixmap,size,minmax)= spslut.transform(\
                                self.__imageData,
                                (1,0),
                                (colormap[6],3.0),
                                "BGRX",
                                COLORMAPLIST[int(str(colormap[0]))],
                                colormap[1],
                                (colormap[2],colormap[3]),
                                (0,255), 1)                
            elif colormap[1]:
                #autoscale
                (self.__pixmap,size,minmax)= spslut.transform(\
                                self.__imageData,
                                (1,0),
                                (colormap[6],3.0),
                                "BGRX",
                                COLORMAPLIST[int(str(colormap[0]))],
                                0,
                                (minData,maxData),
                                (0,255), 1)
            else:
                (self.__pixmap,size,minmax)= spslut.transform(\
                                self.__imageData,
                                (1,0),
                                (colormap[6],3.0),
                                "BGRX",
                                COLORMAPLIST[int(str(colormap[0]))],
                                colormap[1],
                                (colormap[2],colormap[3]),
                                (0,255), 1)

        self.__pixmap = self.__pixmap.astype(numpy.ubyte)

        self.__pixmap.shape = [self.__imageData.shape[0],
                                    self.__imageData.shape[1],
                                    4]

    def __applyMaskToImage(self):
        if self.__selectionMask is None:
            return
        #if not self.__selectionFlag:
        #    print("Return because of selection flag")
        #    return

        if self.colormap is None:
            if self.__image is not None:
                if self.__image.format() == qt.QImage.Format_ARGB32:
                    for i in range(4):
                        self.__pixmap[:,:,i]  = (self.__pixmap0[:,:,i] *\
                                (1 - (0.2 * self.__selectionMask))).astype(numpy.uint8)
                else:
                    self.__pixmap = self.__pixmap0.copy()
                    self.__pixmap[self.__selectionMask>0,0]    = 0x40
                    self.__pixmap[self.__selectionMask>0,2]    = 0x70
                    self.__pixmap[self.__selectionMask>0,3]    = 0x40
            else:
                if self.__defaultColormap > 1:
                    tmp = 1 - 0.2 * self.__selectionMask
                    for i in range(3):
                        self.__pixmap[:,:,i]  = (self.__pixmap0[:,:,i] *\
                                tmp)
                    if 0:
                        #this is to recolor non finite points
                        tmpMask = numpy.isfinite(self.__imageData)
                        goodData = numpy.isfinite(self.__imageData).min()
                        if not goodData:
                            for i in range(3):
                                self.__pixmap[:,:,i] *= tmpMask
                else:
                    self.__pixmap = self.__pixmap0.copy()
                    self.__pixmap[self.__selectionMask>0,0]    = 0x40
                    self.__pixmap[self.__selectionMask>0,2]    = 0x70
                    self.__pixmap[self.__selectionMask>0,3]    = 0x40
                    if 0:
                        #this is to recolor non finite points
                        tmpMask = ~numpy.isfinite(self.__imageData)
                        badData = numpy.isfinite(self.__imageData).max()
                        if badData:
                            self.__pixmap[tmpMask,0]    = 0x00
                            self.__pixmap[tmpMask,1]    = 0xff
                            self.__pixmap[tmpMask,2]    = 0xff
                            self.__pixmap[tmpMask,3]    = 0xff
        elif int(str(self.colormap[0])) > 1:     #color
            tmp = 1 - 0.2 * self.__selectionMask
            for i in range(3):
                self.__pixmap[:,:,i]  = (self.__pixmap0[:,:,i] *\
                        tmp)
            if 0:
                tmpMask = numpy.isfinite(self.__imageData)
                goodData = numpy.isfinite(self.__imageData).min()
                if not goodData:
                    if not goodData:
                        for i in range(3):
                            self.__pixmap[:,:,i] *= tmpMask                
        else:
            self.__pixmap = self.__pixmap0.copy()
            tmp  = 1 - self.__selectionMask
            self.__pixmap[:,:, 2] = (0x70 * self.__selectionMask) +\
                                  tmp * self.__pixmap0[:,:,2]
            self.__pixmap[:,:, 3] = (0x40 * self.__selectionMask) +\
                                  tmp * self.__pixmap0[:,:,3]
            if 0:
                tmpMask = ~numpy.isfinite(self.__imageData)
                badData = numpy.isfinite(self.__imageData).max()
                if badData:
                    self.__pixmap[tmpMask,0]    = 0x00
                    self.__pixmap[tmpMask,1]    = 0xff
                    self.__pixmap[tmpMask,2]    = 0xff
                    self.__pixmap[tmpMask,3]    = 0xff
        return

    def selectColormap(self):
        if self.__imageData is None:
            return
        if self.colormapDialog is None:
            self.__initColormapDialog()
        if self.colormapDialog.isHidden():
            self.colormapDialog.show()
        if QTVERSION < '4.0.0':
            self.colormapDialog.raiseW()
        else:
            self.colormapDialog.raise_()
        self.colormapDialog.show()

    def __initColormapDialog(self):
        goodData = self.__imageData[numpy.isfinite(self.__imageData)]
        maxData = goodData.max()
        minData = goodData.min()
        self.colormapDialog = ColormapDialog.ColormapDialog()
        colormapIndex = self.__defaultColormap
        if colormapIndex == 1:
            colormapIndex = 0
        elif colormapIndex == 6:
            colormapIndex = 1
        self.colormapDialog.colormapIndex  = colormapIndex
        self.colormapDialog.colormapString = self.colormapDialog.colormapList[colormapIndex]
        self.colormapDialog.setDataMinMax(minData, maxData)
        self.colormapDialog.setAutoscale(1)
        self.colormapDialog.setColormap(self.colormapDialog.colormapIndex)
        self.colormapDialog.setColormapType(self.__defaultColormapType, update=False)
        self.colormap = (self.colormapDialog.colormapIndex,
                              self.colormapDialog.autoscale,
                              self.colormapDialog.minValue, 
                              self.colormapDialog.maxValue,
                              minData, maxData)
        if QTVERSION < '4.0.0':
            self.colormapDialog.setCaption("Colormap Dialog")
            self.connect(self.colormapDialog,
                         qt.PYSIGNAL("ColormapChanged"),
                         self.updateColormap)
        else:
            self.colormapDialog.setWindowTitle("Colormap Dialog")
            self.connect(self.colormapDialog,
                         qt.SIGNAL("ColormapChanged"),
                         self.updateColormap)
        self.colormapDialog._update()

    def updateColormap(self, *var):
        if len(var) > 6:
            self.colormap = [var[0],
                             var[1],
                             var[2],
                             var[3],
                             var[4],
                             var[5],
                             var[6]]
        elif len(var) > 5:
            self.colormap = [var[0],
                             var[1],
                             var[2],
                             var[3],
                             var[4],
                             var[5]]
        else:
            self.colormap = [var[0],
                             var[1],
                             var[2],
                             var[3],
                             var[4],
                             var[5]]
        self.plotImage(True)

    def _addImageClicked(self):
        ddict = {}
        ddict['event'] = "addImageClicked"
        ddict['image'] = self.__imageData
        ddict['title'] = self.getGraphTitle()
        ddict['id'] = id(self)
        self.emitMaskImageSignal(ddict)
            
    def _removeImageClicked(self):
        ddict = {}
        ddict['event'] = "removeImageClicked"
        ddict['title'] = self.getGraphTitle()
        ddict['id'] = id(self)
        self.emitMaskImageSignal(ddict)

    def _replaceImageClicked(self):
        ddict = {}
        ddict['event'] = "replaceImageClicked"
        ddict['image'] = self.__imageData
        ddict['title'] = self.getGraphTitle()
        ddict['id'] = id(self)
        self.emitMaskImageSignal(ddict)

    def _saveToolButtonSignal(self):
        self._saveMenu.exec_(self.cursor().pos())

    def _saveMatplotlibImage(self):
        imageData = self.__imageData
        if self._matplotlibSaveImage is None:
            self._matplotlibSaveImage = QPyMcaMatplotlibSave.SaveImageSetup(None,
                                                            image=None)
        title = "Matplotlib " + self.getGraphTitle()
        self._matplotlibSaveImage.setWindowTitle(title)        
        if self.colormap is not None:
            ddict = self._matplotlibSaveImage.getParameters()
            colormapType = ddict['linlogcolormap']
            try:
                colormapIndex, autoscale, vmin, vmax,\
                        dataMin, dataMax, colormapType = self.colormap
                if colormapType == spslut.LOG:
                    colormapType = 'logarithmic'
                else:
                    colormapType = 'linear'
            except:
                colormapIndex, autoscale, vmin, vmax = self.colormap[0:4]
            ddict['linlogcolormap'] = colormapType
            if not autoscale:
                ddict['valuemin'] = vmin
                ddict['valuemax'] = vmax
            else:
                ddict['valuemin'] = 0
                ddict['valuemax'] = 0
            self._matplotlibSaveImage.setParameters(ddict)
        self._matplotlibSaveImage.setImageData(imageData)
        self._matplotlibSaveImage.show()
        self._matplotlibSaveImage.raise_()

    def _otherWidgetGraphSignal(self, ddict):
        self._graphSignal(ddict, ownsignal = False)

    def _graphSignal(self, ddict, ownsignal = None):
        if ownsignal is None:
            ownsignal = True
        emitsignal = False
        if self.__imageData is None:
            return
        if ddict['event'] == "MouseSelection":
            if ddict['xmin'] < ddict['xmax']:
                xmin = ddict['xmin']
                xmax = ddict['xmax']
            else:
                xmin = ddict['xmax']
                xmax = ddict['xmin']
            if ddict['ymin'] < ddict['ymax']:
                ymin = ddict['ymin']
                ymax = ddict['ymax']
            else:
                ymin = ddict['ymax']
                ymax = ddict['ymin']
            i1 = max(int(round(xmin)), 0)
            i2 = min(abs(int(round(xmax)))+1, self.__imageData.shape[1])
            j1 = max(int(round(ymin)),0)
            j2 = min(abs(int(round(ymax)))+1,self.__imageData.shape[0])
            if self.__selectionMask is None:
                self.__selectionMask = numpy.zeros(self.__imageData.shape,
                                     numpy.uint8)
            self.__selectionMask[j1:j2, i1:i2] = 1
            emitsignal = True

        elif ddict['event'] == "MouseAt":
            if ownsignal:
                pass
            if self.__brushMode:
                if self.graphWidget.graph.isZoomEnabled():
                    return
                #if follow mouse is not activated
                #it only enters here when the mouse is pressed.
                #Therefore is perfect for "brush" selections.
                width = self.__brushWidth   #in (row, column) units
                r = self.__imageData.shape[0]
                c = self.__imageData.shape[1]
                xmin = max((ddict['x']-0.5*width), 0)
                xmax = min((ddict['x']+0.5*width), c)
                ymin = max((ddict['y']-0.5*width), 0)
                ymax = min((ddict['y']+0.5*width), r)
                i1 = min(int(round(xmin)), c-1)
                i2 = min(int(round(xmax)), c)
                j1 = min(int(round(ymin)),r-1)
                j2 = min(int(round(ymax)), r)
                if i1 == i2: i2 = i1+1
                if j1 == j2: j2 = j1+1
                if self.__selectionMask is None:
                    self.__selectionMask = numpy.zeros(self.__imageData.shape,
                                     numpy.uint8)
                if self.__eraseMode:
                    self.__selectionMask[j1:j2, i1:i2] = 0 
                else:
                    self.__selectionMask[j1:j2, i1:i2] = 1
                emitsignal = True
        if emitsignal:
            #should this be made by the parent?
            self.plotImage(update = False)
            
            #inform the other widgets
            self._emitMaskChangedSignal()

    def _emitMaskChangedSignal(self):
        #inform the other widgets
        ddict = {}
        ddict['event'] = "selectionMaskChanged"
        ddict['current'] = self.__selectionMask * 1
        ddict['id'] = id(self)
        self.emitMaskImageSignal(ddict)
                            
    def emitMaskImageSignal(self, ddict):
        if QTVERSION < '4.0.0':
            qt.QObject.emit(self,
                        qt.PYSIGNAL('MaskImageWidgetSignal'),
                        ddict)
        else:
            qt.QObject.emit(self,
                        qt.SIGNAL('MaskImageWidgetSignal'),
                        ddict)

    def _saveToolButtonSignal(self):
        self._saveMenu.exec_(self.cursor().pos())

    def _zoomResetSignal(self):
        if DEBUG:
            print("_zoomResetSignal")
        self.graphWidget._zoomReset(replot=False)
        self.plotImage(True)

    def getOutputFileName(self):
        initdir = PyMcaDirs.outputDir
        if self.outputDir is not None:
            if os.path.exists(self.outputDir):
                initdir = self.outputDir
        filedialog = qt.QFileDialog(self)
        filedialog.setFileMode(filedialog.AnyFile)
        filedialog.setAcceptMode(qt.QFileDialog.AcceptSave)
        filedialog.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict["gioconda16"])))
        formatlist = ["ASCII Files *.dat",
                      "EDF Files *.edf",
                      'CSV(, separated) Files *.csv',
                      'CSV(; separated) Files *.csv',
                      'CSV(tab separated) Files *.csv']
        if hasattr(qt, "QStringList"):
            strlist = qt.QStringList()
        else:
            strlist = []
        for f in formatlist:
                strlist.append(f)
        if self._saveFilter is None:
            self._saveFilter =formatlist[0]
        filedialog.setFilters(strlist)
        filedialog.selectFilter(self._saveFilter)
        filedialog.setDirectory(initdir)
        ret = filedialog.exec_()
        if not ret: return ""
        filename = filedialog.selectedFiles()[0]
        if len(filename):
            filename = str(filename)
            self.outputDir = os.path.dirname(filename)
            self._saveFilter = str(filedialog.selectedFilter())
            filterused = "."+self._saveFilter[-3:]
            PyMcaDirs.outputDir = os.path.dirname(filename)
            if len(filename) < 4:
                filename = filename+ filterused
            elif filename[-4:] != filterused :
                filename = filename+ filterused
        else:
            filename = ""
        return filename

    def saveImageList(self, filename=None, imagelist=None, labels=None):
        imageList = []
        if labels is None:
            labels = []
        if imagelist is None:
            if self.__imageData is not None:
                imageList.append(self.__imageData)
                label = self.getGraphTitle()
                label.replace(' ', '_')
                labels.append(label)
                if self.__selectionMask is not None:
                    if self.__selectionMask.max() > 0:
                        imageList.append(self.__selectionMask)
                        labels.append(label+"_Mask")
        else:
            imageList = imagelist
            if len(labels) == 0:
                for i in range(len(imagelist)):
                    labels.append("Image%02d" % i)

        if not len(imageList):
            qt.QMessageBox.information(self,"No Data",
                            "Image list is empty.\nNothing to be saved")
            return
        if filename is None:
            filename = self.getOutputFileName()
            if not len(filename):return

        if filename.lower().endswith(".edf"):
            ArraySave.save2DArrayListAsEDF(imageList, filename, labels)
        elif filename.lower().endswith(".csv"):
            if "," in self._saveFilter:
                csvseparator = ","
            elif ";" in self._saveFilter:
                csvseparator = ";"
            else:
                csvseparator = "\t"
            ArraySave.save2DArrayListAsASCII(imageList, filename, labels,
                                             csv=True,
                                             csvseparator=csvseparator)
        else:
            ArraySave.save2DArrayListAsASCII(imageList, filename, labels,
                                             csv=False)


    def saveClippedSeenImageList(self):
        return self.saveClippedAndSubtractedSeenImageList(subtract=False)


    def saveClippedAndSubtractedSeenImageList(self, subtract=True):
        imageData = self.__imageData
        if imageData is None:
            return
        vmin = None
        label = self.getGraphTitle()
        if not len(label):
            label = "Image01"
        if self.colormap is not None:
            colormapIndex, autoscale, vmin, vmax = self.colormap[0:4]
            if not autoscale:
                imageData = imageData.clip(vmin, vmax)
                label += ".clip(%f,%f)" % (vmin, vmax)
        if subtract:
            if vmin is None:
                vmin = imageData.min()
            imageData = imageData-vmin
            label += "-%f" % vmin
        imageList = [imageData]
        labelList = [label]
        if self.__selectionMask is not None:
            if self.__selectionMask.max() > 0:
                imageList.append(self.__selectionMask)
                labelList.append(label+"_Mask")
        self.saveImageList(filename=None,
                           imagelist=imageList,
                           labels=labelList)

    def setDefaultColormap(self, colormapindex, logflag=False):
        self.__defaultColormap = COLORMAPLIST[min(colormapindex, len(COLORMAPLIST)-1)]
        if logflag:
            self.__defaultColormapType = spslut.LOG
        else:
            self.__defaultColormapType = spslut.LINEAR

    def closeEvent(self, event):
        if self._profileSelectionWindow is not None:
            self._profileSelectionWindow.close()
        if self.colormapDialog is not None:
            self.colormapDialog.close()
        return qt.QWidget.closeEvent(self, event)

    def setInfoText(self, text):
        return self.graphWidget.setInfoText(text)

def test():
    app = qt.QApplication([])
    qt.QObject.connect(app,
                       qt.SIGNAL("lastWindowClosed()"),
                       app,
                       qt.SLOT('quit()'))
    container = MaskImageWidget()
    if len(sys.argv) > 1:
        if sys.argv[1].endswith('edf') or\
           sys.argv[1].endswith('cbf') or\
           sys.argv[1].endswith('ccd') or\
           sys.argv[1].endswith('spe') or\
           sys.argv[1].endswith('tif') or\
           sys.argv[1].endswith('tiff'):
            container = MaskImageWidget(profileselection=True)
            import EdfFile
            edf = EdfFile.EdfFile(sys.argv[1])
            data = edf.GetData(0)
            container.setImageData(data)
        else:
            image = qt.QImage(sys.argv[1])
            #container.setQImage(image, image.width(),image.height())
            container.setQImage(image, 200, 200)
    else:
        container = MaskImageWidget(profileselection=True)
        data = numpy.arange(40000).astype(numpy.int32)
        data.shape = 200, 200
        #data = numpy.eye(200)
        container.setImageData(data)
        #data.shape = 100, 400
        #container.setImageData(None)
        #container.setImageData(data)
    container.show()
    def theSlot(ddict):
        print(ddict['event'])

    if QTVERSION < '4.0.0':
        qt.QObject.connect(container,
                       qt.PYSIGNAL("MaskImageWidgetSignal"),
                       updateMask)
        app.setMainWidget(container)
        app.exec_loop()
    else:
        qt.QObject.connect(container,
                           qt.SIGNAL("MaskImageWidgetSignal"),
                           theSlot)
        app.exec_()

if __name__ == "__main__":
    test()