Example #1
0
    def __init__(self, newbuffer=0):
        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)
        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 15)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        background = self.attr & 240
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background

        log('initial attr=%x' % self.attr)
        self.softspace = 0
        self.serial = 0
        self.pythondll = CDLL('python%s%s' % (sys.version[0], sys.version[2]))
        self.pythondll.PyMem_Malloc.restype = c_size_t
        self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
        self.inputHookPtr = c_void_p.from_address(
            addressof(self.pythondll.PyOS_InputHook)).value
        setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
        return
Example #2
0
    def __init__(self, newbuffer=0):
        """Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        """
        # Do I need the following line? It causes a console to be created whenever
        # readline is imported into a pythonw application which seems wrong. Things
        # seem to work without it...
        # self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None
            )
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xF)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes  # remember the initial colors
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)

        background = self.attr & 0xF0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log("initial attr=%x" % self.attr)
        self.softspace = 0  # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = ctypes.pythonapi
        self.inputHookPtr = c_void_p.from_address(
            addressof(self.pythondll.PyOS_InputHook)
        ).value

        if sys.version_info[:2] > (3, 4):
            self.pythondll.PyMem_RawMalloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_RawMalloc)
        else:
            self.pythondll.PyMem_Malloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_Malloc)
Example #3
0
    def __init__(self, newbuffer=0):
        '''Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        '''
        #Do I need the following line? It causes a console to be created whenever
        #readline is imported into a pythonw application which seems wrong. Things
        #seem to work without it...
        #self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = c_int(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xf)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes  # remember the initial colors

        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        #        self.ansiwriter.defaultstate.bold=False

        background = self.attr & 0xf0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log('initial attr=%x' % self.attr)
        self.softspace = 0  # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = CDLL('python%s%s' % (sys.version[0], sys.version[2]))
        self.inputHookPtr = c_int.from_address(
            addressof(self.pythondll.PyOS_InputHook)).value
        setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
Example #4
0
    def __init__(self, newbuffer=0):
        '''Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        '''
        #Do I need the following line? It causes a console to be created whenever
        #readline is imported into a pythonw application which seems wrong. Things
        #seem to work without it...
        #self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                             GENERIC_READ | GENERIC_WRITE,
                             0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xf)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes # remember the initial colors
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        
        background = self.attr & 0xf0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log('initial attr=%x' % self.attr)
        self.softspace = 0 # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = ctypes.pythonapi
        self.inputHookPtr = \
            c_void_p.from_address(addressof(self.pythondll.PyOS_InputHook)).value

        if sys.version_info[:2] > (3, 4): 
            self.pythondll.PyMem_RawMalloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_RawMalloc)
        else:
            self.pythondll.PyMem_Malloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
Example #5
0
class Console(object):
    '''Console driver for Windows.

    '''
    def __init__(self, newbuffer=0):
        '''Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        '''
        #Do I need the following line? It causes a console to be created whenever
        #readline is imported into a pythonw application which seems wrong. Things
        #seem to work without it...
        #self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = c_int(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xf)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes  # remember the initial colors

        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        #        self.ansiwriter.defaultstate.bold=False

        background = self.attr & 0xf0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log('initial attr=%x' % self.attr)
        self.softspace = 0  # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = CDLL('python%s%s' % (sys.version[0], sys.version[2]))
        self.inputHookPtr = c_int.from_address(
            addressof(self.pythondll.PyOS_InputHook)).value
        setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)

    def __del__(self):
        '''Cleanup the console when finished.'''
        # I don't think this ever gets called
        self.SetConsoleTextAttribute(self.hout, self.saveattr)
        self.SetConsoleMode(self.hin, self.inmode)
        self.FreeConsole()

    def _get_top_bot(self):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        top = rect.Top
        bot = rect.Bottom
        return top, bot

    def fixcoord(self, x, y):
        '''Return a long with x and y packed inside, also handle negative x and y.'''
        if x < 0 or y < 0:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            if x < 0:
                x = info.srWindow.Right - x
                y = info.srWindow.Bottom + y

        # this is a hack! ctypes won't pass structures but COORD is just like a
        # long, so this works.
        return c_int(y << 16 | x)

    def pos(self, x=None, y=None):
        '''Move or query the window cursor.'''
        if x is None:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
        else:
            return self.SetConsoleCursorPosition(self.hout,
                                                 self.fixcoord(x, y))

    def home(self):
        '''Move to home.'''
        self.pos(0, 0)

