-
Notifications
You must be signed in to change notification settings - Fork 1
/
bsWidgets.py
2570 lines (2211 loc) · 105 KB
/
bsWidgets.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/python
# encoding: utf-8
##############################################################################
# bsWidgets.py - npyscreen-based (b)ook(s)tore widgets
#
##############################################################################
# Copyright (c) 2022, 2023 David Villena
# All rights reserved.
# Licensed under the New BSD License
# (http://www.freebsd.org/copyright/freebsd-license.html)
##############################################################################
import curses
import datetime
import locale
import sys
import time
import npyscreen
from npyscreen import fmForm
from npyscreen import wggrid as grid
from npyscreen import wgmultiline as multiline
from npyscreen import wgtextbox as textbox
from npyscreen import wgwidget as widget
import config
#import inspect
from config import SCREENWIDTH as WIDTH
ALLOW_NEW_INPUT = True
EXITED_UP = -1
RAISEERROR = 'RAISEERROR'
EXITED_ESCAPE= 127
def notify_ok_cancel(message, title="", form_color='CURSOR_INVERSE', wrap=True, editw = 0,):
"Display a question message. Returns True if OK button pressed, False if Cancel button pressed."
curses.flushinp() # flush all keyboard input at this point
message = npyscreen.utilNotify._prepare_message(message)
F = npyscreen.utilNotify.ConfirmCancelPopup(name=title, color=form_color)
F.preserve_selected_widget = True
F.show_aty = 9
mlw = F.add(npyscreen.wgmultiline.Pager,)
mlw_width = mlw.width-1
if wrap:
message = npyscreen.utilNotify._wrap_message_lines(message, mlw_width)
mlw.values = message
F.editw = editw
F.edit()
return F.value
def notify(message, title="Message", form_color='STANDOUT', wrap=True, wide=False,):
"Display a message for a time, then close it."
curses.flushinp() # flush all keyboard input at this point
message = npyscreen.utilNotify._prepare_message(message)
if wide:
F = MiniPopup(name=title, color=form_color)
else:
F = MiniPopup(name=title, color=form_color)
F.preserve_selected_widget = True
mlw = F.add(npyscreen.wgmultiline.Pager,)
mlw_width = mlw.width-1
if wrap:
message = npyscreen.utilNotify._wrap_message_lines(message, mlw_width)
mlw.values = message
F.display()
time.sleep(0.6) # let it be seen
def notify_OK(message, title="Message", form_color='STANDOUT', wrap=True, wide=False, editw = 0,):
"Display a message until OK button is pressed."
curses.flushinp() # flush all keyboard input at this point
message = npyscreen.utilNotify._prepare_message(message)
if wide:
F = npyscreen.fmPopup.PopupWide(name=title, color=form_color)
else:
F = npyscreen.fmPopup.Popup(name=title, color=form_color)
F.preserve_selected_widget = True
mlw = F.add(npyscreen.wgmultiline.Pager,)
mlw_width = mlw.width-1
if wrap:
message = npyscreen.utilNotify._wrap_message_lines(message, mlw_width)
else:
message = message.split("\n")
mlw.values = message
F.editw = editw
F.edit()
class NotEnoughSpaceForWidget(Exception):
pass
class MiniPopup(npyscreen.Popup):
DEFAULT_LINES = 12
DEFAULT_COLUMNS = 51
SHOW_ATX = 13
SHOW_ATY = 7
class MyFixedText(textbox.FixedText):
"DV: My own version with self.how_exited incorporated."
def __init__(self, screen, value='', highlight_color='CURSOR', highlight_whole_widget=False, invert_highlight_color=True, **keywords):
super().__init__(screen, value, highlight_color, highlight_whole_widget, invert_highlight_color, **keywords)
self.how_exited = widget.EXITED_DOWN # for editw = n
class MyTextfield(textbox.TextfieldBase):
"My own TextfieldBase, to support Windows/unicode."
def __init__(self, screen, value='', highlight_color='CURSOR', highlight_whole_widget=False, invert_highlight_color=True, fixed_length=True, **keywords):
super().__init__(screen, value, highlight_color, highlight_whole_widget, invert_highlight_color, **keywords) # to TextfieldBase -> Widget
self.fixed_length = fixed_length # added to allow fixed/non-fixed length scrollable fields
def show_brief_message(self, message):
curses.beep()
keep_for_a_moment = self.value
self.value = message
self.editing=False
self.display()
curses.napms(1200)
self.editing=True
self.value = keep_for_a_moment
def when_check_value_changed(self):
"Manages input length according to self.maximum_string_length"
if self.fixed_length: # fixed_length means the field is not horiz-scrollable
if len(self.value) > self.maximum_string_length:
self.value = self.value[:self.maximum_string_length]
# No literal added here.
self.update(clear=True)
else:
pass # no fixed length means the field is horiz-scrollable
def filter_char(self, char):
"Filters some keys for the terminal."
match char:
case ( 459 ): # Numeric pad enter key
char = 13
case ( 465 ): # Numeric pad plus key
char = 43
case ( 464 ): # Numeric pad minus key
char = 45
case ( 463 ): # Numeric pad asterisk key
char = 42
case ( 458 ): # Numeric pad slash key
char = 47
case ( 331 ): # Insert key
char = False
case ( 262 ): # Home key
pass # go on
case ( 339 ): # Page Up key
char = False
case ( 338 ): # Page Down key - And french Œ !
char = False
case ( 358 ): # End key
pass # go on
case ( curses.ascii.ESC ): # Escape key
# numeral/find field :
if "DetailField" in repr(self): # Detail field
pass # go on
elif "MyTextfield" in repr(self): # "regular" text field
pass # go on
else:
char = False
case ( 384 ): # < key
char = 60
case ( 448 ): # > key
char = 62
return char
def _get_ch(self):
"""
>>>---> DV: Heavily modified to display non-ascii characters under Python 3.10
(See original in wgwidget.py)
"""
#try:
# # Python3.3 and above - returns unicode
# ch = self.parent.curses_pad.get_wch()
# self._last_get_ch_was_unicode = True
#except AttributeError:
# For now, disable all attempt to use get_wch()
# but everything that follows could be in the except clause above.
# DV: For GNU/Linux:
if config.system == "Linux":
# Try to read utf-8 if possible.
_stored_bytes =[]
self._last_get_ch_was_unicode = True
global ALLOW_NEW_INPUT
if ALLOW_NEW_INPUT == True and locale.getpreferredencoding() == 'UTF-8':
ch = self.parent.curses_pad.getch()
if ch <= 127:
rtn_ch = ch
self._last_get_ch_was_unicode = False
return rtn_ch
elif ch <= 193:
rtn_ch = ch
self._last_get_ch_was_unicode = False
return rtn_ch
# if we are here, we need to read 1, 2 or 3 more bytes.
# all of the subsequent bytes should be in the range 128 - 191,
# but we'll risk not checking...
elif 194 <= ch <= 223:
# 2 bytes
_stored_bytes.append(ch)
_stored_bytes.append(self.parent.curses_pad.getch())
elif 224 <= ch <= 239:
# 3 bytes
_stored_bytes.append(ch)
_stored_bytes.append(self.parent.curses_pad.getch())
_stored_bytes.append(self.parent.curses_pad.getch())
elif 240 <= ch <= 244:
# 4 bytes
_stored_bytes.append(ch)
_stored_bytes.append(self.parent.curses_pad.getch())
_stored_bytes.append(self.parent.curses_pad.getch())
_stored_bytes.append(self.parent.curses_pad.getch())
elif ch >= 245:
# probably a control character
self._last_get_ch_was_unicode = False
return ch
ch = bytes(_stored_bytes).decode('utf-8', errors='strict')
else:
ch = self.parent.curses_pad.getch()
self._last_get_ch_was_unicode = False
# This line should not be in the except clause.
return ch
# >>> DV: for Windows:
elif config.system == "Windows":
if ALLOW_NEW_INPUT == True:
ch = self.parent.curses_pad.getch()
rtn_ch = ch
self._last_get_ch_was_unicode = False
return rtn_ch
def get_and_use_key_press(self):
"Adapted from class Widget. Substitutes entirely the original function."
# Enter raw mode. In raw mode, normal line buffering and processing of interrupt, quit, suspend,
# and flow control keys are turned off; characters are presented to curses input functions one by one.
curses.raw()
# Enter cbreak mode: normal line buffering is turned off and characters are available to be read one by one.
curses.cbreak()
# meta: if flag is True, allow 8-bit characters to be input. If flag is False, allow only 7-bit chars.
curses.meta(True)
self.parent.curses_pad.keypad(1)
if self.parent.keypress_timeout:
curses.halfdelay(self.parent.keypress_timeout)
ch = self._get_ch()
if ch == -1:
return self.try_while_waiting()
else:
self.parent.curses_pad.timeout(-1)
ch = self._get_ch()
ch = self.filter_char(ch)
if ch == False: # Useless keys
return
# handle escape-prefixed rubbish.
if ch == curses.ascii.ESC:
#self.parent.curses_pad.timeout(1)
self.parent.curses_pad.nodelay(1)
ch2 = self.parent.curses_pad.getch()
if ch2 != -1:
ch = curses.ascii.alt(ch2)
self.parent.curses_pad.timeout(-1) # back to blocking mode
#curses.flushinp()
self.handle_input(ch)
if self.check_value_change:
self.when_check_value_changed()
if self.check_cursor_move:
self.when_check_cursor_moved()
self.try_adjust_widgets()
def edit(self):
self.editing = 1
if self.cursor_position is False:
self.cursor_position = 0
#self.cursor_position = len(self.value or '')
self.parent.curses_pad.keypad(1)
self.how_exited = False # self.do_nothing = pass
while self.editing:
self.display()
self.get_and_use_key_press()
self.begin_at = 0
#self.display() # don't uncomment: DetailField escape issue
self.cursor_position = False
return self.how_exited, self.value
def display_value(self, value):
"It's the display_value() from TextfieldBase."
if value == None:
return ''
else:
try:
str_value = str(value)
except UnicodeEncodeError:
str_value = self.safe_string(value)
return str_value
except ReferenceError:
return ">*ERROR*ERROR*ERROR*<"
return self.safe_string(str_value)
def _get_string_to_print(self):
"From TextfieldBase, adapted to right-screen."
string_to_print = self.display_value(self.value)
if not string_to_print:
return None
string_to_print = string_to_print[self.begin_at:self.maximum_string_length + self.begin_at - self.left_margin]
string_to_print = self.display_value(self.value)[self.begin_at:self.maximum_string_length + self.begin_at - self.left_margin]
return string_to_print
def _print(self):
"Adaptation of _print() from TextfieldBase."
string_to_print = self._get_string_to_print()
if not string_to_print:
if self.parent.name == "BookSelector" or \
self.parent.name == "AuthorSelector" or \
self.parent.name == "PublisherSelector" or \
self.parent.name == "WarehouseSelector" or \
self.parent.name == "UserSelector" :
if self.name != "DetailFld":
self.value = " " # DV: for empty fields of selector-grids, to get a full highlighted row
string_to_print = " " # DV: for empty fields of selector-grids, to get a full highlighted row
else:
return None
else:
return None
string_to_print = string_to_print[self.begin_at:self.maximum_string_length + self.begin_at - self.left_margin]
string_to_print = self.display_value(self.value)[self.begin_at:self.maximum_string_length+self.begin_at-self.left_margin]
column = 0
place_in_string = 0
if self.syntax_highlighting:
self.update_highlighting(start=self.begin_at, end=self.maximum_string_length+self.begin_at-self.left_margin)
while column <= (self.maximum_string_length - self.left_margin):
if not string_to_print or place_in_string > len(string_to_print)-1:
break
width_of_char_to_print = self.find_width_of_char(string_to_print[place_in_string])
if column - 1 + width_of_char_to_print > self.maximum_string_length:
break
try:
highlight = self._highlightingdata[self.begin_at+place_in_string]
except:
highlight = curses.A_NORMAL
self.parent.curses_pad.addstr(self.rely,self.relx+column+self.left_margin,
self._print_unicode_char(string_to_print[place_in_string]),
highlight
)
column += self.find_width_of_char(string_to_print[place_in_string])
place_in_string += 1
else:
if self.do_colors():
if self.show_bold and self.color == 'DEFAULT':
color = self.parent.theme_manager.findPair(self, 'BOLD') | curses.A_BOLD
elif self.show_bold:
color = self.parent.theme_manager.findPair(self, self.color) | curses.A_BOLD
elif self.important:
color = self.parent.theme_manager.findPair(self, 'IMPORTANT') | curses.A_BOLD
else:
color = self.parent.theme_manager.findPair(self)
else:
if self.important or self.show_bold:
color = curses.A_BOLD
else:
color = curses.A_NORMAL
while column <= (self.maximum_string_length - self.left_margin):
if not string_to_print or place_in_string > len(string_to_print)-1:
if self.highlight_whole_widget:
if (self.relx+column+self.left_margin < WIDTH): # DV: modified
self.parent.curses_pad.addstr(self.rely,self.relx+column+self.left_margin,
' ',
color
)
column += width_of_char_to_print
place_in_string += 1
continue
else:
break
width_of_char_to_print = self.find_width_of_char(string_to_print[place_in_string])
if column - 1 + width_of_char_to_print > self.maximum_string_length:
break
self.parent.curses_pad.addstr(self.rely,self.relx+column+self.left_margin,
self._print_unicode_char(string_to_print[place_in_string]),
color
)
column += width_of_char_to_print
place_in_string += 1
pass
###########################################################################################
# Handlers and methods
def set_up_handlers(self):
"Adapted from npyscreen.Textfield"
super(MyTextfield, self).set_up_handlers()
# For OS X
del_key = curses.ascii.alt('~')
self.handlers.update({curses.KEY_LEFT: self.h_cursor_left,
curses.KEY_RIGHT: self.h_cursor_right,
curses.KEY_DC: self.h_delete_right,
curses.ascii.DEL: self.h_delete_left,
curses.ascii.BS: self.h_delete_left,
curses.KEY_BACKSPACE: self.h_delete_left,
# mac os x curses reports DEL as escape oddly
# no solution yet
"^K": self.h_erase_right,
"^U": self.h_erase_left,
curses.ascii.ESC: self.h_escape_exit,
curses.KEY_HOME: self.h_cursor_home,
curses.KEY_END: self.h_cursor_end,
curses.KEY_F1: self.parent.h_display_help,
})
self.complex_handlers.extend((
(self.t_input_isprint, self.h_addch),
# (self.t_is_ck, self.h_erase_right),
# (self.t_is_cu, self.h_erase_left),
))
def t_input_isprint(self, inp):
# DV: for Linux:
if config.system == "Linux":
if self._last_get_ch_was_unicode and inp not in '\n\t\r':
return True
if curses.ascii.isprint(inp) and \
(chr(inp) not in '\n\t\r'):
return True
else:
return False
# DV: for Windows:
elif config.system == "Windows":
if chr(inp).isprintable():
return True
else:
return False
def h_addch(self, inp):
"Copied from npyscreen.Textfield"
if self.editable:
#self.value = self.value[:self.cursor_position] + curses.keyname(input) \
# + self.value[self.cursor_position:]
#self.cursor_position += len(curses.keyname(input))
# workaround for the metamode bug:
if self._last_get_ch_was_unicode == True and isinstance(self.value, bytes):
# probably dealing with python2.
ch_adding = inp
self.value = self.value.decode()
elif self._last_get_ch_was_unicode == True:
ch_adding = inp
else:
try:
ch_adding = chr(inp)
except TypeError:
ch_adding = input
self.value = self.value[:self.cursor_position] + ch_adding \
+ self.value[self.cursor_position:]
self.cursor_position += len(ch_adding)
# or avoid it entirely:
#self.value = self.value[:self.cursor_position] + curses.ascii.unctrl(input) \
# + self.value[self.cursor_position:]
#self.cursor_position += len(curses.ascii.unctrl(input))
def h_exit_up(self, _input):
"""Called when user leaves the widget to the previous widget"""
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = EXITED_UP
try:
self.parent.widget_was_exited() # for bookListing.py
except AttributeError:
pass
def h_exit_down(self, _input):
"""Called when user leaves the widget to the next widget"""
if not self._test_safe_to_exit():
return False
self.editing = False
self.how_exited = widget.EXITED_DOWN
try:
self.parent.widget_was_exited() # for bookListing.py
except AttributeError:
pass
def h_cursor_left(self, input):
self.cursor_position -= 1
def h_cursor_right(self, input):
self.cursor_position += 1
def h_delete_left(self, input):
if self.editable and self.cursor_position > 0:
self.value = self.value[:self.cursor_position-1] + self.value[self.cursor_position:]
self.cursor_position -= 1
self.begin_at -= 1
def h_delete_right(self, input):
if self.editable:
self.value = self.value[:self.cursor_position] + self.value[self.cursor_position+1:]
def h_erase_left(self, input):
if self.editable:
self.value = self.value[self.cursor_position:]
self.cursor_position=0
def h_erase_right(self, input):
if self.editable:
self.value = self.value[:self.cursor_position]
self.cursor_position = len(self.value)
self.begin_at = 0
def h_cursor_home(self, input):
self.cursor_position = 0
def h_cursor_end(self, input):
self.cursor_position = len(self.value)
def h_escape_exit(self, ch):
"Esc key was pressed"
self.parent.textfield_exit()
def handle_mouse_event(self, mouse_event):
#mouse_id, x, y, z, bstate = mouse_event
#rel_mouse_x = x - self.relx - self.parent.show_atx
mouse_id, rel_x, rel_y, z, bstate = self.interpret_mouse_event(mouse_event)
self.cursor_position = rel_x + self.begin_at
self.display()
def space_available(self):
"""The space available left on the screen, returned as rows, columns"""
if self.use_max_space:
y, x = self.parent.useable_space(self.rely, self.relx)
else:
y, x = self.parent.widget_useable_space(self.rely, self.relx)
return y,x
def set_size(self):
"From wgwidget.py: Set the size of the object, reconciling the user's request with the space available"
my, mx = self.space_available()
#my = my+1 # Probably want to remove this.
ny, nx = self.calculate_area_needed()
max_height = self.max_height
max_width = self.max_width
# What to do if max_height or max_width is negative
if max_height not in (None, False) and max_height < 0:
max_height = my + max_height
if max_width not in (None, False) and max_width < 0:
max_width = mx + max_width
if max_height not in (None, False) and max_height <= 0:
raise NotEnoughSpaceForWidget("Not enough space for requested size")
if max_width not in (None, False) and max_width <= 0:
raise NotEnoughSpaceForWidget("Not enough space for requested size")
if ny > 0:
if my >= ny:
self.height = ny
else:
self.height = RAISEERROR
elif max_height:
if max_height <= my:
self.height = max_height
else:
self.height = self.request_height
else:
self.height = (self.request_height or my)
#if mx <= 0 or my <= 0:
# raise Exception("Not enough space for widget")
if nx > 0: # if a minimum space is specified....
if mx >= nx: # if max width is greater than needed space
self.width = nx # width is needed space
else:
self.width = RAISEERROR # else raise an error
elif self.max_width: # otherwise if a max width is speciied
if max_width <= mx:
self.width = max_width
else:
self.width = RAISEERROR
else:
self.width = self.request_width or mx # if both exist, chooses the first
if self.height == RAISEERROR or self.width == RAISEERROR:
# Not enough space for widget
raise NotEnoughSpaceForWidget("Not enough space: max y and x = %s , %s. Height and Width = %s , %s " % (my, mx, self.height, self.width) ) # unsafe. Need to add error here.
def set_text_widths(self):
"Modified for fixed texts. Why the cursor if not editable?"
if self.editable == True: # DV
if self.on_last_line:
self.maximum_string_length = self.width - 1 # Leave room for the cursor
else:
self.maximum_string_length = self.width - 1 # Leave room for the cursor at the end of the string
elif self.editable == False:
self.maximum_string_length = self.width - 0 # DV: Don't leave room for the cursor
class MyTitleText(npyscreen.TitleText):
"My own TitleText adapted for Windows/Unicode. Created only to include MyTextfield"
_entry_type = MyTextfield # My own text input field
def __init__(self, screen, begin_entry_at=16, field_width=None, value=None, format=None, use_two_lines=None, hidden=False, \
labelColor='LABEL', allow_override_begin_entry_at=True, **keywords):
# goes to class TitleText->Widget :
super().__init__(screen, begin_entry_at, field_width, value, use_two_lines, hidden, labelColor, \
allow_override_begin_entry_at, **keywords)
self.how_exited = widget.EXITED_DOWN # for editw = n
def set_name(self, name):
"To change the label/name of the text field in real time."
self.label_widget.value = name
class TitleDateField(MyTitleText):
"Formatted date input field."
def __init__(self, screen, begin_entry_at=16, field_width=None, value=None, format=None, use_two_lines=None, hidden=False, \
labelColor='LABEL', allow_override_begin_entry_at=True, **keywords):
# goes to class MyTitleText:
super().__init__(screen, begin_entry_at, field_width, value, use_two_lines, hidden, labelColor, \
allow_override_begin_entry_at, **keywords)
self.format = self.check_format(format)
if self.format == "FormatError":
self.value = self.format
self.hidden = False # do not touch it
def check_format(self, format):
if format not in config.dateAcceptedFormats:
return "FormatError"
else:
return format
def check_value_is_ok(self):
date = self.value
if self.format[0] == "d":
day = date[:2]
month = date[3:5]
else:
month = date[:2]
day = date[3:5]
year = date[6:]
try:
date = datetime.date(int(year), int(month), int(day))
except ValueError:
return False
return True
class TitleDateTimeField(MyTitleText):
"Formatted date+time input field."
def __init__(self, screen, begin_entry_at=16, field_width=None, value=None, format=None, use_two_lines=None, hidden=False, \
labelColor='LABEL', allow_override_begin_entry_at=True, **keywords):
# goes to class MyTitleText:
super().__init__(screen, begin_entry_at, field_width, value, use_two_lines, hidden, labelColor, \
allow_override_begin_entry_at, **keywords)
self.format = self.check_format(format)
if self.format == "FormatError":
self.value = self.format
self.hidden = False # do not touch it
def check_format(self, format):
if format not in config.datetimeAcceptedFormats:
return "FormatError"
else:
return format
def check_value_is_ok(self):
date = self.value
if self.format[0] == "d":
day = date[:2]
month = date[3:5]
else:
month = date[:2]
day = date[3:5]
if "yyyy" in self.format:
year = date[6:10]
else:
year = date[6:8]
try:
hour = date[9:]
pos = hour.index(":")
h = hour[:pos]
m = hour[pos+1:]
if len(h) != 2 or len(m) != 2:
return False
hour += ":00"
d = datetime.date(int(year), int(month), int(day))
t = time.strptime(hour, '%H:%M:%S')
except ValueError:
return False
return True
class TitleTimeField(MyTitleText):
"Formatted time input field."
def __init__(self, screen, begin_entry_at=16, field_width=None, value=None, format=None, use_two_lines=None, hidden=False, \
labelColor='LABEL', allow_override_begin_entry_at=True, **keywords):
# goes to class MyTitleText:
super().__init__(screen, begin_entry_at, field_width, value, use_two_lines, hidden, labelColor, \
allow_override_begin_entry_at, **keywords)
self.format = self.check_format(format)
if self.format == "FormatError":
self.value = self.format
self.hidden = False # do not touch it
def check_format(self, format):
if format not in config.timeAcceptedFormats:
return "FormatError"
else:
return format
def check_value_is_ok(self):
t1 = self.value
if len(t1) != 8 and len(t1) != 5:
return False
if len(t1) == 5: # we let enter only 5 figures ("HH:MM")
try:
t2 = time.strptime(t1, '%H:%M')
except ValueError:
return False
return True
if len(t1) == 8:
try:
t2 = time.strptime(t1, '%H:%M:%S')
except ValueError:
return False
return True
class MyGridColTitles(grid.SimpleGrid):
"Adapted from npyscreen.GridColTitles. Necessary for col_margin=0"
additional_y_offset = 2
_contained_widgets = MyTextfield # DV: modified
_col_widgets = MyTextfield
def __init__(self, screen, col_titles=None, col_margin=0, *args, **keywords): # DV: modified
if col_titles:
self.col_titles = col_titles
else:
self.col_titles = []
self.col_margin = col_margin # DV: modified
super(MyGridColTitles, self).__init__(screen, col_margin=self.col_margin, *args, **keywords) # DV: modified: va a SimpleGrid.__init__()
def update(self, clear=True):
"From SimpleGrid, adapted to a righthand screen with a wide-screen notes/description column."
if clear == True:
self.clear()
if self.begin_col_display_at < 0:
self.begin_col_display_at = 0
if self.begin_row_display_at < 0:
self.begin_row_display_at = 0
if (self.editing or self.always_show_cursor) and not self.edit_cell:
self.edit_cell = [0,0]
row_indexer = self.begin_row_display_at
for widget_row in self._my_widgets:
column_indexer = self.begin_col_display_at
for cell in widget_row:
cell.grid_current_value_index = (row_indexer, column_indexer)
if self.parent.name == "BookSelector" and self.form.right_screen:
if column_indexer != 5 and column_indexer != 6:
continue # in the 2nd screen, disallow to keep displaying columns over the only two valid
self._print_cell(cell, )
column_indexer += 1
row_indexer += 1
class MyGrid(MyGridColTitles):
"My GridColTitles version."
def __init__(self, screen, col_titles=None, col_widths=[], col_margin=0, *args, **keywords):
self.form = screen
self.col_widths = col_widths
self.col_margin = col_margin
self.form.right_screen = False
super().__init__(screen, col_titles, col_margin, *args, **keywords) # go to MyGridColTitles.__init__
def make_contained_widgets(self):
"Adapted from GridColTitles+SimpleGrid to accept specified column width. Parameter col_widths is optional."
if len(self.col_widths) == 0: # first time in empty initialization, or non-specified col_widths
if self.column_width_requested:
# don't need a margin for the final column
self.columns = (self.width + self.col_margin) // (self.column_width_requested + self.col_margin)
elif self.columns_requested:
self.columns = self.columns_requested
else:
self.columns = self.default_column_number
elif len(self.col_widths) > 0: # with specified column widths
#self.columns = len(self.col_widths)
self.columns = 0
acum = 0
for i in range(len(self.col_widths)):
acum += self.col_widths[i]
self.columns += 1
if acum == WIDTH:
break
column_width = (self.width + self.col_margin - self.additional_x_offset) // self.columns
column_width -= self.col_margin
self._column_width = column_width
if column_width < 1: raise Exception("Too many columns for space available")
# Column titles: -------------------------------------------------------------------
self._my_col_titles = []
x_offset = 0
for title_cell in range(self.columns):
if len(self.col_widths) == 0: # first time in empty initialization, or non-specified col_widths
x_offset = title_cell * (self._column_width+self.col_margin)
column_width = self._column_width
else: # with specified column widths
column_width = self.col_widths[title_cell]
self._my_col_titles.append(self._col_widgets(self.parent, rely=self.rely, relx = self.relx + x_offset, \
width=column_width+self.col_margin, height=1))
x_offset += (column_width + self.col_margin)
# Data rows: -------------------------------------------------------------------
if len(self.col_widths) == 0: # first time in empty initialization, or non-specified col_widths
if self.column_width_requested:
# don't need a margin for the final column
self.columns = (self.width + self.col_margin) // (self.column_width_requested + self.col_margin)
elif self.columns_requested:
self.columns = self.columns_requested
else:
self.columns = self.default_column_number
self._my_widgets = []
for h in range( (self.height - self.additional_y_offset) // self.row_height ):
h_coord = h * self.row_height
row = []
for cell in range(self.columns):
x_offset = cell * (self._column_width + self.col_margin)
row.append(self._contained_widgets(self.parent, rely=h_coord+self.rely + self.additional_y_offset, \
relx = self.relx + x_offset + self.additional_x_offset, width=column_width, height=self.row_height))
self._my_widgets.append(row)
else: # with specified column widths
self._my_widgets = []
for h in range( (self.height - self.additional_y_offset) // self.row_height ):
h_coord = h * self.row_height
row = []
x_offset = 0
for cell in range(self.columns):
column_width = self.col_widths[cell]
row.append(self._contained_widgets(self.parent, rely=h_coord+self.rely + self.additional_y_offset, \
relx = self.relx + x_offset + self.additional_x_offset, width=column_width, height=self.row_height))
x_offset += (column_width + self.col_margin)
self._my_widgets.append(row)
def h_scroll_left(self, inpt):
"Adapted to full-line selection and bi-screen."
if self.begin_col_display_at > 0:
self.begin_col_display_at -= self.columns
if self.begin_col_display_at < 0:
self.begin_col_display_at = 0
if self.edit_cell[1] > 0:
self.edit_cell[1] = self.edit_cell[1] - self.columns # DV
self.form.right_screen = False # meaning the screen on the right hand
# Hacking grid column sizes
self.make_contained_widgets() # refresh screen
self.on_select(inpt)
def h_scroll_right(self, inpt):
"Adapted from SimpleGrid to bi-screen."
# If displayed columns < total columns :
number_of_displayed_columns = self.begin_col_display_at + self.columns
total_columns = len(self.values[self.edit_cell[0]])
if number_of_displayed_columns < total_columns : # DV
self.begin_col_display_at += self.columns # increments first displayed column
self.form.right_screen = True # meaning the screen on the right hand
# Hacking grid right-screen column sizes
if self.parent.name == "BookSelector":
for row in range(len(self._my_widgets)):
self._my_widgets[row][0].maximum_string_length = self.col_widths[-2]
self._my_widgets[row][1].maximum_string_length = self.col_widths[-1]
self._my_widgets[row][1].relx = self.col_widths[-2]
self.on_select(inpt)
def set_up_handlers(self): # Adapted from class SimpleGrid.
"""This function should be called somewhere during object initialisation (which all library-defined widgets do).\
You might like to override this in your own definition, but in most cases the add_handers or add_complex_handlers \
methods are what you want."""
#called in __init__
self.handlers = {
curses.KEY_UP: self.h_move_line_up,
#curses.KEY_LEFT: self.h_move_cell_left,
curses.KEY_LEFT: self.h_scroll_left, # Adjusted
curses.KEY_DOWN: self.h_move_line_down,
#curses.KEY_RIGHT: self.h_move_cell_right,
curses.KEY_RIGHT: self.h_scroll_right, # Adjusted
'^Y': self.h_scroll_left,
'^U': self.h_scroll_right, # for VS Code IDE
curses.KEY_NPAGE: self.h_move_page_down,
curses.KEY_PPAGE: self.h_move_page_up,
curses.KEY_HOME: self.h_show_beginning,
curses.KEY_END: self.h_show_end,
curses.ascii.TAB: self.h_exit,
curses.KEY_BTAB: self.h_exit_up,
ord("f"): self.h_exit,
ord("F"): self.h_exit,
ord("c"): self.h_exit,
ord("C"): self.h_exit,
ord("r"): self.h_exit,
ord("R"): self.h_exit,
ord("u"): self.h_exit,
ord("U"): self.h_exit,
ord("d"): self.h_exit,
ord("D"): self.h_exit,
curses.ascii.ESC: self.h_exit,
curses.KEY_MOUSE: self.h_exit_mouse,
}
self.complex_handlers = []
def h_exit(self, ch):
"Exit from grid with accepted keys, TAB included. Adapted from class SimpleGrid."
self.editing = False # exit from grid
self.how_exited = True # self.find_next_editable, # A default value
try:
config.currentRow = config.fileRows[self.edit_cell[0]][1]
except IndexError: # there are no rows in the table
pass
selectorForm = self.form
match ch:
case ( 102 | 70 ): # "F/f=Find"
selectorForm.find_row()
case ( 99 | 67 ): # "C/c=Create"
selectorForm.create_row()
case ( 114 | 82 ): # "R/r=Read"
selectorForm.read_row()
case ( 117 | 85 ): # "U/u=Update"
selectorForm.update_row()
case ( 100 | 68 ): # "D/d=Delete"
selectorForm.delete_row()
def update(self, clear=True):
"Adapted for bi-screen."
super(MyGrid, self).update(clear = True) # goes to MyGridColTitles.update() and to SimpleGrid.update()
_title_counter = 0
for title_cell in self._my_col_titles:
if self.parent.name == "BookSelector":
if self.form.right_screen:
if title_cell.value.strip() in ["Date","ISBN/SKU"]:
pass # to the try
elif title_cell.value.strip() == "": # coming from the form, on the right-screen
# Hacking grid right-screen column sizes
for row in range(len(self._my_widgets)):
self._my_widgets[row][0].maximum_string_length = self.col_widths[-2]
self._my_widgets[row][1].maximum_string_length = self.col_widths[-1]