Exemplo n.º 1
0
def cursesMain(initwin):
    global stdscr
    stdscr = initwin
    (maxy, maxx) = stdscr.getmaxyx()

    # necessary for init_pair()
    curses.use_default_colors()

    try:
        # returns 256, 32767 on MacOS
        stdscr.addstr(0, 0, '')
        stdscr.addstr('curses.COLORS: %d\n' % curses.COLORS)
        stdscr.addstr('curses.COLOR_PAIRS: %d\n' % curses.COLOR_PAIRS)
        # initially pair 0 is (fg,bg)=(7,0) or white-on-black
        # all others are (0,0) or black-on-black
        for i in range(16):
            (fg, bg) = curses.pair_content(i)
            stdscr.addstr('pair %d has (fg,bg)=(%d,%d)\n' % (i, fg, bg))

        for i in range(curses.COLORS):
            curses.init_pair(i + 1, i, -1)
            stdscr.addch(curses.ACS_CKBOARD, curses.color_pair(i + 1))

#		for i in range(10):
#			stdscr.addstr('X', curses.color_pair(i))

        stdscr.refresh()
        stdscr.getch()
    except curses.error as e:
        print e
Exemplo n.º 2
0
    def start(self):
        '''
        _orig_ESCDELAY = ''
        try:
            _orig_ESCDELAY = os.environ['ESCDELAY']
        except KeyError:
            pass
        os.environ['ESCDELAY'] = str(0)  # Stop escape key from pausing game
        '''
        self.screen = curses.initscr()
        self.has_colors = curses.has_colors()
        if self.has_colors:
            curses.start_color()
        curses.noecho()  # Don't display kb-input
        curses.cbreak(
        )  # Send characters immediately to getch() instead of storing them in buffer.
        curses.nonl()  # Allow to detect Enter-key press
        self.screen.keypad(True)  # Allow curses.KEY_LEFT/KEY_RIGHT/... keys
        self.hide_cursor()  # Hide cursor
        self.set_keyboard_delay(0)  # By default don't block keyboard
        self.screen_height, self.screen_width = self.screen.getmaxyx()
        # init color attrs
        default_attr = curses.color_pair(0)
        default_pair = curses.pair_number(default_attr)
        self.fore_color, self.back_color = curses.pair_content(default_pair)

        self.color_attrs = dict(
        )  # dict{ (fg_color, bg_color) -> curses attr }
        self.color_attrs[(self.fore_color, self.back_color)] = default_attr
        self.next_color_pair = 1
Exemplo n.º 3
0
def colorstr_from_attr(attr):
    colorpair = curses.pair_number(attr)
    fg, bg = curses.pair_content(colorpair)
    r = f'{fg} on {bg}'
    if attr & curses.A_BOLD: r += ' bold'
    if attr & curses.A_UNDERLINE: r += ' underline'
    return r
Exemplo n.º 4
0
def main():
    stdscr = curses.initscr()   # MANDATORY!
    curses.start_color()        # MANDATORY!
    curses.use_default_colors() # optional.

    stdscr.addstr("can_change_color(): " + str(curses.can_change_color()) + '\n')
    stdscr.addstr("COLOR_PAIRS: " + str(curses.COLOR_PAIRS) + '\n\n')

    ####################################

    stdscr.addstr("color 67 before:\n")
    curses.init_pair(20, 67, 0)
    stdscr.addstr(str(curses.color_content(67)) + '\n', curses.color_pair(20))

    stdscr.addstr("color 67 after:\n")
    curses.init_color(67, 0, 255, 0)
    curses.init_pair(21, 67, 0)
    stdscr.addstr(str(curses.color_content(67)) + '\n\n', curses.color_pair(21))

    ####################################

    stdscr.addstr("color 101 before:\n")
    curses.init_pair(22, 101, 0)
    stdscr.addstr(str(curses.color_content(101)) + '\n', curses.color_pair(22))

    stdscr.addstr("color 101 after:\n")
    curses.init_color(101, 128, 128, 128)
    curses.init_pair(23, 101, 0)
    stdscr.addstr(str(curses.color_content(101)) + '\n\n', curses.color_pair(23))

    ####################################

    stdscr.addstr("pair 40 before:\n")
    stdscr.addstr(str(curses.pair_content(40)) + '\n', curses.color_pair(40))

    stdscr.addstr("pair 40 after:\n")
    curses.init_pair(40, 101, 67)
    stdscr.addstr(str(curses.pair_content(40)) + '\n\n', curses.color_pair(40))

    stdscr.getch()

    curses.endwin()     # optional, but recommended.
