-
Notifications
You must be signed in to change notification settings - Fork 30
/
snekde.py
executable file
·1531 lines (1278 loc) · 44.8 KB
/
snekde.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 python3
#
# Copyright © 2019–2020 Keith Packard <keithp@keithp.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
import argparse
import curses
import serial
import serial.tools.list_ports
import sys
termios_error = serial.SerialException
if hasattr(serial, "termios"):
termios_error = termios.error
import threading
import time
from curses import ascii
from pathlib import Path, PurePath
stdscr = 0
snek_lock = threading.Lock()
snek_current_window = 0
snek_edit_win = 0
snek_repl_win = 0
snek_cols = 0
snek_lines = 0
snek_monitor = False
snek_device = False
snek_dialog_waiting = False
snek_cur_path = None
snek_debug_file = False
baud_rates = [57600, 115200]
baud_selection = 1
def snek_debug(message):
global snek_debug_file
if not snek_debug_file:
snek_debug_file = open("log", "w")
snek_debug_file.write(message + "\n")
snek_debug_file.flush()
# snek_debug("Starting snekde")
#
# Read a character from the keyboard, releasing the
# global lock while blocked so that serial input can arrive
#
def my_getch(edit_win):
global snek_lock, snek_current_window, snek_dialog_waiting
while True:
edit_win.set_cursor()
try:
snek_lock.release()
c = edit_win.window.getch()
finally:
snek_lock.acquire()
if c == ord("\r"):
c = ord("\n")
if not snek_dialog_waiting:
break
if c == ord("\n"):
snek_dialog_waiting.close()
snek_dialog_waiting = False
#
# Check for resize
#
if c == curses.KEY_RESIZE:
screen_resize()
return c
class SnekPort:
"""Emulate new pySerial from old pySerial"""
name = None
description = None
device = None
def __init__(self, port):
if type(port) is tuple:
self.device = port[0]
if len(port[1]) > 20:
self.name = self.device
if "/" in self.name:
self.name = self.name[self.name.rfind("/") + 1 :]
else:
self.name = port[1]
self.description = port[1]
self.hwid = port[2]
else:
self.device = port.device
if port.name:
self.name = port.name
else:
self.name = self.device
self.description = port.description
self.product = port.product
self.hwid = port.hwid
if self.name and "/" in self.name:
self.name = self.name[self.name.rfind("/") + 1 :]
# A special hack for pre-3.5 pySerial
#
# That code is missing a call to 'str' to convert the check_output
# result to a string.
if "list_ports_posix" in serial.tools.__dict__:
if hasattr(serial.tools.list_ports_posix, "popen"):
del serial.tools.list_ports_posix.popen
try:
import subprocess
except ImportError:
def popen(argv):
try:
si, so = os.popen4(" ".join(argv))
return so.read().strip()
except:
raise IOError("lsusb failed")
else:
def popen(argv):
try:
return str(
subprocess.check_output(argv, stderr=subprocess.STDOUT)
).strip()
except:
raise IOError("lsusb failed")
serial.tools.list_ports_posix.popen = popen
def snek_list_ports():
ports = []
for port in serial.tools.list_ports.comports():
ports += [SnekPort(port)]
return ports
port_mods = {"239A:": "async"}
class SnekDevice:
"""Link to snek device"""
serial = False
reader_thread = False
writer_thread = False
alive = False
_reader_alive = False
interface = False
write_queue = False
device = ""
interrupt_pending = False
syncronous_put = False
#
# The interface needs to have a condition variable (cv) that is
# signaled when data are available to write and function (receive)
# that gets data that are read
#
def __init__(self, port, interface, rate=115200):
self.interface = interface
self.device = port.device
# For devices without flow control, use snek's ENQ/ACK
# mechanism to avoid overrunning the device input buffer
self.synchronous_put = True
self.synchronous_limit = 16
for port_mod in port_mods:
if port_mod in port.description or port_mod in port.hwid:
if "async" in port_mods[port_mod]:
self.synchronous_put = False
self.serial = serial.Serial(
port=self.device,
baudrate=rate,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
xonxoff=False,
rtscts=False,
dsrdtr=False,
)
def start(self):
"""start worker threads"""
self.alive = True
self._reader_alive = True
# start threads
self.receiver_thread = threading.Thread(target=self.reader, name="rx")
self.receiver_thread.daemon = True
self.receiver_thread.start()
self.transmitter_thread = threading.Thread(target=self.writer, name="tx")
self.transmitter_thread.daemon = True
self.transmitter_thread.start()
def stop_reader(self):
if self.receiver_thread and threading.current_thread() != self.receiver_thread:
self.serial.cancel_read()
self.interface.cv.release()
self.receiver_thread.join()
self.interface.cv.acquire()
def stop_writer(self):
"""set flag to stop worker threads"""
if (
self.transmitter_thread
and threading.current_thread() != self.transmitter_thread
):
self.interface.cv.notify()
self.interface.cv.release()
self.transmitter_thread.join()
self.interface.cv.acquire()
def close(self):
self.alive = False
self.stop_reader()
self.stop_writer()
try:
self.serial.write_timeout = 1
self.serial.write(b"\x0f")
self.serial.reset_output_buffer()
self.serial.close()
except serial.SerialException:
pass
def reader(self):
"""loop and copy serial->"""
try:
while self.alive and self._reader_alive:
# read all that is there or wait for one byte
data = self.serial.read(1)
if data:
self.interface.receive(data)
except (serial.SerialException, termios_error):
# snek_debug('serial interface failed in reader')
self.interface.failed(self.device)
finally:
self.receiver_thread = False
def writer(self):
global snek_lock
"""Copy queued data to the serial port."""
try:
sent = 0
while True:
send_data = b""
interrupt = False
# snek_debug('writer locking')
with snek_lock:
# snek_debug('writer waiting')
# Wait until there's something to do
while (
not self.write_queue
and not self.interrupt_pending
and self.alive
):
self.interface.cv.wait()
# snek_debug('writer awake')
send_data = self.write_queue
interrupt = self.interrupt_pending
self.write_queue = False
self.interrupt_pending = False
if not self.alive:
break
if interrupt:
# snek_debug('interrupt')
self.serial.reset_output_buffer()
self.serial.write(b"\x0f\x03\x0e")
if self.synchronous_put:
while send_data:
amt = self.synchronous_limit - sent
if amt > len(send_data):
amt = len(send_data)
this_time = send_data[:amt]
send_data = send_data[amt:]
self.serial.write(this_time)
sent += amt
if sent >= self.synchronous_limit:
# snek_debug('sync %d limit %d' % (sent, self.synchronous_limit))
snek_monitor.sync()
sent = 0
else:
if send_data:
self.serial.write(send_data)
except (serial.SerialException, termios_error):
# snek_debug('serial interface failed in writer')
self.interface.failed(self.device)
finally:
self.transmitter_thread = False
def interrupt(self):
# snek_debug('pend interrupt waited')
self.interrupt_pending = True
self.interface.cv.notify()
# snek_debug('pended')
def writeb(self, data):
# snek_debug('writeb waited')
if self.write_queue:
self.write_queue += data
else:
self.write_queue = data
self.interface.cv.notify()
def write(self, data):
self.writeb(data.encode("utf-8"))
def command(self, data, intr="\x03"):
self.write("\x0e" + intr + data)
def set_baud(self, baud):
self.serial.baudrate = baud
if self.serial.is_open:
self.serial.close()
self.serial.open()
class EditWin:
"""Editable text object"""
window = 0
lines = 0
cols = 0
y = 0
point = 0
top_line = 0
tab_width = 4
text = ""
cut = ""
mark = -1
changed = False
undo = []
def __init__(self, lines, cols, y, x):
self.lines = lines
self.cols = cols
self.y = y
self.window = curses.newwin(lines, cols, y, x)
self.window.keypad(True)
self.window.notimeout(False)
# Set contents, resetting state back to start
def set_text(self, text):
self.text = text
self.point = 0
self.mark = -1
self.top_line = 0
self.changed = False
# Convert text index to x/y coord
def point_to_cursor(self, point):
line = -1
col = 0
for s in self.text[:point].split("\n"):
line += 1
col = len(s)
return (col, line)
# Convert x/y coord to text index
def cursor_to_point(self, cursor):
(cur_col, cur_line) = cursor
if cur_line < 0:
cur_line = 0
elif cur_line >= len(self.text.split("\n")):
cur_line = len(self.text.split("\n")) - 1
bol = 0
line = 0
point = 0
for s in self.text.split("\n"):
point = bol + min(cursor[0], len(s))
if line == cur_line:
break
line += 1
bol += len(s) + 1
return point
# Make sure current point is visible in the window
def scroll_to_point(self):
while self.point_to_cursor(self.point)[1] < self.top_line:
self.top_line -= 1
while self.point_to_cursor(self.point)[1] >= self.top_line + self.lines:
self.top_line += 1
def addstr(self, line, col, text, attrib=None):
if col < self.cols:
if line == self.lines - 1:
text = text[: self.cols - col - 1]
else:
text = text[: self.cols - col]
if attrib:
self.window.addstr(line, col, text, attrib)
else:
self.window.addstr(line, col, text)
# Repaint the window
def repaint(self):
self.window.erase()
self.scroll_to_point()
selection = self.get_selection()
if selection:
start_selection = self.point_to_cursor(selection[0])
end_selection = self.point_to_cursor(selection[1])
line = 0
for s in self.text.split("\n"):
if self.top_line <= line and line < self.top_line + self.lines:
# Paint the marked region in reverse video
if (
selection
and start_selection[1] <= line
and line <= end_selection[1]
):
if line == start_selection[1]:
before = s[: start_selection[0]]
middle = s[start_selection[0] :]
else:
before = ""
middle = s
if line == end_selection[1]:
after = middle[end_selection[0] :]
middle = middle[: end_selection[0]]
else:
after = ""
self.addstr(line - self.top_line, 0, before)
self.addstr(
line - self.top_line, len(before), middle, curses.A_REVERSE
)
self.addstr(line - self.top_line, len(before) + len(middle), after)
else:
self.addstr(line - self.top_line, 0, s)
line += 1
self.window.refresh()
# Set window size
def resize(self, lines, cols, y, x):
self.lines = lines
self.cols = cols
self.window.resize(lines, cols)
self.window.mvwin(y, x)
self.repaint()
# This window is the input window, set the cursor position
# to the current point
def set_cursor(self):
p = self.point_to_cursor(self.point)
col = min(self.cols - 1, p[0])
self.window.move(p[1] - self.top_line, col)
self.window.refresh()
# Find the indent of the specified line
def indent_at(self, line):
bol = self.cursor_to_point((0, line))
point = bol
while point < len(self.text) and self.text[point] == " ":
point += 1
return point - bol
# Return the last character on the specified line
def last_ch(self, line):
eol = self.cursor_to_point((65536, line))
point = eol - 1
while point > 0 and self.text[point] == " ":
point -= 1
return self.text[point]
# Is 'point' in the indentation of its line?
def in_indent(self, point):
cursor = self.point_to_cursor(point)
if cursor[0] > 0 and self.indent_at(cursor[1]) >= cursor[0]:
return True
return False
# Move left
def left(self):
if self.point > 0:
self.point -= 1
# Move up
def up(self):
pos = self.point_to_cursor(self.point)
point = self.cursor_to_point((pos[0], pos[1] - 1))
if point == self.point:
point = self.cursor_to_point((0, pos[1]))
self.point = point
# Move right
def right(self):
if self.point < len(self.text):
self.point += 1
# Move down
def down(self):
pos = self.point_to_cursor(self.point)
point = self.cursor_to_point((pos[0], pos[1] + 1))
if point == self.point:
point = self.cursor_to_point((65536, pos[1]))
self.point = point
# Move to beginning of line
def bol(self):
pos = self.point_to_cursor(self.point)
self.point = self.cursor_to_point((0, pos[1]))
# Move to end of line
def eol(self):
pos = self.point_to_cursor(self.point)
self.point = self.cursor_to_point((65536, pos[1]))
# Move to beginning of buffer
def bob(self):
self.point = 0
# Move to end of buffer
def eob(self):
self.point = len(self.text)
# Move to previous page. That means moving up by self.lines-1 and
# then placing that line at the bottom of the screen
def prev_page(self):
pos = self.point_to_cursor(self.point)
self.point = self.cursor_to_point((pos[0], pos[1] - (self.lines) - 1))
new_line = self.point_to_cursor(self.point)[1]
top_line = new_line - (self.lines - 1)
top_pos = self.cursor_to_point((0, top_line))
self.top_line = self.point_to_cursor(top_pos)[1]
# Move to next page. This means moving down by self.lines-1 and
# then placing that line at the top of the screen
def next_page(self):
pos = self.point_to_cursor(self.point)
self.point = self.cursor_to_point((pos[0], pos[1] + (self.lines) - 1))
self.top_line = self.point_to_cursor(self.point)[1]
# Check whether in the last line of the buffer
def in_last_line(self):
end = self.point_to_cursor(len(self.text))
return self.point >= self.cursor_to_point((0, end[1]))
def push_undo(self, point, operation):
self.undo.append((point, operation, self.point, self.mark))
def pop_undo(self):
if not self.undo:
return False
(point, operation, self_point, self_mark) = self.undo.pop()
if isinstance(operation, str):
# Replace deleted text
self.text = self.text[:point] + operation + self.text[point:]
else:
# Delete inserted text
self.text = self.text[:point] + self.text[point + operation :]
self.point = self_point
self.mark = self_mark
self.changed = True
return True
# Insert some text, adjusting self.point and self.mark if the text
# is before them
def insert(self, point, text):
self.push_undo(point, len(text))
self.text = self.text[:point] + text + self.text[point:]
if point < self.point:
self.point += len(text)
if point < self.mark:
self.mark += len(text)
self.changed = True
def insert_at_point(self, text):
self.insert(self.point, text)
self.point += len(text)
# Delete some text, adjusting self.point if the delete starts
# before it
def _adjust_delete_position(
self, delete_point, delete_count, moving_point, is_mark
):
if delete_point <= moving_point and moving_point < delete_point + delete_count:
if is_mark:
return -1
moving_point = delete_point
elif delete_point + delete_count <= moving_point:
moving_point -= delete_count
return moving_point
def delete(self, point, count):
self.push_undo(point, self.text[point : point + count])
self.text = self.text[:point] + self.text[point + count :]
self.point = self._adjust_delete_position(point, count, self.point, False)
if self.mark >= 0:
self.mark = self._adjust_delete_position(point, count, self.mark, True)
self.changed = True
def delete_at_point(self, count):
self.delete(self.point, count)
# Delete back to the previous tab stop
def backtab(self):
pos = self.point_to_cursor(self.point)
if pos[0] == 0:
return
to_remove = pos[0] % self.tab_width
if to_remove == 0:
to_remove = self.tab_width
self.point -= to_remove
self.delete_at_point(to_remove)
# Delete something. If there's a mark, delete that. otherwise,
# delete backwards, if in indent of the line, backtab
def backspace(self):
selection = self.get_selection()
if selection:
self.delete(selection[0], selection[1] - selection[0])
self.mark = -1
elif self.point > 0:
if self.in_indent(self.point):
self.backtab()
else:
self.left()
self.delete_at_point(1)
# Set or clear the 'mark', which defines
# the other end of the current selection
def toggle_mark(self):
if self.mark >= 0:
self.mark = -1
else:
self.mark = self.point
# Return the extent of the current selection, False if none
def get_selection(self):
if self.mark >= 0:
return (min(self.mark, self.point), max(self.mark, self.point))
else:
return False
# Copy from mark to point and place in cut buffer
# delete from text if requested
def copy(self, delete=False):
selection = self.get_selection()
if selection:
(start, end) = selection
self.cut = self.text[start:end]
if delete:
self.delete(start, end - start)
self.mark = -1
# Paste any cut buffer at point
def paste(self):
if self.cut:
self.insert_at_point(self.cut)
# Set indent of current line to 'want'. Leave point
# at the end of the indent
def indent(self, want):
self.bol()
have = 0
while self.point < len(self.text) and self.text[self.point] == " ":
self.right()
have += 1
if have < want:
self.insert_at_point(" " * (want - have))
elif have > want:
self.delete_at_point(have - want)
# Automatically indent the current line,
# using the previous line as a guide
def auto_indent(self):
cursor = self.point_to_cursor(self.point)
want = 0
if cursor[1] > 0:
want = self.indent_at(cursor[1] - 1)
if self.last_ch(cursor[1] - 1) == ":":
want += self.tab_width
self.indent(want)
# Delete to end of line, or delete newline if at end of line
def delete_to_eol(self):
current = self.point_to_cursor(self.point)
eol = self.cursor_to_point((65536, current[1]))
if self.point == eol:
self.delete_at_point(1)
else:
self.delete_at_point(eol - self.point)
# Read a character for this window
def getch(self):
self.repaint()
return my_getch(self)
# Return the contents of the previous line
def cur_line(self):
pos = self.point_to_cursor(self.point)
start = self.cursor_to_point((0, pos[1]))
end = self.cursor_to_point((65536, pos[1]))
return self.text[start:end]
def dispatch(self, ch):
if ch == 0 or ch == ord(" ") + 0x80:
self.toggle_mark()
elif ch == ord("c") & 0x1F or ch == ord("c") + 0x80:
self.copy(delete=False)
elif ch == ord("x") & 0x1F or ch == ord("x") + 0x80:
self.copy(delete=True)
elif ch == ord("v") & 0x1F or ch == ord("v") + 0x80:
self.paste()
elif ch == ord("k") & 0x1F:
self.delete_to_eol()
elif ch == ord("z") & 0x1F:
self.pop_undo()
elif ch == curses.KEY_LEFT or ch == ord("b") & 0x1F:
self.left()
elif ch == curses.KEY_RIGHT or ch == ord("f") & 0x1F:
self.right()
elif ch == curses.KEY_UP or ch == ord("p") & 0x1F:
self.up()
elif ch == curses.KEY_DOWN or ch == ord("n") & 0x1F:
self.down()
elif ch == curses.KEY_HOME or ch == ord("a") & 0x1F:
self.bol()
elif ch == curses.KEY_PPAGE:
self.prev_page()
elif ch == curses.KEY_NPAGE:
self.next_page()
elif ch == curses.KEY_END or ch == ord("e") & 0x1F:
self.eol()
elif ch == ord("\t"):
self.auto_indent()
elif ch in (curses.ascii.BS, curses.KEY_BACKSPACE, curses.ascii.DEL):
self.backspace()
elif curses.ascii.isprint(ch) or ch == ord("\n"):
self.insert_at_point(chr(ch))
class ErrorWin:
"""Show an error message"""
label = ""
x = 0
y = 0
nlines = 5
ncols = 40
inputthread = True
window = False
def __init__(self, label, inputthread=True):
self.label = label
self.inputthread = inputthread
self.nlines = 5
self.ncols = min(snek_cols, max(40, len(label) + 2))
self.x = (snek_cols - self.ncols) // 2
self.y = (snek_lines - self.nlines) // 2
self.window = curses.newwin(self.nlines, self.ncols, self.y, self.x)
self.window.keypad(True)
self.window.notimeout(False)
self.run_dialog()
def repaint(self):
self.window.border()
l = len(self.label)
if l > self.ncols:
l = self.ncols
self.window.addstr(1, (self.ncols - l) // 2, self.label)
self.window.addstr(3, 2, "OK")
def close(self):
del self.window
screen_repaint()
def run_dialog(self):
global snek_dialog_waiting
self.repaint()
self.window.move(3, 4)
self.window.refresh()
if self.inputthread:
self.window.getstr()
self.close()
else:
snek_dialog_waiting = self
class GetTextWin:
"""Prompt for line of text"""
label = ""
prompt = ""
x = 0
y = 0
nlines = 5
ncols = 40
window = False
def __init__(self, label, prompt="File:"):
self.label = label
self.prompt = prompt
self.x = (snek_cols - self.ncols) // 2
self.y = (snek_lines - self.nlines) // 2
self.window = curses.newwin(self.nlines, self.ncols, self.y, self.x)
self.window.keypad(True)
self.window.notimeout(False)
def repaint(self):
self.window.border()
self.window.addstr(1, (self.ncols - len(self.label)) // 2, self.label)
self.window.addstr(3, 2, self.prompt)
def run_dialog(self):
self.repaint()
self.window.move(3, 8)
curses.echo()
name = self.window.getstr()
curses.noecho()
del self.window
screen_repaint()
return str(name, encoding="utf-8", errors="ignore")
class GetFileWin:
"""Prompt for a filename"""
label = ""
dir = ""
x = 0
y = 0
nlines = 20
ncols = 60
new = False
window = False
cur_ent = 1
file = ""
full_file = ""
def __init__(self, label, path, new=False):
self.label = label
self.new = new
self.nlines = snek_lines - 2
self.ncols = snek_cols - 10
self.cur_ent = 1
self.top_ent = 0
self.x = (snek_cols - self.ncols) // 2
self.y = (snek_lines - self.nlines) // 2
self.window = curses.newwin(self.nlines, self.ncols, self.y, self.x)
self.window.keypad(True)
self.window.notimeout(False)
if path:
self.dir = path.parent
else:
self.dir = Path().resolve()
self.get_files()
if path:
for i in range(len(self.files)):
if self.files[i] == path.name:
self.set_ent(i)
break
def get_files(self):
files = []
dirs = []
for f in self.dir.glob("*"):
if f.is_dir():
dirs += [f.name]
else:
files += [f.name]
dirs.sort()
files.sort()
self.files = [".."] + dirs + files
self.file_offset = 0
self.cur_ent = 1
self.file = self.files[1]
def set_dir(self, dir):
self.dir = self.path.resolve()
self.get_files()
def ent_line(self, i):
return 4 + i
def ents(self):
return self.nlines - 5
def set_ent(self, ent):
if 0 <= ent and ent < len(self.files):
self.cur_ent = ent
self.file = self.files[self.cur_ent]
if ent < self.file_offset:
self.file_offset = ent
elif ent >= self.file_offset + self.ents():
self.file_offset = ent - self.ents() + 1
def repaint(self):
self.window.border()
self.window.addstr(1, (self.ncols - len(self.label)) // 2, self.label)
self.path = self.dir / PurePath(self.file)
if self.file == "":
self.full_file = str(self.dir / PurePath("x"))[:-1]
else:
self.full_file = str(self.path)
self.window.addstr(2, 2, " " * (self.ncols - 3))
left = max(0, len(self.full_file) - 2 - self.ncols)
self.window.addstr(2, 2, self.full_file[left:])
for i in range(0, self.ents()):
f = self.file_offset + i
self.window.addstr(self.ent_line(i), 2, " " * (self.ncols - 3))
if f < len(self.files):
text = self.files[f]
if (self.dir / PurePath(text)).is_dir():
text = "[" + text + "]"
text = text[0 : self.ncols - 3]
if f == self.cur_ent:
self.window.addstr(self.ent_line(i), 2, text, curses.A_REVERSE)
else:
self.window.addstr(self.ent_line(i), 2, text)
def set_cursor(self):
self.window.move(2, min(2 + len(self.full_file), self.ncols - 2))
self.window.refresh()
def run_dialog(self):
while True:
self.repaint()