Browse Source

Add colorama 0.2.4

Sebastian Pipping 9 years ago
parent
commit
6b726137b8

+ 33
- 0
client-barcode/colorama/LICENSE.txt View File

@@ -0,0 +1,33 @@
1
+Copyright (c) 2010 Jonathan Hartley <tartley@tartley.com>
2
+
3
+Released under the New BSD license (reproduced below), or alternatively you may
4
+use this software under any OSI approved open source license such as those at
5
+http://opensource.org/licenses/alphabetical
6
+
7
+All rights reserved.
8
+
9
+Redistribution and use in source and binary forms, with or without
10
+modification, are permitted provided that the following conditions are met:
11
+
12
+* Redistributions of source code must retain the above copyright notice, this
13
+  list of conditions and the following disclaimer.
14
+
15
+* Redistributions in binary form must reproduce the above copyright notice,
16
+  this list of conditions and the following disclaimer in the documentation
17
+  and/or other materials provided with the distribution.
18
+
19
+* Neither the name(s) of the copyright holders, nor those of its contributors
20
+  may be used to endorse or promote products derived from this software without
21
+  specific prior written permission.
22
+
23
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+

+ 1
- 0
client-barcode/colorama/VERSION View File

@@ -0,0 +1 @@
1
+0.2.4

+ 6
- 0
client-barcode/colorama/__init__.py View File

@@ -0,0 +1,6 @@
1
+from .initialise import init, deinit, reinit
2
+from .ansi import Fore, Back, Style
3
+from .ansitowin32 import AnsiToWin32
4
+
5
+VERSION = '0.2.4'
6
+

+ 49
- 0
client-barcode/colorama/ansi.py View File

@@ -0,0 +1,49 @@
1
+'''
2
+This module generates ANSI character codes to printing colors to terminals.
3
+See: http://en.wikipedia.org/wiki/ANSI_escape_code
4
+'''
5
+
6
+CSI = '\033['
7
+
8
+def code_to_chars(code):
9
+    return CSI + str(code) + 'm'
10
+
11
+class AnsiCodes(object):
12
+    def __init__(self, codes):
13
+        for name in dir(codes):
14
+            if not name.startswith('_'):
15
+                value = getattr(codes, name)
16
+                setattr(self, name, code_to_chars(value))
17
+
18
+class AnsiFore:
19
+    BLACK   = 30
20
+    RED     = 31
21
+    GREEN   = 32
22
+    YELLOW  = 33
23
+    BLUE    = 34
24
+    MAGENTA = 35
25
+    CYAN    = 36
26
+    WHITE   = 37
27
+    RESET   = 39
28
+
29
+class AnsiBack:
30
+    BLACK   = 40
31
+    RED     = 41
32
+    GREEN   = 42
33
+    YELLOW  = 43
34
+    BLUE    = 44
35
+    MAGENTA = 45
36
+    CYAN    = 46
37
+    WHITE   = 47
38
+    RESET   = 49
39
+
40
+class AnsiStyle:
41
+    BRIGHT    = 1
42
+    DIM       = 2
43
+    NORMAL    = 22
44
+    RESET_ALL = 0
45
+
46
+Fore = AnsiCodes( AnsiFore )
47
+Back = AnsiCodes( AnsiBack )
48
+Style = AnsiCodes( AnsiStyle )
49
+

+ 182
- 0
client-barcode/colorama/ansitowin32.py View File

