-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathQDSpy_app.py
444 lines (384 loc) · 15.3 KB
/
QDSpy_app.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
QDSpy module - Application class
Copyright (c) 2024-2025 Thomas Euler
All rights reserved.
2024-08-03 - Initial version
"""
# ---------------------------------------------------------------------
__author__ = "code@eulerlab.de"
import platform
import time
import os
import sys
import pickle
from typing import TextIO
from multiprocessing import Process
import Libraries.multiprocess_helper as mpr
import QDSpy_stim as stm
import QDSpy_config as cfg
import QDSpy_file_support as fsu
import QDSpy_stage as stg
import QDSpy_global as glo
import QDSpy_core
from Libraries.log_helper import Log
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
PLATFORM_WINDOWS = platform.system() == "Windows"
if not PLATFORM_WINDOWS:
WindowsError = FileNotFoundError
# ---------------------------------------------------------------------
class State:
undefined = 0
idle = 1
ready = 2
loading = 3
compiling = 4
playing = 5
canceling = 6
probing = 7
# ...
StateStr = [
"undefined", "idle", "ready", "loading", "compiling", "playing",
"canceling", "probing"
]
class Canceled(Exception):
pass
# ---------------------------------------------------------------------
# Main QDSpy application class
# ---------------------------------------------------------------------
class QDSpyApp(object):
def __init__(self, _title: str):
# Initialize
self._title = _title
self.Conf = cfg.Config()
self.Stim = stm.Stim()
self.currStimPath = os.path.abspath(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 = False
self._logFile = None
# For reporting the stimulus status during presentation
self.Stim_tFrRel_s = 0
self.Stim_nFrTotal = 0
self.Stim_percent = 0
self.Stim_completed = False
self.Stim_soundVol = 0
# Open log file
self._logFile, fn = self.openLogFile(self.Conf.pathLogs)
self.logWrite(" ", f"Saving log file to `{fn}` ...")
# Identify
self.logWrite(
"***",
f"{glo.QDSpy_versionStr} {self._title} - {glo.QDSpy_copyrightStr}"
)
# 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()
#
# Tell the Log object that we need to receive messages from the worker
# for the log file
Log.isRunFromGUI = True
Log.setGUISync(self.Sync, noStdOut=self.noMsgToStdOut)
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)
# 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 LED setting
self.Stage.updateLEDs(self.Conf)
# 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.logWrite("DEBUG", "... done")
# Check if autorun stimulus file present and if so run it
self.handleAutorun()
# -----------------------------------------------------------------
def handleAutorun(self):
'''Check if autorun stimulus file present and if so run it
'''
try:
self.isStimCurr = False
sf = glo.QDSpy_autorunStimFileName
sd = glo.QDSpy_autorunDefFileName
self.currStimFName = os.path.join(self.currStimPath, sf)
isAutoRunExists = fsu.getStimExists(self.currStimFName)
if isAutoRunExists:
# Check if a compiled version of the autorun file exists
self.isStimCurr = fsu.getStimCompileState(self.currStimFName)
if not isAutoRunExists or not self.isStimCurr:
# Use default file as no compiled auto-run file is present
self.currStimFName = os.path.join(self.currQDSPath, sd)
self.logWrite(
"ERROR",
f"No compiled `{sf}` in current stimulus folder"
)
self.logWrite("INFO", f"Using `{sd}` in `{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.logWrite(
"ERROR",
f"No compiled `{sf}` in current stimulus folder, "
f"and `{sd}.pickle` is not in `{self.currQDSPath}`. "
)
self.logWrite("ERROR", "Program is aborted.")
sys.exit(0)
# -------------------------------------------------------------------
# Loading, compiling, running, and aborting stimuli
# -------------------------------------------------------------------
def loadStim(self, _fName: str) -> int:
"""Load stimulus from file `_fName`, returns an error code if the
stimulus was not found or needs to be compiled
"""
self.isStimReady = False
errC = stm.StimErrC.ok
if not fsu.getStimExists(_fName):
# Stimulus file does not exist
errC = stm.StimErrC.invalidFileNamePath
else:
try:
# Try loading compiled stimulus file ...
self.Stim.load(_fName, _onlyInfo=True)
self.setState(State.ready)
self.isStimCurr = fsu.getStimCompileState(_fName)
self.currStimFName = _fName
self.isStimReady = True
except stm.StimException:
# Failed ...
errC = self.Stim.getLastErrC()
self.updateAll()
return errC
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def compileStim(self) -> None:
"""Send stimulus file name via pipe and signal worker thread to
compile the stimulus
"""
self.Sync.pipeCli.send(
[mpr.PipeValType.toSrv_fileName, self.currStimFName, self.currStimPath]
)
self.Sync.setRequestSafe(mpr.COMPILING)
self.logWrite(" ", "Compiling stimulus script ...")
# Wait for the worker to start ...
if self.Sync.waitForState(mpr.COMPILING, self.Conf.guiTimeOut, self.updateAll):
self.setState(State.compiling, True)
# Wait for the worker to finish the compilation, while keeping the
# GUI alive
self.Sync.waitForState(mpr.IDLE, 0.0, self.updateAll)
self.updateAll()
else:
self.logWrite(
"DEBUG",
"compileStim, timeout waiting for COMPILING"
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def runStim(self) -> None:
"""Send stimulus file name via pipe and signal worker thread to
start presenting the stimulus; wait for the stimulus to end ...
"""
#print("runStim", self.currStimFName, self.currStimPath)
self.Sync.pipeCli.send(
[mpr.PipeValType.toSrv_fileName, self.currStimFName, self.currStimPath,
self.Stim_soundVol]
)
self.Sync.setRequestSafe(mpr.PRESENTING)
self.logWrite(" ", "Presenting stimulus ...")
# Wait for the worker to start ...
if self.Sync.waitForState(mpr.PRESENTING, self.Conf.guiTimeOut, self.updateAll):
self.setState(State.playing, True)
# Wait for the worker to finish the presentation, while keeping the
# GUI alive
self.Sync.waitForState(mpr.IDLE, 0.0, self.updateAll)
self.updateAll()
else:
self.logWrite(
"DEBUG",
"runStim, timeout waiting for PRESENTING"
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def abortStim(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
res = self.Sync.waitForState(
mpr.IDLE, self.Conf.guiTimeOut, self.updateAll
)
if res:
self.setState(State.ready, True)
else:
self.logWrite(
"DEBUG",
"abortStimulus, timeout waiting for IDLE"
)
# -------------------------------------------------------------------
# Application control-related
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def closeEvent(self):
"""User requested to close the application
"""
# 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.abortStim()
# ... 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")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def updateAll(self) -> None:
""" Update the status
"""
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
self.processPipe()
#print(StateStr[self.state])
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setState(self, _newState, _doUpdateGUI=False):
""" Update state
"""
self.state = _newState
# -------------------------------------------------------------------
# Communication with worker-thread
# -------------------------------------------------------------------
def processPipe(self):
""" Read data from pipe to worker thread, if available
"""
while self.Sync.pipeCli.poll():
data = self.Sync.pipeCli.recv()
if data[0] == mpr.PipeValType.toCli_log:
# Handle log data -> write to history
self.log(data)
elif data[0] == mpr.PipeValType.toCli_displayInfo:
# Handle display information data -> update
self.Stage = pickle._loads(data[1])
isLCrDev = not self.Stage.scrDevType == stg.ScrDevType.generic
self.isLCrUsed = self.Conf.useLCr and isLCrDev
'''
self.updateAll()
'''
elif data[0] == mpr.PipeValType.toCli_IODevInfo:
# Receive I/O device information
self.isIODevReady = data[1][0]
if self.isIODevReady is None:
self.isIODevReady = False
self.lastIOInfo = data[1]
elif data[0] == mpr.PipeValType.toCli_time:
# Receive information about stimulus presentation progress
self.Stim_tFrRel_s = data[1]
self.Stim_nFrTotal = data[2]
elif data[0] == mpr.PipeValType.toCli_playEndInfo:
# Receive information about stimulus presentation end
self.Stim_completed = data[1]
else:
# ***************************
# TODO: Other types of data need to be processed
# ***************************
pass
def waitForPipe(self, _func, _timeOut_s=1.0):
""" Wait for the passed function to return True or for time-out
"""
n = _timeOut_s / 0.05
while not (_func()) and (n > 0):
self.processPipe()
time.sleep(0.05)
n -= 1
# -------------------------------------------------------------------
# Logging- and log file-related
# -------------------------------------------------------------------
def logWrite(self, _hdr: str, _msg: str, _isProg: bool = False):
"""Log a message to the appropriate output
"""
data = Log.write(_hdr, _msg, _isProg, _getStr=True, _isWorker=False)
if data:
self.log(data)
def log(self, _data):
if len(_data) > 2:
self.writeToLogFile(self._logFile, _data[2])
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'''
@staticmethod
def openLogFile(_fPath) -> TextIO:
"""Open a log file
"""
_fPath = fsu.repairPath(fsu.getQDSpyPath() +_fPath)
#print("openLogFile", _fPath)
os.makedirs(_fPath, exist_ok=True)
fName = time.strftime("%Y%m%d_%H%M%S")
j = 0
while os.path.exists(_fPath + fName):
fName = f"{fName}_{j:04d}"
j += 1
sf = _fPath + fName + glo.QDSpy_logFileExtension
return open(sf, "w"), sf
@staticmethod
def writeToLogFile(_file, _line):
"""Write text in `_line` to file `_file`
"""
if _file:
_file.write(_line +"\r")
@staticmethod
def closeLogFile(_file: TextIO):
"""Close the log file
"""
if _file:
_file.close()
'''
# ---------------------------------------------------------------------