forked from mxcube/BlissFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Qt4_BaseComponents.py
1290 lines (1112 loc) · 38.4 KB
/
Qt4_BaseComponents.py
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
#
# Project: MXCuBE
# https://github.com/mxcube.
#
# This file is part of MXCuBE software.
#
# MXCuBE 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 3 of the License, or
# (at your option) any later version.
#
# MXCuBE 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 MXCuBE. If not, see <http://www.gnu.org/licenses/>.
import logging
import pprint
import types
import os
import sys
#import new
import time
import operator
import weakref
import gc
from PyQt4 import QtCore
from PyQt4 import QtGui
from HardwareRepository import HardwareRepository
from HardwareRepository.BaseHardwareObjects import HardwareObject
from BlissFramework.Utils import PropertyBag
from BlissFramework.Utils import Connectable
from BlissFramework.Utils import Qt4_ProcedureWidgets
from BlissFramework.Utils import Qt4_widget_colors
import BlissFramework
try:
from louie import dispatcher
from louie import saferef
except ImportError:
from pydispatch import dispatcher
from pydispatch import saferef
saferef.safe_ref = saferef.safeRef
_emitterCache = weakref.WeakKeyDictionary()
class _QObject(QtCore.QObject):
def __init__(self, *args, **kwargs):
"""
Descript. :
"""
QtCore.QObject.__init__(self, *args)
try:
self.__ho = weakref.ref(kwargs.get("ho"))
except:
self.__ho = None
def emitter(ob):
"""
Descript. : Returns a QObject surrogate for *ob*, to use in Qt signaling.
This function enables you to connect to and emit signals
from (almost) any python object with having to subclass QObject.
"""
if ob not in _emitterCache:
_emitterCache[ob] = _QObject(ho=ob)
return _emitterCache[ob]
class InstanceEventFilter(QtCore.QObject):
def eventFilter(self, w, e):
"""
Descript. :
"""
obj=w
while obj is not None:
if isinstance(obj,BlissWidget):
if isinstance(e, QtGui.QContextMenuEvent):
#if obj.shouldFilterEvent():
return True
elif isinstance(e, QtGui.QMouseEvent):
if e.button() == QtCore.Qt.RightButton:
return True
elif obj.shouldFilterEvent():
return True
elif isinstance(e, QtGui.QKeyEvent) or isinstance(e, QtGui.QFocusEvent):
if obj.shouldFilterEvent():
return True
return QtCore.QObject.eventFilter(self, w, e)
try:
obj = obj.parent()
except:
obj=None
return QtCore.QObject.eventFilter(self, w, e)
class WeakMethodBound:
def __init__(self , f):
"""
Descript. :
"""
self.f = weakref.ref(f.__func__)
self.c = weakref.ref(f.__self__)
def __call__(self , *args):
"""
Descript. :
"""
obj = self.c()
if obj is None:
return None
else:
f = self.f()
return f.__get__(obj)
class WeakMethodFree:
def __init__(self , f):
"""
Descript. :
"""
self.f = weakref.ref(f)
def __call__(self, *args):
"""
Descript. :
"""
return self.f()
def WeakMethod(f):
"""
Descript. :
"""
try:
f.__func__
except AttributeError :
return WeakMethodFree(f)
return WeakMethodBound(f)
class SignalSlotFilter:
def __init__(self, signal, slot, should_cache):
"""
Descript. :
"""
self.signal = signal
self.slot = WeakMethod(slot)
self.should_cache = should_cache
def __call__(self, *args):
"""
Descript. :
"""
if (BlissWidget._instanceMode == BlissWidget.INSTANCE_MODE_SLAVE and
BlissWidget._instanceMirror == BlissWidget.INSTANCE_MIRROR_PREVENT):
if self.should_cache:
BlissWidget._eventsCache[self.slot]=(time.time(), self.slot, args)
return
s = self.slot()
if s is not None:
s(*args)
class BlissWidget(QtGui.QFrame, Connectable.Connectable):
(INSTANCE_ROLE_UNKNOWN, INSTANCE_ROLE_SERVER, INSTANCE_ROLE_SERVERSTARTING,
INSTANCE_ROLE_CLIENT, INSTANCE_ROLE_CLIENTCONNECTING) = (0, 1, 2, 3, 4)
(INSTANCE_MODE_UNKNOWN, INSTANCE_MODE_MASTER, INSTANCE_MODE_SLAVE) = (0, 1, 2)
(INSTANCE_LOCATION_UNKNOWN, INSTANCE_LOCATION_LOCAL,
INSTANCE_LOCATION_INHOUSE,INSTANCE_LOCATION_INSITE,
INSTANCE_LOCATION_EXTERNAL) = (0,1,2,3,4)
(INSTANCE_USERID_UNKNOWN, INSTANCE_USERID_LOGGED, INSTANCE_USERID_INHOUSE,
INSTANCE_USERID_IMPERSONATE) = (0,1,2,3)
(INSTANCE_MIRROR_UNKNOWN, INSTANCE_MIRROR_ALLOW, INSTANCE_MIRROR_PREVENT) = (0,1,2)
_runMode = False
_instanceRole = INSTANCE_ROLE_UNKNOWN
_instanceMode = INSTANCE_MODE_UNKNOWN
_instanceLocation = INSTANCE_LOCATION_UNKNOWN
_instanceUserId = INSTANCE_USERID_UNKNOWN
_instanceMirror = INSTANCE_MIRROR_UNKNOWN
_filterInstalled = False
_eventsCache = {}
_menuBackgroundColor = None
_menuBar = None
_applicationEventFilter=InstanceEventFilter(None)
@staticmethod
def setRunMode(mode):
"""
Descript. :
"""
if mode:
BlissWidget._runMode = True
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
w.__run()
try:
w.set_expert_mode(False)
except:
logging.getLogger().exception("Could not set %s to user mode", w.name())
else:
BlissWidget._runMode = False
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
w.__stop()
try:
w.set_expert_mode(True)
except:
logging.getLogger().exception("Could not set %s to expert mode", w.name())
@staticmethod
def isRunning():
"""
Descript. :
"""
return BlissWidget._runMode
@staticmethod
def updateMenuBarColor(enable_checkbox=None):
"""
Descript. : Not a direct way how to change menubar color
it is now done by changing stylesheet
"""
color=None
if BlissWidget._menuBar is not None:
if BlissWidget._instanceMode == BlissWidget.INSTANCE_MODE_MASTER:
if BlissWidget._instanceUserId == BlissWidget.INSTANCE_USERID_IMPERSONATE:
color = "lightBlue"
else:
color = "rgb(204,255,204)"
elif BlissWidget._instanceMode == BlissWidget.INSTANCE_MODE_SLAVE:
if BlissWidget._instanceRole == BlissWidget.INSTANCE_ROLE_CLIENTCONNECTING:
color = "rgb(255,204,204)"
elif BlissWidget._instanceUserId == BlissWidget.INSTANCE_USERID_UNKNOWN:
color = "rgb(255, 165, 0)"
else:
color = "yellow"
if color is not None:
BlissWidget._menuBar.set_color(color)
@staticmethod
def setInstanceMode(mode):
"""
Descript. :
"""
BlissWidget._instanceMode = mode
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
try:
w._instanceModeChanged(mode)
except:
pass
if BlissWidget._instanceMode == BlissWidget.INSTANCE_MODE_MASTER:
if BlissWidget._filterInstalled:
QtGui.QApplication.instance().removeEventFilter(BlissWidget._applicationEventFilter)
BlissWidget._filterInstalled = False
BlissWidget.synchronizeWithCache() # why?
else:
if not BlissWidget._filterInstalled:
QtGui.QApplication.instance().installEventFilter(BlissWidget._applicationEventFilter)
BlissWidget._filterInstalled = True
BlissWidget.updateMenuBarColor(BlissWidget._instanceMode == \
BlissWidget.INSTANCE_MODE_MASTER)
def shouldFilterEvent(self):
"""
Descript. :
"""
if BlissWidget._instanceMode == BlissWidget.INSTANCE_MODE_MASTER:
return False
try:
allow_always = self['instanceAllowAlways']
except KeyError:
return False
if not allow_always:
try:
allow_connected = self['instanceAllowConnected']
except KeyError:
return False
connected = BlissWidget._instanceRole in (BlissWidget.INSTANCE_ROLE_SERVER,BlissWidget.INSTANCE_ROLE_CLIENT)
if allow_connected and connected:
return False
return True
return False
def connectGroupBox(self, widget, widget_name, master_sync):
"""
Descript. :
"""
brick_name = self.objectName()
self.connect(widget, QtCore.SIGNAL('toggled(bool)'), lambda \
s:BlissWidget.widgetGroupBoxToggled(brick_name, \
widget_name, master_sync,s))
def connectComboBox(self, widget, widget_name, master_sync):
"""
Descript. :
"""
brick_name = self.objectName()
self.connect(widget, QtCore.SIGNAL('activated(int)'),lambda \
i:BlissWidget.widgetComboBoxActivated(brick_name, \
widget_name, widget, master_sync, i))
def connectLineEdit(self, widget, widget_name, master_sync):
"""
Descript. :
"""
brick_name = self.objectName()
self.connect(widget, QtCore.SIGNAL('textChanged(const QString &)'), lambda \
t:BlissWidget.widgetLineEditTextChanged(brick_name, widget_name, \
master_sync, t))
def connectSpinBox(self,widget,widget_name,master_sync):
"""
Descript. :
"""
brick_name = self.objectName()
self.connect(widget, QtCore.SIGNAL('editorTextChanged'), lambda \
t:BlissWidget.widgetSpinBoxTextChanged(brick_name, widget_name, \
master_sync, t))
def connectGenericWidget(self, widget, widget_name, master_sync):
"""
Descript. :
"""
brick_name = self.objectName()
self.connect(widget, QtCore.SIGNAL('widgetSynchronize'), lambda \
state:BlissWidget.widgetGenericChanged(brick_name, widget_name, \
master_sync, state))
def _instanceModeChanged(self,mode):
"""
Descript. :
"""
for widget, widget_name, master_sync in self._widgetEvents:
if isinstance(widget, QtGui.QGroupBox):
self.connectGroupBox(widget, widget_name, master_sync)
elif isinstance(widget,QtGui.QComboBox):
self.connectComboBox(widget, widget_name, master_sync)
elif isinstance(widget, QtGui.QLineEdit):
self.connectLineEdit(widget, widget_name, master_sync)
elif isinstance(widget, QtGui.QSpinBox):
self.connectSpinBox(widget, widget_name, master_sync)
else:
### verify if widget has the widgetSynchronize method!!!
self.connectGenericWidget(widget, widget_name, master_sync)
self._widgetEvents = []
if self.shouldFilterEvent():
self.setCursor(QtGui.QCursor(QtCore.Qt.ForbiddenCursor))
else:
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
self.instanceModeChanged(mode)
def instanceModeChanged(self, mode):
"""
Descript. :
"""
pass
@staticmethod
def isInstanceModeMaster():
"""
Descript. :
"""
return BlissWidget._instanceMode==BlissWidget.INSTANCE_MODE_MASTER
@staticmethod
def isInstanceModeSlave():
"""
Descript. :
"""
return BlissWidget._instanceMode==BlissWidget.INSTANCE_MODE_SLAVE
@staticmethod
def isInstanceRoleUnknown():
"""
Descript. :
"""
return BlissWidget._instanceRole==BlissWidget.INSTANCE_ROLE_UNKNOWN
@staticmethod
def isInstanceRoleClient():
"""
Descript. :
"""
return BlissWidget._instanceRole==BlissWidget.INSTANCE_ROLE_CLIENT
@staticmethod
def isInstanceRoleServer():
"""
Descript. :
"""
return BlissWidget._instanceRole==BlissWidget.INSTANCE_ROLE_SERVER
@staticmethod
def isInstanceUserIdUnknown():
"""
Descript. :
"""
return BlissWidget._instanceUserId==BlissWidget.INSTANCE_USERID_UNKNOWN
@staticmethod
def isInstanceUserIdLogged():
"""
Descript. :
"""
return BlissWidget._instanceUserId==BlissWidget.INSTANCE_USERID_LOGGED
@staticmethod
def isInstanceUserIdInhouse():
"""
Descript. :
"""
return BlissWidget._instanceUserId==BlissWidget.INSTANCE_USERID_INHOUSE
@staticmethod
def setInstanceRole(role):
"""
Descript. :
"""
if role==BlissWidget._instanceRole:
return
BlissWidget._instanceRole = role
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
#try:
w.instanceRoleChanged(role)
#except:
# pass
@staticmethod
def setInstanceLocation(location):
"""
Descript. :
"""
if location==BlissWidget._instanceLocation:
return
BlissWidget._instanceLocation = location
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
#try:
w.instanceLocationChanged(location)
#except:
# pass
@staticmethod
def setInstanceUserId(user_id):
"""
Descript. :
"""
if user_id==BlissWidget._instanceUserId:
return
BlissWidget._instanceUserId = user_id
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
#try:
w.instanceUserIdChanged(user_id)
#except:
# pass
BlissWidget.updateMenuBarColor()
@staticmethod
def setInstanceMirror(mirror):
"""
Descript. :
"""
if mirror==BlissWidget._instanceMirror:
return
BlissWidget._instanceMirror = mirror
if mirror==BlissWidget.INSTANCE_MIRROR_ALLOW:
BlissWidget.synchronizeWithCache()
for w in QtGui.QApplication.allWidgets():
if isinstance(w, BlissWidget):
#try:
w.instanceMirrorChanged(mirror)
#except:
# pass
def instanceMirrorChanged(self,mirror):
"""
Descript. :
"""
pass
def instanceLocationChanged(self,location):
"""
Descript. :
"""
pass
@staticmethod
def isInstanceLocationUnknown():
"""
Descript. :
"""
return BlissWidget._instanceLocation==BlissWidget.INSTANCE_LOCATION_UNKNOWN
@staticmethod
def isInstanceLocationLocal():
"""
Descript. :
"""
return BlissWidget._instanceLocation==BlissWidget.INSTANCE_LOCATION_LOCAL
@staticmethod
def isInstanceMirrorAllow():
"""
Descript. :
"""
return BlissWidget._instanceMirror==BlissWidget.INSTANCE_MIRROR_ALLOW
def instanceUserIdChanged(self,user_id):
"""
Descript. :
"""
pass
def instanceRoleChanged(self,role):
"""
Descript. :
"""
pass
@staticmethod
def updateWhatsThis():
"""
Descript. :
"""
for widget in QtGui.QApplication.allWidgets():
if isinstance(widget, BlissWidget):
msg = "%s (%s)\n%s" % (widget.objectName(),
widget.__class__.__name__,
widget.getHardwareObjectsInfo())
widget.setWhatsThis(msg)
QtGui.QWhatsThis.enterWhatsThisMode()
@staticmethod
def updateWidget(brick_name,widget_name,method_name,method_args,master_sync):
"""
Descript. :
"""
#somehow active window is None
#TODO fix this
for widget in QtGui.QApplication.topLevelWidgets():
if hasattr(widget, "configuration"):
top_level_widget = widget
if not master_sync or BlissWidget._instanceMode==BlissWidget.INSTANCE_MODE_MASTER:
top_level_widget.emit(QtCore.SIGNAL('applicationBrickChanged'),
brick_name, widget_name, method_name, method_args, master_sync)
@staticmethod
def updateTabWidget(tab_name,tab_index):
"""
Descript. :
"""
if BlissWidget._instanceMode==BlissWidget.INSTANCE_MODE_MASTER:
#TODO fixt this, by removing if
if QtGui.QApplication.activeWindow():
QtGui.QApplication.activeWindow().emit(\
QtCore.SIGNAL('applicationTabChanged'),
tab_name, tab_index)
@staticmethod
def widgetGroupBoxToggled(brick_name,widget_name,master_sync,state):
"""
Descript. :
"""
BlissWidget.updateWidget(brick_name,widget_name,"setChecked",(state,),master_sync)
@staticmethod
def widgetComboBoxActivated(brick_name, widget_name,widget,master_sync,index):
"""
Descript. :
"""
lines=[]
if widget.editable():
for i in range(widget.count()):
lines.append(str(widget.text(i)))
BlissWidget.updateWidget(brick_name,widget_name,"activated",(index,lines),master_sync)
@staticmethod
def widgetLineEditTextChanged(brick_name,widget_name,master_sync,text):
"""
Descript. :
"""
BlissWidget.updateWidget(brick_name,widget_name,"setText",(str(text),),master_sync)
@staticmethod
def widgetSpinBoxTextChanged(brick_name,widget_name,master_sync,text):
"""
Descript. :
"""
BlissWidget.updateWidget(brick_name,widget_name,"setEditorText",(str(text),), master_sync)
@staticmethod
def widgetGenericChanged(brick_name,widget_name,master_sync,state):
"""
Descript. :
"""
BlissWidget.updateWidget(brick_name,widget_name,"widgetSynchronize",(state,),master_sync)
def instanceForwardEvents(self,widget_name,master_sync):
"""
Descript. :
"""
if widget_name=="":
widget=self
else:
widget=getattr(self, widget_name)
if isinstance(widget, QtGui.QComboBox):
#widget.activated = new.instancemethod(ComboBoxActivated,widget,widget.__class__)
widget.activated = ComboBoxActivated
elif isinstance(widget, QtGui.QSpinBox):
#widget.setEditorText = new.instancemethod(SpinBoxSetEditorText,widget,widget.__class__)
widget.setEditorText = SpinBoxSetEditorText
#widget.editorTextChanged = new.instancemethod(SpinBoxEditorTextChanged,widget,widget.__class__)
widget.editorTextChanged = SpinBoxEditorTextChanged
self.connect(widget.lineEdit(), QtCore.SIGNAL('textChanged(const QString &)'), widget.editorTextChanged)
self._widgetEvents.append((widget, widget_name, master_sync))
def instanceSynchronize(self,*args, **kwargs):
"""
Descript. :
"""
for widget_name in args:
self.instanceForwardEvents(widget_name, kwargs.get("master_sync", True))
@staticmethod
def shouldRunEvent():
"""
Descript. :
"""
return BlissWidget._instanceMirror==BlissWidget.INSTANCE_MIRROR_ALLOW
@staticmethod
def addEventToCache(timestamp,method,*args):
"""
Descript. :
"""
try:
m = WeakMethod(method)
except TypeError:
m = method
BlissWidget._eventsCache[m]=(timestamp, m, args)
@staticmethod
def synchronizeWithCache():
"""
Descript. :
"""
events=list(BlissWidget._eventsCache.values())
ordered_events=sorted(events,key=operator.itemgetter(0))
for event_timestamp,event_method,event_args in ordered_events:
try:
m = event_method()
if m is not None:
m(*event_args)
except:
pass
BlissWidget._eventsCache={}
def __init__(self, parent = None, widgetName = ''):
"""
Descript. :
"""
Connectable.Connectable.__init__(self)
QtGui.QFrame.__init__(self, parent)
self.setObjectName(widgetName)
self.propertyBag = PropertyBag.PropertyBag()
self.__enabledState = True #saved enabled state
self.__loadedHardwareObjects = []
self._signalSlotFilters = {}
self._widgetEvents = []
#
# add what's this help
#
self.setWhatsThis("%s (%s)\n" % (widgetName, self.__class__.__name__))
#WhatsThis.add(self, "%s (%s)\n" % (widgetName, self.__class__.__name__))
#
# add properties shared by all BlissWidgets
#
self.addProperty('fontSize', 'string', str(self.font().pointSize()))
self.addProperty('frame', 'boolean', False)
self.addProperty('instanceAllowAlways', 'boolean', False)#, hidden=True)
self.addProperty('instanceAllowConnected', 'boolean', False)#, hidden=True)
self.addProperty('fixedWidth', 'integer', '-1')
self.addProperty('fixedHeight', 'integer', '-1')
#
# connect signals / slots
#
dispatcher.connect(self.__hardwareObjectDiscarded,
'hardwareObjectDiscarded',
HardwareRepository.HardwareRepository())
self.defineSlot('enable_widget', ())
def __run(self):
"""
Descript. :
"""
self.setAcceptDrops(False)
self.blockSignals(False)
self.setEnabled(self.__enabledState)
try:
self.run()
except:
logging.getLogger().exception("Could not set %s to run mode", self.objectName())
def __stop(self):
"""
Descript. :
"""
self.blockSignals(True)
try:
self.stop()
except:
logging.getLogger().exception("Could not stop %s", self.objectName())
#self.setAcceptDrops(True)
self.__enabledState = self.isEnabled()
QtGui.QWidget.setEnabled(self, True)
def __repr__(self):
"""
Descript. :
"""
return repr("<%s: %s>" % (self.__class__, self.objectName()))
def connectSignalSlotFilter(self,sender,signal,slot,should_cache):
"""
Descript. :
"""
uid=(sender, signal, hash(slot))
signalSlotFilter = SignalSlotFilter(signal, slot, should_cache)
self._signalSlotFilters[uid]=signalSlotFilter
QtCore.QObject.connect(sender, signal, signalSlotFilter)
def connect(self, sender, signal, slot, instanceFilter=False, shouldCache=True):
"""
Descript. :
"""
#python2.7
#signal = str(signal)
#python3.4
signal = str(signal.decode('utf8') if type(signal) == bytes else signal)
if signal[0].isdigit():
pysignal = signal[0]=='9'
signal=signal[1:]
else:
pysignal=True
if not isinstance(sender, QtCore.QObject):
if isinstance(sender, HardwareObject):
#logging.warning("You should use %s.connect instead of using %s.connect", sender, self)
# LNLS
#sender.connect(signal, slot)
sender.connect(sender, signal, slot)
return
else:
_sender = emitter(sender)
else:
_sender = sender
if instanceFilter:
self.connectSignalSlotFilter(_sender, pysignal and PYSIGNAL(signal) or SIGNAL(signal), slot, shouldCache)
else:
QtCore.QObject.connect(_sender, pysignal and QtCore.SIGNAL(signal) or QtCore.SIGNAL(signal), slot)
# workaround for PyQt lapse
if hasattr(sender, "connectNotify"):
sender.connectNotify(QtCore.SIGNAL(signal))
def disconnect(self, sender, signal, slot):
"""
Descript. :
"""
signal = str(signal)
if signal[0].isdigit():
pysignal = signal[0]=='9'
signal=signal[1:]
else:
pysignal=True
if isinstance(sender, HardwareObject):
#logging.warning("You should use %s.disconnect instead of using %s.connect", sender,self)
# LNLS
#sender.disconnect(signal, slot)
sender.disconnect(sender, signal, slot)
return
# workaround for PyQt lapse
if hasattr(sender, "disconnectNotify"):
sender.disconnectNotify(signal)
if not isinstance(sender, QObject):
sender = emitter(sender)
try:
uid=(sender, pysignal and QtCore.SIGNAL(signal) or QtCore.SIGNAL(signal), hash(slot))
signalSlotFilter=self._signalSlotFilters[uid]
except KeyError:
QtCore.QObject.disconnect(sender, pysignal and QtCore.SIGNAL(signal) or QtCore.SIGNAL(signal), slot)
else:
QtCore.QObject.disconnect(sender, pysignal and QtCore.SIGNAL(signal) or QtCore.SIGNAL(signal), signalSlotFilter)
del self._signalSlotFilters[uid]
else:
QtCore.QObject.disconnect(sender, pysignal and QtCore.SIGNAL(signal) or QtCore.SIGNAL(signal), signalSlotFilter)
def reparent(self, widget_to):
"""
Descript. :
"""
savedEnabledState = self.isEnabled()
if self.parent() is not None:
self.parent().layout().removeWidget(self)
if widget_to is not None:
widget_to.layout().addWidget(self)
self.setEnabled(savedEnabledState)
def blockSignals(self, block):
"""
Descript. :
"""
for child in self.children():
child.blockSignals(block)
def run(self):
"""
Descript. :
"""
pass
def stop(self):
"""
Descript. :
"""
pass
def restart(self):
"""
Descript. :
"""
self.stop()
self.run()
def loadUIFile(self, filename):
"""
Descript. :
"""
for path in [BlissFramework.getStdBricksPath()]+BlissFramework.getCustomBricksDirs():
#modulePath = sys.modules[self.__class__.__module__].__file__
#path = os.path.dirname(modulePath)
if os.path.exists(os.path.join(path, filename)):
return qtui.QWidgetFactory.create(os.path.join(path, filename))
def createGUIFromUI(self, UIFile):
"""
Descript. :
"""
widget = self.loadUIFile(UIFile)
if widget is not None:
children = self.children() or []
for child in children:
self.removeChild(child) # remove all children first
layout = QtGui.QGridLayout(self, 1, 1)
widget.reparent(self)
widget.show()
layout.addWidget(widget, 0, 0)
self.setLayout(layout)
return widget
def setPersistentPropertyBag(self, persistentPropertyBag):
"""
Descript. :
"""
if id(persistentPropertyBag) != id(self.propertyBag):
for property in persistentPropertyBag:
#
# persistent properties are set
#
if property.getName() in self.propertyBag.properties:
self.propertyBag.getProperty(property.getName()).setValue(property.getUserValue())
elif property.hidden:
self.propertyBag[property.getName()] = property
self.readProperties()
def readProperties(self):
"""
Descript. :
"""
for prop in self.propertyBag:
self._propertyChanged(prop.getName(), None, prop.getUserValue())
"""
def editProperties(self):
if not self.propertyBag.isEmpty():
editor = self.propertyBag.editor()
self.connect(editor, PYSIGNAL('propertyChanged'), self._propertyChanged)
editor.exec_loop()
"""
def addProperty(self, *args, **kwargs):
"""
Descript. :
"""
self.propertyBag.addProperty(*args, **kwargs)
def getProperty(self, property_name):
"""
Descript. :
"""
return self.propertyBag.getProperty(property_name)
def showProperty(self, property_name):
"""
Descript. :
"""
return self.propertyBag.showProperty(property_name)
def hideProperty(self, property_name):
"""
Descript. :
"""
return self.propertyBag.hideProperty(property_name)
def delProperty(self, property_name):
"""
Descript. :
"""
return self.propertyBag.delProperty(property_name)
def getHardwareObject(self, hardware_object_name):
"""
Descript. :
"""
if not hardware_object_name in self.__loadedHardwareObjects:
self.__loadedHardwareObjects.append(hardware_object_name)
ho = HardwareRepository.HardwareRepository().getHardwareObject(hardware_object_name)
return ho
def __hardwareObjectDiscarded(self, hardware_object_name):
"""
Descript. :
"""
if hardware_object_name in self.__loadedHardwareObjects:
# there is a high probability we need to reload this hardware object...
self.readProperties() #force to read properties
def getHardwareObjectsInfo(self):
"""
Descript. :
"""
d = {}
for ho_name in self.__loadedHardwareObjects:
info = HardwareRepository.HardwareRepository().getInfo(ho_name)
if len(info) > 0:
d[ho_name] = info
if len(d):
return "Hardware Objects:\n\n%s" % pprint.pformat(d)
else:
return ""
def __getitem__(self, property_name):
"""
Descript. : Direct access tp properties values
"""
return self.propertyBag[property_name]