@@ -0,0 +1,182 @@
1
+
2
+import re
3
+import sys
4
+
5
+from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
6
+from .winterm import WinTerm, WinColor, WinStyle
7
+from .win32 import windll
8
+
9
+
10
+if windll is not None:
11
+    winterm = WinTerm()
12
+
13
+
14
+def is_a_tty(stream):
15
+    return hasattr(stream, 'isatty') and stream.isatty()
16
+
17
+
18
+class StreamWrapper(object):
19
+    '''
20
+    Wraps a stream (such as stdout), acting as a transparent proxy for all
21
+    attribute access apart from method 'write()', which is delegated to our
22
+    Converter instance.
23
+    '''
24
+    def __init__(self, wrapped, converter):
25
+        # double-underscore everything to prevent clashes with names of
26
+        # attributes on the wrapped stream object.
27
+        self.__wrapped = wrapped
28
+        self.__convertor = converter
29
+
30
+    def __getattr__(self, name):
31
+        return getattr(self.__wrapped, name)
32
+
33
+    def write(self, text):
34
+        self.__convertor.write(text)
35
+
36
+
37
+class AnsiToWin32(object):
38
+    '''
39
+    Implements a 'write()' method which, on Windows, will strip ANSI character
40
+    sequences from the text, and if outputting to a tty, will convert them into
41
+    win32 function calls.
42
+    '''
43
+    ANSI_RE = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')
44
+
45
+    def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
46
+        # The wrapped stream (normally sys.stdout or sys.stderr)
47
+        self.wrapped = wrapped
48
+
49
+        # should we reset colors to defaults after every .write()
50
+        self.autoreset = autoreset
51
+
52
+        # create the proxy wrapping our output stream
53
+        self.stream = StreamWrapper(wrapped, self)
54
+
55
+        on_windows = sys.platform.startswith('win')
56
+
57
+        # should we strip ANSI sequences from our output?
58
+        if strip is None:
59
+            strip = on_windows
60
+        self.strip = strip
61
+
62
+        # should we should convert ANSI sequences into win32 calls?
63
+        if convert is None:
64
+            convert = on_windows and is_a_tty(wrapped)
65
+        self.convert = convert
66
+
67
+        # dict of ansi codes to win32 functions and parameters
68
+        self.win32_calls = self.get_win32_calls()
69
+
70
+        # are we wrapping stderr?
71
+        self.on_stderr = self.wrapped is sys.stderr
72
+
73
+
74
+    def should_wrap(self):
75
+        '''
76
+        True if this class is actually needed. If false, then the output
77
+        stream will not be affected, nor will win32 calls be issued, so
78
+        wrapping stdout is not actually required. This will generally be
79
+        False on non-Windows platforms, unless optional functionality like
80
+        autoreset has been requested using kwargs to init()
81
+        '''
82
+        return self.convert or self.strip or self.autoreset
83
+
84
+
85
+    def get_win32_calls(self):
86
+        if self.convert and winterm:
87
+            return {
88
+                AnsiStyle.RESET_ALL: (winterm.reset_all, ),
89
+                AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
90
+                AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
91
+                AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
92
+                AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
93
+                AnsiFore.RED: (winterm.fore, WinColor.RED),
94
+                AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
95
+                AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
96
+                AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
97
+                AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
98
+                AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
99
+                AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
100
+                AnsiFore.RESET: (winterm.fore, ),
101
+                AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
102
+                AnsiBack.RED: (winterm.back, WinColor.RED),
103
+                AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
104
+                AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
105
+                AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
106
+                AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
107
+                AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
108
+                AnsiBack.WHITE: (winterm.back, WinColor.GREY),
109
+                AnsiBack.RESET: (winterm.back, ),
110
+            }
111
+
112
+
113
+    def write(self, text):
114
+        if self.strip or self.convert:
115
+            self.write_and_convert(text)
116
+        else:
117
+            self.wrapped.write(text)
118
+            self.wrapped.flush()
119
+        if self.autoreset:
120
+            self.reset_all()
121
+
122
+
123
+    def reset_all(self):
124
+        if self.convert:
125
+            self.call_win32('m', (0,))
126
+        elif is_a_tty(self.wrapped):
127
+            self.wrapped.write(Style.RESET_ALL)
128
+
129
+
130
+    def write_and_convert(self, text):
131
+        '''
132
+        Write the given text to our wrapped stream, stripping any ANSI
133
+        sequences from the text, and optionally converting them into win32
134
+        calls.
135
+        '''
136
+        cursor = 0
137
+        for match in self.ANSI_RE.finditer(text):
138
+            start, end = match.span()
139
+            self.write_plain_text(text, cursor, start)
140
+            self.convert_ansi(*match.groups())
141
+            cursor = end
142
+        self.write_plain_text(text, cursor, len(text))
143
+
144
+
145
+    def write_plain_text(self, text, start, end):
146
+        if start < end:
147
+            self.wrapped.write(text[start:end])
148
+            self.wrapped.flush()
149
+
150
+
151
+    def convert_ansi(self, paramstring, command):
152
+        if self.convert:
153
+            params = self.extract_params(paramstring)
154
+            self.call_win32(command, params)
155
+
156
+
157
+    def extract_params(self, paramstring):
158
+        def split(paramstring):
159
+            for p in paramstring.split(';'):
160
+                if p != '':
161
+                    yield int(p)
162
+        return tuple(split(paramstring))
163
+
164
+
165
+    def call_win32(self, command, params):
166
+        if params == []:
167
+            params = [0]
168
+        if command == 'm':
169
+            for param in params:
170
+                if param in self.win32_calls:
171
+                    func_args = self.win32_calls[param]
172
+                    func = func_args[0]
173
+                    args = func_args[1:]
174
+                    kwargs = dict(on_stderr=self.on_stderr)
175
+                    func(*args, **kwargs)
176
+        elif command in ('H', 'f'): # set cursor position
177
+            func = winterm.set_cursor_position
178
+            func(params, on_stderr=self.on_stderr)
179
+        elif command in ('J'):
180
+            func = winterm.erase_data
181
+            func(params, on_stderr=self.on_stderr)
182
+

