This file is indexed.

/usr/share/pyshared/PyMca/QSpsWidget.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
#/*##########################################################################
# Copyright (C) 2004-2011 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.
#############################################################################*/
__revision__ = "$Revision: 1.3 $"
import sys
import spswrap as sps
import PyMcaQt as qt
import SpecFileCntTable
import MaskImageWidget
QTVERSION = qt.qVersion()
import PyMca_Icons as icons
DEBUG = 0
SOURCE_TYPE = 'SPS'
SCAN_MODE = True

if QTVERSION > '4.0.0':
    class QGridLayout(qt.QGridLayout):
        def addMultiCellWidget(self, w, r0, r1, c0, c1, *var):
            self.addWidget(w, r0, c0, 1 + r1 - r0, 1 + c1 - c0)

class SPSFramesMcaWidget(qt.QWidget):
    def __init__(self, parent=None):
        qt.QWidget.__init__(self, parent)
        self.mainLayout = qt.QVBoxLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.graphWidget = MaskImageWidget.MaskImageWidget(self,
                                    imageicons=False,
                                    selection=False)
        self.graph = self.graphWidget.graphWidget.graph 
        self.mainLayout.addWidget(self.graphWidget)

    def setInfo(self, info):
        self.setDataSize(info["rows"], info["cols"])
        self.setTitle(info["Key"])
        self.info=info

    def setDataSource(self, data):
        self.data = data
        self.connect(self.data,
                     qt.SIGNAL("updated"),
                     self._update)
        
        dataObject = self._getDataObject()
        self.graphWidget.setImageData(dataObject.data)
        self.lastDataObject = dataObject

    def _update(self, ddict):
        targetwidgetid = ddict.get('targetwidgetid', None)
        if targetwidgetid not in [None, id(self)]:
            return
        dataObject = self._getDataObject(ddict['Key'],
                                        selection=None)
        if dataObject is not None:
            self.graphWidget.setImageData(dataObject.data)
            self.lastDataObject = dataObject

    def _getDataObject(self, key=None, selection=None):
        if key is None:
            key = self.info['Key']
        dataObject = self.data.getDataObject(key,
                                             selection=None,
                                             poll=False)
        if dataObject is not None:
            dataObject.info['legend'] = self.info['Key']
            dataObject.info['imageselection'] = False
            dataObject.info['scanselection'] = False
            dataObject.info['targetwidgetid'] = id(self)
            self.data.addToPoller(dataObject)
        return dataObject
        

    def setDataSize(self,rows,cols,selsize=None):
        self.rows= rows
        self.cols= cols
        if self.cols<=self.rows:
            self.idx='cols'
        else:
            self.idx='rows'

    def setTitle(self, title):
        self.graph.setTitle("%s"%title)

    def getSelection(self):
        keys = {"plot":self.idx,"x":0,"y":1}
        return [keys]
        

class SPSScanArrayWidget(SpecFileCntTable.SpecFileCntTable):
    def setInfo(self, info):
        if DEBUG: 
            print("info = ", info)
        if info.has_key("envdict"):
            if len(info["envdict"].keys()):
                #We have environment information
                if info["envdict"].has_key("datafile"):
                    if info["envdict"]["datafile"] != "/dev/null":
                        if DEBUG:
                            print("I should send a signal, either from here or from the parent to the dispatcher")
                        if DEBUG:
                            print("SPEC data file = %s" % datafile)
                #usefull keys = ["datafile", "scantype", "axistitles","plotlist", "xlabel", "ylabel"]
                #
                #info = self.data.getKeyInfo(sel[0])
                #except:
                #    info, data = self.data.LoadSource(sel[0])
                cntList = info.get("LabelNames", [])
                ycntidx = info["envdict"].get('plotlist', "")
                if len(ycntidx):
                    ycntidx   = ycntidx.split(',')
                self.build(cntList)
                #self.cntTable.setCounterSelection(self._oldCntSelection)
                return
        if info['cols'] > 0:
            #arrayname = info['Key']
            arrayname = 'Column'
            cntList = []
            for i in range(info['cols']):
                cntList.append('%s_%03d' % (arrayname, i))
        self.build(cntList)
            
    def getSelection(self):
        #get selected counter keys
        cnt_sel = self.getCounterSelection()
        sel_list = []
        
        #build the appropriate selection for mca's
        if len(cnt_sel['cntlist']):
            if len(cnt_sel['y']): #if there is something to plot
                for index in cnt_sel['y']:
                    sel = {}
                    sel['selection'] = {}
                    sel['plot'] = 'scan'
                    sel['scanselection']  = True
                    sel['selection']['x'] = cnt_sel['x'] 
                    sel['selection']['y'] = [index] 
                    sel['selection']['m'] = cnt_sel['m']
                    sel['selection']['cntlist'] = cnt_sel['cntlist']
                    sel_list.append(sel)
        return sel_list


class SPSMcaArrayWidget(qt.QWidget):
    def __init__(self, parent=None, name="SPS_MCA_DATA", fl=0, title="MCA", size=(0,8192)):
        if QTVERSION < '4.0.0':
            qt.QWidget.__init__(self, parent, name, fl)
            layout= qt.QGridLayout(self, 5, 2)
        else:
            qt.QWidget.__init__(self, parent)
            self.setWindowTitle(name)
            layout= QGridLayout(self)
        layout.setMargin(5)
        layout.setSpacing(0)

        self.title= qt.QLabel(self)
        font= self.title.font()
        font.setBold(1)
        self.title.setFont(font)
        if QTVERSION < '4.0.0':
            layout.addMultiCellWidget(self.title, 0, 0, 0, 1, qt.Qt.AlignCenter)
            layout.addRowSpacing(0, 40)
        else:
            #layout.addMultiCellWidget(self.title, 0, 0, 0, 1, qt.Qt.AlignCenter)
            layout.addWidget(self.title, 0, 0)
            layout.setAlignment(self.title, qt.Qt.AlignCenter)
        self.setTitle(title)
        
    def setInfo(self, info):
        self.setDataSize(info["rows"], info["cols"])
        self.setTitle(info["Key"])

    def setDataSize(self,rows,cols,selsize=None):
        self.rows= rows
        self.cols= cols
        if self.cols<=self.rows:
            self.idx='cols'
        else:
            self.idx='rows'

    def setTitle(self, title):
        self.title.setText("%s"%title)

    def getSelection(self):
        keys = {"plot":self.idx,"x":0,"y":1}
        return [keys]

