-
Notifications
You must be signed in to change notification settings - Fork 8
/
QDSpy_GUI_main.py
1186 lines (1027 loc) · 45.8 KB
/
QDSpy_GUI_main.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
QDSpy module - main program of the GUI version of QDSpy
Copyright (c) 2013-2024 Thomas Euler
All rights reserved.
2021-10-15 - Adapt to LINUX
2024-06-11 - Reformatted (using Ruff)
- Small fixes for PEP violations
- `int()` where Qt5 does not accept float
2024-06-19 - Ported from `PyQt5` to `PyQt6`
(note that `QDSApp.setStyle("Fusion")` is needed to make
the GUI designed for Qt5 look decent)
"""
# ---------------------------------------------------------------------
__author__ = "[email protected]"
import os
import sys
import time
import pickle
from PyQt6 import uic
from PyQt6.QtWidgets import QMessageBox, QMainWindow, QLabel, QApplication
from PyQt6.QtWidgets import QFileDialog, QListWidgetItem, QWidget
from PyQt6.QtGui import QPalette, QColor, QBrush, QTextCharFormat, QTextCursor
from PyQt6.QtCore import QRect, QSize
from multiprocessing import Process
import QDSpy_stim as stm
import QDSpy_stim_support as ssp
import QDSpy_config as cfg
import QDSpy_GUI_support as gsu
from QDSpy_GUI_cam import CamWinClass
import QDSpy_multiprocessing as mpr
import QDSpy_stage as stg
import QDSpy_global as glo
import QDSpy_core
import QDSpy_core_support as csp
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
if csp.module_exists("cv2"):
import Devices.camera as cam
PLATFORM_WINDOWS = sys.platform == "win32"
if PLATFORM_WINDOWS:
from ctypes import windll
# ---------------------------------------------------------------------
form_class = uic.loadUiType("QDSpy_GUI_main.ui")[0]
toggle_btn_style_str = "QPushButton:checked{background-color: lightGreen;border: none;}"
user_btn_style_str = "QPushButton:checked{background-color: orange;border: none;}"
# ---------------------------------------------------------------------
fStrPreRed = '<html><head/><body><p><span style="color:#ff0000;">'
fStrPreGreen = '<html><head/><body><p><span style="color:#00aa00;">'
fStrPost = "</span></p></body></html>"
# ---------------------------------------------------------------------
class State:
undefined = 0
idle = 1
ready = 2
loading = 3
compiling = 4
playing = 5
canceling = 6
probing = 7
# ...
# ---------------------------------------------------------------------
class Canceled(Exception):
pass
# ---------------------------------------------------------------------
# Main application window
# ---------------------------------------------------------------------
class MainWinClass(QMainWindow, form_class):
def __init__(self, parent=None):
# Initialize
self.HDMagFactor = 1.0
self.Conf = cfg.Config()
self.Stim = stm.Stim()
self.currStimPath = self.Conf.pathStim
self.currQDSPath = os.getcwd()
self.currStimName = "n/a"
self.currStimFName = ""
self.isStimReady = False
self.isStimCurr = False
self.isViewReady = False
self.isLCrUsed = False
self.isIODevReady = None
self.lastIOInfo = []
self.IOCmdCount = 0
self.Stage = None
self.noMsgToStdOut = cfg.getParsedArgv().gui
self.logWrite("DEBUG", "Initializing GUI")
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle(glo.QDSpy_versionStr)
# Bind GUI ...
self.btnRefreshStimList.clicked.connect(self.OnClick_btnRefreshStimList)
self.listStim.itemClicked.connect(self.OnClick_listStim)
self.listStim.itemDoubleClicked.connect(self.OnDblClick_listStim)
self.btnStimPlay.clicked.connect(self.OnClick_btnStimPlay)
self.btnStimCompile.clicked.connect(self.OnClick_btnStimCompile)
self.btnStimAbort.clicked.connect(self.OnClick_btnStimAbort)
self.btnChangeStimFolder.clicked.connect(self.OnClick_btnChangeStimFolder)
self.checkShowHistory.clicked.connect(self.OnClick_checkShowHistory)
self.pushButtonLED1.clicked.connect(self.OnClick_pushButtonLED)
self.pushButtonLED2.clicked.connect(self.OnClick_pushButtonLED)
self.pushButtonLED3.clicked.connect(self.OnClick_pushButtonLED)
self.pushButtonLED4.clicked.connect(self.OnClick_pushButtonLED)
self.pushButtonLED5.clicked.connect(self.OnClick_pushButtonLED)
self.pushButtonLED6.clicked.connect(self.OnClick_pushButtonLED)
self.btnIOUser1.clicked.connect(self.OnClick_IOUser1)
self.btnIOUser1.setStyleSheet(user_btn_style_str)
self.btnIOUser2.clicked.connect(self.OnClick_IOUser2)
self.btnIOUser2.setStyleSheet(user_btn_style_str)
self.pushButtonLED1.setStyleSheet(toggle_btn_style_str)
self.pushButtonLED2.setStyleSheet(toggle_btn_style_str)
self.pushButtonLED3.setStyleSheet(toggle_btn_style_str)
self.pushButtonLED4.setStyleSheet(toggle_btn_style_str)
self.pushButtonLED5.setStyleSheet(toggle_btn_style_str)
self.pushButtonLED6.setStyleSheet(toggle_btn_style_str)
self.spinBoxLED1.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.spinBoxLED2.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.spinBoxLED3.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.spinBoxLED4.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.spinBoxLED5.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.spinBoxLED6.valueChanged.connect(self.OnClick_spinBoxLED_valueChanged)
self.btnSetLEDCurrents.clicked.connect(self.OnClick_btnSetLEDCurrents)
self.btnRefreshDisplayInfo.clicked.connect(self.OnClick_btnRefreshDisplayInfo)
self.btnToggleLEDEnable.clicked.connect(self.OnClick_btnToggleLEDEnable)
self.btnToggleLEDEnable.setStyleSheet(toggle_btn_style_str)
self.btnProbeStart.clicked.connect(self.OnClick_btnProbeStart)
self.spinBox_probe_width.valueChanged.connect(
self.OnClick_probeParam_valueChanged
)
self.spinBox_probe_height.valueChanged.connect(
self.OnClick_probeParam_valueChanged
)
self.spinBox_probe_intensity.valueChanged.connect(
self.OnClick_probeParam_valueChanged
)
self.spinBox_probe_interval.valueChanged.connect(
self.OnClick_probeParam_valueChanged
)
self.btnLCrInfo0.clicked.connect(self.OnClick_btnLCrInfo0)
self.btnLCrInfo1.clicked.connect(self.OnClick_btnLCrInfo1)
self.btnToggleSeqControl0.clicked.connect(self.OnClick_btnToggleSeqControl0)
self.btnToggleSeqControl0.setStyleSheet(toggle_btn_style_str)
self.btnToggleSeqControl1.clicked.connect(self.OnClick_btnToggleSeqControl1)
self.btnToggleSeqControl1.setStyleSheet(toggle_btn_style_str)
self.btnLCrStartStop0.clicked.connect(self.OnClick_btnLCrStartStop0)
self.btnLCrStartStop0.setStyleSheet(toggle_btn_style_str)
self.btnLCrStartStop1.clicked.connect(self.OnClick_btnLCrStartStop1)
self.btnLCrStartStop1.setStyleSheet(toggle_btn_style_str)
self.winCam = None
self.camList = []
if self.Conf.allowCam and csp.module_exists("cv2"):
self.camList = cam.get_camera_list()
for c in self.camList:
self.comboBoxCams.addItems([c["string"]])
self.checkBoxCamEnable.clicked.connect(self.OnClick_checkBoxCamEnable)
else:
self.checkBoxCamEnable.setEnabled(False)
self.checkBoxStageCSEnable.clicked.connect(self.OnClick_checkStageCSEnable)
self.checkBoxDualScrCSEnable.clicked.connect(
self.OnClick_checkBoxDualScrCSEnable
)
self.spinBoxStageCS_hOffs.valueChanged.connect(
self.OnClick_spinBoxStageCS_hOffs_valueChanged
)
self.spinBoxStageCS_vOffs.valueChanged.connect(
self.OnClick_spinBoxStageCS_vOffs_valueChanged
)
self.spinBoxStageCS_hScale.valueChanged.connect(
self.OnClick_spinBoxStageCS_hScale_valueChanged
)
self.spinBoxStageCS_vScale.valueChanged.connect(
self.OnClick_spinBoxStageCS_vScale_valueChanged
)
self.spinBoxStageCS_rot.valueChanged.connect(
self.OnClick_spinBoxStageCS_rot_valueChanged
)
self.btnSaveStageCS.clicked.connect(self.OnClick_btnSaveStageCS)
self.btnToggleWaitForTrigger.clicked.connect(
self.OnClick_btnToggleWaitForTrigger
)
self.btnToggleWaitForTrigger.setStyleSheet(toggle_btn_style_str)
self.stbarErrMsg = QLabel()
self.stbarStimMsg = QLabel()
self.statusbar.addWidget(self.stbarErrMsg, 2)
self.statusbar.addPermanentWidget(self.stbarStimMsg, 2)
self.lblSelStimName.setText(self.currStimName)
self.lineEditComment.returnPressed.connect(self.OnClick_AddComment)
# Create status objects and a pipe for communicating with the
# presentation process (see below)
self.logWrite("DEBUG", "Creating sync object ...")
self.state = State.undefined
self.Sync = mpr.Sync()
ssp.Log.setGUISync(self.Sync)
self.logWrite("DEBUG", "... done")
# Create process that opens a view (an OpenGL window) and waits for
# instructions to play stimuli
self.logWrite("DEBUG", "Creating worker thread ...")
self.worker = Process(
target=QDSpy_core.main, args=(self.currStimFName, True, self.Sync)
)
self.logWrite("DEBUG", "... done")
self.worker.daemon = True
self.logWrite("DEBUG", "Starting worker thread ...")
self.worker.start()
self.logWrite("DEBUG", "... done")
self.isViewReady = True
self.setState(State.idle, True)
# Update GUI ...
self.updateStimList()
self.updateAll()
if glo.QDSpy_useGUIScalingForHD:
# If screen resolution is above a certain dpi levels (->HD), all GUI
# elements are scaled in order to keep the GUI readable
# (Needed for PyQt5 and lower)
nHDScr = 0
maxdpi = 0
screens = QDSApp.screens()
for s in screens:
dpi = s.logicalDotsPerInch()
if dpi > maxdpi:
maxdpi = dpi
if dpi > glo.QDSpy_dpiThresholdForHD:
nHDScr += 1
if nHDScr == 0:
# "Normal" display
self.HDMagFactor = 1.0
else:
# Scale all GUI elements to account for HD display
self.HDMagFactor = maxdpi / 100.0
listChildren = self.findChildren(QWidget)
for child in listChildren:
rect = child.geometry().getRect()
child.setGeometry(
QRect(
int(rect[0] * self.HDMagFactor),
int(rect[1] * self.HDMagFactor),
int(rect[2] * self.HDMagFactor),
int(rect[3] * self.HDMagFactor),
)
)
rect = self.minimumSize()
self.setMinimumSize(
QSize(
int(rect.width() * self.HDMagFactor),
int(rect.height() * self.HDMagFactor),
)
)
rect = self.maximumSize()
self.setMaximumSize(
QSize(
int(rect.width() * self.HDMagFactor),
int(rect.height() * self.HDMagFactor),
)
)
self.resize(self.maximumSize())
self.logWrite(
"INFO",
"High display pixel density ({0} dpi), scaling GUI"
"by a factor of {1:.2f}".format(maxdpi, self.HDMagFactor),
)
# ************************
# ************************
# ************************
"""
self.winStimView = StimViewWinClass(self, self.updateAll, self.logWrite, self.Sync)
self.winStimView.show()
"""
# ************************
# ************************
# ************************
# Check if worker process is still alive
self.logWrite("DEBUG", "Check worker thread ...")
time.sleep(1.0)
if not (self.worker.is_alive()):
sys.exit(0)
self.logWrite("DEBUG", "... done")
# Wait until the worker thread send info about the stage via the pipe
self.logWrite("DEBUG", "Waiting for stage info from worker ...")
while not self.Stage:
self.processPipe()
time.sleep(0.05)
self.logWrite("DEBUG", "... done")
# Update display info
self.Stage.updateLEDs(self.Conf)
self.currStimPath = os.path.abspath(self.currStimPath)
self.updateDisplayInfo()
# Update IO device info
self.logWrite("DEBUG", "Waiting for IO device state from worker ...")
self.Sync.pipeCli.send([mpr.PipeValType.toSrv_checkIODev, []])
while self.isIODevReady is None:
self.processPipe()
time.sleep(0.05)
self.updateIOInfo()
self.logWrite("DEBUG", "... done")
# Check if autorun stimulus file present and if so run it
try:
self.isStimCurr = False
self.currStimFName = os.path.join(
self.currStimPath, glo.QDSpy_autorunStimFileName
)
isAutoRunExists = gsu.getStimExists(self.currStimFName)
if isAutoRunExists:
# Check if a current compiled version of the autorun file
# exists
self.isStimCurr = gsu.getStimCompileState(self.currStimFName)
if not isAutoRunExists or not self.isStimCurr:
# No current compiled auto-run file present, so use default file
self.currStimFName = os.path.join(
self.currQDSPath, glo.QDSpy_autorunDefFileName
)
self.logWrite(
"ERROR",
"No compiled `{0}` in current stimulus "
"folder, using `{1}` in `{2}`.".format(
glo.QDSpy_autorunStimFileName,
glo.QDSpy_autorunDefFileName,
self.currQDSPath,
),
)
# Run either autorun file ...
self.logWrite("DEBUG", "Running {0} ...".format(self.currStimFName))
self.Stim.load(self.currStimFName, _onlyInfo=True)
self.setState(State.ready)
self.isStimReady = True
self.runStim()
except: # noqa: E722
# Failed ...
if self.Stim.getLastErrC() != stm.StimErrC.ok:
self.updateStatusBar(self.Stim.getLastErrStr(), True)
ssp.Log.isRunFromGUI = False
ssp.Log.write(
"ERROR",
"No compiled `{0}` in current stimulus folder,"
" and `{1}.pickle` is not in `{2}`. Program is"
" aborted.".format(
glo.QDSpy_autorunStimFileName,
glo.QDSpy_autorunDefFileName,
self.currQDSPath,
),
)
sys.exit(0)
# Update GUI
self.updateAll()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def __del__(self):
pass
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def keyPressEvent(self, e):
""" Allow pressing ESC to abort stimulus presentation ...
"""
if e.key() in glo.QDSpy_KEY_KillPresent:
if self.Sync.State.value in [mpr.PRESENTING, mpr.COMPILING, mpr.PROBING]:
self.OnClick_btnStimAbort()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def closeEvent(self, event):
""" User requested to close the application
"""
if glo.QDSpy_isGUIQuitWithDialog:
result = QMessageBox.question(
self,
"Confirm closing QDSpy ...",
"Are you sure you want to quit?",
QMessageBox.Yes | QMessageBox.No,
)
event.ignore()
if result == QMessageBox.No:
event.ignore()
return
# Save position of camera window, and close it if open
if self.winCam is not None:
self.Conf.camWinGeom = self.winCam.geometry().getRect()
self.winCam.close()
# Save config
self.Conf.saveWinPosToConfig()
self.Conf.save()
# Closing is immanent, stop stimulus, if running ...
if self.Sync.State.value in [mpr.PRESENTING, mpr.COMPILING]:
self.OnClick_btnStimAbort()
# Save log
os.makedirs(self.Conf.pathLogs, exist_ok=True)
fName = time.strftime("%Y%m%d_%H%M%S")
j = 0
while os.path.exists(self.Conf.pathLogs + fName):
fName = "{0}_{1:04d}".format(fName, j)
j += 1
fPath = self.Conf.pathLogs + fName + glo.QDSpy_logFileExtension
self.logWrite(" ", "Saving log file to '{0}' ...".format(fPath))
with open(fPath, "w") as logFile:
logFile.write(str(self.textBrowserHistory.toPlainText()))
# ... and clean up
self.logWrite("DEBUG", "Kill worker thread ...")
self.Sync.setRequestSafe(mpr.TERMINATING)
self.worker.join()
while self.worker.is_alive():
time.sleep(0.2)
self.logWrite("DEBUG", "... done")
event.accept()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setState(self, _newState, _doUpdateGUI=False):
""" Update GUI state and GUI as well, if requested
"""
self.state = _newState
if _doUpdateGUI:
self.updateAll()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateAll(self):
""" Update the complete GUI
"""
txt = gsu.getShortText(self, self.currStimPath, self.lblCurrStimFolder)
self.lblCurrStimFolder.setText(txt)
stateWorker = self.Sync.State.value
if stateWorker == mpr.PRESENTING:
self.state = State.playing
elif stateWorker == mpr.COMPILING:
self.state = State.compiling
elif stateWorker == mpr.PROBING:
self.state = State.probing
elif stateWorker in [mpr.CANCELING, mpr.TERMINATING]:
self.state = State.canceling
elif stateWorker == mpr.IDLE:
self.state = State.ready
isStimSelPerm = self.state in {State.undefined, State.idle, State.ready}
self.listStim.setEnabled(isStimSelPerm)
self.btnRefreshStimList.setEnabled(isStimSelPerm)
self.btnChangeStimFolder.setEnabled(isStimSelPerm)
self.btnStimPlay.setText("Play")
self.btnStimPlay.setEnabled(self.isStimReady)
self.btnStimCompile.setText("Compile")
self.btnStimCompile.setEnabled(not (self.isStimCurr))
self.btnStimAbort.setText("Abort")
self.btnStimAbort.setEnabled(
(self.state == State.playing) or (self.state == State.probing)
)
self.btnProbeStart.setText("Start probing\ncenter")
self.btnProbeStart.setEnabled(True)
if self.state == State.loading:
self.btnStimPlay.setText("Loading\n...")
self.btnStimPlay.setEnabled(False)
self.btnStimCompile.setEnabled(False)
self.listStim.setEnabled(False)
elif self.state == State.compiling:
self.btnStimCompile.setText("Compi-\nling ...")
self.btnStimCompile.setEnabled(False)
self.btnStimPlay.setEnabled(False)
self.listStim.setEnabled(False)
elif self.state == State.canceling:
self.btnStimAbort.setText("Aborting ...")
self.btnStimPlay.setEnabled(False)
self.listStim.setEnabled(False)
elif self.state == State.playing:
self.btnStimPlay.setText("Playing\n...")
self.btnStimPlay.setEnabled(False)
self.btnStimCompile.setEnabled(False)
elif self.state == State.probing:
self.btnProbeStart.setText("Probing\ncenter ...")
self.btnProbeStart.setEnabled(False)
self.btnStimPlay.setEnabled(False)
self.btnStimCompile.setEnabled(False)
if self.winCam is not None:
self.checkBoxCamEnable.setCheckState(self.winCam.isHidden())
if self.Stage is not None:
enabledSeq = self.Stage.isLEDSeqEnabled[0]
else:
enabledSeq = True
self.btnSetLEDCurrents.setEnabled(self.isLCrUsed)
self.btnToggleLEDEnable.setEnabled(self.isLCrUsed)
self.btnToggleSeqControl0.setEnabled(False)
self.btnToggleSeqControl1.setEnabled(False)
"""
enabledLEDs = self.btnToggleLEDEnable.isChecked()
self.btnToggleSeqControl.setEnabled(self.isLCrUsed and not(enabledLEDs))
"""
self.btnToggleSeqControl0.setChecked(enabledSeq)
gsu.updateToggleButton(self.btnToggleSeqControl0)
self.btnToggleSeqControl1.setChecked(enabledSeq)
gsu.updateToggleButton(self.btnToggleSeqControl1)
self.btnRefreshDisplayInfo.setEnabled(self.isLCrUsed)
if self.Stage:
for iLED, LED in enumerate(self.Stage.LEDs):
[spinBoxLED, labelLED, btnLED] = gsu.getLEDGUIObjects(self, LED)
spinBoxLED.setEnabled(self.isLCrUsed)
spinBoxLED.setMaximum(LED["max_current"])
btnLED.setEnabled(self.isLCrUsed and not (enabledSeq))
if self.Stage is not None:
btnLED.setChecked(LED["enabled"])
else:
btnLED.setChecked(True)
gsu.updateToggleButton(btnLED)
self.processPipe()
self.updateStatusBar(mpr.StateStr[stateWorker])
QApplication.processEvents()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateStimList(self):
""" Update stimulus list widget
"""
self.currStimFNames = gsu.getStimFileLists(self.currStimPath)
self.listStim.clear()
for stimFName in self.currStimFNames:
self.listStim.addItem(gsu.getFNameNoExt(stimFName))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateStatusBar(self, _msg="Ready", _isErr=False):
""" Update status bar
"""
if _isErr:
self.stbarErrMsg.setText(fStrPreRed + "Error: " + _msg + fStrPost)
else:
self.stbarErrMsg.setText(_msg)
if (len(self.currStimName) > 0) and (self.isStimReady):
self.stbarStimMsg.setText("Stimulus: " + self.currStimName)
else:
self.stbarStimMsg.setText("")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateIOInfo(self):
""" Update IO device info and status
"""
if self.Conf.useDIO:
self.lblIODevName.setText(
"{0}, board #{1}, device #{2} {3}".format(
self.Conf.DIObrdType,
self.Conf.DIObrd,
self.Conf.DIOdev,
"is ready" if self.isIODevReady else "NOT READY",
)
)
self.lblIODevMarkerOut.setText(
"port {0}, pin {1}".format(self.Conf.DIOportOut, self.Conf.DIOpinMarker)
)
self.lblIODevTriggerIn.setText(
"port {0}, pin {1}".format(self.Conf.DIOportIn, self.Conf.DIOpinTrigIn)
)
self.lblIODevUserOut.setText(
"port {0}, pins {1},{2}".format(
self.Conf.DIOportOut_User,
int(self.Conf.DIOpinUserOut1[0]),
int(self.Conf.DIOpinUserOut2[0]),
)
)
self.groupBoxIODevInfo.setEnabled(self.isIODevReady)
self.btnIOUser1.setEnabled(self.isIODevReady)
self.btnIOUser1.setText("{0}\noff".format(self.Conf.DIOpinUserOut1[1]))
self.btnIOUser2.setEnabled(self.isIODevReady)
self.btnIOUser2.setText("{0}\noff".format(self.Conf.DIOpinUserOut2[1]))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateDisplayInfo(self):
""" Update display info and status
"""
try:
self.lblDisplDevName.setText(
"{0}, screen #{1}".format(self.Stage.scrDevName, self.Stage.scrIndex)
)
self.lblDisplDevRes.setText(
"{0}x{1}, {2}bit, {3:.1f}({4:.1f}) Hz{5}".format(
self.Stage.dxScr,
self.Stage.dyScr,
self.Stage.depth,
self.Stage.scrDevFreq_Hz,
self.Stage.scrReqFreq_Hz,
", full" if self.Stage.isFullScr else "",
)
)
self.lblDisplDevInfo.setText(
"{0:.2f}x{1:.2f} µm/pixel<br>offset: {2},{3}, angle: {4}°".format(
self.Stage.scalX_umPerPix,
self.Stage.scalY_umPerPix,
self.Stage.centX_pix,
self.Stage.centY_pix,
self.Stage.rot_angle,
)
)
if len(self.Stage.LEDs) == 0:
self.lblDisplDevLEDs.setText("n/a")
else:
sTemp = ""
pal = QPalette()
LEDsEnabled = self.btnToggleLEDEnable.isChecked()
for iLED, LED in enumerate(self.Stage.LEDs):
sTemp += "{0}={1} ".format(LED["name"], LED["current"])
pal.setColor(QPalette.ColorRole.Window, QColor(LED["Qt_color"]))
pal.setColor(QPalette.ColorRole.WindowText, QColor("white"))
[spinBoxLED, labelLED, btnLED] = gsu.getLEDGUIObjects(self, LED)
spinBoxLED.setValue(LED["current"])
spinBoxLED.setEnabled(LEDsEnabled)
labelLED.setPalette(pal)
labelLED.setText(LED["name"])
btnLED.setEnabled(not LEDsEnabled)
btnLED.setText("")
gsu.updateToggleButton(btnLED)
self.lblDisplDevLEDs.setText(sTemp)
self.spinBoxStageCS_hOffs.setValue(self.Stage.centOffX_pix)
self.spinBoxStageCS_vOffs.setValue(self.Stage.centOffY_pix)
self.spinBoxStageCS_hScale.setValue(self.Stage.scalX_umPerPix)
self.spinBoxStageCS_vScale.setValue(self.Stage.scalY_umPerPix)
self.spinBoxStageCS_rot.setValue(int(self.Stage.rot_angle))
except KeyError:
pass
# -------------------------------------------------------------------
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnRefreshStimList(self):
self.updateStimList()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnChangeStimFolder(self):
newPath = QFileDialog.getExistingDirectory(
self,
"Select new stimulus folder",
self.currStimPath,
options=QFileDialog.ShowDirsOnly,
)
if len(newPath) > 0:
# Change path and update stimulus list ...
self.currStimPath = newPath
self.logWrite(" ", "New stimulus folder `{0}`".format(newPath))
self.updateStimList()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_listStim(self, _selItem):
""" Show name of selected stimulus and some info
"""
txtInfo = "n/a"
txtCompState = "n/a"
txtDuration = "n/a"
self.isStimReady = False
self.isStimCurr = False
self.currStimName = _selItem.text()
self.setState(State.idle)
iSel = self.listStim.currentRow()
if iSel >= 0:
# Try loading selected stimulus pickle file
#
self.currStimFName = self.currStimFNames[iSel]
try:
self.Stim.load(self.currStimFName, _onlyInfo=True)
# Succeed, now get info
self.setState(State.ready)
self.isStimReady = True
self.isStimCurr = gsu.getStimCompileState(self.currStimFName)
if self.isStimCurr:
txtCompState = (
fStrPreGreen + "compiled (.pickle) is up-to-date" + fStrPost
)
else:
txtCompState = "compiled (.pickle), pre-dates .py"
txtInfo = self.Stim.descrStr
mins, secs = divmod(self.Stim.lenStim_s, 60)
hours, mins = divmod(mins, 60)
txtDuration = "{0:.3f} s ({1:02d}:{2:02d}:{3:02d})".format(
self.Stim.lenStim_s, int(hours), int(mins), int(secs)
)
self.updateStatusBar()
except: # noqa: E722
# Failed ...
txtCompState = fStrPreRed + "not compiled (no .pickle)" + fStrPost
if self.Stim.getLastErrC() != stm.StimErrC.ok:
self.updateStatusBar(self.Stim.getLastErrStr(), True)
# Show info ...
self.lblSelStimName.setText(self.currStimName)
self.lblSelStimInfo.setText(txtInfo)
self.lblSelStimStatus.setText(txtCompState)
self.lblSelStimDuration.setText(txtDuration)
self.updateAll()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_checkShowHistory(self, _checked):
self.resize(self.maximumSize() if _checked else self.minimumSize())
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_spinBoxLED_valueChanged(self, _val):
self.btnSetLEDCurrents.setEnabled(True)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_pushButtonLED(self):
self.handleLEDStateChanged()
def handleLEDStateChanged(self):
enabled = []
LEDsEnabled = not (self.btnToggleLEDEnable.isChecked())
for iLED, LED in enumerate(self.Stage.LEDs):
(spinBoxLED, labelLED, btnLED) = gsu.getLEDGUIObjects(self, LED)
btnLED.setEnabled(LEDsEnabled)
val = btnLED.isChecked()
enabled.append(val)
spinBoxLED.setEnabled(LEDsEnabled and not (val))
self.Stage.setLEDEnabled(iLED, val)
self.Sync.pipeCli.send(
[
mpr.PipeValType.toSrv_changedLEDs,
[self.Stage.LEDs, self.Stage.isLEDSeqEnabled],
]
)
self.updateDisplayInfo()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_AddComment(self):
data = {"userComment": self.lineEditComment.text()}
self.logWrite("DATA", data.__str__())
self.lineEditComment.setText("")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnRefreshDisplayInfo(self):
self.Stage.updateLEDs(_Conf=self.Conf)
self.updateDisplayInfo()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnToggleLEDEnable(self):
checked = self.btnToggleLEDEnable.isChecked()
for iLED, LED in enumerate(self.Stage.LEDs):
self.Stage.LEDs[iLED]["enabled"] = checked
self.Stage.isLEDSeqEnabled = [checked] * glo.QDSpy_MaxLightcrafterDev
self.Sync.pipeCli.send(
[
mpr.PipeValType.toSrv_changedLEDs,
[self.Stage.LEDs, self.Stage.isLEDSeqEnabled],
]
)
gsu.updateToggleButton(self.btnToggleLEDEnable)
self.updateDisplayInfo()
self.updateAll()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnToggleSeqControl0(self):
gsu.updateToggleButton(self.btnToggleSeqControl0)
print("OnClick_btnToggleSeqControl0 - TO BE IMPLEMENTED")
# *****************************
# *****************************
def OnClick_btnToggleSeqControl1(self):
gsu.updateToggleButton(self.btnToggleSeqControl1)
print("OnClick_btnToggleSeqControl1 - TO BE IMPLEMENTED")
# *****************************
# *****************************
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnLCrStartStop0(self):
self.handleLCrStartStopButton(self.btnLCrStartStop0, 0)
def OnClick_btnLCrStartStop1(self):
self.handleLCrStartStopButton(self.btnLCrStartStop1, 1)
def handleLCrStartStopButton(self, _btn, _iLcr):
gsu.updateToggleButton(_btn, ["running", "stopped"])
checked = _btn.isChecked()
self.Stage.togglePatternSeq(_iLcr, self.Conf, checked)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnToggleWaitForTrigger(self):
gsu.updateToggleButton(self.btnToggleWaitForTrigger)
print("OnClick_btnToggleWaitForTrigger.TO BE IMPLEMENTED")
# *****************************
# *****************************
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_IOUser1(self):
self.handleIOUserButton(
self.btnIOUser1,
int(self.Conf.DIOpinUserOut1[0]),
int(self.Conf.DIOpinUserOut1[2]) != 0,
)
def OnClick_IOUser2(self):
self.handleIOUserButton(
self.btnIOUser2,
int(self.Conf.DIOpinUserOut2[0]),
int(self.Conf.DIOpinUserOut2[2]) != 0,
)
def handleIOUserButton(self, _btn, _pin, _invert):
gsu.updateToggleButton(_btn)
self.IOCmdCount += 1
data = dict(
[
("port", self.Conf.DIOportOut_User),
("pin", _pin),
("invert", _invert),
("state", _btn.isChecked()),
("cmdCount", self.IOCmdCount),
]
)
self.Sync.pipeCli.send(
[
mpr.PipeValType.toSrv_setIODevPins,
[
data["port"],
data["pin"],
data["invert"],
data["state"],
data["cmdCount"],
],
]
)
currIOCmdCount = self.IOCmdCount
self.processPipe()
if currIOCmdCount == self.IOCmdCount:
self.logWrite("DATA", data.__str__())
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnSetLEDCurrents(self):
if len(self.Stage.LEDs) == 0:
return
curr = []
for iLED, LED in enumerate(self.Stage.LEDs):
(spinBoxLED, labelLED, btnLED) = gsu.getLEDGUIObjects(self, LED)
val = spinBoxLED.value()
curr.append(val)
self.Stage.setLEDCurrent(iLED, val)
self.Sync.pipeCli.send(
[
mpr.PipeValType.toSrv_changedLEDs,
[self.Stage.LEDs, self.Stage.isLEDSeqEnabled],
]
)
self.btnSetLEDCurrents.setEnabled(False)
self.updateDisplayInfo()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnLCrInfo0(self):
self.handleLCrInfoButton(0)
def OnClick_btnLCrInfo1(self):
self.handleLCrInfoButton(1)
def handleLCrInfoButton(self, _iLcr):
self.Stage.inquireLCrInfo(_iLcr, self.Conf)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_checkStageCSEnable(self, _checked):
self.spinBoxStageCS_hOffs.setEnabled(_checked)
self.spinBoxStageCS_vOffs.setEnabled(_checked)
self.spinBoxStageCS_hScale.setEnabled(_checked)
self.spinBoxStageCS_vScale.setEnabled(_checked)
self.spinBoxStageCS_rot.setEnabled(_checked)
self.btnSaveStageCS.setEnabled(_checked)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_checkBoxDualScrCSEnable(self, _checked):
self.spinBoxStageCS_hOffs_Scr1.setEnabled(_checked)
self.spinBoxStageCS_vOffs_Scr1.setEnabled(_checked)
self.spinBoxStageCS_hOffs_Scr2.setEnabled(_checked)
self.spinBoxStageCS_vOffs_Scr2.setEnabled(_checked)
self.spinBoxStageCS_wideScrHeight.setEnabled(_checked)
self.spinBoxStageCS_wideScrWidth.setEnabled(_checked)
self.btnSaveStageCS.setEnabled(_checked)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_spinBoxStageCS_vOffs_valueChanged(self, _val):
self.Stage.centOffY_pix = _val
self.signalStageChange()
def OnClick_spinBoxStageCS_hOffs_valueChanged(self, _val):
self.Stage.centOffX_pix = _val
self.signalStageChange()
def OnClick_spinBoxStageCS_vScale_valueChanged(self, _val):
self.Stage.scalY_umPerPix = _val
self.signalStageChange()
def OnClick_spinBoxStageCS_hScale_valueChanged(self, _val):
self.Stage.scalX_umPerPix = _val
self.signalStageChange()
def OnClick_spinBoxStageCS_rot_valueChanged(self, _val):
self.Stage.rot_angle = _val
self.signalStageChange()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def signalStageChange(self):
self.updateDisplayInfo()
self.Sync.pipeCli.send(
[mpr.PipeValType.toSrv_changedStage, self.Stage.getScaleOffsetAsDict()]
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_probeParam_valueChanged(self, _val):
self.signalProbeParamChange()
def signalProbeParamChange(self):
spot_width = int(self.spinBox_probe_width.value())
spot_height = int(self.spinBox_probe_height.value())
spot_intensity = int(self.spinBox_probe_intensity.value())
spot_interval = float(self.spinBox_probe_interval.value())
self.Sync.pipeCli.send(
[
mpr.PipeValType.toSrv_probeParams,
glo.QDSpy_probing_center,
[spot_width, spot_height, spot_intensity, spot_interval],
]
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnSaveStageCS(self):
self.Conf.saveStageToConfig(self.Stage)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def OnClick_btnStimPlay(self):
self.runStim()
def OnClick_btnStimCompile(self):
self.compileStim()
def OnClick_btnStimAbort(self):
""" Send a request to the worker to cancel the presentation
"""
self.setState(State.canceling)
self.Sync.setRequestSafe(mpr.CANCELING)
self.setState(State.canceling, True)
# Wait for the worker to finish cancelling
if self.Sync.waitForState(mpr.IDLE, self.Conf.guiTimeOut, self.updateAll):