+ 55
- 0
client-barcode/colorama/initialise.py View File

@@ -0,0 +1,55 @@
1
+import atexit
2
+import sys
3
+
4
+from .ansitowin32 import AnsiToWin32
5
+
6
+
7
+orig_stdout = sys.stdout
8
+orig_stderr = sys.stderr
9
+
10
+wrapped_stdout = sys.stdout
11
+wrapped_stderr = sys.stderr
12
+
13
+atexit_done = False
14
+
15
+
16
+def reset_all():
17
+    AnsiToWin32(orig_stdout).reset_all()
18
+
19
+
20
+def init(autoreset=False, convert=None, strip=None, wrap=True):
21
+
22
+    if not wrap and any([autoreset, convert, strip]):
23
+        raise ValueError('wrap=False conflicts with any other arg=True')
24
+
25
+    global wrapped_stdout, wrapped_stderr
26
+    sys.stdout = wrapped_stdout = \
27
+        wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
28
+    sys.stderr = wrapped_stderr = \
29
+        wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
30
+
31
+    global atexit_done
32
+    if not atexit_done:
33
+        atexit.register(reset_all)
34
+        atexit_done = True
35
+
36
+
37
+def deinit():
38
+    sys.stdout = orig_stdout
39
+    sys.stderr = orig_stderr
40
+
41
+
42
+def reinit():
43
+    sys.stdout = wrapped_stdout
44
+    sys.stderr = wrapped_stdout
45
+
46
+
47
+def wrap_stream(stream, convert, strip, autoreset, wrap):
48
+    if wrap:
49
+        wrapper = AnsiToWin32(stream,
50
+            convert=convert, strip=strip, autoreset=autoreset)
51
+        if wrapper.should_wrap():
52
+            stream = wrapper.stream
53
+    return stream
54
+
55
+

+ 109
- 0
client-barcode/colorama/win32.py View File