class SPSXiaArrayWidget(qt.QWidget):
    def __init__(self, parent=None, name="SPS_XIA_DATA", fl=0, title="XIA", size=(0,8192)):
        if QTVERSION < '4.0.0':       
            qt.QWidget.__init__(self, parent, name, fl)
            layout= qt.QGridLayout(self, 2, 1)
        else:
            qt.QWidget.__init__(self, parent)
            layout= qt.QGridLayout(self)
        layout.setMargin(5)
        layout.setSpacing(0)

        self.title= qt.QLabel(self)
        font= self.title.font()
        font.setBold(1)
        self.title.setFont(font)
        self.title.setText(title)

        if QTVERSION < '4.0.0':
            self.detList= qt.QListBox(self)
            self.detList.setSelectionMode(qt.QListBox.Multi)

            layout.addWidget(self.title, 0, 0, qt.Qt.AlignCenter)
            layout.addRowSpacing(0, 40)
            layout.addWidget(self.detList, 1, 0)
        else:
            self.detList= qt.QListWidget(self)
            self.detList.setSelectionMode(qt.QAbstractItemView.ExtendedSelection)

            layout.addWidget(self.title, 0, 0)
            layout.setAlignment(self.title, qt.Qt.AlignCenter)
            ##layout.addRowSpacing(0, 40)
            if DEBUG:
                print("row spacing")
            layout.addWidget(self.detList, 1, 0)

    def setTitle(self, title):
        self.title.setText("%s"%title)

    def setInfo(self, info):
        self.setDataSize(info["rows"], info["cols"], info.get("Detectors", None))
        self.setTitle(info["Key"])

    def setDataSize(self, rows, cols, dets=None):
        self.rows= rows
        self.cols= cols

        if dets is None or (len(dets)!=(rows-1)):
            dets= range(self.rows)

        self.detList.clear()
        if QTVERSION < '4.0.0':
            for idx in range(1, self.rows):
                self.detList.insertItem("Detector %d"%dets[idx-1])
        else:
            for idx in range(1, self.rows):
                self.detList.addItem("Detector %d"%dets[idx-1])

    def getSelection(self):
        selection= []
        if QTVERSION < '4.0.0':
            ylist= [ (idx+1) for idx in range(self.detList.count()) if self.detList.isSelected(idx) ]
        else:
            itemlist = self.detList.selectedItems()
            ylist = [int(str(item.text()).split()[-1]) for item in itemlist]
        for y in ylist:
            selection.append({"plot":"XIA", "x":0, "y":y})
        return selection

class SPS_ImageArray(qt.QWidget):
    def __init__(self, parent=None, name="SPS_ImageArray", fl=0, title="MCA", size=(0,8192)):
        if QTVERSION < '4.0.0':
            qt.QWidget.__init__(self, parent, name, fl)
            layout= qt.QGridLayout(self, 5, 2)
        else:
            qt.QWidget.__init__(self, parent)
            self.setWindowTitle(name)
            layout= QGridLayout(self)
        layout.setMargin(5)
        layout.setSpacing(0)

        self.title= qt.QLabel(self)
        font= self.title.font()
        font.setBold(1)
        self.title.setFont(font)
        if QTVERSION < '4.0.0':
            layout.addMultiCellWidget(self.title, 0, 0, 0, 1, qt.Qt.AlignCenter)
            layout.addRowSpacing(0, 40)
        else:
            #layout.addMultiCellWidget(self.title, 0, 0, 0, 1, qt.Qt.AlignCenter)
            layout.addWidget(self.title, 0, 0)
            layout.setAlignment(self.title, qt.Qt.AlignCenter)
        self.setTitle(title)
        
    def setInfo(self, info):
        self.setDataSize(info["rows"], info["cols"])
        self.setTitle(info["Key"])

    def setDataSize(self,rows,cols,selsize=None):
        self.rows= rows
        self.cols= cols

    def setTitle(self, title):
        self.title.setText("%s"%title)

    def getSelection(self):
        #get selected counter keys
        sel_list = []
        sel = {}
        sel['selection'] = {}
        sel['plot'] = 'image'
        sel['scanselection']  = False
        sel['selection'] = None
        sel_list.append(sel)
        return sel_list
 
