1# -*- coding: ascii -*-
2#
3# Copyright 2007, 2008, 2009, 2010, 2011
4# Andr\xe9 Malo or his licensors, as applicable
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17"""
18=================
19 Terminal writer
20=================
21"""
22__author__ = "Andr\xe9 Malo"
23__docformat__ = "restructuredtext en"
24
25import sys as _sys
26
27
28class _INFO(dict):
29    """ Terminal info dict """
30
31    def __init__(self):
32        """ Initialization """
33        dict.__init__(self, {
34            'NORMAL': '',
35            'BOLD': '',
36            'ERASE': '\n',
37            'RED': '',
38            'YELLOW': '',
39            'GREEN': '',
40        })
41        try:
42            import curses as _curses
43        except ImportError:
44            # fixup if a submodule of curses failed.
45            if 'curses' in _sys.modules:
46                del _sys.modules['curses']
47        else:
48            try:
49                _curses.setupterm()
50            except (TypeError, _curses.error):
51                pass
52            else:
53                def make_color(color):
54                    """ Make color control string """
55                    seq = _curses.tigetstr('setaf').decode('ascii')
56                    if seq is not None:
57                        # XXX may fail - need better logic
58                        seq = seq.replace("%p1", "") % color
59                    return seq
60
61                self['NORMAL'] = _curses.tigetstr('sgr0').decode('ascii')
62                self['BOLD'] = _curses.tigetstr('bold').decode('ascii')
63
64                erase = _curses.tigetstr('el1').decode('ascii')
65                if erase is not None:
66                    self['ERASE'] = erase + \
67                        _curses.tigetstr('cr').decode('ascii')
68
69                self['RED'] = make_color(_curses.COLOR_RED)
70                self['YELLOW'] = make_color(_curses.COLOR_YELLOW)
71                self['GREEN'] = make_color(_curses.COLOR_GREEN)
72
73    def __getitem__(self, key):
74        """ Deliver always """
75        dict.get(self, key) or ""
76
77
78def terminfo():
79    """ Get info singleton """
80    # pylint: disable = E1101, W0612
81    if terminfo.info is None:
82        terminfo.info = _INFO()
83    return terminfo.info
84terminfo.info = None
85
86
87def write(fmt, **kwargs):
88    """ Write stuff on the terminal """
89    parm = dict(terminfo())
90    parm.update(kwargs)
91    _sys.stdout.write(fmt % parm)
92    _sys.stdout.flush()
93
94
95def green(bmt, **kwargs):
96    """ Write something in green on screen """
97    announce("%%(GREEN)s%s%%(NORMAL)s" % bmt, **kwargs)
98
99
100def red(bmt, **kwargs):
101    """ Write something in red on the screen """
102    announce("%%(BOLD)s%%(RED)s%s%%(NORMAL)s" % bmt, **kwargs)
103
104
105def yellow(fmt, **kwargs):
106    """ Write something in yellow on the screen """
107    announce("%%(BOLD)s%%(YELLOW)s%s%%(NORMAL)s" % fmt, **kwargs)
108
109
110def announce(fmt, **kwargs):
111    """ Announce something """
112    write(fmt, **kwargs)
113    _sys.stdout.write("\n")
114    _sys.stdout.flush()
115
116
117