Mercurial > traipse_dev
comparison orpg/external/terminalwriter.py @ 66:c54768cffbd4 ornery-dev
Traipse Dev 'OpenRPG' {090818-00}
Traipse is a distribution of OpenRPG that is designed to be easy to setup and go. Traipse also makes it easy for developers to work on code without fear of sacrifice. 'Ornery-Orc' continues the trend of 'Grumpy' and adds fixes to the code. 'Ornery-Orc''s main goal is to offer more advanced features and enhance the productivity of the user.
Update Summary:
*Unstable*
This is the first wave of Code Refinement updates. Includes new material from Core Beta; new debugger material (partially implemented), beginnings of switch to etree, TerminalWriter, and a little more. open_rpg has been renamed to component; functioning now as component.get(), component.add(), component.delete(). This version has known bugs, specifically with the gametree and nodes. I think the XML files where not removed during testing of Core and switching back.
author | sirebral |
---|---|
date | Tue, 18 Aug 2009 06:33:37 -0500 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
65:4840657c23c5 | 66:c54768cffbd4 |
---|---|
1 """ | |
2 | |
3 Helper functions for writing to terminals and files. | |
4 | |
5 """ | |
6 | |
7 | |
8 import sys, os | |
9 from orpg.external.std import std | |
10 | |
11 def _getdimensions(): | |
12 import termios,fcntl,struct | |
13 call = fcntl.ioctl(0,termios.TIOCGWINSZ,"\000"*8) | |
14 height,width = struct.unpack( "hhhh", call ) [:2] | |
15 return height, width | |
16 | |
17 if sys.platform == 'win32': | |
18 # ctypes access to the Windows console | |
19 | |
20 STD_OUTPUT_HANDLE = -11 | |
21 STD_ERROR_HANDLE = -12 | |
22 FOREGROUND_BLUE = 0x0001 # text color contains blue. | |
23 FOREGROUND_GREEN = 0x0002 # text color contains green. | |
24 FOREGROUND_RED = 0x0004 # text color contains red. | |
25 FOREGROUND_WHITE = 0x0007 | |
26 FOREGROUND_INTENSITY = 0x0008 # text color is intensified. | |
27 BACKGROUND_BLUE = 0x0010 # background color contains blue. | |
28 BACKGROUND_GREEN = 0x0020 # background color contains green. | |
29 BACKGROUND_RED = 0x0040 # background color contains red. | |
30 BACKGROUND_WHITE = 0x0070 | |
31 BACKGROUND_INTENSITY = 0x0080 # background color is intensified. | |
32 | |
33 def GetStdHandle(kind): | |
34 import ctypes | |
35 return ctypes.windll.kernel32.GetStdHandle(kind) | |
36 | |
37 def SetConsoleTextAttribute(handle, attr): | |
38 import ctypes | |
39 ctypes.windll.kernel32.SetConsoleTextAttribute( | |
40 handle, attr) | |
41 | |
42 def _getdimensions(): | |
43 import ctypes | |
44 from ctypes import wintypes | |
45 | |
46 SHORT = ctypes.c_short | |
47 class COORD(ctypes.Structure): | |
48 _fields_ = [('X', SHORT), | |
49 ('Y', SHORT)] | |
50 class SMALL_RECT(ctypes.Structure): | |
51 _fields_ = [('Left', SHORT), | |
52 ('Top', SHORT), | |
53 ('Right', SHORT), | |
54 ('Bottom', SHORT)] | |
55 class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure): | |
56 _fields_ = [('dwSize', COORD), | |
57 ('dwCursorPosition', COORD), | |
58 ('wAttributes', wintypes.WORD), | |
59 ('srWindow', SMALL_RECT), | |
60 ('dwMaximumWindowSize', COORD)] | |
61 STD_OUTPUT_HANDLE = -11 | |
62 handle = GetStdHandle(STD_OUTPUT_HANDLE) | |
63 info = CONSOLE_SCREEN_BUFFER_INFO() | |
64 ctypes.windll.kernel32.GetConsoleScreenBufferInfo( | |
65 handle, ctypes.byref(info)) | |
66 # Substract one from the width, otherwise the cursor wraps | |
67 # and the ending \n causes an empty line to display. | |
68 return info.dwSize.Y, info.dwSize.X - 1 | |
69 | |
70 def get_terminal_width(): | |
71 try: | |
72 height, width = _getdimensions() | |
73 except (SystemExit, KeyboardInterrupt), e: | |
74 raise | |
75 except: | |
76 # FALLBACK | |
77 width = int(os.environ.get('COLUMNS', 80))-1 | |
78 # XXX the windows getdimensions may be bogus, let's sanify a bit | |
79 width = max(width, 40) # we alaways need 40 chars | |
80 return width | |
81 | |
82 terminal_width = get_terminal_width() | |
83 | |
84 # XXX unify with _escaped func below | |
85 def ansi_print(text, esc, file=None, newline=True, flush=False): | |
86 if file is None: | |
87 file = sys.stderr | |
88 text = text.rstrip() | |
89 if esc and not isinstance(esc, tuple): | |
90 esc = (esc,) | |
91 if esc and sys.platform != "win32" and file.isatty(): | |
92 text = (''.join(['\x1b[%sm' % cod for cod in esc]) + | |
93 text + | |
94 '\x1b[0m') # ANSI color code "reset" | |
95 if newline: | |
96 text += '\n' | |
97 | |
98 if esc and sys.platform == "win32" and file.isatty(): | |
99 if 1 in esc: | |
100 bold = True | |
101 esc = tuple([x for x in esc if x != 1]) | |
102 else: | |
103 bold = False | |
104 esctable = {() : FOREGROUND_WHITE, # normal | |
105 (31,): FOREGROUND_RED, # red | |
106 (32,): FOREGROUND_GREEN, # green | |
107 (33,): FOREGROUND_GREEN|FOREGROUND_RED, # yellow | |
108 (34,): FOREGROUND_BLUE, # blue | |
109 (35,): FOREGROUND_BLUE|FOREGROUND_RED, # purple | |
110 (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan | |
111 (37,): FOREGROUND_WHITE, # white | |
112 (39,): FOREGROUND_WHITE, # reset | |
113 } | |
114 attr = esctable.get(esc, FOREGROUND_WHITE) | |
115 if bold: | |
116 attr |= FOREGROUND_INTENSITY | |
117 STD_OUTPUT_HANDLE = -11 | |
118 STD_ERROR_HANDLE = -12 | |
119 if file is sys.stderr: | |
120 handle = GetStdHandle(STD_ERROR_HANDLE) | |
121 else: | |
122 handle = GetStdHandle(STD_OUTPUT_HANDLE) | |
123 SetConsoleTextAttribute(handle, attr) | |
124 file.write(text) | |
125 SetConsoleTextAttribute(handle, FOREGROUND_WHITE) | |
126 else: | |
127 file.write(text) | |
128 | |
129 if flush: | |
130 file.flush() | |
131 | |
132 def should_do_markup(file): | |
133 return hasattr(file, 'isatty') and file.isatty() \ | |
134 and os.environ.get('TERM') != 'dumb' | |
135 | |
136 class TerminalWriter(object): | |
137 _esctable = dict(black=30, red=31, green=32, yellow=33, | |
138 blue=34, purple=35, cyan=36, white=37, | |
139 Black=40, Red=41, Green=42, Yellow=43, | |
140 Blue=44, Purple=45, Cyan=46, White=47, | |
141 bold=1, light=2, blink=5, invert=7) | |
142 | |
143 def __init__(self, file=None, stringio=False): | |
144 if file is None: | |
145 if stringio: | |
146 self.stringio = file = std.cStringIO.StringIO() | |
147 else: | |
148 file = std.sys.stdout | |
149 elif callable(file): | |
150 file = WriteFile(file) | |
151 self._file = file | |
152 self.fullwidth = get_terminal_width() | |
153 self.hasmarkup = should_do_markup(file) | |
154 | |
155 def _escaped(self, text, esc): | |
156 if esc and self.hasmarkup: | |
157 text = (''.join(['\x1b[%sm' % cod for cod in esc]) + | |
158 text +'\x1b[0m') | |
159 return text | |
160 | |
161 def markup(self, text, **kw): | |
162 esc = [] | |
163 for name in kw: | |
164 if name not in self._esctable: | |
165 raise ValueError("unknown markup: %r" %(name,)) | |
166 if kw[name]: | |
167 esc.append(self._esctable[name]) | |
168 return self._escaped(text, tuple(esc)) | |
169 | |
170 def sep(self, sepchar, title=None, fullwidth=None, **kw): | |
171 if fullwidth is None: | |
172 fullwidth = self.fullwidth | |
173 # the goal is to have the line be as long as possible | |
174 # under the condition that len(line) <= fullwidth | |
175 if title is not None: | |
176 # we want 2 + 2*len(fill) + len(title) <= fullwidth | |
177 # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth | |
178 # 2*len(sepchar)*N <= fullwidth - len(title) - 2 | |
179 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) | |
180 N = (fullwidth - len(title) - 2) // (2*len(sepchar)) | |
181 fill = sepchar * N | |
182 line = "%s %s %s" % (fill, title, fill) | |
183 else: | |
184 # we want len(sepchar)*N <= fullwidth | |
185 # i.e. N <= fullwidth // len(sepchar) | |
186 line = sepchar * (fullwidth // len(sepchar)) | |
187 # in some situations there is room for an extra sepchar at the right, | |
188 # in particular if we consider that with a sepchar like "_ " the | |
189 # trailing space is not important at the end of the line | |
190 if len(line) + len(sepchar.rstrip()) <= fullwidth: | |
191 line += sepchar.rstrip() | |
192 | |
193 self.line(line, **kw) | |
194 | |
195 def write(self, s, **kw): | |
196 if s: | |
197 s = str(s) | |
198 if self.hasmarkup and kw: | |
199 s = self.markup(s, **kw) | |
200 self._file.write(s) | |
201 self._file.flush() | |
202 | |
203 def line(self, s='', **kw): | |
204 self.write(s, **kw) | |
205 self.write('\n') | |
206 | |
207 class Win32ConsoleWriter(object): | |
208 | |
209 def __init__(self, file=None, stringio=False): | |
210 if file is None: | |
211 if stringio: | |
212 self.stringio = file = std.cStringIO.StringIO() | |
213 else: | |
214 file = std.sys.stdout | |
215 elif callable(file): | |
216 file = WriteFile(file) | |
217 self._file = file | |
218 self.fullwidth = get_terminal_width() | |
219 self.hasmarkup = should_do_markup(file) | |
220 | |
221 def sep(self, sepchar, title=None, fullwidth=None, **kw): | |
222 if fullwidth is None: | |
223 fullwidth = self.fullwidth | |
224 # the goal is to have the line be as long as possible | |
225 # under the condition that len(line) <= fullwidth | |
226 if title is not None: | |
227 # we want 2 + 2*len(fill) + len(title) <= fullwidth | |
228 # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth | |
229 # 2*len(sepchar)*N <= fullwidth - len(title) - 2 | |
230 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) | |
231 N = (fullwidth - len(title) - 2) // (2*len(sepchar)) | |
232 fill = sepchar * N | |
233 line = "%s %s %s" % (fill, title, fill) | |
234 else: | |
235 # we want len(sepchar)*N <= fullwidth | |
236 # i.e. N <= fullwidth // len(sepchar) | |
237 line = sepchar * (fullwidth // len(sepchar)) | |
238 # in some situations there is room for an extra sepchar at the right, | |
239 # in particular if we consider that with a sepchar like "_ " the | |
240 # trailing space is not important at the end of the line | |
241 if len(line) + len(sepchar.rstrip()) <= fullwidth: | |
242 line += sepchar.rstrip() | |
243 | |
244 self.line(line, **kw) | |
245 | |
246 def write(self, s, **kw): | |
247 if s: | |
248 s = str(s) | |
249 if self.hasmarkup: | |
250 handle = GetStdHandle(STD_OUTPUT_HANDLE) | |
251 | |
252 if self.hasmarkup and kw: | |
253 attr = 0 | |
254 if kw.pop('bold', False): | |
255 attr |= FOREGROUND_INTENSITY | |
256 | |
257 if kw.pop('red', False): | |
258 attr |= FOREGROUND_RED | |
259 elif kw.pop('blue', False): | |
260 attr |= FOREGROUND_BLUE | |
261 elif kw.pop('green', False): | |
262 attr |= FOREGROUND_GREEN | |
263 else: | |
264 attr |= FOREGROUND_WHITE | |
265 | |
266 SetConsoleTextAttribute(handle, attr) | |
267 self._file.write(s) | |
268 self._file.flush() | |
269 if self.hasmarkup: | |
270 SetConsoleTextAttribute(handle, FOREGROUND_WHITE) | |
271 | |
272 def line(self, s='', **kw): | |
273 self.write(s + '\n', **kw) | |
274 | |
275 if sys.platform == 'win32': | |
276 TerminalWriter = Win32ConsoleWriter | |
277 | |
278 class WriteFile(object): | |
279 def __init__(self, writemethod): | |
280 self.write = writemethod | |
281 def flush(self): | |
282 return | |
283 | |
284 |