class SPS_StandardArray(qt.QWidget):
    def __init__(self, parent=None, name="SPS_StandardArray", fl=0, rows=0, cols=0):
        if QTVERSION < '4.0.0':
            qt.QWidget.__init__(self, parent, name, fl)
            layout= qt.QGridLayout(self, 4, 2)
        else:
            qt.QWidget.__init__(self, parent)
            layout= qt.QGridLayout(self)
        layout.setMargin(5)
        layout.setSpacing(0)

        plab= qt.QLabel("Plot", self)
        xlab= qt.QLabel("X :", self)
        ylab= qt.QLabel("Y :", self)

        layout.addWidget(plab, 0, 0, qt.Qt.AlignRight)
        layout.addWidget(xlab, 1, 0, qt.Qt.AlignRight)
        layout.addWidget(ylab, 2, 0, qt.Qt.AlignRight|qt.Qt.AlignTop)

        self.plotCombo= qt.QComboBox(self)
        self.plotCombo.setEditable(0)
        if QTVERSION < '4.0.0':
            self.plotCombo.insertItem("Rows")
            self.plotCombo.insertItem("Columns")
        else:
            self.plotCombo.addItem("Rows")
            self.plotCombo.addItem("Columns")

        self.xCombo= qt.QComboBox(self)
        self.xCombo.setEditable(0)

        if QTVERSION < '4.0.0':
            self.yList= qt.QListBox(self)
            self.yList.setSelectionMode(qt.QListBox.Multi)
        else:
            self.yList= qt.QListWidget(self)
            self.yList.setSelectionMode(qt.QAbstractItemView.ExtendedSelection)

        layout.addWidget(self.plotCombo, 0, 1)
        layout.addWidget(self.xCombo, 1, 1)
        layout.addWidget(self.yList, 2, 1)

        self.connect(self.plotCombo, qt.SIGNAL("activated(int)"), self.__plotChanged)

        self.setDataSize(rows, cols)

    def setDataSize(self, rows, cols):
        self.rows= rows
        self.cols= cols

        idx= self.cols<=self.rows
        if QTVERSION < '4.0.0':
            self.plotCombo.setCurrentItem(idx)
        else:
            self.plotCombo.setCurrentIndex(idx)
        self.__plotChanged(idx)

    def __plotChanged(self, index):
        if index==1:
            txt= "Column"
            val= self.cols
        else:
            txt= "Row"
            val= self.rows
        self.xCombo.clear()
        if QTVERSION < '4.0.0':
            self.xCombo.insertItem("Array Index")
            self.yList.clear()
            for x in range(val):
                self.xCombo.insertItem("%s %d"%(txt,x))
                self.yList.insertItem("%s %d"%(txt,x))
            if val==2:
                self.xCombo.setCurrentItem(0)
                self.__xChanged(0)
        else:
            self.xCombo.addItem("Array Index")
            self.yList.clear()
            for x in range(val):
                self.xCombo.addItem("%s %d"%(txt,x))
                self.yList.addItem("%s %d"%(txt,x))
            if val==2:
                self.xCombo.setCurrentIndex(0)
                self.__xChanged(0)

    def __xChanged(self, index):
        pass

    def getSelection(self):
        selection= []
        if QTVERSION < '4.0.0':
            idx= self.plotCombo.currentItem()
        else:
            idx= self.plotCombo.currentIndex()
        if idx==1: plot= "cols"
        else: plot= "rows"

        if QTVERSION < '4.0.0':
            idx= self.xCombo.currentItem()
        else:
            idx= self.xCombo.currentIndex()
        if idx==0: x= None
        else: x= idx-1

        if QTVERSION < '4.0.0':
            ylist= [ idx for idx in range(self.yList.count()) if self.yList.isSelected(idx) ]
        else:
            itemlist = self.yList.selectedItems()
            ylist = [int(str(item.text()).split()[-1]) for item in itemlist]
        for y in ylist:
            selection.append({"plot":plot, "x":x, "y":y})
        return selection


