Ejemplo n.º 1
0
def get(cap, *args, **kwargs):
    default = kwargs.pop('default', '')

    if 'PWNLIB_NOTERM' in os.environ:
        return ''

    # Hack for readthedocs.org
    if 'READTHEDOCS' in os.environ:
        return ''

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if cache == None:
        init()
    s = cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ''
                else:
                    s = bool(s)
        cache[cap] = s
    # if `s' is not set `curses.tparm' will throw an error if given arguments
    if args and s:
        return curses.tparm(s, *args)
    else:
        return s
Ejemplo n.º 2
0
def get(cap, *args, **kwargs):
    default = kwargs.pop('default', '')

    if 'PWNLIB_NOTERM' in os.environ:
        return ''

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if cache == None:
        init()
    s = cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ''
                else:
                    s = bool(s)
        cache[cap] = s
    # if `s' is not set `curses.tparm' will throw an error if given arguments
    if args and s:
        return curses.tparm(s, *args)
    else:
        return s
Ejemplo n.º 3
0
def get(cap, *args, **kwargs):
    default = kwargs.pop('default', '')

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if cache == None:
        init()
    s = cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ''
                else:
                    s = bool(s)
        cache[cap] = s
    if args:
        return curses.tparm(s, *args)
    else:
        return s
Ejemplo n.º 4
0
def get(cap, *args, **kwargs):
    default = kwargs.pop('default', '')

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if cache == None:
        init()
    s = cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ''
                else:
                    s = bool(s)
        cache[cap] = s
    if args:
        return curses.tparm(s, *args)
    else:
        return s
Ejemplo n.º 5
0
def statusline_bs(text, reverse=False, xpos=None, ypos=None):
  ''' Return a byte string to update the status line.
  '''
  from curses import tigetstr, tparm, tigetflag  # pylint: disable=import-outside-toplevel
  setupterm()
  if tigetflag('hs'):
    seq = (
        tigetstr('tsl'),
        tigetstr('dsl'),
        tigetstr('rev') if reverse else b'',
        text.encode(),
        tigetstr('fsl'),
    )
  else:
    # save cursor position, position, reverse, restore position
    if xpos is None:
      xpos = 0
    if ypos is None:
      ypos = 0
    seq = (
        tigetstr('sc'),  # save cursor position
        tparm(tigetstr("cup"), xpos, ypos),
        tigetstr('rev') if reverse else b'',
        text.encode(),
        tigetstr('el'),
        tigetstr('rc')
    )
  return b''.join(seq)
Ejemplo n.º 6
0
def get(cap, *args, **kwargs):
    default = kwargs.pop('default', b'')

    if 'PWNLIB_NOTERM' in os.environ:
        return default

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if cache is None:
        init()

    s = cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s is None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    s = default
                else:
                    s = bool(s)
        cache[cap] = s

    # if `s' is not set `curses.tparm' will throw an error if given arguments
    if args and s:
        return curses.tparm(s, *args)
    else:
        return s
Ejemplo n.º 7
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except:
            pass
        curses.start_color()
        curses.use_default_colors()

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs') # has_status_line
        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Ejemplo n.º 8
0
    def __init__(self, term_stream=sys.stdout):
        """
        Create a `TerminalController` and initialize its attributes
        with appropriate values for the current terminal.
        `term_stream` is the stream that will be used for terminal
        output; if this stream is not a tty, then the terminal is
        assumed to be a dumb terminal (i.e., have no capabilities).
        """
        # Curses isn't available on all platforms
        self.__valid = True
        try:
            import curses
        except:
            self.__valid = False
            return

        # If the stream isn't a tty, then assume it has no capabilities.
        if not term_stream.isatty():
            self.__valid = False
            return

        # Check the terminal type.  If we fail, then assume that the
        # terminal has no capabilities.
        try:
            curses.setupterm()
        except:
            self.__valid = False
            return

        # Look up numeric capabilities.
        self.COLS = curses.tigetnum('cols')
        self.LINES = curses.tigetnum('lines')
        self.XN = curses.tigetflag('xenl')

        # Look up string capabilities.
        for capability in self._STRING_CAPABILITIES:
            (attrib, cap_name) = capability.split('=')
            setattr(self, attrib, self._tigetstr(cap_name) or '')

        # Colors
        set_fg = self._tigetstr('setf')
        if set_fg:
            for i, color in zip(range(len(self._COLORS)), self._COLORS):
                setattr(self, color, self._tparm(set_fg, i))
        set_fg_ansi = self._tigetstr('setaf')
        if set_fg_ansi:
            for i, color in zip(range(len(self._ANSICOLORS)),
                                self._ANSICOLORS):
                setattr(self, color, self._tparm(set_fg_ansi, i))
        set_bg = self._tigetstr('setb')
        if set_bg:
            for i, color in zip(range(len(self._COLORS)), self._COLORS):
                setattr(self, 'BG_' + color, self._tparm(set_bg, i))
        set_bg_ansi = self._tigetstr('setab')
        if set_bg_ansi:
            for i, color in zip(range(len(self._ANSICOLORS)),
                                self._ANSICOLORS):
                setattr(self, 'BG_' + color, self._tparm(set_bg_ansi, i))
