Debian Codegraph @

lib_pypy/_curses.py

raw symbols SCIP
1 """Reimplementation of the standard extension module '_curses' using cffi."""
2
3 import sys
4 if sys.platform == 'win32':
5 #This module does not exist in windows
6 raise ModuleNotFoundError('No module named _curses', name='_curses')
7 import locale
8 from functools import wraps
9
10 from _curses_cffi import ffi, lib
11
12 version = b"2.2"
13 __version__ = b"2.2"
14
15 def _copy_to_globals(name):
16 globals()[name] = getattr(lib, name)
17
18
19 def _setup():
20 for name in ['ERR', 'OK', 'KEY_MIN', 'KEY_MAX',
21 'A_ATTRIBUTES', 'A_NORMAL', 'A_STANDOUT', 'A_UNDERLINE',
22 'A_REVERSE', 'A_BLINK', 'A_DIM', 'A_BOLD', 'A_ALTCHARSET',
23 'A_PROTECT', 'A_CHARTEXT', 'A_COLOR',
24 'COLOR_BLACK', 'COLOR_RED', 'COLOR_GREEN', 'COLOR_YELLOW',
25 'COLOR_BLUE', 'COLOR_MAGENTA', 'COLOR_CYAN', 'COLOR_WHITE',
26 ]:
27 _copy_to_globals(name)
28
29 if not lib._m_NetBSD:
30 _copy_to_globals('A_INVIS')
31
32 for name in ['A_HORIZONTAL', 'A_LEFT', 'A_LOW', 'A_RIGHT', 'A_TOP',
33 'A_VERTICAL',
34 ]:
35 if hasattr(lib, name):
36 _copy_to_globals(name)
37
38 if lib._m_NCURSES_MOUSE_VERSION:
39 for name in ["BUTTON1_PRESSED", "BUTTON1_RELEASED", "BUTTON1_CLICKED",
40 "BUTTON1_DOUBLE_CLICKED", "BUTTON1_TRIPLE_CLICKED",
41 "BUTTON2_PRESSED", "BUTTON2_RELEASED", "BUTTON2_CLICKED",
42 "BUTTON2_DOUBLE_CLICKED", "BUTTON2_TRIPLE_CLICKED",
43 "BUTTON3_PRESSED", "BUTTON3_RELEASED", "BUTTON3_CLICKED",
44 "BUTTON3_DOUBLE_CLICKED", "BUTTON3_TRIPLE_CLICKED",
45 "BUTTON4_PRESSED", "BUTTON4_RELEASED", "BUTTON4_CLICKED",
46 "BUTTON4_DOUBLE_CLICKED", "BUTTON4_TRIPLE_CLICKED",
47 "BUTTON_SHIFT", "BUTTON_CTRL", "BUTTON_ALT",
48 "ALL_MOUSE_EVENTS", "REPORT_MOUSE_POSITION",
49 ]:
50 _copy_to_globals(name)
51
52 if not lib._m_NetBSD:
53 for key in range(lib.KEY_MIN, lib.KEY_MAX):
54 key_n = lib.keyname(key)
55 if key_n == ffi.NULL:
56 continue
57 key_n = ffi.string(key_n)
58 if key_n == b"UNKNOWN KEY":
59 continue
60 if not isinstance(key_n, str): # python 3
61 key_n = key_n.decode('utf-8')
62 key_n = key_n.replace('(', '').replace(')', '')
63 globals()[key_n] = key
64 _setup()
65
66 if lib.NCURSES_EXT_FUNCS >= 20170401 and lib.NCURSES_EXT_COLORS >= 20170401:
67 _NCURSES_EXTENDED_COLOR_FUNCS = 1
68 _CURSES_COLOR_VAL_TYPE="int"
69 _CURSES_COLOR_NUM_TYPE="int"
70 _CURSES_INIT_COLOR_FUNC = lib.init_extended_color
71 _CURSES_INIT_PAIR_FUNC = lib.init_extended_pair
72 _COLOR_CONTENT_FUNC = lib.extended_color_content
73 _CURSES_PAIR_CONTENT_FUNC = lib.extended_pair_content
74 _CURSES_PAIR_CONTENT_FUNC_NAME = "extended_pair_content"
75 else:
76 _NCURSES_EXTENDED_COLOR_FUNCS = 0
77 _CURSES_COLOR_VAL_TYPE="short"
78 _CURSES_COLOR_NUM_TYPE="short"
79 _CURSES_INIT_COLOR_FUNC = lib.init_color
80 _CURSES_INIT_PAIR_FUNC = lib.init_pair
81 _COLOR_CONTENT_FUNC = lib.color_content
82 _CURSES_PAIR_CONTENT_FUNC = lib.pair_content
83 _CURSES_PAIR_CONTENT_FUNC_NAME = "pair_content"
84
85 def has_extended_color_support():
86 return bool(_NCURSES_EXTENDED_COLOR_FUNCS)
87
88 # ____________________________________________________________
89
90
91 _initialised_setupterm = False
92 _initialised = False
93 _initialised_color = False
94
95
96 def _ensure_initialised_setupterm():
97 if not _initialised_setupterm:
98 raise error("must call (at least) setupterm() first")
99
100
101 def _ensure_initialised():
102 if not _initialised:
103 raise error("must call initscr() first")
104
105
106 def _ensure_initialised_color():
107 if not _initialised:
108 raise error("must call initscr() first")
109 if not _initialised_color:
110 raise error("must call start_color() first")
111
112
113 def _check_ERR(code, fname):
114 if code != lib.ERR:
115 return None
116 elif fname is None:
117 raise error("curses function returned ERR")
118 else:
119 raise error("%s() returned ERR" % (fname,))
120
121
122 def _check_NULL(rval):
123 if rval == ffi.NULL:
124 raise error("curses function returned NULL")
125 return rval
126
127
128 def _call_lib(method_name, *args):
129 return getattr(lib, method_name)(*args)
130
131
132 def _call_lib_check_ERR(method_name, *args):
133 return _check_ERR(_call_lib(method_name, *args), method_name)
134
135
136 def _mk_no_return(method_name):
137 def _execute():
138 _ensure_initialised()
139 return _call_lib_check_ERR(method_name)
140 _execute.__name__ = method_name
141 return _execute
142
143
144 def _mk_flag_func(method_name):
145 # This is in the CPython implementation, but not documented anywhere.
146 # We have to support it, though, even if it make me sad.
147 def _execute(flag=True):
148 _ensure_initialised()
149 if flag:
150 return _call_lib_check_ERR(method_name)
151 else:
152 return _call_lib_check_ERR('no' + method_name)
153 _execute.__name__ = method_name
154 return _execute
155
156
157 def _mk_return_val(method_name, rettype=None):
158 def _execute():
159 ret = _call_lib(method_name)
160 if rettype:
161 return rettype(ret)
162 return ret
163 _execute.__name__ = method_name
164 return _execute
165
166
167 def _mk_w_getyx(method_name):
168 def _execute(self):
169 y = _call_lib(method_name + 'y', self._win)
170 x = _call_lib(method_name + 'x', self._win)
171 return (y, x)
172 _execute.__name__ = method_name
173 return _execute
174
175
176 def _mk_w_no_return(method_name):
177 def _execute(self, *args):
178 return _call_lib_check_ERR(method_name, self._win, *args)
179 _execute.__name__ = method_name
180 return _execute
181
182
183 def _mk_w_return_val(method_name, rettype=None):
184 def _execute(self, *args):
185 ret = _call_lib(method_name, self._win, *args)
186 if rettype:
187 return rettype(ret)
188 return ret
189 _execute.__name__ = method_name
190 return _execute
191
192
193 def _chtype(ch):
194 ret = int(ffi.cast("chtype", ch))
195 if ret != ffi.cast("long long", ch) or isinstance(ch, int) and ch > sys.maxsize:
196 raise OverflowError(f"{ch} cannot be converted to 'chtype'")
197 return ret
198
199 def _bytestype(text):
200 if isinstance(text, bytes):
201 return text
202 elif isinstance(text, str):
203 return text.encode()
204 else:
205 raise TypeError("bytes or str expected, got a '%s' object"
206 % (type(text).__name__,))
207
208 def _convert_to_chtype(win, obj):
209 if isinstance(obj, bytes) and len(obj) == 1:
210 value = ord(obj)
211 elif isinstance(obj, str):
212 if len(obj) != 1:
213 raise TypeError("expect bytes or str of length 1 or int, "
214 "got a str of length %d", len(obj))
215 value = ord(obj)
216 if (128 < value):
217 if win:
218 encoding = win.encoding
219 else:
220 encoding = screen_encoding
221 b = obj.encode(encoding)
222 if len(bytes) == 1:
223 value = ord(b)
224 else:
225 OverflowError("byte doesn't fit in chtype")
226 elif isinstance(obj, int):
227 value = obj
228 else:
229 raise TypeError('expect bytes or str of length 1, or int, got %s' % type(obj))
230 return value
231
232 def _convert_to_string(win, obj):
233 if isinstance(obj, str):
234 value = obj.encode(win.encoding)
235 elif isinstance(obj, bytes):
236 value = obj
237 else:
238 raise TypeError('expect bytes or str, got %s' % type(obj))
239 if b'\0' in value:
240 raise ValueError('embedded null character')
241 return value
242
243 def _extract_yx(args):
244 if len(args) >= 2:
245 return (args[0], args[1], args[2:])
246 return (None, None, args)
247
248
249 def _process_args(funcname, args, count, optcount, frontopt=0):
250 outargs = []
251 if frontopt:
252 if len(args) > count + optcount:
253 # We have the front optional args here.
254 outargs.extend(args[:frontopt])
255 args = args[frontopt:]
256 else:
257 # No front optional args, so make them None.
258 outargs.extend([None] * frontopt)
259 if (len(args) < count) or (len(args) > count + optcount):
260 raise error("%s requires %s to %s arguments" % (
261 funcname, count, count + optcount + frontopt))
262 outargs.extend(args)
263 return outargs
264
265
266 def _argspec(count, optcount=0, frontopt=0):
267 def _argspec_deco(func):
268 @wraps(func)
269 def _wrapped(self, *args):
270 outargs = _process_args(
271 func.__name__, args, count, optcount, frontopt)
272 return func(self, *outargs)
273 return _wrapped
274 return _argspec_deco
275
276
277 # ____________________________________________________________
278
279
280 class error(Exception):
281 pass
282
283
284 class Window(object):
285 def __init__(self, window, encoding=None):
286 if encoding is None:
287 # CPython has a win32 branch here, but _curses is not supported
288 # on win32
289 codeset = locale.nl_langinfo(locale.CODESET)
290 if codeset:
291 encoding = codeset
292 else:
293 encoding = 'utf-8'
294 self._win = window
295 self._encoding = encoding
296
297 def __del__(self):
298 if self._win != lib.stdscr:
299 lib.delwin(self._win)
300
301 untouchwin = _mk_w_no_return("untouchwin")
302 touchwin = _mk_w_no_return("touchwin")
303 redrawwin = _mk_w_no_return("redrawwin")
304 insertln = _mk_w_no_return("winsertln")
305 erase = _mk_w_no_return("werase")
306 deleteln = _mk_w_no_return("wdeleteln")
307
308 is_wintouched = _mk_w_return_val("is_wintouched", bool)
309
310 syncdown = _mk_w_return_val("wsyncdown")
311 syncup = _mk_w_return_val("wsyncup")
312 standend = _mk_w_return_val("wstandend")
313 standout = _mk_w_return_val("wstandout")
314 cursyncup = _mk_w_return_val("wcursyncup")
315 clrtoeol = _mk_w_return_val("wclrtoeol")
316 clrtobot = _mk_w_return_val("wclrtobot")
317 clear = _mk_w_return_val("wclear")
318
319 idcok = _mk_w_no_return("idcok")
320 immedok = _mk_w_no_return("immedok")
321 timeout = _mk_w_no_return("wtimeout")
322
323 getyx = _mk_w_getyx("getcur")
324 getbegyx = _mk_w_getyx("getbeg")
325 getmaxyx = _mk_w_getyx("getmax")
326 getparyx = _mk_w_getyx("getpar")
327
328 clearok = _mk_w_no_return("clearok")
329 idlok = _mk_w_no_return("idlok")
330 leaveok = _mk_w_no_return("leaveok")
331 notimeout = _mk_w_no_return("notimeout")
332 scrollok = _mk_w_no_return("scrollok")
333 insdelln = _mk_w_no_return("winsdelln")
334 syncok = _mk_w_no_return("syncok")
335
336 mvwin = _mk_w_no_return("mvwin")
337 mvderwin = _mk_w_no_return("mvderwin")
338 move = _mk_w_no_return("wmove")
339
340 if not lib._m_STRICT_SYSV_CURSES:
341 resize = _mk_w_no_return("wresize")
342
343 if lib._m_NetBSD:
344 keypad = _mk_w_return_val("keypad")
345 nodelay = _mk_w_return_val("nodelay")
346 else:
347 keypad = _mk_w_no_return("keypad")
348 nodelay = _mk_w_no_return("nodelay")
349
350 @_argspec(1, 1, 2)
351 def addch(self, y, x, ch, attr=None):
352 if attr is None:
353 attr = lib.A_NORMAL
354 ch = _chtype(ch)
355
356 if y is not None:
357 code = lib.mvwaddch(self._win, y, x, ch | attr)
358 else:
359 code = lib.waddch(self._win, ch | attr)
360 return _check_ERR(code, "addch")
361
362 @_argspec(1, 1, 2)
363 def addstr(self, y, x, text, attr=None):
364 text = _convert_to_string(self, text)
365 if attr is not None:
366 attr_old = lib.getattrs(self._win)
367 lib.wattrset(self._win, attr)
368 if y is not None:
369 code = lib.mvwaddstr(self._win, y, x, text)
370 else:
371 code = lib.waddstr(self._win, text)
372 if attr is not None:
373 lib.wattrset(self._win, attr_old)
374 return _check_ERR(code, "addstr")
375
376 @_argspec(2, 1, 2)
377 def addnstr(self, y, x, text, n, attr=None):
378 text = _convert_to_string(self, text)
379 if attr is not None:
380 attr_old = lib.getattrs(self._win)
381 lib.wattrset(self._win, attr)
382 if y is not None:
383 code = lib.mvwaddnstr(self._win, y, x, text, n)
384 else:
385 code = lib.waddnstr(self._win, text, n)
386 if attr is not None:
387 lib.wattrset(self._win, attr_old)
388 return _check_ERR(code, "addnstr")
389
390 def bkgd(self, ch, attr=None):
391 if attr is None:
392 attr = lib.A_NORMAL
393 return _check_ERR(lib.wbkgd(self._win, _chtype(ch) | attr), "bkgd")
394
395 attroff = _mk_w_no_return("wattroff")
396 attron = _mk_w_no_return("wattron")
397 attrset = _mk_w_no_return("wattrset")
398
399 def bkgdset(self, ch, attr=None):
400 if attr is None:
401 attr = lib.A_NORMAL
402 lib.wbkgdset(self._win, _chtype(ch) | attr)
403 return None
404
405 def border(self, ls=0, rs=0, ts=0, bs=0, tl=0, tr=0, bl=0, br=0):
406 lib.wborder(self._win,
407 _chtype(ls), _chtype(rs), _chtype(ts), _chtype(bs),
408 _chtype(tl), _chtype(tr), _chtype(bl), _chtype(br))
409 return None
410
411 def box(self, *args):
412 if len(args) == 0:
413 vertint = 0
414 horint = 0
415 elif len(args) == 2:
416 vertint = _convert_to_chtype(self, args[0])
417 horint = _convert_to_chtype(self, args[1])
418 else:
419 raise TypeError('verch,horch required')
420 lib.box(self._win, vertint, horint)
421 return None
422
423 @_argspec(1, 1, 2)
424 def chgat(self, y, x, num, attr=None):
425 # These optional args are in a weird order.
426 if attr is None:
427 attr = num
428 num = -1
429
430 color = ((attr >> 8) & 0xff)
431 attr = attr - (color << 8)
432
433 if y is not None:
434 code = lib.mvwchgat(self._win, y, x, num, attr, color, ffi.NULL)
435 lib.touchline(self._win, y, 1)
436 else:
437 yy, _ = self.getyx()
438 code = lib.wchgat(self._win, num, attr, color, ffi.NULL)
439 lib.touchline(self._win, yy, 1)
440 return _check_ERR(code, "chgat")
441
442 def delch(self, *args):
443 if len(args) == 0:
444 code = lib.wdelch(self._win)
445 elif len(args) == 2:
446 code = lib.mvwdelch(self._win, *args)
447 else:
448 raise error("delch requires 0 or 2 arguments")
449 return _check_ERR(code, "[mv]wdelch")
450
451 def derwin(self, *args):
452 nlines = 0
453 ncols = 0
454 if len(args) == 2:
455 begin_y, begin_x = args
456 elif len(args) == 4:
457 nlines, ncols, begin_y, begin_x = args
458 else:
459 raise error("derwin requires 2 or 4 arguments")
460
461 win = lib.derwin(self._win, nlines, ncols, begin_y, begin_x)
462 return Window(_check_NULL(win))
463
464 def echochar(self, ch, attr=None):
465 if attr is None:
466 attr = lib.A_NORMAL
467 ch = _chtype(ch)
468
469 if lib._m_ispad(self._win):
470 code = lib.pechochar(self._win, ch | attr)
471 else:
472 code = lib.wechochar(self._win, ch | attr)
473 return _check_ERR(code, "echochar")
474
475 if lib._m_NCURSES_MOUSE_VERSION:
476 enclose = _mk_w_return_val("wenclose", bool)
477
478 getbkgd = _mk_w_return_val("getbkgd")
479
480 def getch(self, *args):
481 if len(args) == 0:
482 val = lib.wgetch(self._win)
483 elif len(args) == 2:
484 val = lib.mvwgetch(self._win, *args)
485 else:
486 raise error("getch requires 0 or 2 arguments")
487 return val
488
489 def get_wch(self, *args):
490 wch = ffi.new("wint_t[1]")
491 if len(args) == 0:
492 val = lib.wget_wch(self._win, wch)
493 elif len(args) == 2:
494 val = lib.mvwget_wch(self._win, *args, wch)
495 else:
496 raise error("get_wch requires 0 or 2 arguments")
497 _check_ERR(val, "get_wch")
498 if val == lib.KEY_CODE_YES:
499 return wch[0]
500 else:
501 return chr(wch[0])
502
503 def getkey(self, *args):
504 if len(args) == 0:
505 val = lib.wgetch(self._win)
506 elif len(args) == 2:
507 val = lib.mvwgetch(self._win, *args)
508 else:
509 raise error("getkey requires 0 or 2 arguments")
510
511 if val == lib.ERR:
512 raise error("no input")
513 elif val <= 255:
514 return chr(val)
515 else:
516 # XXX: The following line is different if `__NetBSD__` is defined.
517 val = lib.keyname(val)
518 if val == ffi.NULL:
519 return ""
520 key_n = ffi.string(val)
521 if not isinstance(key_n, str):
522 key_n = key_n.decode('utf-8')
523 return key_n
524
525 @_argspec(0, 1, 2)
526 def getstr(self, y, x, n=1023):
527 n = min(n, 1023)
528 if n < 0:
529 raise ValueError("'n' must be nonnegative")
530 buf = ffi.new("char[1024]") # /* This should be big enough.. I hope */
531
532 if y is None:
533 val = lib.wgetnstr(self._win, buf, n)
534 else:
535 val = lib.mvwgetnstr(self._win, y, x, buf, n)
536
537 if val == lib.ERR:
538 return ""
539 return ffi.string(buf)
540
541 @_argspec(2, 1, 2)
542 def hline(self, y, x, ch, n, attr=None):
543 ch = _chtype(ch)
544 if attr is None:
545 attr = lib.A_NORMAL
546 if y is not None:
547 _check_ERR(lib.wmove(self._win, y, x), "wmove")
548 return _check_ERR(lib.whline(self._win, ch | attr, n), "hline")
549
550 @_argspec(1, 1, 2)
551 def insch(self, y, x, ch, attr=None):
552 ch = _chtype(ch)
553 if attr is None:
554 attr = lib.A_NORMAL
555 if y is not None:
556 code = lib.mvwinsch(self._win, y, x, ch | attr)
557 else:
558 code = lib.winsch(self._win, ch | attr)
559 return _check_ERR(code, "insch")
560
561 def inch(self, *args):
562 if len(args) == 0:
563 return lib.winch(self._win)
564 elif len(args) == 2:
565 return lib.mvwinch(self._win, *args)
566 else:
567 raise error("inch requires 0 or 2 arguments")
568
569 @_argspec(0, 1, 2)
570 def instr(self, y, x, n=1023):
571 n = min(n, 1023)
572 if n < 0:
573 raise ValueError("'n' must be nonnegative")
574 buf = ffi.new("char[1024]") # /* This should be big enough.. I hope */
575 if y is None:
576 code = lib.winnstr(self._win, buf, n)
577 else:
578 code = lib.mvwinnstr(self._win, y, x, buf, n)
579
580 if code == lib.ERR:
581 return ""
582 return ffi.string(buf)
583
584 @_argspec(1, 1, 2)
585 def insstr(self, y, x, text, attr=None):
586 text = _convert_to_string(self, text)
587 if attr is not None:
588 attr_old = lib.getattrs(self._win)
589 lib.wattrset(self._win, attr)
590 if y is not None:
591 code = lib.mvwinsstr(self._win, y, x, text)
592 else:
593 code = lib.winsstr(self._win, text)
594 if attr is not None:
595 lib.wattrset(self._win, attr_old)
596 return _check_ERR(code, "insstr")
597
598 @_argspec(2, 1, 2)
599 def insnstr(self, y, x, text, n, attr=None):
600 text = _convert_to_string(self, text)
601 if attr is not None:
602 attr_old = lib.getattrs(self._win)
603 lib.wattrset(self._win, attr)
604 if y is not None:
605 code = lib.mvwinsnstr(self._win, y, x, text, n)
606 else:
607 code = lib.winsnstr(self._win, text, n)
608 if attr is not None:
609 lib.wattrset(self._win, attr_old)
610 return _check_ERR(code, "insnstr")
611
612 def is_linetouched(self, line):
613 code = lib.is_linetouched(self._win, line)
614 if code == lib.ERR:
615 raise error("is_linetouched: line number outside of boundaries")
616 if code == lib.FALSE:
617 return False
618 return True
619
620 def noutrefresh(self, *args):
621 if lib._m_ispad(self._win):
622 if len(args) != 6:
623 raise error(
624 "noutrefresh() called for a pad requires 6 arguments")
625 return _check_ERR(lib.pnoutrefresh(self._win, *args),
626 "pnoutrefresh")
627 else:
628 # XXX: Better args check here? We need zero args.
629 return _check_ERR(lib.wnoutrefresh(self._win, *args),
630 "wnoutrefresh")
631
632 nooutrefresh = noutrefresh # "to be removed in 2.3", but in 2.7, 3.x.
633
634 def _copywin(self, dstwin, overlay,
635 sminr, sminc, dminr, dminc, dmaxr, dmaxc):
636 return _check_ERR(lib.copywin(self._win, dstwin._win,
637 sminr, sminc, dminr, dminc, dmaxr, dmaxc,
638 overlay), "copywin")
639
640 def overlay(self, dstwin, *args):
641 if len(args) == 6:
642 return self._copywin(dstwin, True, *args)
643 elif len(args) == 0:
644 return _check_ERR(lib.overlay(self._win, dstwin._win), "overlay")
645 else:
646 raise error("overlay requires one or seven arguments")
647
648 def overwrite(self, dstwin, *args):
649 if len(args) == 6:
650 return self._copywin(dstwin, False, *args)
651 elif len(args) == 0:
652 return _check_ERR(lib.overwrite(self._win, dstwin._win),
653 "overwrite")
654 else:
655 raise error("overwrite requires one or seven arguments")
656
657 def putwin(self, filep):
658 # filestar = ffi.new("FILE *", filep)
659 return _check_ERR(lib.putwin(self._win, filep), "putwin")
660 # XXX CPython 3.5 says: We have to simulate this by writing to
661 # a temporary FILE*, then reading back, then writing to the
662 # argument stream.
663
664 def redrawln(self, beg, num):
665 return _check_ERR(lib.wredrawln(self._win, beg, num), "redrawln")
666
667 def refresh(self, *args):
668 if lib._m_ispad(self._win):
669 if len(args) != 6:
670 raise error(
671 "noutrefresh() called for a pad requires 6 arguments")
672 return _check_ERR(lib.prefresh(self._win, *args), "prefresh")
673 else:
674 # XXX: Better args check here? We need zero args.
675 return _check_ERR(lib.wrefresh(self._win, *args), "wrefresh")
676
677 def setscrreg(self, y, x):
678 return _check_ERR(lib.wsetscrreg(self._win, y, x), "wsetscrreg")
679
680 def subwin(self, *args):
681 nlines = 0
682 ncols = 0
683 if len(args) == 2:
684 begin_y, begin_x = args
685 elif len(args) == 4:
686 nlines, ncols, begin_y, begin_x = args
687 else:
688 raise error("subwin requires 2 or 4 arguments")
689
690 if lib._m_ispad(self._win):
691 win = lib.subpad(self._win, nlines, ncols, begin_y, begin_x)
692 else:
693 win = lib.subwin(self._win, nlines, ncols, begin_y, begin_x)
694 return Window(_check_NULL(win), self.encoding)
695
696 def scroll(self, nlines=None):
697 if nlines is None:
698 return _check_ERR(lib.scroll(self._win), "scroll")
699 else:
700 return _check_ERR(lib.wscrl(self._win, nlines), "scroll")
701
702 def touchline(self, st, cnt, val=None):
703 if val is None:
704 return _check_ERR(lib.touchline(self._win, st, cnt), "touchline")
705 else:
706 return _check_ERR(lib.wtouchln(self._win, st, cnt, val),
707 "touchline")
708
709 @_argspec(2, 1, 2)
710 def vline(self, y, x, ch, n, attr=None):
711 ch = _chtype(ch)
712 if attr is None:
713 attr = lib.A_NORMAL
714 if y is not None:
715 _check_ERR(lib.wmove(self._win, y, x), "wmove")
716 return _check_ERR(lib.wvline(self._win, ch | attr, n), "vline")
717
718 @property
719 def encoding(self):
720 return self._encoding
721
722 @encoding.setter
723 def encoding(self, val):
724 if not val:
725 raise TypeError('encoding may not be deleted')
726 if not isinstance(val, str):
727 raise TypeError('setting encoding to a non-string')
728 encoding = val.encode('ascii')
729 self._encoding = val
730
731 @encoding.deleter
732 def encoding(self):
733 raise TypeError('encoding may not be deleted')
734
735
736 beep = _mk_no_return("beep")
737 def_prog_mode = _mk_no_return("def_prog_mode")
738 def_shell_mode = _mk_no_return("def_shell_mode")
739 doupdate = _mk_no_return("doupdate")
740 endwin = _mk_no_return("endwin")
741 flash = _mk_no_return("flash")
742 nocbreak = _mk_no_return("nocbreak")
743 noecho = _mk_no_return("noecho")
744 nonl = _mk_no_return("nonl")
745 noraw = _mk_no_return("noraw")
746 reset_prog_mode = _mk_no_return("reset_prog_mode")
747 reset_shell_mode = _mk_no_return("reset_shell_mode")
748 resetty = _mk_no_return("resetty")
749 savetty = _mk_no_return("savetty")
750
751 cbreak = _mk_flag_func("cbreak")
752 echo = _mk_flag_func("echo")
753 nl = _mk_flag_func("nl")
754 raw = _mk_flag_func("raw")
755
756 baudrate = _mk_return_val("baudrate")
757 termattrs = _mk_return_val("termattrs")
758
759 termname = _mk_return_val("termname", ffi.string)
760 longname = _mk_return_val("longname", ffi.string)
761
762 can_change_color = _mk_return_val("can_change_color", bool)
763 has_colors = _mk_return_val("has_colors", bool)
764 has_ic = _mk_return_val("has_ic", bool)
765 has_il = _mk_return_val("has_il", bool)
766 isendwin = _mk_return_val("isendwin", bool)
767 flushinp = _mk_return_val("flushinp")
768 noqiflush = _mk_return_val("noqiflush")
769
770 def filter():
771 lib.filter()
772 return None
773
774 def color_converter(color):
775 if color >= lib.COLORS:
776 raise ValueError(f"Color number is greater than COLORS-1 ({lib.COLORS-1}).")
777 elif color < 0:
778 raise ValueError(f"Color number is less than 0.")
779 return color
780
781 def component_converter(color):
782 if color > 1000:
783 raise ValueError("Color component is greater than 1000")
784 elif color < 0:
785 raise ValueError("Color component is less than 0.")
786 return color
787
788
789 def color_content(color):
790 _ensure_initialised_color()
791 r = ffi.new(f"{_CURSES_COLOR_VAL_TYPE} *")
792 g = ffi.new(f"{_CURSES_COLOR_VAL_TYPE} *")
793 b = ffi.new(f"{_CURSES_COLOR_VAL_TYPE} *")
794 color = color_converter(color)
795 if _COLOR_CONTENT_FUNC(color, r, g, b) == lib.ERR:
796 raise error("color_content returned ERR")
797 return (r[0], g[0], b[0])
798
799
800 def color_pair(n):
801 _ensure_initialised_color()
802 return (n << 8)
803
804
805 def curs_set(vis):
806 _ensure_initialised()
807 val = lib.curs_set(vis)
808 _check_ERR(val, "curs_set")
809 return val
810
811
812 def delay_output(ms):
813 _ensure_initialised()
814 return _check_ERR(lib.delay_output(ms), "delay_output")
815
816
817 def erasechar():
818 _ensure_initialised()
819 return lib.erasechar()
820
821
822 def getsyx():
823 _ensure_initialised()
824 yx = ffi.new("int[2]")
825 lib._m_getsyx(yx)
826 return (yx[0], yx[1])
827
828
829 if lib._m_NCURSES_MOUSE_VERSION:
830
831 def getmouse():
832 _ensure_initialised()
833 mevent = ffi.new("MEVENT *")
834 _check_ERR(lib.getmouse(mevent), "getmouse")
835 return (mevent.id, mevent.x, mevent.y, mevent.z, mevent.bstate)
836
837 def ungetmouse(id, x, y, z, bstate):
838 _ensure_initialised()
839 mevent = ffi.new("MEVENT *")
840 mevent.id, mevent.x, mevent.y, mevent.z, mevent.bstate = (
841 id, x, y, z, bstate)
842 return _check_ERR(lib.ungetmouse(mevent), "ungetmouse")
843
844
845 def getwin(filep):
846 # XXX CPython 3.5: there's logic to use a temp file instead
847 return Window(_check_NULL(lib.getwin(filep)))
848
849
850 def halfdelay(tenths):
851 _ensure_initialised()
852 return _check_ERR(lib.halfdelay(tenths), "halfdelay")
853
854
855 if not lib._m_STRICT_SYSV_CURSES:
856 def has_key(ch):
857 _ensure_initialised()
858 return lib.has_key(ch)
859
860
861 def init_color(color, r, g, b):
862 _ensure_initialised_color()
863 color = color_converter(color)
864 r = component_converter(r)
865 g = component_converter(g)
866 b = component_converter(b)
867 return _check_ERR(_CURSES_INIT_COLOR_FUNC(color, r, g, b), "init_color")
868
869
870 def init_pair(pair, f, b):
871 _ensure_initialised_color()
872 if pair >= lib.COLOR_PAIRS:
873 raise ValueError("Color pair is greater than COLOR_PAIRS-1 ({lib.COLOR_PAIRS}).")
874 elif pair < 0:
875 raise ValueError("Color pair is less than 0.")
876 f = color_converter(f)
877 b = color_converter(b)
878 return _check_ERR(_CURSES_INIT_PAIR_FUNC(pair, f, b), "init_pair")
879
880
881
882 def _map_acs():
883 def _mk_acs(name, ichar):
884 if len(ichar) == 1:
885 globals()[name] = lib.acs_map[ord(ichar)]
886 else:
887 globals()[name] = globals()[ichar]
888
889 _mk_acs("ACS_ULCORNER", 'l')
890 _mk_acs("ACS_LLCORNER", 'm')
891 _mk_acs("ACS_URCORNER", 'k')
892 _mk_acs("ACS_LRCORNER", 'j')
893 _mk_acs("ACS_LTEE", 't')
894 _mk_acs("ACS_RTEE", 'u')
895 _mk_acs("ACS_BTEE", 'v')
896 _mk_acs("ACS_TTEE", 'w')
897 _mk_acs("ACS_HLINE", 'q')
898 _mk_acs("ACS_VLINE", 'x')
899 _mk_acs("ACS_PLUS", 'n')
900 _mk_acs("ACS_S1", 'o')
901 _mk_acs("ACS_S9", 's')
902 _mk_acs("ACS_DIAMOND", '`')
903 _mk_acs("ACS_CKBOARD", 'a')
904 _mk_acs("ACS_DEGREE", 'f')
905 _mk_acs("ACS_PLMINUS", 'g')
906 _mk_acs("ACS_BULLET", '~')
907 _mk_acs("ACS_LARROW", ',')
908 _mk_acs("ACS_RARROW", '+')
909 _mk_acs("ACS_DARROW", '.')
910 _mk_acs("ACS_UARROW", '-')
911 _mk_acs("ACS_BOARD", 'h')
912 _mk_acs("ACS_LANTERN", 'i')
913 _mk_acs("ACS_BLOCK", '0')
914 _mk_acs("ACS_S3", 'p')
915 _mk_acs("ACS_S7", 'r')
916 _mk_acs("ACS_LEQUAL", 'y')
917 _mk_acs("ACS_GEQUAL", 'z')
918 _mk_acs("ACS_PI", '{')
919 _mk_acs("ACS_NEQUAL", '|')
920 _mk_acs("ACS_STERLING", '}')
921 _mk_acs("ACS_BSSB", "ACS_ULCORNER")
922 _mk_acs("ACS_SSBB", "ACS_LLCORNER")
923 _mk_acs("ACS_BBSS", "ACS_URCORNER")
924 _mk_acs("ACS_SBBS", "ACS_LRCORNER")
925 _mk_acs("ACS_SBSS", "ACS_RTEE")
926 _mk_acs("ACS_SSSB", "ACS_LTEE")
927 _mk_acs("ACS_SSBS", "ACS_BTEE")
928 _mk_acs("ACS_BSSS", "ACS_TTEE")
929 _mk_acs("ACS_BSBS", "ACS_HLINE")
930 _mk_acs("ACS_SBSB", "ACS_VLINE")
931 _mk_acs("ACS_SSSS", "ACS_PLUS")
932
933
934 def initscr():
935 if _initialised:
936 lib.wrefresh(lib.stdscr)
937 return Window(lib.stdscr)
938
939 win = _check_NULL(lib.initscr())
940 globals()['_initialised_setupterm'] = True
941 globals()['_initialised'] = True
942
943 _map_acs()
944
945 globals()["LINES"] = lib.LINES
946 globals()["COLS"] = lib.COLS
947
948 window = Window(win)
949 globals()['screen_encoding'] = window.encoding
950 return window
951
952
953 def setupterm(term=None, fd=-1):
954 if fd == -1:
955 # XXX: Check for missing stdout here?
956 fd = sys.stdout.fileno()
957
958 if _initialised_setupterm:
959 return None
960
961 if term is None:
962 term = ffi.NULL
963 elif isinstance(term, str):
964 term = term.encode()
965 err = ffi.new("int *")
966 if lib.setupterm(term, fd, err) == lib.ERR:
967 err = err[0]
968 if err == 0:
969 raise error("setupterm: could not find terminal")
970 elif err == -1:
971 raise error("setupterm: could not find terminfo database")
972 else:
973 raise error("setupterm: unknown error")
974
975 globals()["_initialised_setupterm"] = True
976 return None
977
978
979 def intrflush(ch):
980 _ensure_initialised()
981 return _check_ERR(lib.intrflush(ffi.NULL, ch), "intrflush")
982
983
984 # XXX: #ifdef HAVE_CURSES_IS_TERM_RESIZED
985 def is_term_resized(lines, columns):
986 _ensure_initialised()
987 return bool(lib.is_term_resized(lines, columns))
988
989
990 if not lib._m_NetBSD:
991 def keyname(ch):
992 _ensure_initialised()
993 if ch < 0:
994 raise ValueError("invalid key number")
995 knp = lib.keyname(ch)
996 if knp == ffi.NULL:
997 return b""
998 return ffi.string(knp)
999
1000
1001 def killchar():
1002 return lib.killchar()
1003
1004
1005 def meta(ch):
1006 return _check_ERR(lib.meta(lib.stdscr, ch), "meta")
1007
1008
1009 if lib._m_NCURSES_MOUSE_VERSION:
1010
1011 def mouseinterval(interval):
1012 _ensure_initialised()
1013 return _check_ERR(lib.mouseinterval(interval), "mouseinterval")
1014
1015 def mousemask(newmask):
1016 _ensure_initialised()
1017 oldmask = ffi.new("mmask_t *")
1018 availmask = lib.mousemask(newmask, oldmask)
1019 return (availmask, oldmask)
1020
1021
1022 def napms(ms):
1023 _ensure_initialised()
1024 return lib.napms(ms)
1025
1026
1027 def newpad(nlines, ncols):
1028 _ensure_initialised()
1029 return Window(_check_NULL(lib.newpad(nlines, ncols)))
1030
1031
1032 def newwin(nlines, ncols, begin_y=None, begin_x=None):
1033 _ensure_initialised()
1034 if begin_x is None:
1035 if begin_y is not None:
1036 raise error("newwin requires 2 or 4 arguments")
1037 begin_y = begin_x = 0
1038
1039 return Window(_check_NULL(lib.newwin(nlines, ncols, begin_y, begin_x)))
1040
1041
1042 def pair_content(pair):
1043 _ensure_initialised_color()
1044 f = ffi.new(f"{_CURSES_COLOR_NUM_TYPE} *")
1045 b = ffi.new(f"{_CURSES_COLOR_NUM_TYPE} *")
1046 if pair >= lib.COLOR_PAIRS:
1047 raise ValueError("Color pair is greater than COLOR_PAIRS-1 ({lib.COLOR_PAIRS}).")
1048 elif pair < 0:
1049 raise ValueError("Color pair is less than 0.")
1050 if _CURSES_PAIR_CONTENT_FUNC(pair, f, b) == lib.ERR:
1051 raise error(f"{_CURSES_PAIR_CONTENT_FUNC_NAME}() returned ERR")
1052 return (f[0], b[0])
1053
1054
1055 def pair_number(pairvalue):
1056 _ensure_initialised_color()
1057 return (pairvalue & lib.A_COLOR) >> 8
1058
1059
1060 def putp(text):
1061 _ensure_initialised()
1062 text = _bytestype(text)
1063 return _check_ERR(lib.putp(text), "putp")
1064
1065
1066 def qiflush(flag=True):
1067 _ensure_initialised()
1068 if flag:
1069 lib.qiflush()
1070 else:
1071 lib.noqiflush()
1072 return None
1073
1074
1075 # Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES
1076 # and _curses.COLS
1077 def update_lines_cols():
1078 globals()["LINES"] = lib.LINES
1079 globals()["COLS"] = lib.COLS
1080 try:
1081 m = sys.modules["curses"]
1082 m.LINES = lib.LINES
1083 m.COLS = lib.COLS
1084 except (KeyError, AttributeError):
1085 pass
1086
1087
1088 def resizeterm(lines, columns):
1089 _ensure_initialised()
1090 _check_ERR(lib.resizeterm(lines, columns), "resizeterm")
1091 update_lines_cols()
1092
1093
1094 def resize_term(lines, columns):
1095 _ensure_initialised()
1096 _check_ERR(lib.resize_term(lines, columns), "resize_term")
1097 update_lines_cols()
1098
1099
1100 def setsyx(y, x):
1101 _ensure_initialised()
1102 lib.setsyx(y, x)
1103 return None
1104
1105
1106 def start_color():
1107 _check_ERR(lib.start_color(), "start_color")
1108 globals()["COLORS"] = lib.COLORS
1109 globals()["COLOR_PAIRS"] = lib.COLOR_PAIRS
1110 globals()["_initialised_color"] = True
1111 return None
1112
1113
1114 def tigetflag(capname):
1115 _ensure_initialised_setupterm()
1116 return lib.tigetflag(capname.encode())
1117
1118
1119 def tigetnum(capname):
1120 _ensure_initialised_setupterm()
1121 return lib.tigetnum(capname.encode())
1122
1123
1124 def tigetstr(capname):
1125 _ensure_initialised_setupterm()
1126 val = lib.tigetstr(capname.encode())
1127 if int(ffi.cast("intptr_t", val)) in (0, -1):
1128 return None
1129 return ffi.string(val)
1130
1131
1132 def tparm(fmt, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0, i9=0):
1133 args = [ffi.cast("int", i) for i in (i1, i2, i3, i4, i5, i6, i7, i8, i9)]
1134 # fmt is expected to be a byte string; CPython 3.x complains
1135 # "TypeError: a bytes-like object is required, not 'str'", but we
1136 # can do better.
1137 if isinstance(fmt, str):
1138 # error message modeled on "TypeError: must be str, not bytes"
1139 # that you get if you call curses.tigetstr(b'...') on CPython 3.x
1140 raise TypeError('must be bytes, not str')
1141 result = lib.tparm(fmt, *args)
1142 if result == ffi.NULL:
1143 raise error("tparm() returned NULL")
1144 return ffi.string(result)
1145
1146
1147 def typeahead(fd):
1148 _ensure_initialised()
1149 return _check_ERR(lib.typeahead(fd), "typeahead")
1150
1151
1152 def unctrl(ch):
1153 _ensure_initialised()
1154 return ffi.string(lib.unctrl(_chtype(ch)))
1155
1156
1157 def ungetch(ch):
1158 _ensure_initialised()
1159 return _check_ERR(lib.ungetch(_chtype(ch)), "ungetch")
1160
1161
1162 def unget_wch(ch):
1163 _ensure_initialised()
1164 if isinstance(ch, str):
1165 if len(ch) != 1:
1166 raise TypeError("expect bytes or str of length1, or int, "
1167 "got a str of length %d" % len(ch))
1168 elif isinstance(ch, int):
1169 ch = chr(ch)
1170 return _check_ERR(lib.unget_wch(ch), "unget_wch")
1171
1172
1173 def use_env(flag):
1174 lib.use_env(flag)
1175 return None
1176
1177
1178 if not lib._m_STRICT_SYSV_CURSES:
1179
1180 def use_default_colors():
1181 _ensure_initialised_color()
1182 return _check_ERR(lib.use_default_colors(), "use_default_colors")