-
Notifications
You must be signed in to change notification settings - Fork 17
/
ux.py
2012 lines (1635 loc) · 66.2 KB
/
ux.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
# SPDX-FileCopyrightText: 2020 Foundation Devices, Inc. <hello@foundationdevices.com>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# SPDX-FileCopyrightText: 2018 Coinkite, Inc. <coldcardwallet.com>
# SPDX-License-Identifier: GPL-3.0-only
#
# (c) Copyright 2018 by Coinkite Inc. This file is part of Coldcard <coldcardwallet.com>
# and is covered by GPLv3 license found in COPYING.
#
# ux.py - UX/UI related helper functions
#
# NOTE: do not import from main at top.
import gc
import utime
from display import Display, FontSmall, FontTiny
from uasyncio import sleep_ms
from uasyncio.queues import QueueEmpty
from common import system, dis
from data_codecs.qr_type import QRType
from data_codecs.qr_factory import get_qr_decoder_for_data, make_qr_encoder
from utils import is_alphanumeric_qr
LEFT_MARGIN = 8
RIGHT_MARGIN = 6
TOP_MARGIN = 12
VERT_SPACING = 10
MAX_WIDTH = Display.WIDTH - LEFT_MARGIN - \
RIGHT_MARGIN - Display.SCROLLBAR_WIDTH
TEXTBOX_MARGIN = 6
# This signals the need to switch from current
# menu (or whatever) to show something new. The
# stack has already been updated, but the old
# top-of-stack code was waiting for a key event.
class AbortInteraction(Exception):
pass
class UserInteraction:
def __init__(self):
self.stack = []
def is_top_level(self):
return len(self.stack) == 1
def top_of_stack(self):
return self.stack[-1] if self.stack else None
def reset_to_root(self):
root = self.stack[0]
self.reset(root)
def reset(self, new_ux):
self.stack.clear()
gc.collect()
self.push(new_ux)
async def interact(self):
# this is called inside a while(1) all the time
# - execute top of stack item
try:
await self.stack[-1].interact()
except AbortInteraction:
pass
def push(self, new_ux):
self.stack.append(new_ux)
def replace(self, new_ux):
old = self.stack.pop()
del old
self.stack.append(new_ux)
def pop(self):
if len(self.stack) < 2:
# top of stack, do nothing
return True
old = self.stack.pop()
del old
# Singleton. User interacts with this "menu" stack.
the_ux = UserInteraction()
def time_now_ms():
import utime
return utime.ticks_ms()
class KeyInputHandler:
def __init__(self, down="", up="", long="", repeat_delay=None, repeat_speed=None, long_duration=2000):
self.time_pressed = {}
self.down = down
self.up = up
self.long = long
self.repeat_delay = repeat_delay # How long until repeat mode starts
self.repeat_speed = repeat_speed # How many ms between each repeat
self.repeat_active = False
self.long_duration = long_duration
self.kcode_state = 0
self.kcode_last_time_pressed = 0
# Returns a dictionary of all pressed keys mapped to the elapsed time that each has been pressed.
# This can be used for things like showing the progress bar for the Hold to Sign functionality.
def get_all_pressed(self):
now = time_now_ms()
pressed = {}
for key, start_time in self.time_pressed.items():
pressed[key] = now - start_time
return pressed
def __update_kcode_state(self, expected_keys, actual_key):
# print('kcode: state={} expected={} actual={}'.format(self.kcode_state, expected_key, actual_key))
if actual_key in expected_keys:
self.kcode_state += 1
self.kcode_last_time_pressed = time_now_ms()
# print(' state advanced to {}'.format(self.kcode_state))
else:
self.kcode_state = 0
# print(' state reset to {}'.format(self.kcode_state))
# If this key could start a new sequence, then call recursively so we don't skip it
if actual_key == 'u':
# print(' second chance for {}'.format(actual_key))
self.__check_kcode(actual_key)
def __check_kcode(self, key):
if self.kcode_state == 0:
self.__update_kcode_state('u', key)
elif self.kcode_state == 1:
self.__update_kcode_state('u', key)
elif self.kcode_state == 2:
self.__update_kcode_state('d', key)
elif self.kcode_state == 3:
self.__update_kcode_state('d', key)
elif self.kcode_state == 4:
self.__update_kcode_state('l', key)
elif self.kcode_state == 5:
self.__update_kcode_state('r', key)
elif self.kcode_state == 6:
self.__update_kcode_state('l', key)
elif self.kcode_state == 7:
self.__update_kcode_state('r', key)
elif self.kcode_state == 8:
self.__update_kcode_state('xy', key)
elif self.kcode_state == 9:
self.__update_kcode_state('xy', key)
# If the user seems to be entering the kcode, then the caller should
# probably not perform the normal button processing
def kcode_imminent(self):
# print('kcode_immiment() = {}'.format(True if self.kcode_state >= 8 else False))
return self.kcode_state >= 8
def kcode_complete(self):
# print('kcode_complete game = {}'.format(True if self.kcode_state == 10 else False))
return self.kcode_state == 10
def kcode_reset(self):
# print('kcode_reset()')
self.kcode_state = 0
def is_pressed(self, key):
return key in self.time_pressed
def clear(self):
from common import keypad
keypad.clear_keys()
# Reset internal state so that all pending kcodes and repeats are forgotten.
def reset(self):
self.time_pressed = {}
self.kcode_state = 0
self.kcode_last_time_pressed = 0
self.repeat_active = False
# New input function to be used in place of PressRelease and ux_press_release, ux_all_up and ux_poll_once.
async def get_event(self):
from common import keypad
# This awaited sleep is necessary to give the simulator key code a chance to insert keys into the queue
# Without it, the ux_poll_once() below will never find a key.
await sleep_ms(5)
# See if we have a character in the queue and if so process it
# Poll for an event
key, is_down = keypad.get_event()
# if key != None:
# print('key={} is_down={}'.format(key, is_down))
if key == None:
# There was nothing in the queue, so handle the time-dependent events
now = time_now_ms()
for k in self.time_pressed:
# print('k={} self.down={} self.repeat={} self.time_pressed={}'.format(k, self.down, self.repeat, self.time_pressed))
# Handle repeats
if self.repeat_delay != None and k in self.down:
elapsed = now - self.time_pressed[k]
if self.repeat_active == False:
if elapsed >= self.repeat_delay:
self.repeat_active = True
self.time_pressed[k] = now
return (k, 'repeat')
else:
if elapsed >= self.repeat_speed:
self.time_pressed[k] = now
return (k, 'repeat')
# Handle long press expiration
if k in self.long:
elapsed = now - self.time_pressed[k]
if elapsed >= self.long_duration:
del self.time_pressed[k]
return (k, 'long_press')
# Handle kcode timeout - User seemed to give up, so go back to normal key processing
if self.kcode_state > 0 and now - self.kcode_last_time_pressed >= 3000:
# print('Resetting kcode due to timeout')
self.kcode_state = 0
return None
now = time_now_ms()
# Handle the event
if is_down:
self.__check_kcode(key)
# Check to see if we are interested in this key event
if key in self.down:
self.time_pressed[key] = now
return (key, 'down')
if key in self.long:
self.time_pressed[key] = now
else: # up
# Removing this will cancel long presses of the key as well
if key in self.time_pressed:
self.repeat_active = False
del self.time_pressed[key]
# Check to see if we are interested in this key event
if key in self.up:
return (key, 'up')
key_to_char_map_lower = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
'0': ' ',
}
key_to_char_map_upper = {
'2': 'ABC',
'3': 'DEF',
'4': 'GHI',
'5': 'JKL',
'6': 'MNO',
'7': 'PQRS',
'8': 'TUV',
'9': 'WXYZ',
'0': ' ',
}
key_to_char_map_numbers = {
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
'7': '7',
'8': '8',
'9': '9',
'0': '0 ',
}
# Class that implements a state machine for editing a text string like a passphrase.
# Takes KeyInputHandler events as state change events, along with elapsed time.
IDLE_KEY_TIMEOUT = 500
class TextInputHandler:
def __init__(self, text="", num_only=False, max_length=None):
self.text = [ch for ch in text]
self.cursor_pos = len(self.text) # Put cursor at the end if there is any initial text
self.last_key_down_time = 0
self.last_key = None
self.next_map_index = 0
self.curr_key_map = key_to_char_map_numbers if num_only else key_to_char_map_lower
self.num_only = num_only
self.max_length = max_length
if self.max_length:
# Make sure user-passed value doesn't exceed the max, if given
self.text = self.text[0:self.max_length]
def _next_key_map(self):
if self.num_only:
return
if self.curr_key_map == key_to_char_map_lower:
self.curr_key_map = key_to_char_map_upper
elif self.curr_key_map == key_to_char_map_upper:
self.curr_key_map = key_to_char_map_numbers
elif self.curr_key_map == key_to_char_map_numbers:
self.curr_key_map = key_to_char_map_lower
def get_mode_description(self):
if self.curr_key_map == key_to_char_map_lower:
return 'a-z'
elif self.curr_key_map == key_to_char_map_upper:
return 'A-Z'
elif self.curr_key_map == key_to_char_map_numbers:
return '0-9'
async def handle_event(self, event):
now = time_now_ms()
key, event_type = event
if event_type == 'down':
# Outer code handles these
if key in 'xy':
return
# print("key={}".format(key))
if key in '*#rl':
if key == '#':
self._next_key_map()
elif key == '*':
if self.cursor_pos > 0:
# Delete the character under the cursor
self.cursor_pos = max(self.cursor_pos-1, 0)
if len(self.text) > self.cursor_pos:
del self.text[self.cursor_pos]
elif key == 'l':
self.cursor_pos = max(self.cursor_pos - 1, 0)
elif key == 'r':
# Allow cursor_pos to go at most one past the end
self.cursor_pos = min(
self.cursor_pos + 1, len(self.text))
# print('cursor_pos={} next_map_index={} key={} text={}'.format(
# self.cursor_pos, self.next_map_index, key, self.text))
self.last_key_down_time = 0
return
# Check for symbols pop-up
if key == '1' and self.curr_key_map != key_to_char_map_numbers:
if self.max_length and len(self.text) >= self.max_length:
pass
else:
# Show the symbols pop-up, otherwise fall through and handle '1' as a normal key press
symbol = await ux_show_symbols_popup('!')
if symbol == None:
return
# Insert the symbol
self.text.insert(self.cursor_pos, symbol)
self.cursor_pos += 1
return
if self.last_key == None:
# print("first press of {}".format(key))
# A new keypress, so insert the first character mapped to this key, unless max reached
if self.max_length and len(self.text) >= self.max_length:
pass
else:
self.text.insert(
self.cursor_pos, self.curr_key_map[key][self.next_map_index])
self.cursor_pos += 1
if len(self.curr_key_map[key]) == 1:
# Just immediate commit this key since there are no other possible choices to wait for
return
elif self.last_key == key:
# User is pressing the same key within the idle timeout, so cycle to the next key
# making sure to wrap around if they keep going.
self.next_map_index = (
self.next_map_index + 1) % len(self.curr_key_map[key])
# Overwrite the last key
self.text[self.cursor_pos -
1] = self.curr_key_map[key][self.next_map_index]
else:
if self.max_length and len(self.text) >= self.max_length:
pass
else:
# User pressed a different key, but before the idle timeout, so we finalize the last
# character and start the next character as tentative.
self.cursor_pos += 1 # Finalize the last character
self.next_map_index = 0 # Reset the map index
# Append the new key
self.text.insert(
self.cursor_pos, self.curr_key_map[key][self.next_map_index])
# Insert or overwrite the character
# print('cursor_pos={} next_map_index={} key={} text={}'.format(
# self.cursor_pos, self.next_map_index, key, self.text))
# Always record the value and time of the key, regardless of which case we were in above
self.last_key = key
self.last_key_down_time = now
# This method should be called periodically (like event 10ms) if there is no key event.
# Return True if a timeout occurred, so the caller can render the updated state.
def check_timeout(self):
now = time_now_ms()
if self.last_key_down_time != 0 and now - self.last_key_down_time >= IDLE_KEY_TIMEOUT:
# print("timeout!")
# Reset for next key
self.last_key_down_time = 0
self.last_key = None
self.last_index = -1
self.next_map_index = 0
return True
return False
def get_text(self):
return "".join(self.text)
def get_num(self):
return int("".join(self.text))
async def ux_enter_text(title="Enter Text", label="Text", initial_text='', left_btn='BACK', right_btn='CONTINUE',
num_only=False, max_length=None):
from common import dis
from display import FontSmall
font = FontSmall
input = KeyInputHandler(down='1234567890*#rlxy', up='xy')
text_handler = TextInputHandler(text=initial_text, num_only=num_only, max_length=max_length)
while 1:
# redraw
system.turbo(True)
dis.clear()
dis.draw_header(title, left_text=text_handler.get_mode_description())
# Draw the title
y = Display.HEADER_HEIGHT + TEXTBOX_MARGIN
dis.text(None, y+2, label)
# Draw a bounding box around the text area
y += font.leading + TEXTBOX_MARGIN
dis.draw_rect(TEXTBOX_MARGIN, y, Display.WIDTH - (TEXTBOX_MARGIN * 2),
Display.HEIGHT - y - TEXTBOX_MARGIN - Display.FOOTER_HEIGHT, 1, fill_color=0, border_color=1)
# Draw the text and any other stuff
y += 4
dis.text_input(None, y, text_handler.get_text(),
cursor_pos=text_handler.cursor_pos, font=font)
dis.draw_footer(left_btn, right_btn, input.is_pressed(
'x'), input.is_pressed('y'))
dis.show()
system.turbo(False)
# Wait for key inputs
event = None
while True:
event = await input.get_event()
if event != None:
break
# No event, so handle the idle timing
if text_handler.check_timeout():
break
if event != None:
key, event_type = event
# Check for footer button actions first
if event_type == 'down':
await text_handler.handle_event(event)
if event_type == 'up':
if key == 'x':
return None
if key == 'y':
return text_handler.get_num() if num_only else text_handler.get_text()
symbol_rows = [
'!@#$%^&*',
'+/-=\\?|~',
'_"`\',.:;',
'()[]{}<>',
]
async def ux_show_symbols_popup(title="Enter Passphrase"):
from common import dis
from display import FontSmall
# print('ux_show_symbols_popup()')
font = FontSmall
input = KeyInputHandler(down='rlduxy', up='xy')
text_handler = TextInputHandler()
cursor_row = 0
cursor_col = 0
num_symbols_per_row = 8
num_rows = len(symbol_rows)
h_margin = 12
v_margin = 10
char_spacing = 22
width = num_symbols_per_row * char_spacing + (2 * h_margin)
height = num_rows * font.leading + (2 * v_margin)
while 1:
system.turbo(True)
# redraw
x = Display.WIDTH // 2 - width // 2
y = Display.HEIGHT - Display.FOOTER_HEIGHT - height - 14
dis.draw_rect(x, y, width, height, 2, 0, 1)
x += h_margin
y += v_margin
# Draw the grid of symbols
curr_row = 0
for symbols in symbol_rows:
dis.text(x, y, symbols,
cursor_pos=(cursor_col if curr_row ==
cursor_row else None),
font=font,
fixed_spacing=char_spacing,
cursor_shape='block')
curr_row += 1
y += font.leading
dis.draw_footer('CANCEL', 'SELECT', input.is_pressed(
'x'), input.is_pressed('y'))
dis.show()
system.turbo(False)
# Wait for key inputs
event = None
while True:
event = await input.get_event()
if event != None:
break
# No event, so handle the idle timing
if text_handler.check_timeout():
break
num_symbols = len(symbol_rows[cursor_row])
if event != None:
key, event_type = event
# Check for footer button actions first
if event_type == 'down':
if key == 'u':
cursor_row = (cursor_row - 1) % num_rows
elif key == 'd':
cursor_row = (cursor_row + 1) % num_rows
elif key == 'l':
cursor_col = (cursor_col - 1) % num_symbols
elif key == 'r':
cursor_col = (cursor_col + 1) % num_symbols
if event_type == 'up':
if key == 'x':
return None
if key == 'y':
return symbol_rows[cursor_row][cursor_col]
# NOTE: This function factors in the scrollbar width even if the scrollbar might not end up being shown,
# because the line breaking code uses it BEFORE knowing if scrolling is required.
def chars_per_line(font):
return (Display.WIDTH - LEFT_MARGIN - Display.SCROLLBAR_WIDTH) // font.advance
def word_wrap(ln, font):
from common import dis
max_width = Display.WIDTH - LEFT_MARGIN - \
RIGHT_MARGIN - Display.SCROLLBAR_WIDTH
while ln:
sp = 0
last_space = 0
line_width = 0
first_non_space = 0
# Strip out leading and trailing spaces
ln = ln.strip()
while sp < len(ln):
ch = ln[sp]
if ch.isspace():
last_space = sp
ch_w = dis.char_width(ch, font)
line_width += ch_w
if line_width >= max_width:
# If we found a space, we can break there, but if we didn't
# then just break before we went over.
if last_space != 0:
sp = last_space
break
sp += 1
line = ln[first_non_space:sp]
ln = ln[sp:]
yield line
async def ux_show_story(msg, title='Passport', sensitive=False, font=FontSmall, escape='', left_btn='BACK',
right_btn='CONTINUE', scroll_label=None, left_btn_enabled=True, right_btn_enabled=True,
center_vertically=False, center=False, overlay=None, clear_keys=False):
from common import dis, keypad
from utils import split_by_char_size
system.turbo(True)
# Clear the keys before starting
if clear_keys:
keypad.clear_keys()
if hasattr(msg, 'readline'):
lines = split_by_char_size(msg.getvalue(), font)
else:
lines = split_by_char_size(msg, font)
# trim blank lines at end
while not lines[-1]:
lines = lines[:-1]
top = 0
H = (Display.HEIGHT - Display.HEADER_HEIGHT -
Display.FOOTER_HEIGHT) // font.leading
max_visible_lines = (Display.HEIGHT - Display.HEADER_HEIGHT - Display.FOOTER_HEIGHT) // font.leading
input = KeyInputHandler(down='rldu0xy', up='xy' + escape, repeat_delay=250, repeat_speed=10)
system.turbo(False)
allow_right_btn_action = True
turbo = None # We rely on this being 3 states: None, False, True
while 1:
# redraw
dis.clear()
dis.draw_header(title)
y = Display.HEADER_HEIGHT
# Only take center_vertically into account if there are more lines than will fit on the page
if len(lines) <= max_visible_lines and center_vertically:
avail_height = (Display.HEIGHT -
Display.HEADER_HEIGHT - Display.FOOTER_HEIGHT)
text_height = len(lines) * font.leading - font.descent
y += avail_height // 2 - text_height // 2
content_to_height_ratio = H / len(lines)
show_scrollbar= True if content_to_height_ratio < 1 else False
last_to_show = min(top+H+1, len(lines))
for ln in lines[top:last_to_show]:
x = LEFT_MARGIN if not center else None
dis.text(x, y, ln, font=font, scrollbar_visible=show_scrollbar)
y += font.leading
if show_scrollbar:
dis.scrollbar(top / len(lines), content_to_height_ratio)
# Show the scroll_label if given and if we have not reached the bottom yet
scroll_enable_right_btn = True
right_btn_label = right_btn
if scroll_label != None:
if H + top < len(lines):
scroll_enable_right_btn = False
right_btn_label = scroll_label
dis.draw_footer(left_btn, right_btn_label,
input.is_pressed('x'), input.is_pressed('y'))
# Draw overlay image, if any
if overlay:
(x, y, image) = overlay
dis.icon(x, y, image)
dis.show()
# We only want to turn it off once rather than whenever it's False, so we
# set to None to avoid turning turbo off again.
if turbo == False:
system.turbo(False)
turbo = None
# Wait for key inputs
event = None
while True:
while True:
event = await input.get_event()
if event != None:
break
key, event_type = event
# print('key={} event_type={}'.format(key, event_type))
if event_type == 'down' or event_type == 'repeat':
system.turbo(True)
turbo = True
if key == 'u':
top = max(0, top-1)
break
elif key == 'd':
if len(lines) > H:
top = min(len(lines) - H, top+1)
break
elif key == 'y':
if event_type == 'repeat':
allow_right_btn_action = False
elif event_type == 'down':
allow_right_btn_action = True
if not scroll_enable_right_btn:
if len(lines) > H:
top = min(len(lines) - H, top+1)
else:
continue
break
elif key in 'xy':
# allow buttons to redraw for pressed state
break
else:
continue
if event_type == 'down':
if key == '0':
top = 0
break
else:
continue
if event_type == 'up':
turbo = False # We set to False here, but actually turn off after rendering
if key in escape:
return key
# No left_btn means don't exit on the 'x' key
if left_btn_enabled and (key == 'x'):
return key
if key == 'y':
if scroll_enable_right_btn:
if right_btn_enabled and allow_right_btn_action:
return key
break
else:
if len(lines) > H:
top = min(len(lines) - H, top+1)
break
else:
continue
async def ux_confirm(msg, title='Passport', negative_btn='NO', positive_btn='YES', center=True, center_vertically=True, scroll_label=None):
resp = await ux_show_story(msg, title=title, center=center, center_vertically=center_vertically, left_btn=negative_btn, right_btn=positive_btn, scroll_label=scroll_label)
return resp == 'y'
# async def ux_dramatic_pause(msg, seconds):
# from common import dis, system
#
# # show a full-screen msg, with a dramatic pause + progress bar
# n = seconds * 8
# dis.fullscreen(msg)
# for i in range(n):
# system.progress_bar((i*100)//n)
# await sleep_ms(125)
def blocking_sleep(ms):
start = utime.ticks_ms()
while (1):
now = utime.ticks_ms()
if now - start >= ms:
return
def save_error_log(msg, filename):
from files import CardSlot, CardMissingError
wrote_to_sd = False
try:
with CardSlot() as card:
# Full path and short filename
fname, nice = card.get_file_path(filename)
with open(fname, 'wb') as fd:
line = 'Saved %s to microSD' % nice
fd.write(msg)
wrote_to_sd = True
except CardMissingError:
line = 'Insert microSD to save log'
except Exception:
line = 'Failed to save %s' % filename
return wrote_to_sd, line
def ux_show_fatal(msg):
from common import dis
from display import FontTiny
font = FontTiny
ch_per_line = chars_per_line(font)
lines = []
for ln in msg.split('\n'):
if len(ln) > ch_per_line:
lines.extend(word_wrap(ln, font))
else:
# ok if empty string, just a blank line
lines.append(ln)
# Draw
top = 0
max_visible_lines = (
Display.HEIGHT - Display.HEADER_HEIGHT) // font.leading + 1
num_lines = len(lines)
max_top = max(0, num_lines - max_visible_lines)
PER_LINE_DELAY = 500
LONG_DELAY = 2000
INITIAL_DELAY = 5000
delay = INITIAL_DELAY
direction = 1
# Write
filename = 'error.log'
wrote_to_sd, lines[0] = save_error_log(msg, filename)
while (1):
system.turbo(True)
# Draw
dis.clear()
dis.draw_header('Error')
# Draw the subset of lines that is visible
y = Display.HEADER_HEIGHT
for ln in lines[top:top+max_visible_lines]:
dis.text(LEFT_MARGIN, y, ln, font=font)
y += font.leading
dis.show()
system.turbo(False)
blocking_sleep(delay)
# More lines than can be displayed - early exit if no scrolling needed
if num_lines <= max_visible_lines:
return
# Change direction if we reach the top or bottom
if direction == 1:
top = min(max_top, top + 1)
if top == max_top:
direction = -1
else:
top = max(0, top - 1)
if top == 0:
direction = 1
delay = PER_LINE_DELAY
if top == 0 or top == max_top:
if wrote_to_sd is False:
wrote_to_sd, lines[0] = save_error_log(msg, filename)
delay = LONG_DELAY
def show_fatal_error(msg):
all_lines = msg.split('\n')[0:]
# Remove lines we don't want to shorten
lines = all_lines[1:-2]
# Insert lines we want to add for readability or keep from the original msg
lines.insert(0, "")
lines.insert(1, "")
lines.append("")
lines.append(all_lines[-2])
ux_show_fatal("\n".join(lines))
def restore_menu():
# redraw screen contents after disrupting it w/ non-ux things (usb upload)
m = the_ux.top_of_stack()
if hasattr(m, 'update_contents'):
m.update_contents()
if hasattr(m, 'show'):
m.show()
def abort_and_goto(m):
import common
common.keypad.clear_keys()
the_ux.reset(m)
def abort_and_push(m):
common.keypad.clear_keys()
the_ux.push(m)
# async def show_qr_codes(addrs, is_alnum, start_n):
# o = QRDisplay(addrs, is_alnum, start_n)
# await o.interact_bare()
# class QRDisplay(UserInteraction):
# # Show a QR code for (typically) a list of addresses. Can only work on Mk3
#
# def __init__(self, addrs, is_alnum, start_n=0,path='', account=0, change=0):
# self.is_alnum = is_alnum
# self.idx = 0 # start with first address
# self.invert = False # looks better, but neither mode is ideal
# self.addrs = addrs
# self.start_n = start_n
# self.qr_data = None
# self.left_down = False
# self.right_down = False
# self.input = KeyInputHandler(down='xyudlr', up='xy')
#
# def render_qr(self, msg):
# # Version 2 would be nice, but can't hold what we need, even at min error correction,
# # so we are forced into version 3 = 29x29 pixels
# # - see <https://www.qrcode.com/en/about/version.html>
# # - to display 29x29 pixels, we have to double them up: 58x58
# # - not really providing enough space around it
# # - inverted QR (black/white swap) still readable by scanners, altho wrong
#
# from utils import imported
#
# with imported('uQR') as uqr:
# if self.is_alnum:
# # targeting 'alpha numeric' mode, typical len is 42
# ec = uqr.ERROR_CORRECT_Q
# assert len(msg) <= 47
# else:
# # has to be 'binary' mode, altho shorter msg, typical 34-36
# ec = uqr.ERROR_CORRECT_M
# assert len(msg) <= 42
#
# q = uqr.QRCode(version=3, box_size=1, border=0,
# mask_pattern=3, error_correction=ec)
# if self.is_alnum:
# here = uqr.QRData(msg.upper().encode('ascii'),
# mode=uqr.MODE_ALPHA_NUM, check_data=False)
# else:
# here = uqr.QRData(msg.encode('ascii'),
# mode=uqr.MODE_8BIT_BYTE, check_data=False)
# q.add_data(here)
# q.make(fit=False)
#
# self.qr_data = q.get_matrix()
#
# def redraw(self):
# # Redraw screen.
# from common import dis, system
# from display import FontTiny
#
# system.turbo(True)
# font = FontTiny
# inv = self.invert
#
# # what we are showing inside the QR
# msg, path = self.addrs[self.idx]
#