class QSpsWidget(qt.QWidget):
    HiddenArrays= ["MCA_DATA_PARAM", "XIA_STAT", "XIA_DET"]
    WidgetArrays= {"scan":SPSScanArrayWidget, 
                   "xia": SPSXiaArrayWidget, 
                   "mca": SPSMcaArrayWidget, 
                   "array": SPS_StandardArray,
                   "image": SPS_ImageArray,
                   "frames_mca":SPSFramesMcaWidget,
                   "frames_image":qt.QWidget,
                   "empty": qt.QWidget}
    TypeArrays= {"MCA_DATA": "mca", "XIA_PLOT": "mca",
                 "XIA_DATA": "xia", "XIA_BASELINE":"xia",
                 "SCAN_D": "scan", "image_data":"image" }

    def __init__(self, parent=None, name="SPSSelector", fl=0):
        if QTVERSION < '4.0.0':
            qt.QWidget.__init__(self, parent, name, fl)
        else:
            qt.QWidget.__init__(self, parent)

        self.dataSource= None

        self.data= None
        self.currentSpec= None
        self.currentArray= None
        self.selection= None
        self.openFile = self.refreshSpecList

        self.selectPixmap= qt.QPixmap(icons.selected)
        self.unselectPixamp= qt.QPixmap(icons.unselected)

        mainLayout= qt.QVBoxLayout(self)

        # --- spec name selection
        specWidget= qt.QWidget(self)
        self.specCombo= qt.QComboBox(specWidget)
        self.specCombo.setEditable(0)
        if QTVERSION < '4.0.0':
            self.reload= qt.QIconSet(qt.QPixmap(icons.reload))
            refreshButton= qt.QToolButton(specWidget)
            refreshButton.setIconSet(self.reload)
            self.closeIcon= qt.QIconSet(qt.QPixmap(icons.fileclose))
            closeButton= qt.QToolButton(specWidget)
            closeButton.setIconSet(self.closeIcon)
        else:
            self.reload= qt.QIcon(qt.QPixmap(icons.reload))
            refreshButton= qt.QToolButton(specWidget)
            refreshButton.setIcon(self.reload)
            self.closeIcon= qt.QIcon(qt.QPixmap(icons.fileclose))
            closeButton= qt.QToolButton(specWidget)
            closeButton.setIcon(self.closeIcon)
        refreshButton.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Minimum))
        closeButton.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Minimum))
        specLayout= qt.QHBoxLayout(specWidget)
        specLayout.addWidget(self.specCombo)
        specLayout.addWidget(refreshButton)
        specLayout.addWidget(closeButton)

        self.connect(refreshButton, qt.SIGNAL("clicked()"), self.refreshSpecList)
        self.connect(closeButton,qt.SIGNAL("clicked()"), self.closeCurrentSpec)
        self.connect(self.specCombo, qt.SIGNAL("activated(const QString &)"), 
                    self.refreshArrayList)

        # --- splitter
        self.splitter= qt.QSplitter(self)
        if QTVERSION < '4.0.0':
            self.splitter.setOrientation(qt.QSplitter.Vertical)
        else:
            self.splitter.setOrientation(qt.Qt.Vertical)

        # --- shm array list
        if QTVERSION < '4.0.0':
            self.arrayList= qt.QListView(self.splitter, "ShmArrayList")
            self.arrayList.addColumn("")
            self.arrayList.addColumn("Array Name")
            self.arrayList.addColumn("Rows")
            self.arrayList.addColumn("Cols")
            self.arrayList.setSorting(-1)
            self.arrayList.header().setClickEnabled(0,-1)
            self.arrayList.setAllColumnsShowFocus(1)
            self.arrayList.setSelectionMode(qt.QListView.Single)
            self.connect(self.arrayList,
                         qt.SIGNAL("selectionChanged()"),
                         self.__arraySelection)
        else:
            self.arrayList= qt.QTreeWidget(self.splitter)
            labels = ["","Array Name", "Rows","Cols"]
            self.arrayList.setColumnCount(len(labels))
            self.arrayList.setHeaderLabels(labels)
            self.arrayList.setSelectionMode(qt.QAbstractItemView.SingleSelection)
            self.connect(self.arrayList,
                         qt.SIGNAL("itemSelectionChanged()"),
                         self.__arraySelection)

        # --- array parameter
        if QTVERSION < '4.0.0':
            self.paramIndex= {}
            self.paramWidget= qt.QWidgetStack(self.splitter)
            for wtype in self.WidgetArrays.keys():
                widclass= self.WidgetArrays[wtype]
                wid= widclass(self.paramWidget)
                self.paramWidget.addWidget(wid)
                self.paramIndex[wtype]= self.paramWidget.id(wid)
        else:
            self.paramIndex= {}
            self.paramWidget= qt.QStackedWidget(self.splitter)
            for wtype in self.WidgetArrays.keys():
                widclass= self.WidgetArrays[wtype]
                wid= widclass(self.paramWidget)
                self.paramWidget.addWidget(wid)
                self.paramIndex[wtype]= self.paramWidget.indexOf(wid)

        # --- command buttons
        butWidget= qt.QWidget(self)
        butWidget.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Minimum,
                                               qt.QSizePolicy.Minimum))
        addButton= qt.QPushButton("Add", butWidget)
        removeButton= qt.QPushButton("Remove", butWidget)
        replaceButton= qt.QPushButton("Replace", butWidget)

        butLayout= qt.QHBoxLayout(butWidget)
        butLayout.addWidget(addButton)
        butLayout.addWidget(removeButton)
        butLayout.addWidget(replaceButton)
        butLayout.setMargin(5)

        self.connect(addButton, qt.SIGNAL("clicked()"), self.__addClicked)
        self.connect(replaceButton, qt.SIGNAL("clicked()"), self.__replaceClicked)
        self.connect(removeButton, qt.SIGNAL("clicked()"), self.__removeClicked)

        # --- main layout
        mainLayout.setMargin(5)
        mainLayout.setSpacing(5)
        mainLayout.addWidget(specWidget)
        if __name__ != "__main__":
            specWidget.hide()
        mainLayout.addWidget(self.splitter)
        mainLayout.addWidget(butWidget)

    def setData(self,data=None):
        if DEBUG:
            print("setData(self, data) called")
            print("spec data = ",data)
        self.data= data
        self.refreshSpecList()
        self.refreshDataSelection()

    def setDataSource(self,data=None):
        if DEBUG:
            print("setDataSource(self, data) called")
            print("spec data = ",data)
        self.data= data
        self.refreshSpecList()
        self.refreshDataSelection()
        if data is None:
            self.arrayList.clear()
        else:
            self.refreshArrayList(data.sourceName)

    def refreshSpecList(self):
        speclist= sps.getspeclist()
        if self.specCombo.count():
            selected= str(self.specCombo.currentText())
        else:    selected= None
        self.specCombo.clear()
        if len(speclist):
            for spec in speclist:
                if QTVERSION < '4.0.0':
                    self.specCombo.insertItem(spec)
                else:
                    self.specCombo.addItem(spec)
            self.selectSpec(selected or speclist[0])

    def selectSpec(self, specname=None):
        if QTVERSION < '4.0.0':
            for idx in range(self.specCombo.count()):
                if str(self.specCombo.text(idx))==specname:
                    self.specCombo.setCurrentItem(idx)
        else:
            for idx in range(self.specCombo.count()):
                if str(self.specCombo.itemText(idx))==specname:
                    self.specCombo.setCurrentIndex(idx)

    def __getCurrentSpec(self):
        if self.specCombo.count():
            return str(self.specCombo.currentText())
        else:    return None

    def refreshDataSelection(self, source=None):
        spec= self.__getCurrentSpec()
        if spec is not None and self.dataSource is not None:
            arraylist= self.dataSource.GetDataList(spec)
            item= self.arrayList.firstChild()
            while item is not None:
                name= str(item.text(1))
                if name in arraylist:    item.setPixmap(0, self.selectPixmap)
                else:            item.setPixmap(0, self.unselectPixmap)
            item= item.nextSibling()

    def closeCurrentSpec(self):
        spec= self.__getCurrentSpec()
        if spec is not None and self.dataSource is not None:
            arraylist= self.DataSource.GetDataList(spec)
            if len(arraylist):
                msg= "%d spectrums are linked to that SPEC source.\n"%(len(arraylist))
                msg+= "Do you really want to delete all these spectrums ??"
                ans= qt.QMessageBox.information(self, "Remove Spec Shared %s"%spec, msg, \
                        qt.QMessageBox.No, qt.QMessageBox.Yes)
                if ans.qt.QMessageBox.Yes:
                    self.dataSource.RemoveData(spec)

    def refreshArrayList(self,qstring):
        self.arrayList.clear()
        #spec= self.__getCurrentSpec()
        self.currentSpec = str(qstring)
        spec = self.currentSpec
        if spec is not None:
            arraylist= {}
            for array in sps.getarraylist(spec):
                if array not in self.HiddenArrays:
                    info= sps.getarrayinfo(spec, array)
                    rows= info[0]
                    cols= info[1]
                    type= info[2]
                    flag= info[3]
                    if DEBUG:
                        print(" array = ", array)
                        print(" flag = ", flag)
                        print(" type = ", type)
                    if type!=sps.STRING:
                        if (flag & sps.TAG_ARRAY) == sps.TAG_ARRAY:
                            arraylist[array]= (rows, cols)
            if len(arraylist.keys()):
                arrayorder= arraylist.keys()
                arrayorder.sort()
                arrayorder.reverse()
                if QTVERSION < '4.0.0':
                    for name in arrayorder:
                        self.arrayList.insertItem(qt.QListViewItem(self.arrayList, 
                            "", name, str(arraylist[name][0]), str(arraylist[name][1])))
                else:
                    for name in arrayorder:
                        item = (qt.QTreeWidgetItem(self.arrayList, 
                            ["", name, str(arraylist[name][0]), str(arraylist[name][1])]))
                self.refreshDataSelection()
            
        self.__getParamWidget("empty")

    def __arraySelection(self):
        if QTVERSION < '4.0.0':
            item= self.arrayList.selectedItem()
            if item is not None:
                self.currentArray= str(item.text(1))
            else:
                #click on empty space
                return
        else:
            item= self.arrayList.selectedItems()
            if len(item):
                item = item[0]
                self.currentArray= str(item.text(1))
            else:
                #click on empty space
                return
        #self.data.SetSource(self.currentSpec)
        #self.data.LoadSource(self.currentArray)
        info= self.data.getKeyInfo(self.currentArray)
        wid= None
        atype = None
        if 0 and ((info['flag'] & sps.TAG_FRAMES) == sps.TAG_FRAMES) and\
           ((info['flag'] & sps.TAG_IMAGE) == sps.TAG_IMAGE):
            atype = "frames_image"
        elif ((info['flag'] & sps.TAG_FRAMES) == sps.TAG_FRAMES) and\
           ((info['flag'] & sps.TAG_MCA) == sps.TAG_MCA):
            atype = "frames_mca"
        elif (info['flag'] & sps.TAG_IMAGE) == sps.TAG_IMAGE:
            atype = "image"
        elif (info['flag'] & sps.TAG_MCA)  == sps.TAG_MCA:
            atype = "mca"
        elif (info['flag'] & sps.TAG_SCAN) == sps.TAG_SCAN:
            atype = "scan"
        elif (info['rows'] > 100) and (info['cols'] > 100):
            atype = "image"
        if atype is not None:
            wid= self.__getParamWidget(atype)
            wid.setInfo(info)
            if hasattr(wid, "setDataSource"):
                wid.setDataSource(self.data)
        else:
            for (array, atype) in self.TypeArrays.items():
                if self.currentArray[0:len(array)]==array:
                    wid= self.__getParamWidget(atype)
                    wid.setInfo(info)
                    if hasattr(wid, "setDataSource"):
                        wid.setDataSource(self.data)
                    break
        if wid is None:
            arrayType = "ARRAY"
            wid= self.__getParamWidget("array")
            wid.setDataSize(info["rows"], info["cols"])
        else:
            arrayType = atype.upper()

        #emit a selection to inform about the change
        ddict = {}
        ddict['SourceName'] = self.data.sourceName
        ddict['SourceType'] = self.data.sourceType
        ddict['event'] = "SelectionTypeChanged"
        if arrayType in ["IMAGE"]:
            ddict['SelectionType'] = self.data.sourceName +" "+self.currentArray
        elif arrayType in ["MCA", "XIA"]:
            ddict['SelectionType'] = "MCA"
        elif arrayType in ["ARRAY"]:
            ddict['SelectionType'] = "MCA"
        else:
            ddict['SelectionType'] = arrayType
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL("otherSignals"), (ddict,))
        else:
            self.emit(qt.SIGNAL("otherSignals"), ddict)

    def __getParamWidget(self, widtype):
        if QTVERSION < '4.0.0':
            wid= self.paramWidget.visibleWidget()
            if self.paramWidget.id(wid)!=self.paramIndex[widtype]:
                self.paramWidget.raiseWidget(self.paramIndex[widtype])
                wid= self.paramWidget.visibleWidget()
        else:
            wid= self.paramWidget.currentWidget()
            if self.paramWidget.indexOf(wid) != self.paramIndex[widtype]:
                self.paramWidget.setCurrentIndex(self.paramIndex[widtype])
                wid = self.paramWidget.currentWidget()
        return wid

    def __replaceClicked(self):
        if DEBUG:
            print("replace clicked")
        selkeys= self.__getSelectedKeys()
        if len(selkeys):
            #self.eh.event(self.repEvent, selkeys)
            if DEBUG:
                print("Replace event")
            sel = {}
            sel['SourceType'] = SOURCE_TYPE
            sellistsignal = []
            for selection in selkeys:
                selsignal = {}
                selsignal['SourceType'] = self.data.sourceType
                selsignal['SourceName'] = self.data.sourceName
                selsignal['selection'] = None
                selsignal['Key'] = selection['Key']
                if not sel.has_key('SourceName'):
                    sel['SourceName'] = selection['SourceName']
                arrayname = selection['Key']
                if not sel.has_key('Key'):
                    sel['Key'] = selection['Key']
                if not sel.has_key(arrayname):
                    sel[arrayname] = {'rows':[],'cols':[]}
                if selection['plot'] == 'cols':
                     selsignal["selection"] = {"cols":{}}
                     selsignal["selection"]["cols"] = {}
                     selsignal["selection"]["cols"]["x"] = [selection['x']]
                     selsignal["selection"]["cols"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".c.%d" % int(selection['y'])
                     sel[arrayname]['cols'].append({'x':selection['x'],'y':selection['y']})
                elif selection['plot'] == 'rows':
                     sel[arrayname]['rows'].append({'x':selection['x'],'y':selection['y']})                              
                     selsignal["selection"] = {"rows":{}}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".r.%d" % int(selection['y'])
                elif selection['plot'] == 'XIA':
                     sel[arrayname]['rows'].append({'x':selection['x'],
                                            'y':selection['y']})                              
                     #selsignal["Key"] += ".r.%d" % int(selection['y'])
                     selsignal["selection"] = {"rows":{}, "XIA":True}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        " #%02d" % int(selection['y'])

                elif selection['plot'] == 'scan':
                     if SCAN_MODE:
                         #sel[arrayname]['cols'].append({'x':selection['selection']['x'][0],
                         #                               'y':selection['selection']['y'][0]})
                         selsignal["selection"] = selection['selection']
                         selsignal['legend'] = self.data.sourceName + " " + \
                                              selsignal['Key']
                         selsignal['scanselection'] = True
                         #print "cheeting"
                         #selsignal['scanselection'] = False
                     else:
                         #do it as a col
                         sel[arrayname]['cols'].append({'x':selection['selection']['x'],
                                                        'y':selection['selection']['y']})
                         selsignal["selection"] = {'cols':{}}
                         selsignal["selection"]["cols"]["x"] = selection['selection']['x']
                         selsignal["selection"]["cols"]["y"] = selection['selection']['y']
                         selsignal['legend'] = self.data.sourceName + " " + \
                                               selsignal['Key']
                         selsignal['scanselection'] = True
                         #print "cheeting"
                         #selsignal['scanselection'] = False
                         
                elif selection['plot'] == 'image':
                    selsignal["selection"] = selection['selection']   
                    selsignal['legend'] = self.data.sourceName + " " + \
                                              selsignal['Key']
                    selsignal['scanselection']  = False
                    selsignal['imageselection'] = True
                sellistsignal.append(selsignal)
            self.setSelected([sel],reset=1)
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL("replaceSelection"), (sellistsignal,))
            else:
                self.emit(qt.SIGNAL("replaceSelection"), sellistsignal)

    def __addClicked(self):
        if DEBUG:
            print("select clicked")
        selkeys= self.__getSelectedKeys()
        if DEBUG:
            print("selected keys = ",selkeys )
        if len(selkeys):
            #self.eh.event(self.addEvent, selkeys)
            if DEBUG:
                print("Select event")
            sel = {}
            sel['SourceType'] = SOURCE_TYPE 
            sellistsignal = []           
            for selection in selkeys:
                selsignal = {}
                selsignal['SourceType'] = self.data.sourceType
                selsignal['SourceName'] = self.data.sourceName
                selsignal['selection'] = None
                selsignal['Key'] = selection['Key']
                if not sel.has_key('SourceName'):
                    sel['SourceName'] = selection['SourceName']
                arrayname = selection['Key']
                if not sel.has_key('Key'):
                    sel['Key'] = selection['Key']
                if not sel.has_key(arrayname):
                    sel[arrayname] = {'rows':[],'cols':[]}
                if selection['plot'] == 'XIA':
                     sel[arrayname]['rows'].append({'x':selection['x'],
                                            'y':selection['y']})                              
                     #selsignal["Key"] += ".r.%d" % int(selection['y'])
                     selsignal["selection"] = {"rows":{}, "XIA":True}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        " #%02d" % int(selection['y'])
                elif selection['plot'] == 'cols':
                     sel[arrayname]['cols'].append({'x':selection['x'],
                                                    'y':selection['y']})
                     #selsignal["Key"] += ".c.%d" % int(selection['y'])
                     selsignal["selection"] = {"cols":{}}
                     selsignal["selection"]["cols"] = {}
                     selsignal["selection"]["cols"]["x"] = [selection['x']]
                     selsignal["selection"]["cols"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".c.%d" % int(selection['y'])
                elif selection['plot'] == 'rows':
                     sel[arrayname]['rows'].append({'x':selection['x'],
                                            'y':selection['y']})                              
                     #selsignal["Key"] += ".r.%d" % int(selection['y'])
                     selsignal["selection"] = {"rows":{}}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".r.%d" % int(selection['y'])
                elif selection['plot'] == 'scan':
                     if SCAN_MODE:
                         #sel[arrayname]['cols'].append({'x':selection['selection']['x'][0],
                         #                               'y':selection['selection']['y'][0]})
                         selsignal["selection"] = selection['selection']
                         selsignal['legend'] = self.data.sourceName + " " + \
                                              selsignal['Key']
                         selsignal['scanselection'] = True
                         #print "cheeting"
                         #selsignal['scanselection'] = False
                     else:
                         #do it as a col
                         sel[arrayname]['cols'].append({'x':selection['selection']['x'],
                                                        'y':selection['selection']['y']})
                         selsignal["selection"] = {'cols':{}}
                         selsignal["selection"]["cols"]["x"] = selection['selection']['x']
                         selsignal["selection"]["cols"]["y"] = selection['selection']['y']
                         selsignal['legend'] = self.data.sourceName + " " + \
                                               selsignal['Key']
                         selsignal['scanselection'] = True
                         #print "cheeting"
                         #selsignal['scanselection'] = False
                elif selection['plot'] == 'image':
                    selsignal["selection"] = selection['selection']   
                    selsignal['legend'] = self.data.sourceName + " " + \
                                              selsignal['Key']
                    selsignal['scanselection']  = False
                    selsignal['imageselection'] = True

                sellistsignal.append(selsignal)
            if self.selection is None: 
                self.setSelected([sel],reset=1)
            else:
                self.setSelected([sel],reset=0)
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL("addSelection"), (sellistsignal,))
            else:
                self.emit(qt.SIGNAL("addSelection"),  sellistsignal)
            
    def __getSelectedKeys(self):
        selkeys= []
        if QTVERSION < '4.0.0':
            parwid= self.paramWidget.visibleWidget()
        else:
            parwid= self.paramWidget.currentWidget()
        if self.currentArray is not None:
            for sel in parwid.getSelection():
                sel["SourceName"]= self.currentSpec
                sel['SourceType'] = SOURCE_TYPE            
                sel["Key"]= self.currentArray
                selkeys.append(sel)
        return selkeys

    def __removeClicked(self):
        if DEBUG:
            print("remove clicked")
        selkeys= self.__getSelectedKeys()
        if len(selkeys):
            #self.eh.event(self.delEvent, selkeys)
            if DEBUG:
                print("Remove Event")
                print("self.selection before = ",self.selection)
            returnedselection=[]
            sellistsignal = []           
            for selection in selkeys:
                selsignal = {}
                selsignal['SourceType'] = self.data.sourceType
                selsignal['SourceName'] = self.data.sourceName
                selsignal['selection'] = None
                selsignal['Key'] = selection['Key']
                sel = {}
                sel['SourceName'] = selection['SourceName']
                sel['SourceType'] = SOURCE_TYPE            
                sel['Key'] = selection['Key']
                arrayname = selection['Key']
                sel[arrayname] = {'rows':[],'cols':[]}
                if selection['plot'] == 'cols':
                     sel[arrayname]['cols'].append({'x':selection['x'],'y':selection['y']})
                     selsignal["selection"] = {"cols":{}}
                     selsignal["selection"]["cols"] = {}
                     selsignal["selection"]["cols"]["x"] = [selection['x']]
                     selsignal["selection"]["cols"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".c.%d" % int(selection['y'])
                elif selection['plot'] == 'rows':
                     sel[arrayname]['rows'].append({'x':selection['x'],'y':selection['y']})
                     selsignal["selection"] = {"rows":{}}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        ".r.%d" % int(selection['y'])
                elif selection['plot'] == 'XIA':
                     sel[arrayname]['rows'].append({'x':selection['x'],
                                            'y':selection['y']})                              
                     #selsignal["Key"] += ".r.%d" % int(selection['y'])
                     selsignal["selection"] = {"rows":{}, "XIA":True}
                     selsignal["selection"]["rows"] = {}
                     selsignal["selection"]["rows"]["x"] = [selection['x']]
                     selsignal["selection"]["rows"]["y"] = [selection['y']]
                     if type(self.data.sourceName) == type(''):
                        sname = [self.data.sourceName]
                     else:
                        sname = self.data.sourceName
                     selsignal["legend"] = sname[0] +\
                                        " "+selsignal['Key']+\
                                        " #%02d" % int(selection['y'])
                elif selection['plot'] == 'scan':
                     #sel[arrayname]['cols'].append({'x':selection['selection']['x'][0],
                     #                               'y':selection['selection']['y'][0]})
                     selsignal["selection"] = selection['selection']
                     selsignal['legend'] = self.data.sourceName + " " + \
                                          selsignal['Key']
                     selsignal['scanselection'] = True

                elif selection['plot'] == 'image':
                    selsignal["selection"] = selection['selection']   
                    selsignal['legend'] = self.data.sourceName + " " + \
                                              selsignal['Key']
                    selsignal['scanselection']  = False
                    selsignal['imageselection'] = True

                sellistsignal.append(selsignal)
                returnedselection.append(sel)
                if self.selection is not None:
                    if DEBUG:
                        print("step 1")
                    if self.selection.has_key(sel['SourceName']):
                        if DEBUG:
                            print("step 2")
                        if self.selection[sel['SourceName']].has_key(arrayname):
                            if DEBUG:
                                print("step 3")
                            if self.selection[sel['SourceName']][arrayname].has_key('rows'):
                                if DEBUG:
                                    print("step 4")
                                for couple in  sel[arrayname]['rows']:
                                    if couple in  self.selection[sel['SourceName']][arrayname]['rows']:
                                        index= self.selection[sel['SourceName']][arrayname]['rows'].index(couple)
                                        del self.selection[sel['SourceName']][arrayname]['rows'][index]  
                                for couple in  sel[arrayname]['cols']:
                                    if couple in  self.selection[sel['SourceName']][arrayname]['cols']:
                                        index= self.selection[sel['SourceName']][arrayname]['cols'].index(couple)
                                        del self.selection[sel['SourceName']][arrayname]['cols'][index]
                                seln = {}
                                seln['SourceName'] = sel['SourceName'] 
                                seln['SourceType'] = SOURCE_TYPE            
                                seln['Key']        = sel['Key']
                                seln[seln['Key']]  = self.selection[seln['SourceName']][seln['Key']]
                                self.setSelected([seln],reset=0)
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL("removeSelection"), (sellistsignal,))
            else:
                self.emit(qt.SIGNAL("removeSelection"), sellistsignal)
            
    def removeSelection(self,selection):
        if type(selection) != type([]):
            selection=[selection]
        for sel in selection:
                arrayname = sel['Key']                
                if self.selection is not None:
                    if DEBUG:
                        print("step 1")
                    if self.selection.has_key(sel['SourceName']):
                        if DEBUG:
                            print("step 2")
                        if self.selection[sel['SourceName']].has_key(arrayname):
                            if DEBUG:
                                print("step 3")
                            if self.selection[sel['SourceName']][arrayname].has_key('rows'):
                                if DEBUG:
                                    print("step 4")
                                for couple in  sel[arrayname]['rows']:
                                    if couple in  self.selection[sel['SourceName']][arrayname]['rows']:
                                        index= self.selection[sel['SourceName']][arrayname]['rows'].index(couple)
                                        del self.selection[sel['SourceName']][arrayname]['rows'][index]  
                                for couple in  sel[arrayname]['cols']:
                                    if couple in  self.selection[sel['SourceName']][arrayname]['cols']:
                                        index= self.selection[sel['SourceName']][arrayname]['cols'].index(couple)
                                        del self.selection[sel['SourceName']][arrayname]['cols'][index]
                                seln = {}
                                seln['SourceName'] = sel['SourceName'] 
                                seln['SourceType'] = SOURCE_TYPE            
                                seln['Key']        = sel['Key']
                                seln[seln['Key']]  = self.selection[seln['SourceName']][seln['Key']]
                                self.setSelected([seln],reset=0)
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL("removeSelection"), (selection,))
        else:
            self.emit(qt.SIGNAL("removeSelection"), (selection))
                             
    def setSelected(self,sellist,reset=1):
        if DEBUG:
            print("setSelected(self,sellist,reset=1) called")
            print("sellist = ",sellist)
            print("selection before = ",self.selection)
            print("reset = ",reset)
        if reset:
            self.selection = {}
        elif self.selection is None:
            self.selection = {}
        for sel in sellist:
            specname = sel['SourceName']
            #selkey is the array name what to do if multiple array names?
            if type(sel["Key"]) == type([]):
                selkey = sel["Key"][0]
            else:
                selkey = sel["Key"]
            if not self.selection.has_key(specname):
                self.selection[specname]= {}
            if not self.selection[specname].has_key(selkey):
                self.selection[specname][selkey] = {'rows':[],'cols':[]}
            if sel[selkey].has_key('rows'):
                for rowsel in sel[selkey]['rows']:
                    if rowsel not in self.selection[specname][selkey]['rows']:
                        self.selection[specname][selkey]['rows'].append(rowsel)   
            if sel[selkey].has_key('cols'):
                for rowsel in sel[selkey]['cols']:
                    if rowsel not in self.selection[specname][selkey]['cols']:
                        self.selection[specname][selkey]['cols'].append(rowsel)   
        if DEBUG:
            print("self.selection after = ",self.selection)
        self.__refreshSelection()

    def getSelection(self):
        """
        Give the dicionary of dictionaries as an easy to understand list of
        individual selections
        """
        selection = []
        if self.selection is None: return selection
        for sourcekey in self.selection.keys():
            for arraykey in self.selection[sourcekey].keys():
                sel={}
                sel['SourceName']   = sourcekey
                sel['SourceType']   = 'SPS'
                sel['Key']          = arraykey
                sel[arraykey]        = self.selection[sourcekey][arraykey]
                selection.append(sel)
        return selection

        
    def __refreshSelection(self):
        return
        if DEBUG:
            print("__refreshSelection(self) called")
            print(self.selection)
        if self.selection is not None:
            sel = self.selection.get(self.data.SourceName, {})
            selkeys = []
            for key in sel.keys():
                if (sel[key]['mca'] != []) or (sel[key]['scan']['Ycnt'] !=  []):
                    selkeys.append(key)
            if DEBUG:
                print("selected scans =",selkeys)
                print("but self.selection = ",self.selection)
                print("and self.selection.get(self.data.SourceName, {}) =",sel)
            self.scanList.markScanSelected(selkeys)
            scandict = sel.get(self.currentScan, {})
            if scandict.has_key('mca'):
                self.mcaTable.markMcaSelected(scandict['mca'])
            else:
                self.mcaTable.markMcaSelected([])
            if scandict.has_key('scan'):
                self.cntTable.markCntSelected(scandict['scan'])
            else:
                self.cntTable.markCntSelected({})
                
    def isSelectionUpdated(self,sellist):
        outsel = []
        if type(sellist) != type([]):
            sellist = [sellist]
        for dict in  sellist:
            #for dict in selection:
                if dict.has_key('SourceName'):
                    spec = dict['SourceName']
                    if dict.has_key('Key'):
                        shm  = dict['Key']
                        if dict.has_key(shm):
                            check = 0
                            rows = []
                            cols = []
                            if dict[shm].has_key('cols'):
                                cols = dict[shm]['cols']
                                if len(cols):
                                    check =  1
                            if dict[shm].has_key('rows'):
                                rows = dict[shm]['rows']
                                if len(rows):
                                    check =  1
                            if check and sps.specrunning(spec):
                                if sps.isupdated(spec,shm):
                                    outsel.append({'SourceName':spec,
                                                   'Key':shm,
                                                   shm:{'rows':rows,
                                                        'cols':cols},
                                                    'SourceType':'SPS'})
        return outsel                                    
                                        
                                        
        

