-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplayLogic.py
312 lines (254 loc) · 10.5 KB
/
displayLogic.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
import logsetup
from prompt_toolkit import HTML
from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.shortcuts import ProgressBar, yes_no_dialog
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.styles import BaseStyle
from prompt_toolkit.completion import Completer, CompleteEvent, Completion
from prompt_toolkit.document import Document
from prompt_toolkit.application import Application, create_app_session
from prompt_toolkit.application.current import get_app
from prompt_toolkit.widgets import Dialog, Button, Label, TextArea, ValidationToolbar
from prompt_toolkit.layout import Layout
from prompt_toolkit.layout.containers import AnyContainer, HSplit, VSplit
from prompt_toolkit.layout.dimension import Dimension as D
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.validation import Validator
import time, os, signal, sys, asyncio, logging, concurrent
from typing import Any, Callable, List, Optional, Tuple, TypeVar, Iterable
from functools import partial
import datetime
import digitisationLogic as dl
logger = logging.getLogger("displayLogic")
def _create_app(dialog: AnyContainer, style: Optional[BaseStyle], customBindings: Optional[KeyBindings] = None) -> Application[Any]:
# Key bindings.
bindings = customBindings if customBindings else KeyBindings()
bindings.add("tab")(focus_next)
bindings.add("s-tab")(focus_previous)
bindings.add("down")(focus_next)
bindings.add("up")(focus_previous)
return Application(
layout=Layout(dialog),
key_bindings=merge_key_bindings([load_key_bindings(), bindings]),
mouse_support=True,
style=style,
full_screen=False,
erase_when_done=True
)
async def mainDialog(camera, batchSize, shutterSpeed):
batchSize = [batchSize]
shutterSpeed = [shutterSpeed]
kb = KeyBindings()
@kb.add('q')
def quithdl(event)-> None:
get_app().exit((-1, shutterSpeed[0]))
@kb.add('o')
def scanOne(event) -> None:
get_app().layout.focus(btnOne)
fp = dl.takePicture(camera)
dl.getPictures(camera, fp)
@kb.add('f')
def moveForward(event) -> None:
get_app().layout.focus(btnForward)
asyncio.run_coroutine_threadsafe(dl.moveForward(), asyncio.get_event_loop())
@kb.add('b')
def moveBackward(event) -> None:
get_app().layout.focus(btnBackward)
asyncio.run_coroutine_threadsafe(dl.moveBackward(), asyncio.get_event_loop())
@kb.add('s')
def scanBatch(event):
get_app().layout.focus(btnBatch)
get_app().exit((batchSize[0], shutterSpeed[0]))
@kb.add('h')
def focusShutterspeed(event):
get_app().layout.focus(shutterTextField)
@kb.add('a')
def focusBatchSize(event):
get_app().layout.focus(batchSizeTextArea)
title = "Slide Digitalisation"
width = len(title) + 4
btnBatch = Button(text="[s]can batch", handler=partial(scanBatch, None), width=width, left_symbol="", right_symbol="")
btnOne = Button(text="Scan [o]ne (w/o) moving", handler=partial(scanOne, None), width=width, left_symbol="", right_symbol="")
btnForward = Button(text="[f]orward", handler=partial(moveForward, None), width=width, left_symbol="", right_symbol="")
btnBackward = Button(text="[b]ackward", handler=partial(moveBackward, None), width=width, left_symbol="", right_symbol="")
btnQuit = Button(text="[q]uit", handler=partial(quithdl, None), width=width, left_symbol="", right_symbol="")
def batchSizeAcceptor(buf: Buffer) -> bool:
get_app().layout.focus(btnBatch)
batchSize[0] = int(buf.text)
return True # Keep text.
def is_valid(text):
try:
batchSize[0] = int(text)
return True
except ValueError:
return False
def batchSizeTextChangeHandler(buf: Buffer):
try:
batchSize[0] = int(buf.text)
except ValueError:
pass
batchSizeValidator = Validator.from_callable(is_valid, error_message='Numbers only')
batchSizeTextArea = TextArea(
text=str(batchSize[0]),
multiline=False,
password=False,
validator=batchSizeValidator,
accept_handler=batchSizeAcceptor
)
batchSizeTextArea.buffer.on_text_changed.add_handler(batchSizeTextChangeHandler)
def shutterSpeedValid(text):
try:
if text.startswith('1/'):
return int(text[2:]) > 1
else:
return int(text) > 0
except:
return False
def shutterSpeedAcceptor(buf: Buffer) -> bool:
if shutterSpeedValid(buf.text):
dl.setShutterspeed(camera, buf.text)
shutterSpeed[0] = dl.getShutterspeed(camera)
shutterTextField.text = shutterSpeed[0]
get_app().layout.focus(btnOne)
return True
return False
shutterSpeedValidator = Validator.from_callable(shutterSpeedValid, error_message='Not a valid shutter speed')
shutterTextField = TextArea(
text=shutterSpeed[0],
multiline=False,
password=False,
width=8,
validator=shutterSpeedValidator,
accept_handler=shutterSpeedAcceptor
)
## TODO: When in text fields, keyBindings still respond (and move the cursor out of the text field).
## Not a real problem here though.
dialog = Dialog(
title=title,
body=HSplit([Label(text="Please select:"),
btnBatch,
btnOne,
btnForward,
btnBackward,
VSplit([Label(text="B[a]tch size:"), batchSizeTextArea]),
ValidationToolbar(),
VSplit([Label(text="S[h]utter speed:"), shutterTextField]),
ValidationToolbar(), ## TODO: both validation toolbars respond to the same events.
Label(text='Press enter above to accept'),
btnQuit
],
padding=0),
#padding=D(preferred=1, max=1)),
buttons=[],
with_background=True
)
return await _create_app(dialog, None, kb).run_async()
async def pauseDialog():
kb = KeyBindings()
@kb.add('f')
def moveForward(event) -> None:
get_app().layout.focus(btnForward)
asyncio.run_coroutine_threadsafe(dl.moveForward(), asyncio.get_event_loop())
@kb.add('b')
def moveBackward(event) -> None:
get_app().layout.focus(btnBackward)
asyncio.run_coroutine_threadsafe(dl.moveBackward(), asyncio.get_event_loop())
@kb.add('c')
def continueScanning(event) -> None:
get_app().exit(0)
@kb.add('q')
def quitScanning(event) -> None:
get_app().exit(-1)
title = "Paused"
width = len(title) + 4
btnContinue = Button(text="[c]ontinue", handler=partial(continueScanning, None), width=width, left_symbol="", right_symbol="")
btnForward = Button(text="[f]orward", handler=partial(moveForward, None), width=width, left_symbol="", right_symbol="")
btnBackward = Button(text="[b]ackward", handler=partial(moveBackward, None), width=width, left_symbol="", right_symbol="")
btnQuit = Button(text="[q]uit", handler=partial(quitScanning, None), width=width, left_symbol="", right_symbol="")
dialog = Dialog(
title=title,
body=HSplit([Label(text="Please select:"),
btnContinue,
btnForward,
btnBackward,
btnQuit
],
padding=0),
#padding=D(preferred=1, max=1)),
buttons=[],
with_background=True
)
return await _create_app(dialog, None, kb).run_async()
async def batchScanDialogue(camera, batchSize, scanProgress = 0, time_elapsed = datetime.timedelta(0)):
bottom_toolbar = HTML('<b>[i/d]</b> Increment / decrement batch size <b>[p]</b> Pause <b>[a]</b> Abort batch')
title = HTML('Slide scanning...')
# Create custom key bindings first.
kb = KeyBindings()
cancel = [False]
pause = [False]
batches = [batchSize]
@kb.add('i')
def increment(event):
batches[0] += 1
@kb.add('d')
def decrement(event):
batches[0] -= 1
@kb.add('p')
def p(event):
pause[0] = True
@kb.add('a')
def a(event):
" Send Abort (control-c) signal. "
cancel[0] = True
#os.kill(os.getpid(), signal.SIGINT)
# Use `patch_stdout`, to make sure that prints go above the
# application. Doesn't seem to work on Windows
with patch_stdout():
with ProgressBar(title=title, key_bindings=kb, bottom_toolbar=bottom_toolbar,) as pb:
previousBatch = 0
pbc = pb(total = batches[0])
pbc.start_time -= time_elapsed
pbc.items_completed = scanProgress
if scanProgress > 0:
pbc.progress_bar.invalidate()
while scanProgress < batches[0]:
logger.debug("At scanProgress: %d" %scanProgress)
if batches[0] != previousBatch:
pbc.total = batches[0]
pbc.progress_bar.invalidate()
previousBatch = batches[0]
# Do picture taking and transfer here
await dl.takeOneAndMove(camera, pause)
scanProgress += 1
pbc.item_completed()
# Pause when the pause flag has been set.
if pause[0]:
return batches[0], scanProgress, pbc.time_elapsed
# Stop when the cancel flag has been set.
if cancel[0]:
return batches[0], -1, None
pbc.done = True
return batches[0], -1, pbc.time_elapsed
async def main():
batchSize = origBatchSize = 36
camera = await dl.setup()
shutterSpeed = dl.getShutterspeed(camera)
while True:
batchSize, shutterSpeed = await mainDialog(camera, batchSize, shutterSpeed)
logger.debug("Main Dialog returned %d" %batchSize)
if batchSize == -1:
break
scanProgress = 0
time_elapsed = datetime.timedelta(0)
while True:
batchSize, scanProgress, time_elapsed = await batchScanDialogue(camera, batchSize, scanProgress, time_elapsed)
if scanProgress == -1:
break
pausRes = await pauseDialog()
if pausRes < 0:
break
if batchSize == 1:
batchSize = origBatchSize
dl.teardown()