summaryrefslogtreecommitdiff
path: root/PyMca5/PyMcaGui/pymca/PyMcaMain.py
blob: df1030f960e49805e768a3feb4b2b26df8c6f925 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
#!/usr/bin/env python
#/*##########################################################################
# Copyright (C) 2004-2019 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import os
import sys, getopt
import traceback
import logging
if sys.platform == 'win32':
    import ctypes
    from ctypes.wintypes import MAX_PATH

nativeFileDialogs = None
_logger = logging.getLogger(__name__)
backend=None
if __name__ == '__main__':
    options     = '-f'
    longoptions = ['spec=',
                   'shm=',
                   'debug=',
                   'qt=',
                   'backend=',
                   'nativefiledialogs=',
                   'PySide=',
                   'binding=',
                   'logging=']
    try:
        opts, args = getopt.getopt(
                     sys.argv[1:],
                     options,
                     longoptions)
    except getopt.error:
        print("%s" % sys.exc_info()[1])
        sys.exit(1)

    keywords={}
    debugreport = 0
    qtversion = None
    binding = None
    for opt, arg in opts:
        if  opt in ('--spec'):
            keywords['spec'] = arg
        elif opt in ('--shm'):
            keywords['shm']  = arg
        elif opt in ('--debug'):
            if arg.lower() not in ['0', 'false']:
                debugreport = 1
                _logger.setLevel(logging.DEBUG)
            # --debug is also parsed later for the global logging level
        elif opt in ('-f'):
            keywords['fresh'] = 1
        elif opt in ('--qt'):
            qtversion = arg
        elif opt in ('--backend'):
            backend = arg
        elif opt in ('--nativefiledialogs'):
            if int(arg):
                nativeFileDialogs = True
            else:
                nativeFileDialogs = False
        elif opt in ('--PySide'):
            print("Please use --binding=PySide")
            import PySide.QtCore
        elif opt in ('--binding'):
            binding = arg.lower()
            if binding == "pyqt5":
                import PyQt5.QtCore
            elif binding == "pyqt4":
                if sys.version_info < (3,):
                    try:
                        import sip
                        sip.setapi('QString', 2)
                        sip.setapi('QVariant', 2)
                        sip.setapi('QDate', 2)
                        sip.setapi('QDateTime', 2)
                        sip.setapi('QTextStream', 2)
                        sip.setapi('QTime', 2)
                        sip.setapi('QUrl', 2)
                    except:
                        print("Cannot set sip API")
                import PyQt4.QtCore
            elif binding == "pyside2":
                import PySide2.QtCore
            elif binding == "pyside":
                import PySide.QtCore
            else:
                raise ValueError("Unknown Qt binding <%s>" % binding)
    if binding is None:
        if qtversion == '3':
            raise NotImplementedError("Qt3 is no longer supported")
        elif qtversion == '4':
            if sys.version_info < (3,):
                try:
                    import sip
                    sip.setapi('QString', 2)
                    sip.setapi('QVariant', 2)
                    sip.setapi('QDate', 2)
                    sip.setapi('QDateTime', 2)
                    sip.setapi('QTextStream', 2)
                    sip.setapi('QTime', 2)
                    sip.setapi('QUrl', 2)
                except:
                    print("Cannot set sip API")
            import PyQt4.QtCore
        elif qtversion == '5':
            import PyQt5.QtCore

    from PyMca5.PyMcaCore.LoggingLevel import getLoggingLevel
    logging.basicConfig(level=getLoggingLevel(opts))
    if "HDF5_USE_FILE_LOCKING" not in os.environ:
        if "h5py" in sys.modules:
             _logger.warning("h5py already imported")
        os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
        _logger.info("%s set to %s" % ("HDF5_USE_FILE_LOCKING",
                                       os.environ["HDF5_USE_FILE_LOCKING"]))

from PyMca5.PyMcaGui import PyMcaQt as qt
QTVERSION = qt.qVersion()
if sys.platform == 'darwin':
    if backend is not None:
        if backend.lower() in ["gl", "opengl"]:
            if hasattr(qt, 'QOpenGLWidget'):
                print("Warning: OpenGL backend not fully supported")
try:
    import silx
    if (sys.version_info < (3,)) and ("PyQt4.QtCore" in sys.modules):
        # PyQt4 is the most reliable binding at the ESRF for python 2
        silxLogger = logging.getLogger("silx.DEPRECATION")
        silxLogger.setLevel(logging.CRITICAL)
    # try to import silx prior to importing matplotlib to prevent
    # unnecessary warning
    import silx.gui.plot
except:
    pass
from PyMca5.PyMcaGui.pymca import PyMcaMdi
IconDict = PyMcaMdi.IconDict
IconDict0 = PyMcaMdi.IconDict0
if hasattr(qt, "QString"):
    QString = qt.QString
else:
    QString = qt.safe_str

try:
    from PyMca5.PyMcaGui.physics.xrf import XRFMCPyMca
    XRFMC_FLAG = True
except:
    XRFMC_FLAG = False

try:
    from PyMca5.PyMcaGui.pymca import SumRulesTool
    SUMRULES_FLAG = True
except:
    SUMRULES_FLAG = False

# prefer lazy import to avoid OpenCL related crashes on startup
TOMOGUI_FLAG = True

import PyMca5
from PyMca5 import PyMcaDataDir
__version__ = PyMca5.version()

if __name__ == "__main__":
    sys.excepthook = qt.exceptionHandler

    app = qt.QApplication(sys.argv)
    if sys.platform not in ["win32", "darwin"]:
        # some themes of Ubuntu 16.04 give black tool tips on black background
        app.setStyleSheet("QToolTip { color: #000000; background-color: #fff0cd; border: 1px solid black; }")

    mpath = PyMcaDataDir.PYMCA_DATA_DIR
    if mpath[-3:] == "exe":
        mpath = os.path.dirname(mpath)

    fname = os.path.join(mpath, 'PyMcaSplashImage.png')
    if not os.path.exists(fname):
       while len(mpath) > 3:
         fname = os.path.join(mpath, 'PyMcaSplashImage.png')
         if not os.path.exists(fname):
             mpath = os.path.dirname(mpath)
         else:
             break
    if os.path.exists(fname):
        pixmap = qt.QPixmap(QString(fname))
        splash  = qt.QSplashScreen(pixmap)
    else:
        splash = qt.QSplashScreen()
    splash.show()
    splash.raise_()
    from PyMca5.PyMcaGui.pymca import ChangeLog
    font = splash.font()
    font.setBold(1)
    splash.setFont(font)
    try:
        # there is a deprecation warning in Python 3.8 when
        # dealing with the alignement flags.
        alignment = int(qt.Qt.AlignLeft|qt.Qt.AlignBottom)
        splash.showMessage( 'PyMca %s' % __version__,
                alignment,
                qt.Qt.white)
    except:
        # fall back to original implementation in case of troubles
        splash.showMessage( 'PyMca %s' % __version__,
                qt.Qt.AlignLeft|qt.Qt.AlignBottom,
                qt.Qt.white)
    if sys.platform == "darwin":
        qApp = qt.QApplication.instance()
        qApp.processEvents()

from PyMca5.PyMcaGraph.Plot import Plot
from PyMca5.PyMcaGui.pymca import ScanWindow
from PyMca5.PyMcaGui.pymca import McaWindow

from PyMca5.PyMcaGui.pymca import PyMcaImageWindow
from PyMca5.PyMcaGui.pymca import PyMcaHKLImageWindow

try:
    #This is to make sure it is properly frozen
    #and that Object3D is fully supported
    import OpenGL.GL
    #import Object3D.SceneGLWindow as SceneGLWindow
    from PyMca5.PyMcaGui.pymca import PyMcaGLWindow
    OBJECT3D = False
    if ("PyQt4.QtOpenGL" in sys.modules) or \
       ("PySide.QtOpenGL") in sys.modules or \
       ("PySide2.QtOpenGL") in sys.modules or \
       ("PyQt5.QtOpenGL") in sys.modules:
        OBJECT3D = True
except:
    _logger.info("pyopengl not installed")
    OBJECT3D = False


# Silx OpenGL availability (former Object3D)
try:
    import PyMca5.PyMcaGui.pymca.SilxGLWindow
    isSilxGLAvailable = True
except ImportError:
    isSilxGLAvailable = False

if isSilxGLAvailable:
    SceneGLWindow = PyMca5.PyMcaGui.pymca.SilxGLWindow
elif OBJECT3D:
    SceneGLWindow = PyMcaGLWindow

try:
    from PyMca5.PyMcaGui.pymca import SilxScatterWindow
except:
    _logger.info("Cannot import SilxScatterWindow")

_logger.info("SilxGL availability: %s", isSilxGLAvailable)

# check that OpenGL is actually supported (ESRF rnice problems)
OPENGL_DRIVERS_OK = True
if sys.platform.startswith("linux"):
    import subprocess
    if subprocess.call("which glxinfo > /dev/null", shell=True) == 0:
        if subprocess.call("glxinfo > /dev/null", shell=True):
            OPENGL_DRIVERS_OK = False
            isSilxGLAvailable = False
            OBJECT3D = False
            _logger.warning("OpenGL disabled. Errors using glxinfo command")