@@ -0,0 +1,109 @@
1
+
2
+# from winbase.h
3
+STDOUT = -11
4
+STDERR = -12
5
+
6
+try:
7
+    from ctypes import windll
8
+except ImportError:
9
+    windll = None
10
+    SetConsoleTextAttribute = lambda *_: None
11
+else:
12
+    from ctypes import (
13
+        byref, Structure, c_char, c_short, c_uint32, c_ushort
14
+    )
15
+
16
+    handles = {
17
+        STDOUT: windll.kernel32.GetStdHandle(STDOUT),
18
+        STDERR: windll.kernel32.GetStdHandle(STDERR),
19
+    }
20
+
21
+    SHORT = c_short
22
+    WORD = c_ushort
23
+    DWORD = c_uint32
24
+    TCHAR = c_char
25
+
26
+    class COORD(Structure):
27
+        """struct in wincon.h"""
28
+        _fields_ = [
29
+            ('X', SHORT),
30
+            ('Y', SHORT),
31
+        ]
32
+
33
+    class  SMALL_RECT(Structure):
34
+        """struct in wincon.h."""
35
+        _fields_ = [
36
+            ("Left", SHORT),
37
+            ("Top", SHORT),
38
+            ("Right", SHORT),
39
+            ("Bottom", SHORT),
40
+        ]
41
+
42
+    class CONSOLE_SCREEN_BUFFER_INFO(Structure):
43
+        """struct in wincon.h."""
44
+        _fields_ = [
45
+            ("dwSize", COORD),
46
+            ("dwCursorPosition", COORD),
47
+            ("wAttributes", WORD),
48
+            ("srWindow", SMALL_RECT),
49
+            ("dwMaximumWindowSize", COORD),
50
+        ]
51
+        def __str__(self):
52
+            return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
53
+                self.dwSize.Y, self.dwSize.X
54
+                , self.dwCursorPosition.Y, self.dwCursorPosition.X
55
+                , self.wAttributes
56
+                , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
57
+                , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
58
+            )
59
+
60
+    def GetConsoleScreenBufferInfo(stream_id=STDOUT):
61
+        handle = handles[stream_id]
62
+        csbi = CONSOLE_SCREEN_BUFFER_INFO()
63
+        success = windll.kernel32.GetConsoleScreenBufferInfo(
64
+            handle, byref(csbi))
65
+        return csbi
66
+
67
+
68
+    def SetConsoleTextAttribute(stream_id, attrs):
69
+        handle = handles[stream_id]
70
+        return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
71
+
72
+
73
+    def SetConsoleCursorPosition(stream_id, position):
74
+        position = COORD(*position)
75
+        # If the position is out of range, do nothing.
76
+        if position.Y <= 0 or position.X <= 0:
77
+            return
78
+        # Adjust for Windows' SetConsoleCursorPosition:
79
+        #    1. being 0-based, while ANSI is 1-based.
80
+        #    2. expecting (x,y), while ANSI uses (y,x).
81
+        adjusted_position = COORD(position.Y - 1, position.X - 1)
82
+        # Adjust for viewport's scroll position
83
+        sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
84
+        adjusted_position.Y += sr.Top
85
+        adjusted_position.X += sr.Left
86
+        # Resume normal processing
87
+        handle = handles[stream_id]
88
+        return windll.kernel32.SetConsoleCursorPosition(handle, adjusted_position)
89
+
90
+    def FillConsoleOutputCharacter(stream_id, char, length, start):
91
+        handle = handles[stream_id]
92
+        char = TCHAR(char)
93
+        length = DWORD(length)
94
+        num_written = DWORD(0)
95
+        # Note that this is hard-coded for ANSI (vs wide) bytes.
96
+        success = windll.kernel32.FillConsoleOutputCharacterA(
97
+            handle, char, length, start, byref(num_written))
98
+        return num_written.value
99
+
100
+    def FillConsoleOutputAttribute(stream_id, attr, length, start):
101
+        ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
102
+        handle = handles[stream_id]
103
+        attribute = WORD(attr)
104
+        length = DWORD(length)
105
+        num_written = DWORD(0)
106
+        # Note that this is hard-coded for ANSI (vs wide) bytes.
107
+        return windll.kernel32.FillConsoleOutputAttribute(
108
+            handle, attribute, length, start, byref(num_written))
109
+

+ 102
- 0
client-barcode/colorama/winterm.py View File