# Map ANSI color escape sequences into Windows Console Attributes

    terminal_escape = re.compile('(\001?\033\\[[0-9;]+m\002?)')
    escape_parts = re.compile('\001?\033\\[([0-9;]+)m\002?')
    escape_to_color = {
        '0;30': 0x0,  #black
        '0;31': 0x4,  #red
        '0;32': 0x2,  #green
        '0;33': 0x4 + 0x2,  #brown?
        '0;34': 0x1,  #blue
        '0;35': 0x1 + 0x4,  #purple
        '0;36': 0x2 + 0x4,  #cyan
        '0;37': 0x1 + 0x2 + 0x4,  #grey
        '1;30': 0x1 + 0x2 + 0x4,  #dark gray
        '1;31': 0x4 + 0x8,  #red
        '1;32': 0x2 + 0x8,  #light green
        '1;33': 0x4 + 0x2 + 0x8,  #yellow
        '1;34': 0x1 + 0x8,  #light blue
        '1;35': 0x1 + 0x4 + 0x8,  #light purple
        '1;36': 0x1 + 0x2 + 0x8,  #light cyan
        '1;37': 0x1 + 0x2 + 0x4 + 0x8,  #white
        '0': None,
    }

    # This pattern should match all characters that change the cursor position differently
    # than a normal character.
    motion_char_re = re.compile('([\n\r\t\010\007])')

    def write_scrolling(self, text, attr=None):
        '''write text at current cursor position while watching for scrolling.

        If the window scrolls because you are at the bottom of the screen
        buffer, all positions that you are storing will be shifted by the
        scroll amount. For example, I remember the cursor position of the
        prompt so that I can redraw the line but if the window scrolls,
        the remembered position is off.

        This variant of write tries to keep track of the cursor position
        so that it will know when the screen buffer is scrolled. It
        returns the number of lines that the buffer scrolled.

        '''
        x, y = self.pos()
        w, h = self.size()
        scroll = 0  # the result
        # split the string into ordinary characters and funny characters
        chunks = self.motion_char_re.split(text)
        for chunk in chunks:
            log('C:' + chunk)
            n = self.write_color(chunk, attr)
            if len(chunk) == 1:  # the funny characters will be alone
                if chunk[0] == '\n':  # newline
                    x = 0
                    y += 1
                elif chunk[0] == '\r':  # carriage return
                    x = 0
                elif chunk[0] == '\t':  # tab
                    x = 8 * (int(x / 8) + 1)
                    if x > w:  # newline
                        x -= w
                        y += 1
                elif chunk[0] == '\007':  # bell
                    pass
                elif chunk[0] == '\010':
                    x -= 1
                    if x < 0:
                        y -= 1  # backed up 1 line
                else:  # ordinary character
                    x += 1
                if x == w:  # wrap
                    x = 0
                    y += 1
                if y == h:  # scroll
                    scroll += 1
                    y = h - 1
            else:  # chunk of ordinary characters
                x += n
                l = int(x / w)  # lines we advanced
                x = x % w  # new x value
                y += l
                if y >= h:  # scroll
                    scroll += y - h + 1
                    y = h - 1
        return scroll

    def write_color(self, text, attr=None):
        '''write text at current cursor position and interpret color escapes.

        return the number of characters written.
        '''
        log('write_color("%s", %s)' % (text, attr))
        chunks = self.terminal_escape.split(text)
        log('chunks=%s' % repr(chunks))
        junk = c_int(0)
        n = 0  # count the characters we actually write, omitting the escapes
        for chunk in chunks:
            m = self.escape_parts.match(chunk)
            if m:
                attr = self.escape_to_color[m.group(1)]
                continue
            n += len(chunk)
            log('attr=%s' % attr)
            if attr is None:
                attr = self.attr
            self.SetConsoleTextAttribute(self.hout, attr)
            #self.WriteConsoleW(self.hout, ensure_str(chunk), len(chunk), byref(junk), None)
        return n

    def write_color(self, text, attr=None):
        text = ensure_unicode(text)
        n, res = self.ansiwriter.write_color(text, attr)
        junk = c_int(0)
        for attr, chunk in res:
            log(unicode(attr))
            log(unicode(chunk))
            self.SetConsoleTextAttribute(self.hout, attr.winattr)
            self.WriteConsoleW(self.hout, chunk, len(chunk), byref(junk), None)
        return n

    def write_plain(self, text, attr=None):
        '''write text at current cursor position.'''
        log('write("%s", %s)' % (text, attr))
        if attr is None:
            attr = self.attr
        n = c_int(0)
        self.SetConsoleTextAttribute(self.hout, attr)
        self.WriteConsoleW(self.hout, ensure_unicode(chunk), len(chunk),
                           byref(junk), None)
        return len(text)

    # make this class look like a file object
    def write(self, text):
        log('write("%s")' % text)
        return self.write_color(text)

    #write = write_scrolling

    def isatty(self):
        return True

    def flush(self):
        pass

    def page(self, attr=None, fill=' '):
        '''Fill the entire screen.'''
        if attr is None:
            attr = self.attr
        if len(fill) != 1:
            raise ValueError
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
            self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))

        w = info.dwSize.X
        n = c_int(0)
        for y in range(info.dwSize.Y):
            self.FillConsoleOutputAttribute(self.hout, attr, w,
                                            self.fixcoord(0, y), byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), w,
                                             self.fixcoord(0, y), byref(n))

        self.attr = attr

    def text(self, x, y, text, attr=None):
        '''Write text at the given position.'''
        if attr is None:
            attr = self.attr

        pos = self.fixcoord(x, y)
        n = c_int(0)
        self.WriteConsoleOutputCharacterW(self.hout, text, len(text), pos,
                                          byref(n))
        self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))

    def clear_to_end_of_window(self):
        top, bot = self._get_top_bot()
        pos = self.pos()
        w, h = self.size()
        self.rectangle((pos[0], pos[1], w, pos[1] + 1))
        if pos[1] < bot:
            self.rectangle((0, pos[1] + 1, w, bot + 1))

    def rectangle(self, rect, attr=None, fill=' '):
        '''Fill Rectangle.'''
        x0, y0, x1, y1 = rect
        n = c_int(0)
        if attr is None:
            attr = self.attr
        for y in range(y0, y1):
            pos = self.fixcoord(x0, y)
            self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0, pos,
                                            byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), x1 - x0,
                                             pos, byref(n))

    def scroll(self, rect, dx, dy, attr=None, fill=' '):
        '''Scroll a rectangle.'''
        if attr is None:
            attr = self.attr

        x0, y0, x1, y1 = rect
        source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
        dest = self.fixcoord(x0 + dx, y0 + dy)
        style = CHAR_INFO()
        style.Char.AsciiChar = fill[0]
        style.Attributes = attr

        return self.ScrollConsoleScreenBufferW(self.hout, byref(source),
                                               byref(source), dest,
                                               byref(style))

    def scroll_window(self, lines):
        '''Scroll the window by the indicated number of lines.'''
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        log('sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
        top = rect.Top + lines
        bot = rect.Bottom + lines
        h = bot - top
        maxbot = info.dwSize.Y - 1
        if top < 0:
            top = 0
            bot = h
        if bot > maxbot:
            bot = maxbot
            top = bot - h

        nrect = SMALL_RECT()
        nrect.Top = top
        nrect.Bottom = bot
        nrect.Left = rect.Left
        nrect.Right = rect.Right
        log('sn: top=%d bot=%d' % (top, bot))
        r = self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
        log('r=%d' % r)

    def get(self):
        '''Get next event from queue.'''
        inputHookFunc = c_int.from_address(self.inputHookPtr).value

        Cevent = INPUT_RECORD()
        count = c_int(0)
        while 1:
            if inputHookFunc:
                call_function(inputHookFunc, ())
            status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1,
                                            byref(count))
            if status and count.value == 1:
                e = event(self, Cevent)
                log_sock(ensure_unicode(e.keyinfo), "keypress")
                return e

    def getkeypress(self):
        '''Return next key press event from the queue, ignoring others.'''
        while 1:
            e = self.get()
            if e.type == 'KeyPress' and e.keycode not in key_modifiers:
                log(e)
                if e.keyinfo.keyname == 'next':
                    self.scroll_window(12)
                elif e.keyinfo.keyname == 'prior':
                    self.scroll_window(-12)
                else:
                    return e
            elif e.type == 'KeyRelease' and e.keyinfo == (True, False, False,
                                                          83):
                log("getKeypress:%s,%s,%s" % (e.keyinfo, e.keycode, e.type))
                return e

    def getchar(self):
        '''Get next character from queue.'''

        Cevent = INPUT_RECORD()
        count = c_int(0)
        while 1:
            status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1,
                                            byref(count))
            if (status and count.value == 1 and Cevent.EventType == 1
                    and Cevent.Event.KeyEvent.bKeyDown):
                sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
                if len(sym) == 0:
                    sym = Cevent.Event.KeyEvent.uChar.AsciiChar
                return sym

    def peek(self):
        '''Check event queue.'''
        Cevent = INPUT_RECORD()
        count = c_int(0)
        status = self.PeekConsoleInputW(self.hin, byref(Cevent), 1,
                                        byref(count))
        if status and count == 1:
            return event(self, Cevent)

    def title(self, txt=None):
        '''Set/get title.'''
        if txt:
            self.SetConsoleTitleW(txt)
        else:
            buffer = create_unicode_buffer(200)
            n = self.GetConsoleTitleW(buffer, 200)
            if n > 0:
                return buffer.value[:n]

    def size(self, width=None, height=None):
        '''Set/get window size.'''
        info = CONSOLE_SCREEN_BUFFER_INFO()
        status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if not status:
            return None
        if width is not None and height is not None:
            wmin = info.srWindow.Right - info.srWindow.Left + 1
            hmin = info.srWindow.Bottom - info.srWindow.Top + 1
            #print wmin, hmin
            width = max(width, wmin)
            height = max(height, hmin)
            #print width, height
            self.SetConsoleScreenBufferSize(self.hout,
                                            self.fixcoord(width, height))
        else:
            return (info.dwSize.X, info.dwSize.Y)

    def cursor(self, visible=None, size=None):
        '''Set cursor on or off.'''
        info = CONSOLE_CURSOR_INFO()
        if self.GetConsoleCursorInfo(self.hout, byref(info)):
            if visible is not None:
                info.bVisible = visible
            if size is not None:
                info.dwSize = size
            self.SetConsoleCursorInfo(self.hout, byref(info))

    def bell(self):
        self.write('\007')

    def next_serial(self):
        '''Get next event serial number.'''
        self.serial += 1
        return self.serial