from PyMca5.PyMcaGui.pymca import QDispatcher
from PyMca5.PyMcaGui import ElementsInfo
from PyMca5.PyMcaGui import PeakIdentifier
from PyMca5.PyMcaGui.pymca import PyMcaBatch
###########import Fit2Spec
from PyMca5.PyMcaGui.pymca import Mca2Edf
try:
    from PyMca5.PyMcaGui.pymca import QStackWidget
    from PyMca5.PyMcaGui.pymca import StackSelector
    STACK = True
except:
    STACK = False
from PyMca5.PyMcaGui.pymca import PyMcaPostBatch
from PyMca5.PyMcaGui import RGBCorrelator
from PyMca5.PyMcaGui import MaterialEditor

from PyMca5.PyMcaIO import ConfigDict
from PyMca5 import PyMcaDirs

XIA_CORRECT = False
if QTVERSION > '4.3.0':
    try:
        from PyMca5.PyMcaCore import XiaCorrect
        XIA_CORRECT = True
    except:
        pass

SOURCESLIST = QDispatcher.QDataSource.source_types.keys()

class PyMcaMain(PyMcaMdi.PyMcaMdi):
    def __init__(self, parent=None, name="PyMca", fl=None,**kw):
            if fl is None:
                fl = qt.Qt.WA_DeleteOnClose
            PyMcaMdi.PyMcaMdi.__init__(self, parent, name, fl)
            maxheight = qt.QDesktopWidget().height()
            if maxheight < 799:
                self.setMinimumHeight(int(0.8*maxheight))
                self.setMaximumHeight(int(0.9*maxheight))
            self.setWindowTitle(name)
            self.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict['gioconda16'])))
            self.changeLog = None

            self._widgetDict = {}
            self.initSourceBrowser()
            self.initSource()

            self.elementsInfo= None
            self.attenuationTool =  None
            self.identifier  = None
            self.__batch     = None
            self.__mca2Edf   = None
            self.__fit2Spec  = None
            self.__correlator  = None
            self.__imagingTool = None
            self._xrfmcTool = None
            self._sumRulesTool = None
            self.__reconsWidget = None
            self.openMenu = qt.QMenu()
            self.openMenu.addAction("PyMca Configuration", self.openSource)
            self.openMenu.addAction("Data Source",
                         self.sourceWidget.sourceSelector._openFileSlot)
            self.openMenu.addAction("Load Training Data",
                                        self.loadTrainingData)
            self.trainingDataMenu = None

            self.__useTabWidget = True

            if not self.__useTabWidget:
                self.mcaWindow = McaWindow.McaWidget(self.mdi)
                self.scanWindow = ScanWindow.ScanWindow(self.mdi)
                self.imageWindowDict = None
                self.connectDispatcher(self.mcaWindow, self.sourceWidget)
                self.connectDispatcher(self.scanWindow, self.sourceWidget)
                self.mdi.addWindow(self.mcaWindow)
                self.mdi.addWindow(self.scanWindow)
            else:
                if backend is not None:
                    Plot.defaultBackend = backend
                self.mainTabWidget = qt.QTabWidget(self.mdi)
                self.mainTabWidget.setWindowTitle("Main Window")
                self.mcaWindow = McaWindow.McaWindow(backend=backend)
                self.mcaWindow.showRoiWidget(qt.Qt.BottomDockWidgetArea)

                self.scanWindow = ScanWindow.ScanWindow(info=True,
                                                        backend=backend)
                self.scanWindow._togglePointsSignal()
                if OBJECT3D or isSilxGLAvailable:
                    self.glWindow = SceneGLWindow.SceneGLWindow()
                self.mainTabWidget.addTab(self.mcaWindow, "MCA")
                self.mainTabWidget.addTab(self.scanWindow, "SCAN")
                if OBJECT3D or isSilxGLAvailable:
                    self.mainTabWidget.addTab(self.glWindow, "OpenGL")
                if QTVERSION < '5.0.0':
                    self.mdi.addWindow(self.mainTabWidget)
                else:
                    self.mdi.addSubWindow(self.mainTabWidget)
                #print "Markus patch"
                #self.mainTabWidget.show()
                #print "end Markus patch"
                self.mainTabWidget.showMaximized()
                if False:
                    self.connectDispatcher(self.mcaWindow, self.sourceWidget)
                    self.connectDispatcher(self.scanWindow, self.sourceWidget)
                else:
                    self.imageWindowDict = {}
                    self.imageWindowCorrelator = None
                    self.sourceWidget.sigAddSelection.connect( \
                             self.dispatcherAddSelectionSlot)
                    self.sourceWidget.sigRemoveSelection.connect( \
                             self.dispatcherRemoveSelectionSlot)
                    self.sourceWidget.sigReplaceSelection.connect( \
                             self.dispatcherReplaceSelectionSlot)
                    self.mainTabWidget.currentChanged[int].connect( \
                        self.currentTabIndexChanged)

            self.sourceWidget.sigOtherSignals.connect( \
                         self.dispatcherOtherSignalsSlot)
            if 0:
                if 'shm' in kw:
                    if len(kw['shm']) >= 8:
                        if kw['shm'][0:8] in ['MCA_DATA', 'XIA_DATA']:
                            self.mcaWindow.showMaximized()
                            self.toggleSource()
                else:
                    self.mcaWindow.showMaximized()
            currentConfigDict = ConfigDict.ConfigDict()
            try:
                defaultFileName = PyMca5.getDefaultSettingsFile()
                self.configDir  = os.path.dirname(defaultFileName)
            except:
                if not ('fresh' in kw):
                    raise
            if not ('fresh' in kw):
                if os.path.exists(defaultFileName):
                    currentConfigDict.read(defaultFileName)
                    self.setConfig(currentConfigDict)
            if ('spec' in kw) and ('shm' in kw):
                if len(kw['shm']) >= 8:
                    #if kw['shm'][0:8] in ['MCA_DATA', 'XIA_DATA']:
                    if kw['shm'][0:8] in ['MCA_DATA']:
                        #self.mcaWindow.showMaximized()
                        self.toggleSource()
                        self._startupSelection(source=kw['spec'],
                                                selection=kw['shm'])
                    else:
                        self._startupSelection(source=kw['spec'],
                                                selection=None)
                else:
                     self._startupSelection(source=kw['spec'],
                                                selection=None)

    def connectDispatcher(self, viewer, dispatcher=None):
        #I could connect sourceWidget to myself and then
        #pass the selections to the active window!!
        #That will be made in a next iteration I guess
        if dispatcher is None:
            dispatcher = self.sourceWidget
        dispatcher.sigAddSelection.connect(viewer._addSelection)
        dispatcher.sigRemoveSelection.connect(viewer._removeSelection)
        dispatcher.sigReplaceSelection.connect(viewer._replaceSelection)

    def currentTabIndexChanged(self, index):
        legend = "%s" % self.mainTabWidget.tabText(index)
        for key in self.imageWindowDict.keys():
            if key == legend:
                value = True
            else:
                value = False
            self.imageWindowDict[key].setPlotEnabled(value)

    def _is2DSelection(self, ddict):
        if 'imageselection' in ddict:
            if ddict['imageselection']:
                return True
        if 'selection' in ddict:
            if ddict['selection'] is None:
                return False
            if 'selectiontype' in ddict['selection']:
                if ddict['selection']['selectiontype'] == '2D':
                    return True
        return False

    def _isScatterSelection(self, ddict):
        if 'imageselection' in ddict:
            if ddict['imageselection']:
                return False
        if 'selection' in ddict:
            if ddict['selection'] is None:
                return False
            if "x" in ddict['selection']:
                if hasattr(ddict['selection']['x'], "__len__"):
                    if len(ddict['selection']['x']) != 2:
                        return False
                    size0 = ddict['dataobject'].x[0].size
                    size1 = ddict['dataobject'].x[1].size
                    if size0 != size1:
                        return False
                    if hasattr(ddict['dataobject'], "y"):
                        if ddict['dataobject'].y:
                            if ddict['dataobject'].y[0].size != size0 * size1:
                                return False
                    if "PyMca5.PyMcaGui.pymca.SilxScatterWindow" in sys.modules:
                        if silx.version_info > (0, 10, 2):
                            return True
        return False

    def _is3DSelection(self, ddict):
        if self._is2DSelection(ddict):
            return False

        if 'selection' in ddict:
            if ddict['selection'] is None:
                return False
            if 'selectiontype' in ddict['selection']:
                if ddict['selection']['selectiontype'] == '3D':
                    return True

            if 'x' in ddict['selection']:
                if hasattr(ddict['selection']['x'], "__len__"):
                    if len(ddict['selection']['x']) > 1:
                        return True
        return False

    def _isStackSelection(self, ddict):
        if self._is2DSelection(ddict):
            return False
        if self._is3DSelection(ddict):
            return False
        if 'selection' in ddict:
            if ddict['selection'] is None:
                return False
            if 'selectiontype' in ddict['selection']:
                if ddict['selection']['selectiontype'] == 'STACK':
                    return True
        return False


    def dispatcherAddSelectionSlot(self, ddict):
        if self.__useTabWidget:
            if self.mainTabWidget.isHidden():
                #make sure it is visible in case of being closed
                self.mainTabWidget.show()

        try:
            self._dispatcherAddSelectionSlot(ddict)
        except:
            if _logger.getEffectiveLevel() == logging.DEBUG:
                raise
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Error: %s" % sys.exc_info()[1])
            msg.setInformativeText(str(sys.exc_info()[1]))
            msg.setDetailedText(traceback.format_exc())
            msg.exec_()

    def _dispatcherAddSelectionSlot(self, dictOrList):
        _logger.info("self._dispatcherAddSelectionSlot(ddict), ddict = %s",
                      dictOrList)
        if type(dictOrList) == type([]):
            ddict = dictOrList[0]
        else:
            ddict = dictOrList

        toadd = False
        if self._isScatterSelection(ddict):
            _logger.info("ScatterPlot selection")
            legend = ddict['legend']
            if legend not in self.imageWindowDict.keys():
                if OPENGL_DRIVERS_OK:
                    backend = "gl"
                else:
                    backend = "mpl"
                imageWindow = SilxScatterWindow.SilxScatterWindow(backend=backend)
                self.imageWindowDict[legend] = imageWindow
                self.imageWindowDict[legend].setPlotEnabled(True)
                if self.mainTabWidget.indexOf(self.imageWindowDict[legend]) < 0:
                    self.mainTabWidget.addTab(self.imageWindowDict[legend],
                                          legend)
                self.imageWindowDict[legend]._addSelection(ddict)
                self.mainTabWidget.setCurrentWidget(imageWindow)
                return
            if self.mainTabWidget.indexOf(self.imageWindowDict[legend]) < 0:
                self.mainTabWidget.addTab(self.imageWindowDict[legend],
                                          legend)
                #self.imageWindowDict[legend].setPlotEnabled(False)
                self.imageWindowDict[legend]._addSelection(ddict)
                self.mainTabWidget.setCurrentWidget(self.imageWindowDict\
                                                        [legend])
            else:
                self.imageWindowDict[legend]._addSelection(ddict)
            return
        elif self._is2DSelection(ddict):
            _logger.info("2D selection")
            if self.imageWindowCorrelator is None:
                self.imageWindowCorrelator = RGBCorrelator.RGBCorrelator()
                #toadd = True
            title  = "ImageWindow RGB Correlator"
            self.imageWindowCorrelator.setWindowTitle(title)
            legend = ddict['legend']
            if legend not in self.imageWindowDict.keys():
                hkl = False
                try:
                    motor_mne = ddict['dataobject'].info['motor_mne'].split()
                    if ('phi' in motor_mne) and ('chi' in motor_mne):
                        if ('mu'  in motor_mne) and ('gam' in motor_mne) :
                           if 'del' in motor_mne:
                               #SIXC
                               hkl = True
                        if ('tth' in motor_mne) and ('th' in motor_mne):
                            #FOURC
                            hkl = True
                except:
                    pass
                if hkl:
                    imageWindow = PyMcaHKLImageWindow.PyMcaHKLImageWindow(
                            name=legend,
                            correlator=self.imageWindowCorrelator,
                            scanwindow=self.scanWindow)
                else:
                    imageWindow = PyMcaImageWindow.PyMcaImageWindow(
                            name=legend,
                            correlator=self.imageWindowCorrelator,
                            scanwindow=self.scanWindow)
                self.imageWindowDict[legend] = imageWindow

                imageWindow.sigAddImageClicked.connect( \
                     self.imageWindowCorrelator.addImageSlot)
                imageWindow.sigRemoveImageClicked.connect( \
                     self.imageWindowCorrelator.removeImageSlot)
                imageWindow.sigReplaceImageClicked.connect( \
                     self.imageWindowCorrelator.replaceImageSlot)
                self.mainTabWidget.addTab(imageWindow, legend)
                if toadd:
                    self.mainTabWidget.addTab(self.imageWindowCorrelator,
                        "RGB Correlator")
                self.imageWindowDict[legend].setPlotEnabled(False)
                self.imageWindowDict[legend]._addSelection(ddict)
                self.mainTabWidget.setCurrentWidget(imageWindow)
                #self.imageWindowDict[legend].setPlotEnabled(True)
                return
            if self.mainTabWidget.indexOf(self.imageWindowDict[legend]) < 0:
                self.mainTabWidget.addTab(self.imageWindowDict[legend],
                                          legend)
                self.imageWindowDict[legend].setPlotEnabled(False)
                self.imageWindowDict[legend]._addSelection(ddict)
                self.mainTabWidget.setCurrentWidget(self.imageWindowDict\
                                                        [legend])
            else:
                self.imageWindowDict[legend]._addSelection(ddict)
        elif self._isStackSelection(ddict):
            _logger.info("Stack selection")
            legend = ddict['legend']
            widget = QStackWidget.QStackWidget()
            widget.notifyCloseEventToWidget(self)
            widget.setStack(ddict['dataobject'])
            widget.setWindowTitle(legend)
            widget.show()
            self._widgetDict[id(widget)] = widget
        else:
            if OBJECT3D or isSilxGLAvailable:
                if ddict['dataobject'].info['selectiontype'] == "1D":
                    _logger.info("1D selection")
                    self.mcaWindow._addSelection(dictOrList)
                    self.scanWindow._addSelection(dictOrList)
                else:
                    _logger.info("3D selection")
                    self.mainTabWidget.setCurrentWidget(self.glWindow)
                    self.glWindow._addSelection(dictOrList)
            else:
                _logger.info("1D selection")
                self.mcaWindow._addSelection(dictOrList)
                self.scanWindow._addSelection(dictOrList)

    def dispatcherRemoveSelectionSlot(self, ddict):
        try:
            return self._dispatcherRemoveSelectionSlot(ddict)
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Error: %s" % sys.exc_info()[1])
            msg.exec_()


    def _dispatcherRemoveSelectionSlot(self, dictOrList):
        _logger.debug("self.dispatcherRemoveSelectionSlot(ddict), ddict = %s", dictOrList)
        if type(dictOrList) == type([]):
            ddict = dictOrList[0]
        else:
            ddict = dictOrList
        if self._isScatterSelection(ddict) or self._is2DSelection(ddict):
            legend = ddict['legend']
            if legend in self.imageWindowDict.keys():
                index = self.mainTabWidget.indexOf(self.imageWindowDict[legend])
                if index >0:
                    self.imageWindowDict[legend].close()
                    self.imageWindowDict[legend].setParent(None)
                    self.mainTabWidget.removeTab(index)
                    self.imageWindowDict[legend]._removeSelection(ddict)
                    del self.imageWindowDict[legend]
        elif self._is3DSelection(ddict):
            self.glWindow._removeSelection(dictOrList)
        else:
            self.mcaWindow._removeSelection(dictOrList)
            self.scanWindow._removeSelection(dictOrList)

    def dispatcherReplaceSelectionSlot(self, ddict):
        try:
            return self._dispatcherReplaceSelectionSlot(ddict)
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Error: %s" % sys.exc_info()[1])
            msg.exec_()

    def _dispatcherReplaceSelectionSlot(self, dictOrList):
        _logger.debug("self.dispatcherReplaceSelectionSlot(ddict), ddict = %s",
                      dictOrList)
        if type(dictOrList) == type([]):
            ddict = dictOrList[0]
        else:
            ddict = dictOrList
        if self._isScatterSelection(ddict) or self._is2DSelection(ddict):
            legend = ddict['legend']
            for key in list(self.imageWindowDict.keys()):
                index = self.mainTabWidget.indexOf(self.imageWindowDict[key])
                if key == legend:
                    continue
                if index >= 0:
                    self.imageWindowDict[key].close()
                    self.imageWindowDict[key].setParent(None)
                    self.mainTabWidget.removeTab(index)
                    self.imageWindowDict[key]._removeSelection(ddict)
                    del self.imageWindowDict[key]
            if legend in self.imageWindowDict.keys():
                self.imageWindowDict[legend].setPlotEnabled(False)
            self.dispatcherAddSelectionSlot(ddict)
            index = self.mainTabWidget.indexOf(self.imageWindowDict[legend])
            if index != self.mainTabWidget.currentIndex():
                self.mainTabWidget.setCurrentWidget(self.imageWindowDict[legend])
            if legend in self.imageWindowDict.keys():
                # force an update
                self.imageWindowDict[legend].setPlotEnabled(True)
                self.imageWindowDict[legend].setPlotEnabled(False)
        elif self._is3DSelection(ddict):
            self.glWindow._replaceSelection(dictOrList)
        else:
            self.mcaWindow._replaceSelection(dictOrList)
            self.scanWindow._replaceSelection(dictOrList)

    def dispatcherOtherSignalsSlot(self, dictOrList):
        _logger.debug("self.dispatcherOtherSignalsSlot(ddict), ddict = %s",
                      dictOrList)
        if type(dictOrList) == type([]):
            ddict = dictOrList[0]
        else:
            ddict = dictOrList
        if not self.__useTabWidget:
            return
        if ddict['event'] == "SelectionTypeChanged":
            if ddict['SelectionType'].upper() == "COUNTERS":
                self.mainTabWidget.setCurrentWidget(self.scanWindow)
                return
            for i in range(self.mainTabWidget.count()):
                if str(self.mainTabWidget.tabText(i)) == \
                                   ddict['SelectionType']:
                    self.mainTabWidget.setCurrentIndex(i)
            return
        if ddict['event'] == "SourceTypeChanged":
            pass
            return
        _logger.debug("Unhandled dict")

    def setConfig(self, configDict):
        if 'PyMca' in configDict:
            self.__configurePyMca(configDict['PyMca'])
        if 'ROI' in configDict:
            self.__configureRoi(configDict['ROI'])
        if 'Elements' in configDict:
            self.__configureElements(configDict['Elements'])
        if 'Fit' in configDict:
            self.__configureFit(configDict['Fit'])
        if 'ScanSimpleFit' in configDict:
            self.__configureScanSimpleFit(configDict['ScanSimpleFit'])
        if 'ScanCustomFit' in configDict:
            self.__configureScanCustomFit(configDict['ScanCustomFit'])

    def getConfig(self):
        d = {}
        d['PyMca']    = {}
        d['PyMca']['VERSION']   = __version__
        d['PyMca']['ConfigDir'] = self.configDir
        d['PyMca']['nativeFileDialogs'] = PyMcaDirs.nativeFileDialogs

        #geometry
        d['PyMca']['Geometry']  ={}
        r = self.geometry()
        d['PyMca']['Geometry']['MainWindow'] = [r.x(), r.y(), r.width(), r.height()]
        r = self.splitter.sizes()
        d['PyMca']['Geometry']['Splitter'] = r
        r = self.mcaWindow.geometry()
        d['PyMca']['Geometry']['McaWindow'] = [r.x(), r.y(), r.width(), r.height()]

        #sources
        d['PyMca']['Sources'] = {}
        d['PyMca']['Sources']['lastFileFilter'] = self.sourceWidget.sourceSelector.lastFileFilter
        for source in SOURCESLIST:
            d['PyMca'][source] = {}
            if (self.sourceWidget.sourceSelector.lastInputDir is not None) and \
               len(self.sourceWidget.sourceSelector.lastInputDir):
                d['PyMca'][source]['lastInputDir'] = self.sourceWidget.sourceSelector.lastInputDir
                try:
                    PyMcaDirs.inputDir = self.sourceWidget.sourceSelector.lastInputDir
                except ValueError:
                    pass
            else:
                d['PyMca'][source]['lastInputDir'] = "None"
            if source == "SpecFile":
                d['PyMca'][source]['SourceName'] = []
                for key in self.sourceWidget.sourceList:
                    if key.sourceType == source:
                        d['PyMca'][source]['SourceName'].append(key.sourceName)
            elif source == "EdfFile":
                d['PyMca'][source]['SourceName'] = []
                for key in self.sourceWidget.sourceList:
                    if key.sourceType == source:
                        d['PyMca'][source]['SourceName'].append(key.sourceName)
                    #if key == "EDF Stack":
                    #    d['PyMca'][source]['SourceName'].append(self.sourceWidget.selectorWidget[source]._edfstack)
                    #else:
                    #    d['PyMca'][source]['SourceName'].append(self.sourceWidget.selectorWidget[source].mapComboName[key])
            elif source == "HDF5":
                d['PyMca'][source]['SourceName'] = []
                for key in self.sourceWidget.sourceList:
                    if key.sourceType == source:
                        d['PyMca'][source]['SourceName'].append(key.sourceName)
            selectorWidget = self.sourceWidget.selectorWidget[source]
            if hasattr(selectorWidget,'setWidgetConfiguration'):
                d['PyMca'][source]['WidgetConfiguration'] = selectorWidget.getWidgetConfiguration()

            #d['PyMca'][source]['Selection'] = self.sourceWidget[source].getSelection()

        # McaWindow calibrations
        d["PyMca"]["McaWindow"] = {}
        d["PyMca"]["McaWindow"]["calibrations"] = self.mcaWindow.getCalibrations()

        #ROIs
        d['ROI'] = {}
        if self.mcaWindow.roiWidget is None:
            roilist = []
            roidict = {}
        else:
            roilist, roidict = self.mcaWindow.roiWidget.getROIListAndDict()
        d['ROI']['roilist'] = roilist
        d['ROI']['roidict'] = {}
        d['ROI']['roidict'].update(roidict)

        #fit related
        d['Elements'] = {}
        d['Elements']['Material'] = {}
        d['Elements']['Material'].update(ElementsInfo.Elements.Material)
        d['Fit'] = {}
        if self.mcaWindow.advancedfit.configDir is not None:
            d['Fit'] ['ConfigDir'] = self.mcaWindow.advancedfit.configDir * 1
        d['Fit'] ['Configuration'] = {}
        d['Fit'] ['Configuration'].update(self.mcaWindow.advancedfit.mcafit.configure())
        d['Fit'] ['Information'] = {}
        d['Fit'] ['Information'].update(self.mcaWindow.advancedfit.info)
        d['Fit'] ['LastFit'] = {}
        d['Fit'] ['LastFit']['hidden'] = self.mcaWindow.advancedfit.isHidden()
        d['Fit'] ['LastFit']['xdata0'] = self.mcaWindow.advancedfit.mcafit.xdata0
        d['Fit'] ['LastFit']['ydata0'] = self.mcaWindow.advancedfit.mcafit.ydata0
        d['Fit'] ['LastFit']['sigmay0']= self.mcaWindow.advancedfit.mcafit.sigmay0
        d['Fit'] ['LastFit']['fitdone']= self.mcaWindow.advancedfit._fitdone()
        #d['Fit'] ['LastFit']['fitdone']= 1
        #d['Fit'] ['LastFit']['xmin'] = self.mcaWindow.advancedfit.mcafit.sigma0
        #d['Fit'] ['LastFit']['xmax'] = self.mcaWindow.advancedfit.mcafit.sigma0

        #ScanFit related
        d['ScanSimpleFit'] = {}
        d['ScanSimpleFit']['Configuration'] = {}

        try:
            d['ScanSimpleFit']['Configuration'].update(
                self.scanWindow.scanFit.getConfiguration())
        except:
            if _logger.getEffectiveLevel() == logging.DEBUG:
                raise
            _logger.warning("Error getting ScanFit configuration")
        return d

    def saveConfig(self, config, filename = None):
        d = ConfigDict.ConfigDict()
        d.update(config)
        if filename is None:
            filename = PyMca5.getDefaultSettingsFile()
        d.write(filename)

    def __configurePyMca(self, ddict):
        savedVersion = ddict.get("VERSION", '4.7.2')
        if 'ConfigDir' in ddict:
            self.configDir = ddict['ConfigDir']

        if 'Geometry' in ddict:
            r = qt.QRect(*ddict['Geometry']['MainWindow'])
            self.setGeometry(r)
            key = 'Splitter'
            if key in ddict['Geometry'].keys():
                self.splitter.setSizes(ddict['Geometry'][key])
            if hasattr(self.mcaWindow, "graph"):
                # this was the way of working of 4.x.x versions
                key = 'McaWindow'
                if key in ddict['Geometry'].keys():
                    r = qt.QRect(*ddict['Geometry']['McaWindow'])
                    self.mcaWindow.setGeometry(r)
                key = 'McaGraph'
                if key in ddict['Geometry'].keys():
                    r = qt.QRect(*ddict['Geometry']['McaGraph'])
                    self.mcaWindow.graph.setGeometry(r)
                self.show()
            qApp = qt.QApplication.instance()
            qApp.processEvents()
            qApp.postEvent(self, qt.QResizeEvent(qt.QSize(ddict['Geometry']['MainWindow'][2]+1,
                                                          ddict['Geometry']['MainWindow'][3]+1),
                                                 qt.QSize(ddict['Geometry']['MainWindow'][2],
                                                          ddict['Geometry']['MainWindow'][3])))
            self.mcaWindow.showMaximized()

        native = ddict.get('nativeFileDialogs', True)
        if native in ["False", "0", 0]:
            native = False
        else:
            native = True
        PyMcaDirs.nativeFileDialogs = native

        if 'Sources' in ddict:
            if 'lastFileFilter' in ddict['Sources']:
                self.sourceWidget.sourceSelector.lastFileFilter = ddict['Sources']['lastFileFilter']
        for source in SOURCESLIST:
            if source in ddict:
                if 'lastInputDir' in ddict[source]:
                    if ddict[source] ['lastInputDir'] not in ["None", []]:
                        self.sourceWidget.sourceSelector.lastInputDir =  ddict[source] ['lastInputDir']
                        try:
                            PyMcaDirs.inputDir = ddict[source] ['lastInputDir']
                        except ValueError:
                            pass
                if 'SourceName' in ddict[source]:
                    if type(ddict[source]['SourceName']) != type([]):
                        ddict[source]['SourceName'] = [ddict[source]['SourceName'] * 1]
                    for SourceName0 in ddict[source]['SourceName']:
                        if type(SourceName0) == type([]):
                            SourceName = SourceName0[0]
                        else:
                            SourceName = SourceName0
                        if len(SourceName):
                            try:
                                if not os.path.exists(SourceName):
                                    continue
                                self.sourceWidget.sourceSelector.openFile(SourceName, justloaded =1)
                                continue
                                #This event is not needed
                                ndict = {}
                                ndict["event"] = "NewSourceSelected"
                                ndict["sourcelist"] = [SourceName]
                                self.sourceWidget._sourceSelectorSlot(ndict)
                                continue
                                if source == "EdfFile":
                                    self.sourceWidget.selectorWidget[source].openFile(SourceName, justloaded=1)
                                else:
                                    self.sourceWidget.selectorWidget[source].openFile(SourceName)
                            except:
                                msg = qt.QMessageBox(self)
                                msg.setIcon(qt.QMessageBox.Critical)
                                txt = "Error: %s\n opening file %s" % (sys.exc_info()[1],SourceName )
                                msg.setInformativeText(txt)
                                msg.setDetailedText(traceback.format_exc())
                                msg.exec_()

                if 'WidgetConfiguration' in ddict[source]:
                    selectorWidget = self.sourceWidget.selectorWidget[source]
                    if hasattr(selectorWidget,'setWidgetConfiguration'):
                        try:
                            selectorWidget.setWidgetConfiguration(ddict[source]['WidgetConfiguration'])
                        except:
                            msg = qt.QMessageBox(self)
                            msg.setIcon(qt.QMessageBox.Critical)
                            txt = "Error: %s\n configuring %s widget" % (sys.exc_info()[1], source )
                            msg.setInformativeText(txt)
                            msg.setDetailedText(traceback.format_exc())
                            msg.exec_()
        if "McaWindow" in ddict:
            self.mcaWindow.setCalibrations(ddict["McaWindow"]["calibrations"])

    def __configureRoi(self, ddict):
        if 'roidict' in ddict:
            if 'roilist' in ddict:
                roilist = ddict['roilist']
                if type(roilist) != type([]):
                    roilist=[roilist]
                roidict = ddict['roidict']
                if self.mcaWindow.roiWidget is None:
                    self.mcaWindow.showRoiWidget(qt.Qt.BottomDockWidgetArea)
                self.mcaWindow.roiWidget.fillFromROIDict(roilist=roilist,
                                                         roidict=roidict)

    def __configureElements(self, ddict):
        if 'Material' in ddict:
            ElementsInfo.Elements.Material.update(ddict['Material'])

    def __configureFit(self, d):
        if 'Configuration' in d:
            self.mcaWindow.advancedfit.configure(d['Configuration'])
            if not self.mcaWindow.advancedfit.isHidden():
                self.mcaWindow.advancedfit._updateTop()
        if 'ConfigDir' in d:
            self.mcaWindow.advancedfit.configDir = d['ConfigDir'] * 1
        if False and ('LastFit' in d):
            if (d['LastFit']['ydata0'] != None) and \
               (d['LastFit']['ydata0'] != 'None'):
                self.mcaWindow.advancedfit.setdata(x=d['LastFit']['xdata0'],
                                                   y=d['LastFit']['ydata0'],
                                              sigmay=d['LastFit']['sigmay0'],
                                              **d['Information'])
                if d['LastFit']['hidden'] == 'False':
                    self.mcaWindow.advancedfit.show()
                    self.mcaWindow.advancedfit.raiseW()
                    if d['LastFit']['fitdone']:
                        try:
                            self.mcaWindow.advancedfit.fit()
                        except:
                            pass
                else:
                    print("hidden")

    def __configureFit(self, d):
        if 'Configuration' in d:
            self.mcaWindow.advancedfit.mcafit.configure(d['Configuration'])
            if not self.mcaWindow.advancedfit.isHidden():
                self.mcaWindow.advancedfit._updateTop()
        if 'ConfigDir' in d:
            self.mcaWindow.advancedfit.configDir = d['ConfigDir'] * 1
        if False and ('LastFit' in d):
            if (d['LastFit']['ydata0'] != None) and \
               (d['LastFit']['ydata0'] != 'None'):
                self.mcaWindow.advancedfit.setdata(x=d['LastFit']['xdata0'],
                                                   y=d['LastFit']['ydata0'],
                                              sigmay=d['LastFit']['sigmay0'],
                                              **d['Information'])
                if d['LastFit']['hidden'] == 'False':
                    self.mcaWindow.advancedfit.show()
                    self.mcaWindow.advancedfit.raiseW()
                    if d['LastFit']['fitdone']:
                        try:
                            self.mcaWindow.advancedfit.fit()
                        except:
                            pass
                else:
                    _logger.info("hidden")

    def __configureScanCustomFit(self, ddict):
        pass

    def __configureScanSimpleFit(self, ddict):
        if 'Configuration' in ddict:
            self.scanWindow.scanFit.setConfiguration(ddict['Configuration'])

    def initMenuBar(self):
        if self.options["MenuFile"]:
            #build the actions
            #fileopen
            self.actionOpen = qt.QAction(self)
            self.actionOpen.setText(QString("&Open"))
            self.actionOpen.setIcon(self.Icons["fileopen"])
            self.actionOpen.setShortcut(qt.QKeySequence(qt.Qt.CTRL+qt.Qt.Key_O))
            self.actionOpen.triggered[bool].connect(self.onOpen)
            #filesaveas
            self.actionSaveAs = qt.QAction(self)
            self.actionSaveAs.setText(QString("&Save"))
            self.actionSaveAs.setIcon(self.Icons["filesave"])
            self.actionSaveAs.setShortcut(\
                qt.QKeySequence(qt.Qt.CTRL+qt.Qt.Key_S))
            self.actionSaveAs.triggered[bool].connect(self.onSaveAs)

            #filesave
            self.actionSave = qt.QAction(self)
            self.actionSave.setText(QString("Save &Default Settings"))
            #self.actionSave.setIcon(self.Icons["filesave"])
            #self.actionSave.setShortcut(qt.Qt.CTRL+qt.Qt.Key_S)
            self.actionSave.triggered[bool].connect(self.onSave)

            #fileprint
            self.actionPrint = qt.QAction(self)
            self.actionPrint.setText(QString("&Print"))
            self.actionPrint.setIcon(self.Icons["fileprint"])
            self.actionPrint.setShortcut(\
                qt.QKeySequence(qt.Qt.CTRL+qt.Qt.Key_P))
            self.actionPrint.triggered[bool].connect(self.onPrint)

            #filequit
            self.actionQuit = qt.QAction(self)
            self.actionQuit.setText(QString("&Quit"))
            #self.actionQuit.setIcon(self.Icons["fileprint"])
            self.actionQuit.setShortcut(\
                                       qt.QKeySequence(qt.Qt.CTRL+qt.Qt.Key_Q))
            qApp = qt.QApplication.instance()
            self.actionQuit.triggered.connect(qApp.closeAllWindows)

            #self.menubar = qt.QMenuBar(self)
            self.menuFile= qt.QMenu(self.menuBar())
            self.menuFile.addAction(self.actionOpen)
            self.menuFile.addAction(self.actionSaveAs)
            self.menuFile.addAction(self.actionSave)
            self.menuFile.addSeparator()
            self.menuFile.addAction(self.actionPrint)
            self.menuFile.addSeparator()
            self.menuFile.addAction(self.actionQuit)
            self.menuBar().addMenu(self.menuFile)
            self.menuFile.setTitle("&File")
            self.onInitMenuBar(self.menuBar())

        if self.options["MenuTools"]:
            self.menuTools= qt.QMenu()
            #self.menuTools.setCheckable(1)
            self.menuTools.aboutToShow[()].connect(self.menuToolsAboutToShow)
            self.menuTools.setTitle("&Tools")
            self.menuBar().addMenu(self.menuTools)

        if self.options["MenuWindow"]:
            self.menuWindow= qt.QMenu()
            #self.menuWindow.setCheckable(1)
            self.menuWindow.aboutToShow[()].connect(self.menuWindowAboutToShow)
            self.menuWindow.setTitle("&Window")
            self.menuBar().addMenu(self.menuWindow)

        if self.options["MenuHelp"]:
            self.menuHelp= qt.QMenu(self)
            self.menuHelp.addAction("&Menu", self.onMenuHelp)
            self.menuHelp.addAction("&Data Display HOWTOs", self.onDisplayHowto)
            self.menuHelp.addAction("MCA &HOWTOs",self.onMcaHowto)
            self.menuHelp.addSeparator()
            self.menuHelp.addAction("&About", self.onAbout)
            self.menuHelp.addAction("Changes", self.onChanges)
            self.menuHelp.addAction("About &Qt",self.onAboutQt)
            self.menuBar().addSeparator()
            self.menuHelp.setTitle("&Help")
            self.menuBar().addMenu(self.menuHelp)
            self.menuBrowser    = None
            self.displayBrowser = None
            self.mcaBrowser     = None

    def initSourceBrowser(self):
        self.sourceFrame     = qt.QWidget(self.splitter)
        self.splitter.insertWidget(0, self.sourceFrame)
        self.sourceFrame.setWindowTitle("Source Selector")
        self.sourceFrame.setWindowIcon(self.windowIcon())
        #self.splitter.setResizeMode(self.sourceFrame,qt.QSplitter.KeepSize)
        self.sourceFrameLayout = qt.QVBoxLayout(self.sourceFrame)
        self.sourceFrameLayout.setContentsMargins(0, 0, 0, 0)
        self.sourceFrameLayout.setSpacing(0)
        #layout.setAutoAdd(1)

        sourceToolbar = qt.QWidget(self.sourceFrame)
        layout1       = qt.QHBoxLayout(sourceToolbar)
        #self.line1 = qt.QFrame(sourceToolbar,"line1")
        self.line1 = Line(sourceToolbar)
        self.line1.setFrameShape(qt.QFrame.HLine)
        self.line1.setFrameShadow(qt.QFrame.Sunken)
        self.line1.setFrameShape(qt.QFrame.HLine)
        layout1.addWidget(self.line1)
        #self.closelabel = qt.QLabel(sourceToolbar)
        self.closelabel = PixmapLabel(sourceToolbar)
        self.closelabel.setPixmap(qt.QPixmap(IconDict0['close']))
        layout1.addWidget(self.closelabel)
        self.closelabel.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Fixed))
        #self.sourceBrowserTab=qt.QTabWidget(self.sourceFrame)

        self.sourceFrameLayout.addWidget(sourceToolbar)

        #connections
        self.line1.sigLineDoubleClickEvent.connect(self.sourceReparent)
        self.closelabel.sigPixmapLabelMousePressEvent.connect(self.toggleSource)

        #tips
        self.line1.setToolTip("DoubleClick toggles floating window mode")
        self.closelabel.setToolTip("Hides Source Area")

    def sourceReparent(self,ddict = None):
        if self.sourceFrame.parent() is not None:
            self.sourceFrame.setParent(None)
            self.sourceFrame.move(self.cursor().pos())
            self.sourceFrame.show()
        else:
            try:
                self.splitter.insertWidget(0, self.sourceFrame)
            except:
                self.sourceFrame.setParent(self.splitter)

    def initSource(self):
        self.sourceWidget = QDispatcher.QDispatcher(self.sourceFrame)
        self.sourceFrameLayout.addWidget(self.sourceWidget)

    def _startupSelection(self, source, selection):
        self.sourceWidget.sourceSelector.openSource(source)
        if selection is None:
            return

        if len(selection) >= 8:
            if selection[0:8] == "MCA_DATA":
                ddict= {}
                ddict['event'] = "addSelection"
                ddict['SourceName'] = source
                ddict['Key'] = selection
                ddict["selection"] = {'cols': {'y': [1], 'x': [0]}}
                ddict["legend"] = ddict['SourceName'] + ' %s.c.1' %selection
                ddict["SourceType"] =  'SPS'
                self.sourceWidget._addSelectionSlot([ddict])
                self.mcaWindow.controlWidget.calbox.setCurrentIndex(2)
                self.mcaWindow.calibration = self.mcaWindow.calboxoptions[2]
                self.mcaWindow.controlWidget._calboxactivated("Internal")
        else:
            return
        """
        elif selection == "XIA_DATA":
            ddict= {}
            ddict['event'] = "addSelection"
            ddict['SourceName'] = "armando5"
            ddict['Key'] = selection
            ddict["selection"] = {'rows': {'y': [1], 'x': [0]}}
            ddict["legend"] = ddict['SourceName'] + ' XIA_DATA.c.1'
            ddict["SourceType"] =  'SPS'
            self.sourceWidget._addSelectionSlot([ddict])
        """

    def menuToolsAboutToShow(self):
        _logger.debug("menu ToolsAboutToShow")
        self.menuTools.clear()
        if self.sourceFrame.isHidden():
            self.menuTools.addAction("Show Source",self.toggleSource)
        else:
            self.menuTools.addAction("Hide Source",self.toggleSource)
        self.menuTools.addAction("Elements   Info",self.__elementsInfo)
        self.menuTools.addAction("Material Transmission",self.__attTool)
        self.menuTools.addAction("Identify  Peaks",self.__peakIdentifier)
        self.menuTools.addAction("Batch   Fitting",self.__batchFitting)
        self.menuTools.addAction("Convert Mca to Edf",self.__mca2EdfConversion)
        #self.menuTools.addAction("Fit to Specfile",self.__fit2SpecConversion)
        self.menuTools.addAction("RGB Correlator",self.__rgbCorrelator)
        if STACK:
            self.menuTools.addAction("ROI Imaging",self.__roiImaging)
        if XIA_CORRECT:
            self.menuTools.addAction("XIA Correct",
                                     self.__xiaCorrect)
        if XRFMC_FLAG:
            self.menuTools.addAction("XMI-MSIM PyMca",
                                     self._xrfmcPyMca)
        if SUMRULES_FLAG:
            self.menuTools.addAction("Sum Rules Tool", self._sumRules)
        _logger.debug("Fit to Specfile missing")
        if TOMOGUI_FLAG:
            self.menuTools.addAction("Tomography reconstruction",
                                     self.__tomoRecons)

    def fontdialog(self):
        fontd = qt.QFontDialog.getFont(self)
        if fontd[1]:
            qApp = qt.QApplication.instance()
            qApp.setFont(fontd[0],1)


    def toggleSource(self,**kw):
        _logger.debug("toggleSource called")
        if self.sourceFrame.isHidden():
            self.sourceFrame.show()
            self.sourceFrame.raise_()
        else:
            self.sourceFrame.hide()

    def __elementsInfo(self):
        if self.elementsInfo is None:
            self.elementsInfo=ElementsInfo.ElementsInfo(None,"Elements Info")
        if self.elementsInfo.isHidden():
           self.elementsInfo.show()
        self.elementsInfo.raise_()

    def __attTool(self):
        if self.attenuationTool is None:
            self.attenuationTool = MaterialEditor.MaterialEditor(toolmode=True)
        if self.attenuationTool.isHidden():
            self.attenuationTool.show()
        self.attenuationTool.raise_()

    def __peakIdentifier(self):
        if self.identifier is None:
            self.identifier=PeakIdentifier.PeakIdentifier(energy=5.9,
                                useviewer=1)
            self.identifier.mySlot()
        if self.identifier.isHidden():
            self.identifier.show()
        self.identifier.raise_()

    def __batchFitting(self):
        if self.__batch is None:
            self.__batch = PyMcaBatch.McaBatchGUI(fl=0,actions=1)
        if self.__batch.isHidden():
            self.__batch.show()
        self.__batch.raise_()

    def __mca2EdfConversion(self):
        if self.__mca2Edf is None:
            self.__mca2Edf = Mca2Edf.Mca2EdfGUI(fl=0,actions=1)
        if self.__mca2Edf.isHidden():
            self.__mca2Edf.show()
        self.__mca2Edf.raise_()

    def __fit2SpecConversion(self):
        if self.__fit2Spec is None:
            self.__fit2Spec = Fit2Spec.Fit2SpecGUI(fl=0,actions=1)
        if self.__fit2Spec.isHidden():
            self.__fit2Spec.show()
        self.__fit2Spec.raise_()

    def __rgbCorrelator(self):
        if self.__correlator is None:
            self.__correlator = []
        fileTypeList = ["Batch Result Files (*dat)",
                        "EDF Files (*edf)",
                        "EDF Files (*ccd)",
                        "All Files (*)"]
        message = "Open ONE Batch result .dat file or SEVERAL EDF files"
        filelist = self.__getStackOfFiles(fileTypeList, message)
        if not(len(filelist)):
            return
        filelist.sort()
        self.sourceWidget.sourceSelector.lastInputDir = os.path.dirname(filelist[0])
        PyMcaDirs.inputDir = os.path.dirname(filelist[0])
        self.__correlator.append(PyMcaPostBatch.PyMcaPostBatch())
        for correlator in self.__correlator:
            if correlator.isHidden():
                correlator.show()
            correlator.raise_()
        self.__correlator[-1].sigRGBCorrelatorSignal.connect( \
                self._deleteCorrelator)
        correlator.addFileList(filelist)

    def __sumRules(self):
        if self.__correlator is None:
            self.__correlator = []

    def __tomoRecons(self):
        if self.__reconsWidget is None:
            try:
                from tomogui.gui.ProjectWidget \
                     import ProjectWindow as TomoguiProjectWindow
            except ImportError:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                txt = "This functionality requires tomogui, silx and FreeART"
                msg.setInformativeText(txt)
                msg.setDetailedText(traceback.format_exc())
                msg.exec_()
                return
            self.__reconsWidget = TomoguiProjectWindow()
        if self.__reconsWidget.isHidden():
            self.__reconsWidget.show()
        self.__reconsWidget.raise_()

    def _deleteCorrelator(self, ddict):
        n = len(self.__correlator)
        if ddict['event'] == "RGBCorrelatorClosed":
            for i in range(n):
                if id(self.__correlator[i]) == ddict["id"]:
                    self.__correlator[i].deleteLater()
                    del self.__correlator[i]
                    break

    def __getStackOfFiles(self, typelist, message="", getfilter=False):
        wdir = PyMcaDirs.inputDir
        fileTypeList = typelist
        filterused = None
        if False and PyMcaDirs.nativeFileDialogs:
            #windows cannot handle thousands of files in a file dialog
            filetypes = ""
            for filetype in fileTypeList:
                filetypes += filetype+"\n"
            filelist = qt.QFileDialog.getOpenFileNames(self,
                        message,
                        wdir,
                        filetypes)
            if not len(filelist):
                if getfilter:
                    return [], filterused
                else:
                    return []
            else:
                sample  = qt.safe_str(filelist[0])
                for filetype in fileTypeList:
                    ftype = filetype.replace("(", "").replace(")","")
                    extensions = ftype.split()[2:]
                    for extension in extensions:
                        if sample.endswith(extension[-3:]):
                            filterused = filetype
                            break
        else:
            fdialog = qt.QFileDialog(self)
            fdialog.setModal(True)
            fdialog.setWindowTitle(message)
            if hasattr(qt, "QStringList"):
                strlist = qt.QStringList()
            else:
                strlist = []
            for filetype in fileTypeList:
                strlist.append(filetype.replace("(","").replace(")",""))
            if hasattr(fdialog, "setFilters"):
                fdialog.setFilters(strlist)
            else:
                fdialog.setNameFilters(strlist)
            fdialog.setFileMode(fdialog.ExistingFiles)
            fdialog.setDirectory(wdir)
            if QTVERSION > '4.3.0':
                history = fdialog.history()
                if len(history) > 6:
                    fdialog.setHistory(history[-6:])
            ret = fdialog.exec_()
            if ret == qt.QDialog.Accepted:
                filelist = fdialog.selectedFiles()
                if getfilter:
                    filterused = qt.safe_str(fdialog.selectedFilter())
                fdialog.close()
                del fdialog
            else:
                fdialog.close()
                del fdialog
                if getfilter:
                    return [], filterused
                else:
                    return []
        filelist = [qt.safe_str(x) for x in filelist]
        if getfilter:
            return filelist, filterused
        else:
            return filelist


    def __roiImaging(self):
        if self.__imagingTool is None:
            rgbWidget = None
            try:
                widget = QStackWidget.QStackWidget(mcawidget=self.mcaWindow,
                                                   rgbwidget=rgbWidget,
                                                   master=True)
                widget.notifyCloseEventToWidget(self)
                self.__imagingTool = id(widget)
                self._widgetDict[self.__imagingTool] = widget
                #w = StackSelector.StackSelector(self)
                #stack = w.getStack()
                widget.loadStack()
                widget.show()
            except IOError:
                widget = None
                del self._widgetDict[self.__imagingTool]
                self.__imagingTool = None
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                txt = "Input Output Error: %s" % (sys.exc_info()[1])
                msg.setInformativeText(txt)
                msg.setDetailedText(traceback.format_exc())
                msg.exec_()
                return
            except:
                widget = None
                del self._widgetDict[self.__imagingTool]
                self.__imagingTool = None
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                txt = "Error info = %s" % (sys.exc_info()[1])
                msg.setInformativeText(txt)
                msg.setDetailedText(traceback.format_exc())
                msg.exec_()
                return
        else:
            widget = self._widgetDict[self.__imagingTool]
            if widget.isHidden():
                widget.show()
            widget.raise_()


    def customEvent(self, event):
        if hasattr(event, 'dict'):
            ddict = event.dict
            if 'event' in ddict:
                if ddict['event'] == "closeEventSignal":
                    if ddict['id'] in self._widgetDict:
                        if ddict['id'] == self.__imagingTool:
                            self.__imagingTool = None
                        del self._widgetDict[ddict['id']]

    def closeEvent(self, event):
        if __name__ == "__main__":
            app = qt.QApplication.instance()
            allWidgets = app.allWidgets()
            for widget in allWidgets:
                try:
                    # we cannot afford to crash here
                    if id(widget) != id(self):
                        if widget.parent() is None:
                            widget.close()
                except:
                    _logger.debug("Error closing widget")
            from PyMca5.PyMcaGui.plotting import PyMcaPrintPreview
            PyMcaPrintPreview.resetSingletonPrintPreview()
        return PyMcaMdi.PyMcaMdi.closeEvent(self, event)

    def __xiaCorrect(self):
        qApp = qt.QApplication.instance()
        XiaCorrect.mainGUI(qApp)

    def _xrfmcPyMca(self):
        if self._xrfmcTool is None:
            self._xrfmcTool = XRFMCPyMca.XRFMCPyMca()
        self._xrfmcTool.show()
        self._xrfmcTool.raise_()

    def _sumRules(self):
        if self._sumRulesTool is None:
            self._sumRulesTool = SumRulesTool.SumRulesWindow()
        self._sumRulesTool.show()
        self._sumRulesTool.raise_()

    def onOpen(self):
        self.openMenu.exec_(self.cursor().pos())

    def onSave(self):
        self._saveAs()

    def onSaveAs(self):
        index = self.mainTabWidget.currentIndex()
        text  = str(self.mainTabWidget.tabText(index))
        self.saveMenu = qt.QMenu()
        self.saveMenu.addAction("PyMca Configuration", self._onSaveAs)
        if text.upper() == 'MCA':
            self.saveMenu.addAction("Active Mca",
                             self.mcaWindow._saveIconSignal)
        elif text.upper() == 'SCAN':
            self.saveMenu.addAction("Active Scan",
                             self.scanWindow._saveIconSignal)
        elif text in self.imageWindowDict.keys():
            self.saveMenu.addAction("Active Image",
                  self.imageWindowDict[text].graphWidget._saveIconSignal)
        self.saveMenu.exec_(self.cursor().pos())

    def _onSaveAs(self):
        cwd = os.getcwd()
        outfile = qt.QFileDialog(self)
        if hasattr(outfile, "setFilters"):
            outfile.setFilters(['PyMca  *.ini'])
        else:
            outfile.setNameFilters(['PyMca  *.ini'])
        outfile.setFileMode(outfile.AnyFile)
        outfile.setAcceptMode(qt.QFileDialog.AcceptSave)

        if os.path.exists(self.configDir):
            cwd =self.configDir
        outfile.setDirectory(cwd)
        ret = outfile.exec_()
        if ret:
            if hasattr(outfile, "selectedFilter"):
                filterused = qt.safe_str(outfile.selectedFilter()).split()
            else:
                filterused = qt.safe_str(outfile.selectedNameFilter()).split()
            extension = ".ini"
            outdir=qt.safe_str(outfile.selectedFiles()[0])
            try:
                outputDir  = os.path.dirname(outdir)
            except:
                outputDir  = "."
            try:
                outputFile = os.path.basename(outdir)
            except:
                outputFile  = "PyMca.ini"
            outfile.close()
            del outfile
        else:
            outfile.close()
            del outfile
            return
        #always overwrite for the time being
        if len(outputFile) < len(extension[:]):
            outputFile += extension[:]
        elif outputFile[-4:] != extension[:]:
            outputFile += extension[:]
        filename = os.path.join(outputDir, outputFile)
        if os.path.exists(filename):
            try:
                os.remove(filename)
            except IOError:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                txt = "Input Output Error: %s" % (sys.exc_info()[1])
                msg.setInformativeText(txt)
                msg.setDetailedText(traceback.format_exc())
                msg.exec_()
                return
        try:
            self._saveAs(filename)
            self.configDir = outputDir
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Error Saving Configuration: %s" % (sys.exc_info()[1]))
            msg.exec_()
            return

    def _saveAs(self, filename=None):
        if filename is None:
            filename = PyMca5.getDefaultSettingsFile()
        self.saveConfig(self.getConfig(), filename)

    def loadTrainingData(self):
        if self.trainingDataMenu is None:
            self.trainingDataMenu = qt.QMenu()
            self.trainingSources = {"XRF Analysis": os.path.join(PyMcaDataDir.PYMCA_DATA_DIR, 'XRFSpectrum.mca'),
                        "Tertiary Excitation": os.path.join(PyMcaDataDir.PYMCA_DATA_DIR, 'Steel.spe')}
            self.trainingActions = []
            for key in ["XRF Analysis", "Tertiary Excitation"]:
                action = qt.QAction(key, None)
                self.trainingActions.append(action)
                self.trainingDataMenu.addAction(action)
        try:
            source = None
            selectedAction = self.trainingDataMenu.exec_(qt.QCursor.pos())
            if selectedAction is not None:
                key = qt.safe_str(selectedAction.text())
                source = self.trainingSources[key]
                self.sourceWidget.sourceSelector.openSource(source)
                # only in case of the steel sample we set the input dir to simplify accessing the supplied cfg file
                if key in ["Tertiary Excitation"]:
                    # we do not change the input dir currently used by the source selector
                    #self.sourceWidget.sourceSelector.lastInputDir = os.path.dirname(source)
                    # but we change the input dir to allow easy loading of the config file from the
                    # fit configuration window
                    PyMcaDirs.inputDir = os.path.dirname(source)
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setWindowTitle("Error opening data source")
            if source:
                msg.setText("Cannot open data source %s" % source)
            else:
                msg.setText("Cannot open data source")
            msg.setInformativeText(str(sys.exc_info()[1]))
            msg.setDetailedText(traceback.format_exc())
            msg.exec_()

    def openSource(self,index=0):
        _logger.debug("index = %d ", index)
        if index <= 0:
            outfile = qt.QFileDialog(self)
            outfile.setWindowTitle("Select PyMca Configuration File")
            if os.path.exists(self.configDir):
                outfile.setDirectory(self.configDir)
            if hasattr(outfile, "setFilters"):
                outfile.setFilters(['PyMca  *.ini'])
            else:
                outfile.setNameFilters(['PyMca  *.ini'])
            outfile.setFileMode(outfile.ExistingFile)
            ret = outfile.exec_()
            if ret:
                filename = qt.safe_str(outfile.selectedFiles()[0])
                outfile.close()
                del outfile
            else:
                outfile.close()
                del outfile
                return
            currentConfigDict = ConfigDict.ConfigDict()
            self.configDir  = os.path.dirname(filename)
            currentConfigDict.read(filename)
            self.setConfig(currentConfigDict)
            return
        else:
            index -= 1
        source = SOURCESLIST[index]
        if self.sourceFrame.isHidden():
            self.sourceFrame.show()
        self.sourceFrame.raise_()
        self.sourceBrowserTab.showPage(self.sourceWidget[source])
        qApp = qt.QApplication.instance()
        qApp.processEvents()
        self.sourceWidget[source].openFile()

    def onMenuHelp(self):
        if self.menuBrowser is None:
            self.menuBrowser= qt.QTextBrowser()
            self.menuBrowser.setWindowTitle(QString("Main Menu Help"))
            ddir=PyMcaDataDir.PYMCA_DOC_DIR
            if not os.path.exists(os.path.join(ddir,"HTML","Menu.html")):
                ddir = os.path.dirname(ddir)
            self.menuBrowser.setSearchPaths([os.path.join(ddir,"HTML")])
            self.menuBrowser.setSource(qt.QUrl(QString("Menu.html")))
            self.menuBrowser.show()
        if self.menuBrowser.isHidden():
            self.menuBrowser.show()
        self.menuBrowser.raise_()

    def onDisplayHowto(self):
        if self.displayBrowser is None:
            self.displayBrowser= qt.QTextBrowser()
            self.displayBrowser.setWindowTitle(QString("Data Display HOWTO"))
            ddir=PyMcaDataDir.PYMCA_DOC_DIR
            if not os.path.exists(os.path.join(ddir,"HTML","Display-HOWTO.html")):
                ddir = os.path.dirname(ddir)
            self.displayBrowser.setSearchPaths([os.path.join(ddir,"HTML")])
            self.displayBrowser.setSource(qt.QUrl(QString("Display-HOWTO.html")))
            self.displayBrowser.show()
        if self.displayBrowser.isHidden():
            self.displayBrowser.show()
        self.displayBrowser.raise_()

    def onMcaHowto(self):
        if self.mcaBrowser is None:
            self.mcaBrowser= MyQTextBrowser()
            self.mcaBrowser.setWindowTitle(QString("MCA HOWTO"))
            ddir=PyMcaDataDir.PYMCA_DOC_DIR
            if not os.path.exists(ddir+"/HTML"+"/MCA-HOWTO.html"):
                ddir = os.path.dirname(ddir)
            self.mcaBrowser.setSearchPaths([os.path.join(ddir,"HTML"),
                                            os.path.join(ddir,"HTML", "PyMCA_files"),
                                            os.path.join(ddir,"HTML", "images")])
            self.mcaBrowser.setSource(qt.QUrl(QString("MCA-HOWTO.html")))
            #f = open(os.path.join(dir,"HTML","MCA-HOWTO.html"))
            #self.mcaBrowser.setHtml(f.read())
            #f.close()
            self.mcaBrowser.show()
        if self.mcaBrowser.isHidden():
            self.mcaBrowser.show()
        self.mcaBrowser.raise_()

    def onAbout(self):
        qt.QMessageBox.about(self, "PyMca",
                "PyMca Application\nVersion: "+__version__)
        #self.onDebug()

    def onChanges(self):
        if self.changeLog is None:
            self.changeLog = qt.QTextEdit()
            self.changeLog.setCursor(self.cursor())
            self.changeLog.setWindowTitle("PyMCA %s Changes" % __version__)
            self.changeLog.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict['gioconda16'])))
            # Does this belong to the data dir or the doc dir?
            mpath = PyMcaDataDir.PYMCA_DATA_DIR
            fname = os.path.join(mpath,'changelog.txt')
            if not os.path.exists(fname):
               while len(mpath) > 3:
                 fname = os.path.join(mpath,'changelog.txt')
                 #print "looking for ", fname
                 if not os.path.exists(fname):
                     mpath = os.path.dirname(mpath)
                 else:
                     break
            if os.path.exists(fname):
                self.log = ChangeLog.ChangeLog(textfile='changelog.txt')
                self.changeLog.setDocument(self.log)
                self.changeLog.setMinimumWidth(500)
            else:
                self.log = ChangeLog.ChangeLog()
                self.log.setPlainText('Cannot find file changelog.txt')
        self.changeLog.show()

    def onDebug(self):
        if "PyQt5.QtCore" in sys.modules:
            _logger.debug("Module name PyQt  %s", qt.PYQT_VERSION_STR)
        for module in sys.modules.values():
            try:
                if 'Revision' in module.__revision__:
                    if module.__name__ != "__main__":
                        _logger.debug("Module name = %s, %s",
                                      module.__name__,
                                      module.__revision__.replace("$", ""))
            except:
                pass

    def onPrint(self):
        _logger.debug("onPrint called")

        if not self.scanWindow.isHidden():
            self.scanWindow.printGraph()
            return

        if not self.__useTabWidget:
            self.mcaWindow.show()
            self.mcaWindow.raise_()
        else:
            self.mainTabWidget.setCurrentWidget(self.mcaWindow)
        self.mcaWindow.printGraph()