Ejemplo n.º 9
0
def get_flag(name: str, default: bool = False) -> bool:
    """
    get as a flag
    :return:
    """
    ret = curses.tigetflag(name)
    if ret == -1:
        raise TermInfoWrongType(name, bool)

    if ret == 0:
        return default
    return ret
Ejemplo n.º 10
0
    def __init__(self, term_stream=sys.stdout):
        """
        Create a `TerminalController` and initialize its attributes
        with appropriate values for the current terminal.
        `term_stream` is the stream that will be used for terminal
        output; if this stream is not a tty, then the terminal is
        assumed to be a dumb terminal (i.e., have no capabilities).
        """
        # Curses isn't available on all platforms
        try: import curses
        except: return

        # If the stream isn't a tty, then assume it has no capabilities.
        if not term_stream.isatty(): return

        # Check the terminal type.  If we fail, then assume that the
        # terminal has no capabilities.
        try: curses.setupterm()
        except: return

        # We want unicode output and have unicode input.
        reload(sys)
        sys.setdefaultencoding('utf8')

        # Look up numeric capabilities.
        self.COLS = curses.tigetnum('cols')
        self.LINES = curses.tigetnum('lines')
        self.XN = curses.tigetflag('xenl')
        
        # Look up string capabilities.
        for capability in self._STRING_CAPABILITIES:
            (attrib, cap_name) = capability.split('=')
            setattr(self, attrib, self._tigetstr(cap_name) or '')

        # Colors
        set_fg = self._tigetstr('setf')
        if set_fg:
            for i,color in zip(range(len(self._COLORS)), self._COLORS):
                setattr(self, color, self._tparm(set_fg, i))
        set_fg_ansi = self._tigetstr('setaf')
        if set_fg_ansi:
            for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS):
                setattr(self, color, self._tparm(set_fg_ansi, i))
        set_bg = self._tigetstr('setb')
        if set_bg:
            for i,color in zip(range(len(self._COLORS)), self._COLORS):
                setattr(self, 'BG_'+color, self._tparm(set_bg, i))
        set_bg_ansi = self._tigetstr('setab')
        if set_bg_ansi:
            for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS):
                setattr(self, 'BG_'+color, self._tparm(set_bg_ansi, i))
Ejemplo n.º 11
0
    def set_meta_caps(self):
        for cap in meta_caps:
            param = ''

            if cap['type'] == 'str':
                param = tigetstr(cap['cap']) or ''

            elif cap['type'] == 'int':
                param = tigetnum(cap['cap']) or ''

            elif cap['type'] == 'bool':
                param = tigetflag(cap['cap']) or ''

            setattr(self, cap['name'], param)
Ejemplo n.º 12
0
    def set_meta_caps(self):
        for cap in meta_caps:
            param = ''

            if cap['type'] == 'str':
                param = tigetstr(cap['cap']) or ''

            elif cap['type'] == 'int':
                param = tigetnum(cap['cap']) or ''

            elif cap['type'] == 'bool':
                param = tigetflag(cap['cap']) or ''

            setattr(self, cap['name'], param)