Example #6
0
class Console(object):
    '''Console driver for Windows.

    '''

    def __init__(self, newbuffer=0):
        '''Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        '''
        #Do I need the following line? It causes a console to be created whenever
        #readline is imported into a pythonw application which seems wrong. Things
        #seem to work without it...
        #self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                             GENERIC_READ | GENERIC_WRITE,
                             0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xf)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes # remember the initial colors
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        
        background = self.attr & 0xf0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log('initial attr=%x' % self.attr)
        self.softspace = 0 # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = ctypes.pythonapi
        self.inputHookPtr = \
            c_void_p.from_address(addressof(self.pythondll.PyOS_InputHook)).value

        if sys.version_info[:2] > (3, 4): 
            self.pythondll.PyMem_RawMalloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_RawMalloc)
        else:
            self.pythondll.PyMem_Malloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)



        
    def __del__(self):
        '''Cleanup the console when finished.'''
        # I don't think this ever gets called
        self.SetConsoleTextAttribute(self.hout, self.saveattr)
        self.SetConsoleMode(self.hin, self.inmode)
        self.FreeConsole()

    def _get_top_bot(self):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        top = rect.Top 
        bot = rect.Bottom 
        return top,bot

    def fixcoord(self, x, y):
        '''Return a long with x and y packed inside, 
        also handle negative x and y.'''
        if x < 0 or y < 0:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            if x < 0:
                x = info.srWindow.Right - x
                y = info.srWindow.Bottom + y

        # this is a hack! ctypes won't pass structures but COORD is 
        # just like a long, so this works.
        return c_int(y << 16 | x)

    def pos(self, x=None, y=None):
        '''Move or query the window cursor.'''
        if x is None:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
        else:
            return self.SetConsoleCursorPosition(self.hout, 
                                                 self.fixcoord(x, y))

    def home(self):
        '''Move to home.'''
        self.pos(0, 0)