if 0:

    #
    # GraphWindow operations
    #
    def openGraph(self,name="MCA Graph"):
            """
            Creates a new GraphWindow on the MDI
            """
            self.setFollowActiveWindow(0)

            #name= self.__getNewGraphName()
            if name == "MCA Graph":
                graph = McaWindow.McaWindow(self.mdi, name=name)
            graph.windowClosed[()].connect(self.closeGraph)
            graph.show()

            if len(self.mdi.windowList())==1:
                    graph.showMaximized()
            else:   self.windowTile()

            self.setFollowActiveWindow(1)

    def getActiveGraph(self):
            """
            Return active GraphWindow instance or a new one
            """
            graph= self.mdi.activeWindow()
            if graph is None:
                    graph= self.openGraph()
            return graph

    def getGraph(self, name):
            """
            Return GraphWindow instance indexed by name
            Or None if not found
            """
            for graph in self.mdi.windowList():
                if qt.safe_str(graph.caption())== name:
                    return graph
            return None

    def closeGraph(self, name):
            """
            Called after a graph is closed
            """
            _logger.info("closeGraph", name)

    def __getGraphNames(self):
            return [ str(window.caption()) for window in self.mdi.windowList() ]


    def __getNewGraphName(self):
            names= self.__getGraphNames()
            idx= 0
            while "Graph %d"%idx in names:
                    idx += 1
            return "Graph %d"%(idx)