@@ -0,0 +1,102 @@
1
+
2
+from . import win32
3
+
4
+
5
+# from wincon.h
6
+class WinColor(object):
7
+    BLACK   = 0
8
+    BLUE    = 1
9
+    GREEN   = 2
10
+    CYAN    = 3
11
+    RED     = 4
12
+    MAGENTA = 5
13
+    YELLOW  = 6
14
+    GREY    = 7
15
+
16
+# from wincon.h
17
+class WinStyle(object):
18
+    NORMAL = 0x00 # dim text, dim background
19
+    BRIGHT = 0x08 # bright text, dim background
20
+
21
+
22
+class WinTerm(object):
23
+
24
+    def __init__(self):
25
+        self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
26
+        self.set_attrs(self._default)
27
+        self._default_fore = self._fore
28
+        self._default_back = self._back
29
+        self._default_style = self._style
30
+
31
+    def get_attrs(self):
32
+        return self._fore + self._back * 16 + self._style
33
+
34
+    def set_attrs(self, value):
35
+        self._fore = value & 7
36
+        self._back = (value >> 4) & 7
37
+        self._style = value & WinStyle.BRIGHT
38
+
39
+    def reset_all(self, on_stderr=None):
40
+        self.set_attrs(self._default)
41
+        self.set_console(attrs=self._default)
42
+
43
+    def fore(self, fore=None, on_stderr=False):
44
+        if fore is None:
45
+            fore = self._default_fore
46
+        self._fore = fore
47
+        self.set_console(on_stderr=on_stderr)
48
+
49
+    def back(self, back=None, on_stderr=False):
50
+        if back is None:
51
+            back = self._default_back
52
+        self._back = back
53
+        self.set_console(on_stderr=on_stderr)
54
+
55
+    def style(self, style=None, on_stderr=False):
56
+        if style is None:
57
+            style = self._default_style
58
+        self._style = style
59
+        self.set_console(on_stderr=on_stderr)
60
+
61
+    def set_console(self, attrs=None, on_stderr=False):
62
+        if attrs is None:
63
+            attrs = self.get_attrs()
64
+        handle = win32.STDOUT
65
+        if on_stderr:
66
+            handle = win32.STDERR
67
+        win32.SetConsoleTextAttribute(handle, attrs)
68
+
69
+    def set_cursor_position(self, position=None, on_stderr=False):
70
+        if position is None:
71
+            #I'm not currently tracking the position, so there is no default.
72
+            #position = self.get_position()
73
+            return
74
+        handle = win32.STDOUT
75
+        if on_stderr:
76
+            handle = win32.STDERR
77
+        win32.SetConsoleCursorPosition(handle, position)
78
+
79
+    def erase_data(self, mode=0, on_stderr=False):
80
+        # 0 (or None) should clear from the cursor to the end of the screen.
81
+        # 1 should clear from the cursor to the beginning of the screen.
82
+        # 2 should clear the entire screen. (And maybe move cursor to (1,1)?)
83
+        #
84
+        # At the moment, I only support mode 2. From looking at the API, it 
85
+        #    should be possible to calculate a different number of bytes to clear, 
86
+        #    and to do so relative to the cursor position.
87
+        if mode[0] not in (2,):
88
+            return
89
+        handle = win32.STDOUT
90
+        if on_stderr:
91
+            handle = win32.STDERR
92
+        # here's where we'll home the cursor
93
+        coord_screen = win32.COORD(0,0) 
94
+        csbi = win32.GetConsoleScreenBufferInfo(handle)
95
+        # get the number of character cells in the current buffer
96
+        dw_con_size = csbi.dwSize.X * csbi.dwSize.Y
97
+        # fill the entire screen with blanks
98
+        win32.FillConsoleOutputCharacter(handle, ord(' '), dw_con_size, coord_screen)
99
+        # now set the buffer's attributes accordingly
100
+        win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen );
101
+        # put the cursor at (0, 0)
102
+        win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))

Loading…
Cancel
Save