# Map ANSI color escape sequences into Windows Console Attributes

    terminal_escape = re.compile('(\001?\033\\[[0-9;]+m\002?)')
    escape_parts = re.compile('\001?\033\\[([0-9;]+)m\002?')
    escape_to_color = { '0;30': 0x0,             #black
                        '0;31': 0x4,             #red
                        '0;32': 0x2,             #green
                        '0;33': 0x4+0x2,         #brown?
                        '0;34': 0x1,             #blue
                        '0;35': 0x1+0x4,         #purple
                        '0;36': 0x2+0x4,         #cyan
                        '0;37': 0x1+0x2+0x4,     #grey
                        '1;30': 0x1+0x2+0x4,     #dark gray
                        '1;31': 0x4+0x8,         #red
                        '1;32': 0x2+0x8,         #light green
                        '1;33': 0x4+0x2+0x8,     #yellow
                        '1;34': 0x1+0x8,         #light blue
                        '1;35': 0x1+0x4+0x8,     #light purple
                        '1;36': 0x1+0x2+0x8,     #light cyan
                        '1;37': 0x1+0x2+0x4+0x8, #white
                        '0': None,
                       }

    # This pattern should match all characters that change the cursor position differently
    # than a normal character.
    motion_char_re = re.compile('([\n\r\t\010\007])')

    def write_scrolling(self, text, attr=None):
        '''write text at current cursor position while watching for scrolling.

        If the window scrolls because you are at the bottom of the screen
        buffer, all positions that you are storing will be shifted by the
        scroll amount. For example, I remember the cursor position of the
        prompt so that I can redraw the line but if the window scrolls,
        the remembered position is off.

        This variant of write tries to keep track of the cursor position
        so that it will know when the screen buffer is scrolled. It
        returns the number of lines that the buffer scrolled.

        '''
        text = ensure_unicode(text)
        x, y = self.pos()
        w, h = self.size()
        scroll = 0 # the result
        # split the string into ordinary characters and funny characters
        chunks = self.motion_char_re.split(text)
        for chunk in chunks:
            n = self.write_color(chunk, attr)
            if len(chunk) == 1: # the funny characters will be alone
                if chunk[0] == '\n': # newline
                    x = 0
                    y += 1
                elif chunk[0] == '\r': # carriage return
                    x = 0
                elif chunk[0] == '\t': # tab
                    x = 8 * (int(x / 8) + 1)
                    if x > w: # newline
                        x -= w
                        y += 1
                elif chunk[0] == '\007': # bell
                    pass
                elif chunk[0] == '\010':
                    x -= 1
                    if x < 0:
                        y -= 1 # backed up 1 line
                else: # ordinary character
                    x += 1
                if x == w: # wrap
                    x = 0
                    y += 1
                if y == h: # scroll
                    scroll += 1
                    y = h - 1
            else: # chunk of ordinary characters
                x += n
                l = int(x / w) # lines we advanced
                x = x % w # new x value
                y += l
                if y >= h: # scroll
                    scroll += y - h + 1
                    y = h - 1
        return scroll

    def write_color(self, text, attr=None):
        text = ensure_unicode(text)
        n, res= self.ansiwriter.write_color(text, attr)
        junk = DWORD(0)
        for attr,chunk in res:
            log("console.attr:%s"%(attr))
            log("console.chunk:%s"%(chunk))
            self.SetConsoleTextAttribute(self.hout, attr.winattr)
            for short_chunk in split_block(chunk):
                self.WriteConsoleW(self.hout, short_chunk, 
                                   len(short_chunk), byref(junk), None)
        return n

    def write_plain(self, text, attr=None):
        '''write text at current cursor position.'''
        text = ensure_unicode(text)
        log('write("%s", %s)' %(text, attr))
        if attr is None:
            attr = self.attr
        junk = DWORD(0)
        self.SetConsoleTextAttribute(self.hout, attr)
        for short_chunk in split_block(chunk):
            self.WriteConsoleW(self.hout, ensure_unicode(short_chunk), 
                               len(short_chunk), byref(junk), None)
        return len(text)

    #This function must be used to ensure functioning with EMACS
    #Emacs sets the EMACS environment variable
    if "EMACS" in os.environ:
        def write_color(self, text, attr=None):
            text = ensure_str(text)
            junk = DWORD(0)
            self.WriteFile(self.hout, text, len(text), byref(junk), None)
            return len(text)
        write_plain = write_color

    # make this class look like a file object
    def write(self, text):
        text = ensure_unicode(text)
        log('write("%s")' % text)
        return self.write_color(text)

    #write = write_scrolling

    def isatty(self):
        return True

    def flush(self):
        pass

    def page(self, attr=None, fill=' '):
        '''Fill the entire screen.'''
        if attr is None:
            attr = self.attr
        if len(fill) != 1:
            raise ValueError
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
            self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))

        w = info.dwSize.X
        n = DWORD(0)
        for y in range(info.dwSize.Y):
            self.FillConsoleOutputAttribute(self.hout, attr, 
                                            w, self.fixcoord(0, y), byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), 
                                             w, self.fixcoord(0, y), byref(n))

        self.attr = attr

    def text(self, x, y, text, attr=None):
        '''Write text at the given position.'''
        if attr is None:
            attr = self.attr

        pos = self.fixcoord(x, y)
        n = DWORD(0)
        self.WriteConsoleOutputCharacterW(self.hout, text, 
                                          len(text), pos, byref(n))
        self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))

    def clear_to_end_of_window(self):
        top, bot = self._get_top_bot()
        pos = self.pos()
        w, h = self.size()
        self.rectangle( (pos[0], pos[1], w, pos[1] + 1))
        if pos[1] < bot:
            self.rectangle((0, pos[1] + 1, w, bot + 1))

    def rectangle(self, rect, attr=None, fill=' '):
        '''Fill Rectangle.'''
        x0, y0, x1, y1 = rect
        n = DWORD(0)
        if attr is None:
            attr = self.attr
        for y in range(y0, y1):
            pos = self.fixcoord(x0, y)
            self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0, 
                                            pos, byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), x1 - x0,
                                             pos, byref(n))

    def scroll(self, rect, dx, dy, attr=None, fill=' '):
        '''Scroll a rectangle.'''
        if attr is None:
            attr = self.attr
        x0, y0, x1, y1 = rect
        source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
        dest = self.fixcoord(x0 + dx, y0 + dy)
        style = CHAR_INFO()
        style.Char.AsciiChar = ensure_str(fill[0])
        style.Attributes = attr

        return self.ScrollConsoleScreenBufferW(self.hout, byref(source), 
                                          byref(source), dest, byref(style))

    def scroll_window(self, lines):
        '''Scroll the window by the indicated number of lines.'''
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        log('sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
        top = rect.Top + lines
        bot = rect.Bottom + lines
        h = bot - top
        maxbot = info.dwSize.Y-1
        if top < 0:
            top = 0
            bot = h
        if bot > maxbot:
            bot = maxbot
            top = bot - h

        nrect = SMALL_RECT()
        nrect.Top = top
        nrect.Bottom = bot
        nrect.Left = rect.Left
        nrect.Right = rect.Right
        log('sn: top=%d bot=%d' % (top, bot))
        r=self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
        log('r=%d' % r)

    def get(self):
        '''Get next event from queue.'''
        inputHookFunc = c_void_p.from_address(self.inputHookPtr).value

        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            if inputHookFunc:
                call_function(inputHookFunc, ())
            status = self.ReadConsoleInputW(self.hin, 
                                        byref(Cevent), 1, byref(count))
            if status and count.value == 1:
                e = event(self, Cevent)
                return e

    def getkeypress(self):
        '''Return next key press event from the queue, ignoring others.'''
        while 1:
            e = self.get()
            if e.type == 'KeyPress' and e.keycode not in key_modifiers:
                log("console.getkeypress %s"%e)
                if e.keyinfo.keyname == 'next':
                    self.scroll_window(12)
                elif e.keyinfo.keyname == 'prior':
                    self.scroll_window(-12)
                else:
                    return e
            elif ((e.type == 'KeyRelease') and 
                  (e.keyinfo == KeyPress('S', False, True, False, 'S'))):
                log("getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type))
                return e
            
                
    def getchar(self):
        '''Get next character from queue.'''

        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            status = self.ReadConsoleInputW(self.hin, 
                                            byref(Cevent), 1, byref(count))
            if (status and 
                (count.value == 1) and 
                (Cevent.EventType == 1) and
                Cevent.Event.KeyEvent.bKeyDown):
                sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
                if len(sym) == 0:
                    sym = Cevent.Event.KeyEvent.uChar.AsciiChar
                return sym

    def peek(self):
        '''Check event queue.'''
        Cevent = INPUT_RECORD()
        count = DWORD(0)
        status = self.PeekConsoleInputW(self.hin, 
                                byref(Cevent), 1, byref(count))
        if status and count == 1:
            return event(self, Cevent)

    def title(self, txt=None):
        '''Set/get title.'''
        if txt:
            self.SetConsoleTitleW(txt)
        else:
            buffer = create_unicode_buffer(200)
            n = self.GetConsoleTitleW(buffer, 200)
            if n > 0:
                return buffer.value[:n]

    def size(self, width=None, height=None):
        '''Set/get window size.'''
        info = CONSOLE_SCREEN_BUFFER_INFO()
        status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if not status:
            return None
        if width is not None and height is not None:
            wmin = info.srWindow.Right - info.srWindow.Left + 1
            hmin = info.srWindow.Bottom - info.srWindow.Top + 1
            #print wmin, hmin
            width = max(width, wmin)
            height = max(height, hmin)
            #print width, height
            self.SetConsoleScreenBufferSize(self.hout, 
                                            self.fixcoord(width, height))
        else:
            return (info.dwSize.X, info.dwSize.Y)

    def cursor(self, visible=None, size=None):
        '''Set cursor on or off.'''
        info = CONSOLE_CURSOR_INFO()
        if self.GetConsoleCursorInfo(self.hout, byref(info)):
            if visible is not None:
                info.bVisible = visible
            if size is not None:
                info.dwSize = size
            self.SetConsoleCursorInfo(self.hout, byref(info))

    def bell(self):
        self.write('\007')

    def next_serial(self):
        '''Get next event serial number.'''
        self.serial += 1
        return self.serial
Example #7
0
class Console(object):
    def __init__(self, newbuffer=0):
        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)
        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 15)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)
        background = self.attr & 240
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background

        log('initial attr=%x' % self.attr)
        self.softspace = 0
        self.serial = 0
        self.pythondll = CDLL('python%s%s' % (sys.version[0], sys.version[2]))
        self.pythondll.PyMem_Malloc.restype = c_size_t
        self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
        self.inputHookPtr = c_void_p.from_address(
            addressof(self.pythondll.PyOS_InputHook)).value
        setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
        return

    def __del__(self):
        self.SetConsoleTextAttribute(self.hout, self.saveattr)
        self.SetConsoleMode(self.hin, self.inmode)
        self.FreeConsole()

    def _get_top_bot(self):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        top = rect.Top
        bot = rect.Bottom
        return (top, bot)

    def fixcoord(self, x, y):
        if x < 0 or y < 0:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            if x < 0:
                x = info.srWindow.Right - x
                y = info.srWindow.Bottom + y
        return c_int(y << 16 | x)

    def pos(self, x=None, y=None):
        if x is None:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
        return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y))
        return

    def home(self):
        self.pos(0, 0)

    terminal_escape = re.compile('(\x01?\x1b\\[[0-9;]+m\x02?)')
    escape_parts = re.compile('\x01?\x1b\\[([0-9;]+)m\x02?')
    escape_to_color = {
        '0;30': 0,
        '0;31': 4,
        '0;32': 2,
        '0;33': 6,
        '0;34': 1,
        '0;35': 5,
        '0;36': 6,
        '0;37': 7,
        '1;30': 7,
        '1;31': 12,
        '1;32': 10,
        '1;33': 14,
        '1;34': 9,
        '1;35': 13,
        '1;36': 11,
        '1;37': 15,
        '0': None
    }
    motion_char_re = re.compile('([\n\r\t\x08\x07])')

    def write_scrolling(self, text, attr=None):
        x, y = self.pos()
        w, h = self.size()
        scroll = 0
        chunks = self.motion_char_re.split(text)
        for chunk in chunks:
            n = self.write_color(chunk, attr)
            if len(chunk) == 1:
                if chunk[0] == '\n':
                    x = 0
                    y += 1
                else:
                    if chunk[0] == '\r':
                        x = 0
                    elif chunk[0] == '\t':
                        x = 8 * (int(x / 8) + 1)
                        if x > w:
                            x -= w
                            y += 1
                    elif chunk[0] == '\x07':
                        pass
                    elif chunk[0] == '\x08':
                        x -= 1
                        if x < 0:
                            y -= 1
                    else:
                        x += 1
                    if x == w:
                        x = 0
                        y += 1
                if y == h:
                    scroll += 1
                    y = h - 1
            else:
                x += n
                l = int(x / w)
                x = x % w
                y += l
                if y >= h:
                    scroll += y - h + 1
                    y = h - 1

        return scroll

    def write_color(self, text, attr=None):
        text = ensure_unicode(text)
        n, res = self.ansiwriter.write_color(text, attr)
        junk = DWORD(0)
        for attr, chunk in res:
            log('console.attr:%s' % unicode(attr))
            log('console.chunk:%s' % unicode(chunk))
            self.SetConsoleTextAttribute(self.hout, attr.winattr)
            for short_chunk in split_block(chunk):
                self.WriteConsoleW(self.hout, short_chunk, len(short_chunk),
                                   byref(junk), None)

        return n

    def write_plain(self, text, attr=None):
        text = ensure_unicode(text)
        log('write("%s", %s)' % (text, attr))
        if attr is None:
            attr = self.attr
        junk = DWORD(0)
        self.SetConsoleTextAttribute(self.hout, attr)
        for short_chunk in split_block(chunk):
            self.WriteConsoleW(self.hout, ensure_unicode(short_chunk),
                               len(short_chunk), byref(junk), None)

        return len(text)

    if os.environ.has_key('EMACS'):

        def write_color(self, text, attr=None):
            text = ensure_str(text)
            junk = DWORD(0)
            self.WriteFile(self.hout, text, len(text), byref(junk), None)
            return len(text)

        write_plain = write_color

    def write(self, text):
        text = ensure_unicode(text)
        log('write("%s")' % text)
        return self.write_color(text)

    def isatty(self):
        return True

    def flush(self):
        pass

    def page(self, attr=None, fill=' '):
        if attr is None:
            attr = self.attr
        if len(fill) != 1:
            raise ValueError
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
            self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))
        w = info.dwSize.X
        n = DWORD(0)
        for y in range(info.dwSize.Y):
            self.FillConsoleOutputAttribute(self.hout, attr, w,
                                            self.fixcoord(0, y), byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), w,
                                             self.fixcoord(0, y), byref(n))

        self.attr = attr
        return

    def text(self, x, y, text, attr=None):
        if attr is None:
            attr = self.attr
        pos = self.fixcoord(x, y)
        n = DWORD(0)
        self.WriteConsoleOutputCharacterW(self.hout, text, len(text), pos,
                                          byref(n))
        self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))
        return

    def clear_to_end_of_window(self):
        top, bot = self._get_top_bot()
        pos = self.pos()
        w, h = self.size()
        self.rectangle((pos[0], pos[1], w, pos[1] + 1))
        if pos[1] < bot:
            self.rectangle((0, pos[1] + 1, w, bot + 1))

    def rectangle(self, rect, attr=None, fill=' '):
        x0, y0, x1, y1 = rect
        n = DWORD(0)
        if attr is None:
            attr = self.attr
        for y in range(y0, y1):
            pos = self.fixcoord(x0, y)
            self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0, pos,
                                            byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), x1 - x0,
                                             pos, byref(n))

        return

    def scroll(self, rect, dx, dy, attr=None, fill=' '):
        if attr is None:
            attr = self.attr
        x0, y0, x1, y1 = rect
        source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
        dest = self.fixcoord(x0 + dx, y0 + dy)
        style = CHAR_INFO()
        style.Char.AsciiChar = ensure_str(fill[0])
        style.Attributes = attr
        return self.ScrollConsoleScreenBufferW(self.hout, byref(source),
                                               byref(source), dest,
                                               byref(style))

    def scroll_window(self, lines):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        log('sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
        top = rect.Top + lines
        bot = rect.Bottom + lines
        h = bot - top
        maxbot = info.dwSize.Y - 1
        if top < 0:
            top = 0
            bot = h
        if bot > maxbot:
            bot = maxbot
            top = bot - h
        nrect = SMALL_RECT()
        nrect.Top = top
        nrect.Bottom = bot
        nrect.Left = rect.Left
        nrect.Right = rect.Right
        log('sn: top=%d bot=%d' % (top, bot))
        r = self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
        log('r=%d' % r)

    def get(self):
        inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            if inputHookFunc:
                call_function(inputHookFunc, ())
            status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1,
                                            byref(count))
            if status and count.value == 1:
                e = event(self, Cevent)
                return e

    def getkeypress(self):
        while 1:
            e = self.get()
            if e.type == 'KeyPress' and e.keycode not in key_modifiers:
                log('console.getkeypress %s' % e)
                if e.keyinfo.keyname == 'next':
                    self.scroll_window(12)
                elif e.keyinfo.keyname == 'prior':
                    self.scroll_window(-12)
                else:
                    return e
            elif e.type == 'KeyRelease' and e.keyinfo == KeyPress(
                    'S', False, True, False, 'S'):
                log('getKeypress:%s,%s,%s' % (e.keyinfo, e.keycode, e.type))
                return e

    def getchar(self):
        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1,
                                            byref(count))
            if status and count.value == 1 and Cevent.EventType == 1 and Cevent.Event.KeyEvent.bKeyDown:
                sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
                if len(sym) == 0:
                    sym = Cevent.Event.KeyEvent.uChar.AsciiChar
                return sym

    def peek(self):
        Cevent = INPUT_RECORD()
        count = DWORD(0)
        status = self.PeekConsoleInputW(self.hin, byref(Cevent), 1,
                                        byref(count))
        if status and count == 1:
            return event(self, Cevent)

    def title(self, txt=None):
        if txt:
            self.SetConsoleTitleW(txt)
        else:
            buffer = create_unicode_buffer(200)
            n = self.GetConsoleTitleW(buffer, 200)
            if n > 0:
                return buffer.value[:n]

    def size(self, width=None, height=None):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if not status:
            return
        if width is not None and height is not None:
            wmin = info.srWindow.Right - info.srWindow.Left + 1
            hmin = info.srWindow.Bottom - info.srWindow.Top + 1
            width = max(width, wmin)
            height = max(height, hmin)
            self.SetConsoleScreenBufferSize(self.hout,
                                            self.fixcoord(width, height))
        else:
            return (info.dwSize.X, info.dwSize.Y)
        return

    def cursor(self, visible=None, size=None):
        info = CONSOLE_CURSOR_INFO()
        if self.GetConsoleCursorInfo(self.hout, byref(info)):
            if visible is not None:
                info.bVisible = visible
            if size is not None:
                info.dwSize = size
            self.SetConsoleCursorInfo(self.hout, byref(info))
        return

    def bell(self):
        self.write('\x07')

    def next_serial(self):
        self.serial += 1
        return self.serial