class MyQTextBrowser(qt.QTextBrowser):
    def setSource(self, name):
        if name == QString("./PyMCA.html") or ("PyMCA.html" in ("%s" % name)):
            if sys.platform == 'win32':
                ddir=PyMcaDataDir.PYMCA_DOC_DIR
                if not os.path.exists(os.path.join(ddir, "HTML", "PyMCA.html")):
                    ddir = os.path.dirname(ddir)
                cmd = os.path.join(ddir,"HTML", "PyMCA.pdf")
                os.system('"%s"' % cmd)
                return
            try:
                self.report.show()
            except:
                self.report = qt.QTextBrowser()
                self.report.setCaption(QString("PyMca Report"))
                ddir=PyMcaDataDir.PYMCA_DOC_DIR
                self.report.mimeSourceFactory().addFilePath(QString(ddir+"/HTML"))
                self.report.mimeSourceFactory().addFilePath(QString(ddir+"/HTML/PyMCA_files"))
                self.report.setSource(name)
            if self.report.isHidden():self.report.show()
            self.report.raiseW()
        else:
            qt.QTextBrowser.setSource(self, name)

class Line(qt.QFrame):
    sigLineDoubleClickEvent = qt.pyqtSignal(object)
    def mouseDoubleClickEvent(self,event):
        _logger.debug("Double Click Event")
        ddict={}
        ddict['event']="DoubleClick"
        ddict['data'] = event
        self.sigLineDoubleClickEvent.emit(ddict)