Exemplo n.º 5
0
 def _regrouppairs(self):
     """Goes through all the color pairs currently defined, and if two
     tokens have the same color, they are reassigned to the same color pair.
     
     When you change colors... they won't be exactly right, but it frees up 
     pairs."""
     madepairs = {}
     for (token, colpair) in list(self._tokentocolorpair.items()):
         fg,bg = curses.pair_content(colpair)
         if (fg,bg) in madepairs:
             self._tokentocolorpair[token] = madepairs[(fg,bg)]
         else:
             madepairs[(fg,bg)] = colpair
Exemplo n.º 6
0
def curse_attr(*args):
    color = 0
    attr = 0
    for arg in set(args):
        if type(arg) is int:
            color = arg
        elif arg == 'light':
            color += 8
        elif f'COLOR_{arg.upper()}' in dir(curses):
            color += getattr(curses, f'COLOR_{arg.upper()}') + 1
        elif f'A_{arg.upper()}' in dir(curses):
            attr |= getattr(curses, f'A_{arg.upper()}')
        else:
            raise ValueError(f'Could not interpret {arg} as curses attribute.')
    if curses.pair_content(color) == (0, 0):
        curses.init_pair(color, color - 1, -1)
    return attr | curses.color_pair(color)
Exemplo n.º 7
0
def create_color_pair(session, window, color_set_name, color_set) -> int:
    '''
    Create a new curses color pair, store its associated name in session.
    Receives color_set dict of fg/bg color names or curses color numbers.

    Return color pair number.
    '''
    i = len(session['colors'])

    # In case color_set does not define fg or bg, send current color set
    # to be merged over the missing values.
    current = curses.pair_content(curses.pair_number(window.getbkgd() & \
                                                     curses.A_COLOR))
    fg = color_set.get('fg', None)
    bg = color_set.get('bg', None)
    set_color_pair(i, fg, bg, merge_with=current)

    session['colors'][color_set_name] = i
    return i
Exemplo n.º 8
0
def __leaf_08(ql: Qiling):
    stdscr = ql.os.stdscr

    if stdscr is None:
        ql.reg.ax = 0x0720
    else:
        cy, cx = stdscr.getyx()
        inch = stdscr.inch(cy, cx)
        attr = inch & curses.A_COLOR
        ch = inch & 0xFF
        ql.reg.al = ch
        pair_number = curses.pair_number(attr)

        fg, bg = curses.pair_content(pair_number)
        orig_fg = REVERSE_COLORS_MAPPING[fg]
        orig_bg = REVERSE_COLORS_MAPPING[bg]

        if attr & curses.A_BLINK:
            orig_bg |= 0b1000

        ql.reg.ah = ((orig_bg << 4) & orig_fg)
Exemplo n.º 9
0
 def current_fg(self):
     colorpair = curses.pair_number(colors.get(self.current_color))
     fg, bg = curses.pair_content(colorpair)
     return f'{fg}'
Exemplo n.º 10
0
 def _findColor(self,color1,color2):
     for i in range(1,curses.COLOR_PAIRS):
         f,b=curses.pair_content(i)
         if f==color1 and b==color2:
             return i
     return -1