Example #8
0
    def __init__(self, newbuffer=0):
        '''Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        '''
        #Do I need the following line? It causes a console to be created whenever
        #readline is imported into a pythonw application which seems wrong. Things
        #seem to work without it...
        #self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None)
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xf)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes  # remember the initial colors
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)

        background = self.attr & 0xf0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log('initial attr=%x' % self.attr)
        self.softspace = 0  # this is for using it as a file-like object
        self.serial = 0
        #
        try:
            IMP = sys._mercurial[0]
        except AttributeError:
            IMP = sys._git[0]

        # print('\n\n\npython%s%s' % (sys.version[0], sys.version[2]), "\n\n", IMP)
        if IMP.lower() == "pypy":
            if sys.winver > "3":
                nameLib = "libpypy3-c"
            else:
                nameLib = "libpypy-c"

            self.pythondll = CDLL(nameLib)
        else:
            self.pythondll = ctypes.pythonapi

        if IMP.lower() == "pypy":
            self.inputHookPtr = None
            # print("Falta resolver la vinculación con 'PyOS_InputHook'")
            # setattr(Console, 'PyMem_Malloc', self.pythondll.PyPyMem_Malloc)

            # print("PYPY it´s runing!!!\n\n\n")
            if sys.winver > "3":
                self.pythondll.PyPyMem_Malloc.restype = c_size_t
                self.pythondll.PyPyMem_Malloc.argtypes = [c_size_t]
        elif sys.version_info[:2] > (3, 4):  # Common Python3.4++
            self.pythondll.PyMem_RawMalloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]

            self.inputHookPtr = \
                c_void_p.from_address(addressof(self.pythondll.PyOS_InputHook)).value
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_RawMalloc)
        else:  # Common Python3.4--
            self.pythondll.PyMem_Malloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]

            self.inputHookPtr = \
                c_void_p.from_address(addressof(self.pythondll.PyOS_InputHook)).value
            setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