def test():
    import sys
    if 0:
        import SPSLayer
    else:
        import QSpsDataSource

    a= qt.QApplication(sys.argv)
    a.connect(a, qt.SIGNAL("lastWindowClosed()"),a,qt.SLOT("quit()"))
    def repSelection(sel):
        print("replaceSelection", sel)
    def removeSelection(sel):
        print("removeSelection", sel)
    def addSelection(sel):
        print("addSelection", sel)

    w= QSpsWidget()
    if QTVERSION < '4.0.0':
        qt.QObject.connect(w,qt.PYSIGNAL("addSelection"),addSelection)
        qt.QObject.connect(w,qt.PYSIGNAL("removeSelection"),removeSelection)
        qt.QObject.connect(w,qt.PYSIGNAL("replaceSelection"),repSelection)
    else:
        qt.QObject.connect(w,qt.SIGNAL("addSelection"),addSelection)
        qt.QObject.connect(w,qt.SIGNAL("removeSelection"),removeSelection)
        qt.QObject.connect(w,qt.SIGNAL("replaceSelection"),repSelection)
    #d = QSpsDataSource.QSpsDataSource()
    #w.setData(d)
    """
    w.eh.register("addSelection", addSelection)
    w.eh.register("repSelection", repSelection)
    """
    w.show()
    if QTVERSION < '4.0.0':
        a.exec_loop()
    else:
        a.exec_()

if __name__=="__main__":
    test()