Exemplo n.º 11
0
def module_funcs(stdscr):
    "Test module-level functions"

    for func in [curses.baudrate, curses.beep, curses.can_change_color,
                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
                 curses.filter, curses.flash, curses.flushinp,
                 curses.has_colors, curses.has_ic, curses.has_il,
                 curses.isendwin, curses.killchar, curses.longname,
                 curses.nocbreak, curses.noecho, curses.nonl,
                 curses.noqiflush, curses.noraw,
                 curses.reset_prog_mode, curses.termattrs,
                 curses.termname, curses.erasechar, curses.getsyx]:
        func()

    # Functions that actually need arguments
    if curses.tigetstr("cnorm"):
        curses.curs_set(1)
    curses.delay_output(1)
    curses.echo() ; curses.echo(1)

    f = tempfile.TemporaryFile()
    stdscr.putwin(f)
    f.seek(0)
    curses.getwin(f)
    f.close()

    curses.halfdelay(1)
    curses.intrflush(1)
    curses.meta(1)
    curses.napms(100)
    curses.newpad(50,50)
    win = curses.newwin(5,5)
    win = curses.newwin(5,5, 1,1)
    curses.nl() ; curses.nl(1)
    curses.putp('abc')
    curses.qiflush()
    curses.raw() ; curses.raw(1)
    curses.setsyx(5,5)
    curses.tigetflag('hc')
    curses.tigetnum('co')
    curses.tigetstr('cr')
    curses.tparm('cr')
    curses.typeahead(sys.__stdin__.fileno())
    curses.unctrl('a')
    curses.ungetch('a')
    curses.use_env(1)

    # Functions only available on a few platforms
    if curses.has_colors():
        curses.start_color()
        curses.init_pair(2, 1,1)
        curses.color_content(1)
        curses.color_pair(2)
        curses.pair_content(curses.COLOR_PAIRS - 1)
        curses.pair_number(0)

        if hasattr(curses, 'use_default_colors'):
            curses.use_default_colors()

    if hasattr(curses, 'keyname'):
        curses.keyname(13)

    if hasattr(curses, 'has_key'):
        curses.has_key(13)

    if hasattr(curses, 'getmouse'):
        (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
        # availmask indicates that mouse stuff not available.
        if availmask != 0:
            curses.mouseinterval(10)
            # just verify these don't cause errors
            m = curses.getmouse()
            curses.ungetmouse(*m)
Exemplo n.º 12
0
Arquivo: dos.py Projeto: yzz127/qiling
 def int10(self):
     # BIOS video support
     # https://en.wikipedia.org/wiki/INT_10H
     # https://stanislavs.org/helppc/idx_interrupt.html
     # implemented by curses
     ah = self.ql.reg.ah
     al = self.ql.reg.al
     if ah==0:
         # time to set up curses
         # copied from curses.wrapper
         self.stdscr = curses.initscr()
         curses.noecho()
         curses.cbreak()
         self.stdscr.keypad(1)
         try:
             curses.start_color()
         except:
             pass
         if al == 0 or al == 1:
             curses.resizeterm(25, 40)
         elif al == 2 or al == 3:
             curses.resizeterm(25, 80)
         elif al == 4 or al == 5 or al == 9 or al == 0xD or al == 0x13:
             curses.resizeterm(200, 320)
         elif al == 6:
             curses.resizeterm(200, 640)
         elif al == 8:
             curses.resizeterm(200, 160)
         elif al == 0xA or al == 0xE:
             curses.resizeterm(200, 640)
         elif al == 0xF:
             curses.resizeterm(350, 640)
         elif al == 0x10:
             curses.resizeterm(350, 640)
         elif al == 0x11 or al == 0x12:
             curses.resizeterm(480, 640)
         else:
             self.ql.nprint("Exception: int 10h syscall Not Found, al: %s" % hex(al))
             raise NotImplementedError()
         # Quoted from https://linux.die.net/man/3/resizeterm
         #
         # If ncurses is configured to supply its own SIGWINCH handler, 
         # the resizeterm function ungetch's a KEY_RESIZE which will be 
         # read on the next call to getch.
         ch = self._get_ch_non_blocking()
         if ch == curses.KEY_RESIZE:
             self.ql.nprint(f"[!] You term has been resized!")
         elif ch != -1:
             curses.ungetch(ch)
         self.stdscr.scrollok(True)
             
         if not curses.has_colors():
             self.ql.nprint(f"[!] Warning: your terminal doesn't support colors, content might not be displayed correctly.")
         
         # https://en.wikipedia.org/wiki/BIOS_color_attributes
         # blink support?
         if curses.has_colors():
             for fg in range(16):
                 for bg in range(16):
                     color_pair_index = 16*fg + bg + 1
                     if fg not in self.color_pairs:
                         self.color_pairs[fg] = {}
                     curses.init_pair(color_pair_index, COLORS_MAPPING[fg], COLORS_MAPPING[bg])
                     color_pair = curses.color_pair(color_pair_index)
                     self.color_pairs[fg][bg] = color_pair
                     self.revese_color_pairs[color_pair] = (fg, bg)
     elif ah == 1:
         # limited support
         ch = self.ql.reg.ch
         if (ch & 0x20) != 0:
             curses.curs_set(0)
     elif ah == 2:
         # page number ignored
         dh = self.ql.reg.dh # row
         dl = self.ql.reg.dl # column
         self.stdscr.move(dh, dl)
     elif ah == 5:
         # No idea how to implement, do nothing here.
         self.ql.reg.al = 0
         pass
     elif ah == 6:
         al = self.ql.reg.al # lines to scroll
         ch = self.ql.reg.ch # row of upper-left cornner
         cl = self.ql.reg.cl # column of upper-left corner
         dh = self.ql.reg.dh # row of lower right corner
         dl = self.ql.reg.dl # column of lower righ corner
         bh = self.ql.reg.bh
         fg = bh & 0xF
         bg = (bh & 0xF0) >> 4
         y, x = self.stdscr.getmaxyx()
         cy, cx = self.stdscr.getyx()
         attr = self._get_attr(fg, bg)
         if ch != 0 or cl != 0 or dh != y - 1 or dl != x - 1:
             self.ql.nprint(f"[!] Warning: Partial scroll is unsupported. Will scroll the whole page.")
             self.ql.nprint(f"[!] Resolution: {y}x{x} but asked to scroll [({ch},{cl}),({dh}, {dl})]")
         if al != 0:
             self.stdscr.scroll(al)
             ny = 0
             if cy - al < 0:
                 ny = 0
             else:
                 ny = cy - al + 1
             if al > y:
                 al = y
             for ln in range(al):
                 self.stdscr.addstr(ny + ln, 0, " "*x, attr)
             self.stdscr.move(cy, cx)
         else:
             self.stdscr.clear()
             # Alternate way?
             #for ln in range(y):
             #    self.stdscr.addstr(ln, 0, " "*x, attr)
             self.stdscr.bkgd(" ", attr)
             self.stdscr.move(0, 0)
     elif ah == 8:
         if self.stdscr is None:
             self.ql.reg.ax = 0x0720
         else:
             cy, cx = self.stdscr.getyx()
             inch = self.stdscr.inch(cy, cx)
             attr = inch & curses.A_COLOR
             ch = inch & 0xFF
             self.ql.reg.al = ch
             pair_number = curses.pair_number(attr)
             fg, bg = curses.pair_content(pair_number)
             orig_fg = REVERSE_COLORS_MAPPING[fg]
             orig_bg = REVERSE_COLORS_MAPPING[bg]
             if attr & curses.A_BLINK != 0:
                 orig_bg |= 0b1000
             self.ql.reg.ah = ((orig_bg << 4) & orig_fg)
     elif ah == 0xE:
         self.ql.dprint(0, f"Echo: {hex(al)} -> {curses.ascii.unctrl(al)}")
         y, x = self.stdscr.getmaxyx()
         cy, cx = self.stdscr.getyx()
         fg = self.ql.reg.bl
         # https://stackoverflow.com/questions/27674158/how-to-get-color-information-with-mvinch
         # https://linux.die.net/man/3/inch
         # https://github.com/mirror/ncurses/blob/master/include/curses.h.in#L1197
         # wtf curses...
         attr = self.stdscr.inch(cy, cx) & curses.A_COLOR
         if al == 0xa:
             # \n will erase current line with echochar, so we have to handle it carefully.
             self.ql.nprint(f"Resolution: {x}x{y}, Cursor position: {cx},{cy}, Going to get a new line.")
             if y-1 == cy:
                 # scroll doesn't affect our cursor
                 self.stdscr.scroll(1)
                 self.stdscr.move(cy, 0)
             else:
                 self.stdscr.move(cy+1, 0)
         else:
             self.stdscr.echochar(al, attr)
     else:
         self.ql.nprint("Exception: int 10h syscall Not Found, ah: %s" % hex(ah))
         raise NotImplementedError()
     if self.stdscr is not None:
         self.stdscr.refresh()
Exemplo n.º 13
0
    def __init__(self, colour):
        self.colour = colour

        fg_enum, bg_enum = curses.pair_content(curses.pair_number(self.colour))
        self.fg = Default_colour(fg_enum)
        self.bg = Default_colour(bg_enum)
Exemplo n.º 14
0
    def loop(self, debug: bool = False) -> None:
        """The key-handling event loop.

        This method takes care of reading the user's key strokes and triggering associated commands.

        Args:
            debug: if True, the key-event loop is not automatically started.
        """
        key = 0
        # key is the last character pressed
        while True:
            # handle possible keys
            try:
                if key in TUI.KEYDICT:
                    cmd = TUI.KEYDICT[key]
                    if cmd not in STATE.inactive_commands:
                        if isinstance(cmd, tuple):
                            TUI.COMMANDS[cmd[0]](self, cmd[1])
                        else:
                            TUI.COMMANDS[cmd](self)
                elif key == curses.KEY_RESIZE:
                    self.resize_handler(None, None)
            except StopIteration:
                LOGGER.debug("Stopping key event loop.")
                # raised by quit command
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__
                break

            # highlight current line
            current_attributes: List[Optional[int]] = []
            for x_pos in range(0, self.viewport.pad.getmaxyx()[1]):
                x_ch = self.viewport.pad.inch(STATE.current_line, x_pos)
                # store attributes by filtering out the character text
                current_attributes.append(x_ch & curses.A_CHARTEXT)
                # extract color information
                x_color = x_ch & curses.A_COLOR
                color_pair_content = curses.pair_content(
                    curses.pair_number(x_color))
                # if the current color attribute is lower in priority than the current line
                # highlighting, use that instead
                if all(col <= 0 for col in color_pair_content):
                    self.viewport.pad.chgat(
                        STATE.current_line,
                        x_pos,
                        1,
                        curses.color_pair(
                            TUI.COLOR_NAMES.index("cursor_line") + 1),
                    )
                else:
                    # otherwise, we remove the stored attributes in order to not reset them later
                    current_attributes[-1] = None

            for stream, name in zip((self.stderr, self.stdout),
                                    ("stderr", "stdout")):
                stream.flush()
                if stream.lines:
                    stream.split()
                    LOGGER.info("sys.%s contains:\n%s", name,
                                "\n".join(stream.lines))
                    # wrap before checking the height:
                    stream.wrap(self.width)
                    if stream.height > 1 and not debug:
                        stream.popup(
                            self,
                            background=TUI.COLOR_NAMES.index(f"popup_{name}"))
                    else:
                        self.prompt_print(stream.lines)
                    stream.clear()

            # Refresh the screen
            self.viewport.refresh()

            # Wait for next input
            key = self.stdscr.getch()
            LOGGER.debug("Key press registered: %s", str(key))

            # reset highlight of current line
            for x_pos in range(0, self.viewport.pad.getmaxyx()[1]):
                attr = current_attributes[x_pos]
                if attr is not None:
                    self.viewport.pad.chgat(STATE.current_line, x_pos, 1, attr)
Exemplo n.º 15
0
Arquivo: display.py Projeto: Josca/im
 def _define_style(self, i_style: int, i_fg_color: int, i_bg_color):
     self._old_pairs[i_style] = curses.pair_content(i_style)
     curses.init_pair(i_style, i_fg_color, i_bg_color)
Exemplo n.º 16
0
#
Exemplo n.º 17
0
    def _init_colour(self):
        """Allocate curses colours and "colour pairs" for user-specified colours.

    Curses manages colour in the following way: first, entries within a
    finite palette of colours (usually 255) are assigned a particular RGB value;
    next, foreground and background pairs of these colours are defined in a
    second palette of colour pairs (also finite; perhaps around 32767 entries).
    This function takes the `colour_fg` and `colour_bg` dicts supplied to the
    constructor and attempts to allocate enough colours and colour pairs to
    handle all of the colour combinations that they specify.

    If this method determines that the terminal isn't capable of accepting a
    custom colour palette, or if there turn out not to be enough colours or
    colour pairs to accommodate the user-supplied colour dicts, this method will
    simply allow the default foreground and background colour to be used.
    """
        # The default colour for all characters without colours listed is boring
        # white on black, or "system default", or somesuch.
        self._colour_pair = collections.defaultdict(lambda: 0)
        # And if the terminal doesn't support true color, that's all you get.
        if not curses.can_change_color(): return

        # Collect all unique foreground and background colours. If this terminal
        # doesn't have enough colours for all of the colours the user has supplied,
        # plus the two default colours, plus the largest colour id (which we seem
        # not to be able to assign, at least not with xterm-256color) stick with
        # boring old white on black.
        colours = set(six.itervalues(self._colour_fg)).union(
            six.itervalues(self._colour_bg))
        if (curses.COLORS - 2) < len(colours): return

        # Get all unique characters that have a foreground and/or background colour.
        # If this terminal doesn't have enough colour pairs for all characters plus
        # the default colour pair, stick with boring old white on black.
        characters = set(self._colour_fg).union(self._colour_bg)
        if (curses.COLOR_PAIRS - 1) < len(characters): return

        # Get the identifiers for both colours in the default colour pair.
        cpair_0_fg_id, cpair_0_bg_id = curses.pair_content(0)

        # With all this, make a mapping from colours to the IDs we'll use for them.
        ids = (
            set(range(curses.COLORS - 1))
            -  # The largest ID is not assignable?
            {cpair_0_fg_id, cpair_0_bg_id})  # We don't want to change these.
        ids = list(reversed(
            sorted(ids)))  # We use colour IDs from large to small.
        ids = ids[:len(colours)]  # But only those colour IDs we actually need.
        colour_ids = dict(zip(colours, ids))

        # Program these colours into curses.
        for colour, cid in six.iteritems(colour_ids):
            curses.init_color(cid, *colour)

        # Now add the default colours to the colour-to-ID map.
        cpair_0_fg = curses.color_content(cpair_0_fg_id)
        cpair_0_bg = curses.color_content(cpair_0_bg_id)
        colour_ids[cpair_0_fg] = cpair_0_fg_id
        colour_ids[cpair_0_bg] = cpair_0_bg_id

        # The color pair IDs we'll use for all characters count up from 1; note that
        # the "default" colour pair of 0 is already defined, since _colour_pair is a
        # defaultdict.
        self._colour_pair.update({
            character: pid
            for pid, character in enumerate(characters, start=1)
        })

        # Program these color pairs into curses, and that's all there is to do.
        for character, pid in six.iteritems(self._colour_pair):
            # Get foreground and background colours for this character. Note how in
            # the absence of a specified background colour, the same colour as the
            # foreground is used.
            cpair_fg = self._colour_fg.get(character, cpair_0_fg_id)
            cpair_bg = self._colour_bg.get(character, cpair_fg)
            # Get colour IDs for those colours and initialise a colour pair.
            cpair_fg_id = colour_ids[cpair_fg]
            cpair_bg_id = colour_ids[cpair_bg]
            curses.init_pair(pid, cpair_fg_id, cpair_bg_id)
Exemplo n.º 18
0
def display_info(stdscr):
    display_info_line(stdscr, "COLS: {}".format(curses.COLS))
    display_info_line(stdscr, "LINES: {}".format(curses.LINES))
    display_info_line(stdscr, "Bold", curses.color_pair(0) | curses.A_BOLD)
    display_info_line(stdscr, "Blink", curses.A_BLINK)
    display_info_line(stdscr, "Blink + Standout", curses.A_BLINK | curses.A_STANDOUT)
    display_info_line(stdscr, "Stand out", curses.A_STANDOUT)
    display_info_line(stdscr, "Dim", curses.A_DIM)
    display_info_line(stdscr, "Underline", curses.A_UNDERLINE)
    display_info_line(stdscr, "Normal", curses.A_NORMAL)
    display_info_line(stdscr, "Reverse", curses.A_REVERSE)
    display_info_line(stdscr, "Color", curses.A_COLOR)
    display_info_line(stdscr, "Chartext", curses.A_CHARTEXT)
    display_info_line(stdscr, "Low", curses.A_LOW)
    display_info_line(stdscr, "Left", curses.A_LEFT)
    display_info_line(stdscr, "Can change color pair: %s" % curses.can_change_color())
    display_info_line(stdscr, "Color pairs: %s" % curses.COLOR_PAIRS)
    display_info_line(stdscr, "# of colors: %d" % curses.COLORS)

    if curses.can_change_color():
        display_info_line(stdscr, "The terminal should show a green gradient below. If it's colorful instead, curses can't change terminal color.")
        matrix.init_colors()
        for i in range(matrix.NUMBER_OF_COLOR + 1):
            color_num = matrix.START_COLOR_NUM + i
            display_info_line(stdscr, "Pair {} {} {}".format(color_num, curses.color_content(color_num), curses.pair_content(color_num)), curses.color_pair(color_num))

    stdscr.getch()
Exemplo n.º 19
0
def display_info(stdscr):
    display_info_line(stdscr, "COLS: {}".format(curses.COLS))
    display_info_line(stdscr, "LINES: {}".format(curses.LINES))
    display_info_line(stdscr, "Bold", curses.color_pair(0) | curses.A_BOLD)
    display_info_line(stdscr, "Blink", curses.A_BLINK)
    display_info_line(stdscr, "Blink + Standout", curses.A_BLINK | curses.A_STANDOUT)
    display_info_line(stdscr, "Stand out", curses.A_STANDOUT)
    display_info_line(stdscr, "Dim", curses.A_DIM)
    display_info_line(stdscr, "Underline", curses.A_UNDERLINE)
    display_info_line(stdscr, "Normal", curses.A_NORMAL)
    display_info_line(stdscr, "Reverse", curses.A_REVERSE)
    display_info_line(stdscr, "Color", curses.A_COLOR)
    display_info_line(stdscr, "Chartext", curses.A_CHARTEXT)
    display_info_line(stdscr, "Low", curses.A_LOW)
    display_info_line(stdscr, "Left", curses.A_LEFT)
    display_info_line(stdscr, "Can change color pair: %s" % curses.can_change_color())
    display_info_line(stdscr, "Color pairs: %s" % curses.COLOR_PAIRS)
    display_info_line(stdscr, "# of colors: %d" % curses.COLORS)

    if curses.can_change_color():
        display_info_line(stdscr, "The terminal should show a green gradient below. If it's colorful instead, curses can't change terminal color.")
        matrix.init_colors()
        for i in range(matrix.NUMBER_OF_COLOR):
            color_num = matrix.START_COLOR_NUM + i
            display_info_line(stdscr, "Pair {} {} {}".format(color_num, curses.color_content(color_num), curses.pair_content(color_num)), curses.color_pair(color_num))

    stdscr.getch()
Exemplo n.º 20
0
def init_colour(color_bg, color_fg):
    """
  Based on `human_ui.CursesUi._init_colour`
  (https://github.com/deepmind/pycolab/blob/master/pycolab/human_ui.py)
  """
    curses.start_color()
    # The default colour for all characters without colours listed is boring
    # white on black, or "system default", or somesuch.
    colour_pair = collections.defaultdict(lambda: 0)
    # And if the terminal doesn't support true color, that's all you get.
    if not curses.can_change_color():
        return colour_pair

    # Collect all unique foreground and background colours. If this terminal
    # doesn't have enough colours for all of the colours the user has supplied,
    # plus the two default colours, plus the largest colour id (which we seem
    # not to be able to assign, at least not with xterm-256color) stick with
    # boring old white on black.
    colours = set(six.itervalues(color_fg)).union(six.itervalues(color_bg))
    if (curses.COLORS - 2) < len(colours):
        return colour_pair

    # Get all unique characters that have a foreground and/or background colour.
    # If this terminal doesn't have enough colour pairs for all characters plus
    # the default colour pair, stick with boring old white on black.
    characters = set(color_fg).union(color_bg)
    if (curses.COLOR_PAIRS - 1) < len(characters):
        return colour_pair

    # Get the identifiers for both colours in the default colour pair.
    cpair_0_fg_id, cpair_0_bg_id = curses.pair_content(0)

    # With all this, make a mapping from colours to the IDs we'll use for them.
    ids = set(
        range(curses.COLORS - 1)
    ) - {  # The largest ID is not assignable?
        cpair_0_fg_id,
        cpair_0_bg_id,
    }  # We don't want to change these.
    ids = list(reversed(sorted(ids)))  # We use colour IDs from large to small.
    ids = ids[:len(colours)]  # But only those colour IDs we actually need.
    colour_ids = dict(zip(colours, ids))

    # Program these colours into curses.
    for colour, cid in six.iteritems(colour_ids):
        curses.init_color(cid, *colour)

    # Now add the default colours to the colour-to-ID map.
    cpair_0_fg = curses.color_content(cpair_0_fg_id)
    cpair_0_bg = curses.color_content(cpair_0_bg_id)
    colour_ids[cpair_0_fg] = cpair_0_fg_id
    colour_ids[cpair_0_bg] = cpair_0_bg_id

    # The color pair IDs we'll use for all characters count up from 1; note that
    # the "default" colour pair of 0 is already defined, since _colour_pair is a
    # defaultdict.
    colour_pair.update(
        {character: pid
         for pid, character in enumerate(characters, start=1)})

    # Program these color pairs into curses, and that's all there is to do.
    for character, pid in six.iteritems(colour_pair):
        # Get foreground and background colours for this character. Note how in
        # the absence of a specified background colour, the same colour as the
        # foreground is used.
        cpair_fg = color_fg.get(character, cpair_0_fg_id)
        cpair_bg = color_bg.get(character, cpair_fg)
        # Get colour IDs for those colours and initialise a colour pair.
        cpair_fg_id = colour_ids[cpair_fg]
        cpair_bg_id = colour_ids[cpair_bg]
        curses.init_pair(pid, cpair_fg_id, cpair_bg_id)

    return colour_pair
Exemplo n.º 21
0
#