Example #9
0
class Console(object):
    """Console driver for Windows."""

    def __init__(self, newbuffer=0):
        """Initialize the Console object.

        newbuffer=1 will allocate a new buffer so the old content will be restored
        on exit.
        """
        # Do I need the following line? It causes a console to be created whenever
        # readline is imported into a pythonw application which seems wrong. Things
        # seem to work without it...
        # self.AllocConsole()

        if newbuffer:
            self.hout = self.CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE, 0, None, 1, None
            )
            self.SetConsoleActiveScreenBuffer(self.hout)
        else:
            self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)

        self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
        self.inmode = DWORD(0)
        self.GetConsoleMode(self.hin, byref(self.inmode))
        self.SetConsoleMode(self.hin, 0xF)
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        self.attr = info.wAttributes
        self.saveattr = info.wAttributes  # remember the initial colors
        self.defaultstate = AnsiState()
        self.defaultstate.winattr = info.wAttributes
        self.ansiwriter = AnsiWriter(self.defaultstate)

        background = self.attr & 0xF0
        for escape in self.escape_to_color:
            if self.escape_to_color[escape] is not None:
                self.escape_to_color[escape] |= background
        log("initial attr=%x" % self.attr)
        self.softspace = 0  # this is for using it as a file-like object
        self.serial = 0

        self.pythondll = ctypes.pythonapi
        self.inputHookPtr = c_void_p.from_address(
            addressof(self.pythondll.PyOS_InputHook)
        ).value

        if sys.version_info[:2] > (3, 4):
            self.pythondll.PyMem_RawMalloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_RawMalloc)
        else:
            self.pythondll.PyMem_Malloc.restype = c_size_t
            self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
            setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_Malloc)

    def __del__(self):
        """Cleanup the console when finished."""
        # I don't think this ever gets called
        self.SetConsoleTextAttribute(self.hout, self.saveattr)
        self.SetConsoleMode(self.hin, self.inmode)
        self.FreeConsole()

    def _get_top_bot(self):
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        top = rect.Top
        bot = rect.Bottom
        return top, bot

    def fixcoord(self, x, y):
        """Return a long with x and y packed inside,
        also handle negative x and y."""
        if x < 0 or y < 0:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            if x < 0:
                x = info.srWindow.Right - x
                y = info.srWindow.Bottom + y

        # this is a hack! ctypes won't pass structures but COORD is
        # just like a long, so this works.
        return c_int(y << 16 | x)

    def pos(self, x=None, y=None):
        """Move or query the window cursor."""
        if x is None:
            info = CONSOLE_SCREEN_BUFFER_INFO()
            self.GetConsoleScreenBufferInfo(self.hout, byref(info))
            return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
        else:
            return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y))

    def home(self):
        """Move to home."""
        self.pos(0, 0)

    # Map ANSI color escape sequences into Windows Console Attributes

    terminal_escape = re.compile("(\001?\033\\[[0-9;]+m\002?)")
    escape_parts = re.compile("\001?\033\\[([0-9;]+)m\002?")
    escape_to_color = {
        "0;30": 0x0,  # black
        "0;31": 0x4,  # red
        "0;32": 0x2,  # green
        "0;33": 0x4 + 0x2,  # brown?
        "0;34": 0x1,  # blue
        "0;35": 0x1 + 0x4,  # purple
        "0;36": 0x2 + 0x4,  # cyan
        "0;37": 0x1 + 0x2 + 0x4,  # grey
        "1;30": 0x1 + 0x2 + 0x4,  # dark gray
        "1;31": 0x4 + 0x8,  # red
        "1;32": 0x2 + 0x8,  # light green
        "1;33": 0x4 + 0x2 + 0x8,  # yellow
        "1;34": 0x1 + 0x8,  # light blue
        "1;35": 0x1 + 0x4 + 0x8,  # light purple
        "1;36": 0x1 + 0x2 + 0x8,  # light cyan
        "1;37": 0x1 + 0x2 + 0x4 + 0x8,  # white
        "0": None,
    }

    # This pattern should match all characters that change the cursor position differently
    # than a normal character.
    motion_char_re = re.compile("([\n\r\t\010\007])")

    def write_scrolling(self, text, attr=None):
        """write text at current cursor position while watching for scrolling.

        If the window scrolls because you are at the bottom of the screen
        buffer, all positions that you are storing will be shifted by the
        scroll amount. For example, I remember the cursor position of the
        prompt so that I can redraw the line but if the window scrolls,
        the remembered position is off.

        This variant of write tries to keep track of the cursor position
        so that it will know when the screen buffer is scrolled. It
        returns the number of lines that the buffer scrolled.

        """
        text = ensure_unicode(text)
        x, y = self.pos()
        w, h = self.size()
        scroll = 0  # the result
        # split the string into ordinary characters and funny characters
        chunks = self.motion_char_re.split(text)
        for chunk in chunks:
            n = self.write_color(chunk, attr)
            if len(chunk) == 1:  # the funny characters will be alone
                if chunk[0] == "\n":  # newline
                    x = 0
                    y += 1
                elif chunk[0] == "\r":  # carriage return
                    x = 0
                elif chunk[0] == "\t":  # tab
                    x = 8 * (int(x / 8) + 1)
                    if x > w:  # newline
                        x -= w
                        y += 1
                elif chunk[0] == "\007":  # bell
                    pass
                elif chunk[0] == "\010":
                    x -= 1
                    if x < 0:
                        y -= 1  # backed up 1 line
                else:  # ordinary character
                    x += 1
                if x == w:  # wrap
                    x = 0
                    y += 1
                if y == h:  # scroll
                    scroll += 1
                    y = h - 1
            else:  # chunk of ordinary characters
                x += n
                l = int(x / w)  # lines we advanced
                x = x % w  # new x value
                y += l
                if y >= h:  # scroll
                    scroll += y - h + 1
                    y = h - 1
        return scroll

    def write_color(self, text, attr=None):
        text = ensure_unicode(text)
        n, res = self.ansiwriter.write_color(text, attr)
        junk = DWORD(0)
        for attr, chunk in res:
            log("console.attr:%s" % (attr))
            log("console.chunk:%s" % (chunk))
            self.SetConsoleTextAttribute(self.hout, attr.winattr)
            for short_chunk in split_block(chunk):
                self.WriteConsoleW(
                    self.hout, short_chunk, len(short_chunk), byref(junk), None
                )
        return n

    def write_plain(self, text, attr=None):
        """Write text at current cursor position."""
        text = ensure_unicode(text)
        log('write("%s", %s)' % (text, attr))
        if attr is None:
            attr = self.attr
        junk = DWORD(0)
        self.SetConsoleTextAttribute(self.hout, attr)
        for short_chunk in split_block(chunk):
            self.WriteConsoleW(
                self.hout,
                ensure_unicode(short_chunk),
                len(short_chunk),
                byref(junk),
                None,
            )
        return len(text)

    # This function must be used to ensure functioning with EMACS
    # Emacs sets the EMACS environment variable
    if "EMACS" in os.environ:

        def write_color(self, text, attr=None):
            text = ensure_str(text)
            junk = DWORD(0)
            self.WriteFile(self.hout, text, len(text), byref(junk), None)
            return len(text)

        write_plain = write_color

    # make this class look like a file object
    def write(self, text):
        text = ensure_unicode(text)
        log('write("%s")' % text)
        return self.write_color(text)

    # write = write_scrolling

    def isatty(self):
        return True

    def flush(self):
        pass

    def page(self, attr=None, fill=" "):
        """Fill the entire screen."""
        if attr is None:
            attr = self.attr
        if len(fill) != 1:
            raise ValueError
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
            self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))

        w = info.dwSize.X
        n = DWORD(0)
        for y in range(info.dwSize.Y):
            self.FillConsoleOutputAttribute(
                self.hout, attr, w, self.fixcoord(0, y), byref(n)
            )
            self.FillConsoleOutputCharacterW(
                self.hout, ord(fill[0]), w, self.fixcoord(0, y), byref(n)
            )

        self.attr = attr

    def text(self, x, y, text, attr=None):
        """Write text at the given position."""
        if attr is None:
            attr = self.attr

        pos = self.fixcoord(x, y)
        n = DWORD(0)
        self.WriteConsoleOutputCharacterW(
            self.hout, text, len(text), pos, byref(n))
        self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))

    def clear_to_end_of_window(self):
        top, bot = self._get_top_bot()
        pos = self.pos()
        w, h = self.size()
        self.rectangle((pos[0], pos[1], w, pos[1] + 1))
        if pos[1] < bot:
            self.rectangle((0, pos[1] + 1, w, bot + 1))

    def rectangle(self, rect, attr=None, fill=" "):
        """Fill Rectangle."""
        x0, y0, x1, y1 = rect
        n = DWORD(0)
        if attr is None:
            attr = self.attr
        for y in range(y0, y1):
            pos = self.fixcoord(x0, y)
            self.FillConsoleOutputAttribute(
                self.hout, attr, x1 - x0, pos, byref(n))
            self.FillConsoleOutputCharacterW(
                self.hout, ord(fill[0]), x1 - x0, pos, byref(n)
            )

    def scroll(self, rect, dx, dy, attr=None, fill=" "):
        """Scroll a rectangle."""
        if attr is None:
            attr = self.attr
        x0, y0, x1, y1 = rect
        source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
        dest = self.fixcoord(x0 + dx, y0 + dy)
        style = CHAR_INFO()
        style.Char.AsciiChar = ensure_str(fill[0])
        style.Attributes = attr

        return self.ScrollConsoleScreenBufferW(
            self.hout, byref(source), byref(source), dest, byref(style)
        )

    def scroll_window(self, lines):
        """Scroll the window by the indicated number of lines."""
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        rect = info.srWindow
        log("sw: rtop=%d rbot=%d" % (rect.Top, rect.Bottom))
        top = rect.Top + lines
        bot = rect.Bottom + lines
        h = bot - top
        maxbot = info.dwSize.Y - 1
        if top < 0:
            top = 0
            bot = h
        if bot > maxbot:
            bot = maxbot
            top = bot - h

        nrect = SMALL_RECT()
        nrect.Top = top
        nrect.Bottom = bot
        nrect.Left = rect.Left
        nrect.Right = rect.Right
        log("sn: top=%d bot=%d" % (top, bot))
        r = self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
        log("r=%d" % r)

    def get(self):
        """Get next event from queue."""
        inputHookFunc = c_void_p.from_address(self.inputHookPtr).value

        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            if inputHookFunc:
                call_function(inputHookFunc, ())
            status = self.ReadConsoleInputW(
                self.hin, byref(Cevent), 1, byref(count))
            if status and count.value == 1:
                e = event(self, Cevent)
                return e

    def getkeypress(self):
        """Return next key press event from the queue, ignoring others."""
        while 1:
            e = self.get()
            if e.type == "KeyPress" and e.keycode not in key_modifiers:
                log("console.getkeypress %s" % e)
                if e.keyinfo.keyname == "next":
                    self.scroll_window(12)
                elif e.keyinfo.keyname == "prior":
                    self.scroll_window(-12)
                else:
                    return e
            elif (e.type == "KeyRelease") and (
                e.keyinfo == KeyPress("S", False, True, False, "S")
            ):
                log("getKeypress:%s,%s,%s" % (e.keyinfo, e.keycode, e.type))
                return e

    def getchar(self):
        """Get next character from queue."""

        Cevent = INPUT_RECORD()
        count = DWORD(0)
        while 1:
            status = self.ReadConsoleInputW(
                self.hin, byref(Cevent), 1, byref(count))
            if (
                status
                and (count.value == 1)
                and (Cevent.EventType == 1)
                and Cevent.Event.KeyEvent.bKeyDown
            ):
                sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
                if len(sym) == 0:
                    sym = Cevent.Event.KeyEvent.uChar.AsciiChar
                return sym

    def peek(self):
        """Check event queue."""
        Cevent = INPUT_RECORD()
        count = DWORD(0)
        status = self.PeekConsoleInputW(
            self.hin, byref(Cevent), 1, byref(count))
        if status and count == 1:
            return event(self, Cevent)

    def title(self, txt=None):
        """Set/get title."""
        if txt:
            self.SetConsoleTitleW(txt)
        else:
            buffer = create_unicode_buffer(200)
            n = self.GetConsoleTitleW(buffer, 200)
            if n > 0:
                return buffer.value[:n]

    def size(self, width=None, height=None):
        """Set/get window size."""
        info = CONSOLE_SCREEN_BUFFER_INFO()
        status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if not status:
            return None
        if width is not None and height is not None:
            wmin = info.srWindow.Right - info.srWindow.Left + 1
            hmin = info.srWindow.Bottom - info.srWindow.Top + 1
            # print wmin, hmin
            width = max(width, wmin)
            height = max(height, hmin)
            # print width, height
            self.SetConsoleScreenBufferSize(
                self.hout, self.fixcoord(width, height))
        else:
            return (info.dwSize.X, info.dwSize.Y)

    def cursor(self, visible=None, size=None):
        """Set cursor on or off."""
        info = CONSOLE_CURSOR_INFO()
        if self.GetConsoleCursorInfo(self.hout, byref(info)):
            if visible is not None:
                info.bVisible = visible
            if size is not None:
                info.dwSize = size
            self.SetConsoleCursorInfo(self.hout, byref(info))

    def bell(self):
        self.write("\007")

    def next_serial(self):
        """Get next event serial number."""
        self.serial += 1
        return self.serial