class PixmapLabel(qt.QLabel):
    sigPixmapLabelMousePressEvent = qt.pyqtSignal(object)
    def mousePressEvent(self,event):
        _logger.debug("Mouse Press Event")
        ddict={}
        ddict['event']="MousePress"
        ddict['data'] = event
        self.sigPixmapLabelMousePressEvent.emit(ddict)

if __name__ == '__main__':
    PROFILING = 0
    if PROFILING:
        import profile
        import pstats
    PyMcaMainWidgetInstance = PyMcaMain(**keywords)
    if nativeFileDialogs is not None:
        PyMcaDirs.nativeFileDialogs = nativeFileDialogs
    if debugreport:
        PyMcaMainWidgetInstance.onDebug()
    app.lastWindowClosed.connect(app.quit)

    splash.finish(PyMcaMainWidgetInstance)
    PyMcaMainWidgetInstance.show()
    PyMcaMainWidgetInstance.raise_()
    PyMcaMainWidgetInstance.mcaWindow.replot()

    #try to interpret rest of command line arguments as data sources
    try:
        for source in args:
            PyMcaMainWidgetInstance.sourceWidget.sourceSelector.openSource(source)
    except:
        msg = qt.QMessageBox(PyMcaMainWidgetInstance)
        msg.setIcon(qt.QMessageBox.Critical)
        msg.setWindowTitle("Error opening data source")
        msg.setText("Cannot open data source %s" % source)
        msg.setInformativeText(str(sys.exc_info()[1]))
        msg.setDetailedText(traceback.format_exc())
        msg.exec_()

    if PROFILING:
        profile.run('sys.exit(app.exec_())',"test")
        p=pstats.Stats("test")
        p.strip_dirs().sort_stats(-1).print_stats()
    else:
        ret = app.exec_()
        app = None
        sys.exit(ret)