Ejemplo n.º 13
0
def status(msg, *args, **kwargs):
  ''' Write a message to the terminal's status line.

      Parameters:
      * `msg`: message string
      * `args`: if not empty, the message is %-formatted with `args`
      * `file`: optional keyword argument specifying the output file.
        Default: `sys.stderr`.

      Hack: if there is no status line use the xterm title bar sequence :-(
  '''
  if args:
    msg = msg % args
  f = kwargs.pop('file', None)
  if kwargs:
    raise ValueError("unexpected keyword arguments: %r" % (kwargs,))
  if f is None:
    f = sys.stderr
  try:
    has_ansi_status = f.has_ansi_status
  except AttributeError:
    try:
      import curses  # pylint: disable=import-outside-toplevel
    except ImportError:
      has_ansi_status = None
    else:
      curses.setupterm()
      has_status = curses.tigetflag('hs')
      if has_status == -1:
        warning(
            'status: curses.tigetflag(hs): not a Boolean capability, presuming false'
        )
        has_ansi_status = None
      elif has_status > 0:
        has_ansi_status = (
            curses.tigetstr('to_status_line'),
            curses.tigetstr('from_status_line')
        )
      else:
        warning('status: hs=%s, presuming false', has_status)
        has_ansi_status = None
    f.has_ansi_status = has_ansi_status
  if has_ansi_status:
    msg = has_ansi_status[0] + msg + has_ansi_status[1]
  else:
    msg = '\033]0;' + msg + '\007'
  f.write(msg)
  f.flush()
Ejemplo n.º 14
0
Archivo: ui.py Proyecto: sit0/ranger
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except curses.error:
            pass
        curses.start_color()
        try:
            curses.use_default_colors()
        except curses.error:
            pass

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        self.settings.signal_bind('setopt.freeze_files', self.redraw_statusbar)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs')  # has_status_line

            # Save tmux setting `automatic-rename`
            if self.settings.update_tmux_title and 'TMUX' in os.environ:
                try:
                    self._tmux_automatic_rename = check_output([
                        'tmux', 'show-window-options', '-v', 'automatic-rename'
                    ]).strip()
                except CalledProcessError:
                    self._tmux_automatic_rename = None

        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title and 'TMUX' in os.environ:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()

        if 'vcsthread' in self.__dict__:
            self.vcsthread.unpause()
Ejemplo n.º 15
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except curses.error:
            pass
        curses.start_color()
        try:
            curses.use_default_colors()
        except curses.error:
            pass

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        self.settings.signal_bind('setopt.freeze_files', self.redraw_statusbar)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs')  # has_status_line

            # Save tmux setting `automatic-rename`
            if self.settings.update_tmux_title and 'TMUX' in os.environ:
                try:
                    self._tmux_automatic_rename = check_output(
                        ['tmux', 'show-window-options', '-v', 'automatic-rename']).strip()
                except CalledProcessError:
                    self._tmux_automatic_rename = None

        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title and 'TMUX' in os.environ:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()

        if 'vcsthread' in self.__dict__:
            self.vcsthread.unpause()
Ejemplo n.º 16
0
def get(cap, *args, **kwargs):
    """
    Get a terminal capability exposes through the `curses` module.
    """
    # Hack for readthedocs.org
    if "READTHEDOCS" in os.environ:
        return ""

    if _win_compat != None:
        ret = _win_compat.get(cap).get(args)
        return ret

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if _cache == {}:
        # Fix for BPython
        try:
            curses.setupterm()
        except:
            pass

    s = _cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ""
                else:
                    s = bool(s)
        _cache[cap] = s

    # if 's' is not set 'curses.tparm' will throw an error if given arguments
    if args and s:
        r = curses.tparm(s, *args)
        return r.decode("utf-8")
    else:
        if isinstance(s, bytes):
            return s.decode("utf-8")
        else:
            return s
Ejemplo n.º 17
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except curses.error:
            pass
        curses.start_color()
        try:
            curses.use_default_colors()
        except curses.error:
            pass

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        self.settings.signal_bind('setopt.freeze_files', self.redraw_statusbar)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs')  # has_status_line

        self.update_size()
        self.is_on = True

        self.handle_multiplexer()

        if 'vcsthread' in self.__dict__:
            self.vcsthread.unpause()
Ejemplo n.º 18
0
#
Ejemplo n.º 19
0
 def getflag(self, capname):
     self[capname] = curses.tigetflag(capname)
     if self[capname] is None:
         raise RuntimeError(
             'This terminal is not capable of doing ' + capname)
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
 def flag(self, name):
     return curses.tigetflag(name) > 0
Ejemplo n.º 22
0
#