Debian Codegraph @

rpython/tool/terminal.py

raw symbols SCIP
1 # Copyright: 2009 Nadia Alramli
2 # License: BSD
3
4 """Terminal controller module
5 Example of usage:
6 print(BG_BLUE + 'Text on blue background' + NORMAL)
7 print(BLUE + UNDERLINE + 'Blue underlined text' + NORMAL)
8 print(BLUE + BG_YELLOW + BOLD + 'text' + NORMAL)
9 """
10 from __future__ import print_function
11
12 import sys
13
14 # The current module
15 MODULE = sys.modules[__name__]
16
17 COLORS = "BLUE GREEN CYAN RED MAGENTA YELLOW WHITE BLACK".split()
18 # List of terminal controls, you can add more to the list.
19 CONTROLS = {
20 'BOL':'cr', 'UP':'cuu1', 'DOWN':'cud1', 'LEFT':'cub1', 'RIGHT':'cuf1',
21 'CLEAR_SCREEN':'clear', 'CLEAR_EOL':'el', 'CLEAR_BOL':'el1',
22 'CLEAR_EOS':'ed', 'BOLD':'bold', 'BLINK':'blink', 'DIM':'dim',
23 'REVERSE':'rev', 'UNDERLINE':'smul', 'NORMAL':'sgr0',
24 'HIDE_CURSOR':'cinvis', 'SHOW_CURSOR':'cnorm'
25 }
26
27 # List of numeric capabilities
28 VALUES = {
29 'COLUMNS':'cols', # Width of the terminal (80 for unknown)
30 'LINES':'lines', # Height of the terminal (25 for unknown)
31 'MAX_COLORS': 'colors',
32 }
33
34 def default():
35 """Set the default attribute values"""
36 for color in COLORS:
37 setattr(MODULE, color, '')
38 setattr(MODULE, 'BG_%s' % color, '')
39 for control in CONTROLS:
40 setattr(MODULE, control, '')
41 MODULE.COLUMNS = 80
42 MODULE.LINES = 25
43 MODULE.MAX_COLORS = 1
44
45 def setup():
46 """Set the terminal control strings"""
47 # Initializing the terminal
48 curses.setupterm()
49 # Get the color escape sequence template or '' if not supported
50 # setab and setaf are for ANSI escape sequences
51 bgColorSeq = curses.tigetstr('setab') or curses.tigetstr('setb') or ''
52 fgColorSeq = curses.tigetstr('setaf') or curses.tigetstr('setf') or ''
53
54 for color in COLORS:
55 # Get the color index from curses
56 colorIndex = getattr(curses, 'COLOR_%s' % color)
57 # Set the color escape sequence after filling the template with index
58 setattr(MODULE, color, curses.tparm(fgColorSeq, colorIndex))
59 # Set background escape sequence
60 setattr(
61 MODULE, 'BG_%s' % color, curses.tparm(bgColorSeq, colorIndex)
62 )
63 for control in CONTROLS:
64 # Set the control escape sequence
65 setattr(MODULE, control, curses.tigetstr(CONTROLS[control]) or '')
66 if hasattr(curses, 'tigetnum'):
67 for value in VALUES:
68 # Set terminal related values
69 setattr(MODULE, value, curses.tigetnum(VALUES[value]))
70
71 def render(text):
72 """Helper function to apply controls easily
73 Example:
74 apply("%(GREEN)s%(BOLD)stext%(NORMAL)s") -> a bold green text
75 """
76 return text % MODULE.__dict__
77
78 try:
79 import curses
80 setup()
81 except Exception as e:
82 # There is a failure; set all attributes to default
83 print('Warning: %s' % e)
84 default()