Python curses 模块,KEY_LEFT 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.KEY_LEFT

项目:defuse_division    作者:lelandbatey    | 项目源码 | 文件源码
def build_keymap(args):
    """
    Function build_keymap returns a dictionary from curses keys to game.Keys.
    """
    if args.vimkeys:
        return {
            ord('k'): Keys.UP,
            ord('j'): Keys.DOWN,
            ord('h'): Keys.LEFT,
            ord('l'): Keys.RIGHT,
            ord(' '): Keys.PROBE,
            ord('f'): Keys.FLAG,
        }
    return {
        curses.KEY_UP: Keys.UP,
        curses.KEY_DOWN: Keys.DOWN,
        curses.KEY_LEFT: Keys.LEFT,
        curses.KEY_RIGHT: Keys.RIGHT,
        ord('\n'): Keys.PROBE,
        ord('f'): Keys.FLAG,
    }
项目:questionnaire    作者:kylebebak    | 项目源码 | 文件源码
def one(prompt, *args, **kwargs):
    """Instantiates a picker, registers custom handlers for going back,
    and starts the picker.
    """
    indicator = '?'
    if sys.version_info < (3, 0):
        indicator = '>'
    def go_back(picker):
        return None, -1

    options, verbose_options = prepare_options(args)
    idx = kwargs.get('idx', 0)

    picker = Picker(verbose_options, title=prompt, indicator=indicator, default_index=idx)
    picker.register_custom_handler(ord('h'), go_back)
    picker.register_custom_handler(curses.KEY_LEFT, go_back)
    with stdout_redirected(sys.stderr):
        option, index = picker.start()
        if index == -1:
            raise QuestionnaireGoBack
        if kwargs.get('return_index', False):
            # `one` was called by a special client, e.g. `many`
            return index
        return options[index]
项目:cursed    作者:johannestaas    | 项目源码 | 文件源码
def update(cls):
        key = cls.getch()
        if key is not None:
            if key == curses.KEY_UP:
                cls.PAD_Y = max(cls.PAD_Y - 1, 0)
            elif key == curses.KEY_DOWN:
                cls.PAD_Y = min(
                    cls.PAD_Y + 1,
                    cls.PAD_HEIGHT - (cls.HEIGHT + 1)
                )
            elif key == curses.KEY_LEFT:
                cls.PAD_X = max(cls.PAD_X - 1, 0)
            elif key == curses.KEY_RIGHT:
                cls.PAD_X = min(
                    cls.PAD_X + 1,
                    cls.PAD_WIDTH - (cls.WIDTH + 1)
                )
            elif key == ord('q'):
                cls.trigger('quit')
        for y in range(cls.PAD_Y, cls.PAD_Y + cls.HEIGHT):
            s = cls.MAP[y][cls.PAD_X:cls.PAD_X + cls.PAD_HEIGHT]
            s = ''.join(x for x in s)
            cls.addstr(s, cls.PAD_X, y)
        cls.refresh()
项目:ascii_qgis    作者:NathanW2    | 项目源码 | 文件源码
def focus(self):
        modeline.update_activeWindow("Map")
        curses.curs_set(0)
        while True:
            event = self.mapwin.getch()
            # if event == -1:
            #     continue
            logging.info(event)
            try_handle_global_event(event)

            if event == curses.KEY_UP:
                self.pan("up")
            if event == curses.KEY_DOWN:
                self.pan("down")
            if event == curses.KEY_LEFT:
                self.pan("left")
            if event == curses.KEY_RIGHT:
                self.pan("right")
            if event == curses.KEY_NPAGE:
                self.zoom_out(5)
            if event == curses.KEY_PPAGE:
                self.zoom_in(5)
项目:Music-Scraper    作者:srivatsan-ramesh    | 项目源码 | 文件源码
def update_screen():
        """
        Updates the screen each time a key is pressed.
        """
        if not GUI.gui_stopped:
            if GUI.key == curses.KEY_DOWN:
                GUI.on_key_down()
            elif GUI.key == curses.KEY_UP:
                GUI.on_key_up()
            elif GUI.key == curses.KEY_LEFT:
                GUI.on_key_left()
            elif GUI.key == curses.KEY_RIGHT:
                GUI.on_key_right()
            if GUI.key == ord("\n") and GUI.row_num != 0:
                GUI.on_key_enter()

            GUI.box.erase()
            GUI.display_list()
            GUI.add_bottom_menus()
            GUI.screen.refresh()
            GUI.box.refresh()
项目:SnakeGame    作者:KyrosDigital    | 项目源码 | 文件源码
def __init__(self, x, y, window):
        self.body_list = []
        self.hit_score = 0
        self.timeout = TIMEOUT

        for i in range(SNAKE_LENGTH, 0, -1):
            self.body_list.append(Body(x - i, y))

        self.body_list.append(Body(x, y, '0'))
        self.window = window
        self.direction = KEY_RIGHT
        self.last_head_coor = (x, y)
        self.direction_map = {
            KEY_UP: self.move_up,
            KEY_DOWN: self.move_down,
            KEY_LEFT: self.move_left,
            KEY_RIGHT: self.move_right
        }
项目:SnakeGame    作者:KyrosDigital    | 项目源码 | 文件源码
def __init__(self, x, y, window):
        self.body_list = []
        self.hit_score = 0
        self.timeout = TIMEOUT
        #0 Append The Snake's range to the Body object for Snakes Body
        for i in range(SNAKE_LENGTH, 0, -1):
            self.body_list.append(Body(x - i, y))

        #1 Define and append the snakes head
        self.body_list.append(Body(x, y, '0'))
        #2 define the window
        self.window = window
        #3 Move snake to right when game starts
        self.direction = KEY_RIGHT
        #4 set snakes lst head coordinate
        self.last_head_coor = (x, y)
        #5 define direction map
        self.direction_map = {
            KEY_UP: self.move_up,
            KEY_DOWN: self.move_down,
            KEY_LEFT: self.move_left,
            KEY_RIGHT: self.move_right
        }
项目:SnakeGame    作者:KyrosDigital    | 项目源码 | 文件源码
def __init__(self, x, y, window):
        self.body_list = []
        self.hit_score = 0
        self.timeout = TIMEOUT

        for i in range(SNAKE_LENGTH, 0, -1):
            self.body_list.append(Body(x - i, y))

        self.body_list.append(Body(x, y, '0'))
        self.window = window
        self.direction = KEY_RIGHT
        self.last_head_coor = (x, y)
        self.direction_map = {
            KEY_UP: self.move_up,
            KEY_DOWN: self.move_down,
            KEY_LEFT: self.move_left,
            KEY_RIGHT: self.move_right
        }
项目:SnakeGame    作者:KyrosDigital    | 项目源码 | 文件源码
def __init__(self, x, y, window):
        self.body_list = []
        self.hit_score = 0
        self.timeout = TIMEOUT

        for i in range(SNAKE_LENGTH, 0, -1):
            self.body_list.append(Body(x - i, y))

        self.body_list.append(Body(x, y, '0'))
        self.window = window
        self.direction = KEY_RIGHT
        self.last_head_coor = (x, y)
        self.direction_map = {
            KEY_UP: self.move_up,
            KEY_DOWN: self.move_down,
            KEY_LEFT: self.move_left,
            KEY_RIGHT: self.move_right
        }
项目:SnakeGame    作者:KyrosDigital    | 项目源码 | 文件源码
def __init__(self, x, y, window):
        self.body_list = []
        self.hit_score = 0
        self.timeout = TIMEOUT

        for i in range(SNAKE_LENGTH, 0, -1):
            self.body_list.append(Body(x - i, y))

        self.body_list.append(Body(x, y, '0'))
        self.window = window
        self.direction = KEY_RIGHT
        self.last_head_coor = (x, y)
        self.direction_map = {
            KEY_UP: self.move_up,
            KEY_DOWN: self.move_down,
            KEY_LEFT: self.move_left,
            KEY_RIGHT: self.move_right
        }
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def put(self, char):
        pos = self._cursor.position
        cnt = len(self._text)

        if isinstance(char, str) and cnt < self._max_len and ord(char) >= 0x20:
            self._text = self._text[:pos] + char + self._text[pos:]
            self._cursor.count = len(self._text)
            self._cursor.position = pos + 1
        elif char == curses.KEY_LEFT and pos > 0:
            self._cursor.position = pos - 1
        elif char == curses.KEY_RIGHT and pos < cnt:
            self._cursor.position = pos + 1
        elif char == curses.KEY_HOME:
            self._cursor.position = 0
        elif char == curses.KEY_END:
            self._cursor.position = cnt
        elif char == curses.KEY_BACKSPACE and pos > 0:
            self._text = self._text[:pos - 1] + self._text[pos:]
            self._cursor.count = len(self._text)
            self._cursor.position = pos - 1
        elif char == curses.KEY_DC:
            self._text = self._text[:pos] + self._text[pos + 1:]
            self._cursor.count = len(self._text)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def handle_key(self, k):
        if k == ord('q'):
            self.close(None)
        elif k == ord('d'):
            self._change_date()
        elif k == ord('l'):
            self._change_level()
        elif k == ord('f'):
            self._change_facility()
        elif k == ord('h'):
            self._change_host()
        elif k == ord('p'):
            self._change_program()
        elif k == curses.KEY_NPAGE:
            self._buf.go_to_next_page()
        elif k == curses.KEY_PPAGE:
            self._buf.go_to_previous_page()
        elif k == curses.KEY_DOWN:
            self._buf.go_to_next_line()
        elif k == curses.KEY_UP:
            self._buf.go_to_previous_line()
        elif k == curses.KEY_RIGHT:
            self.scroll_right()
        elif k == curses.KEY_LEFT:
            self.scroll_left()
项目:HPCinstall    作者:NCAR    | 项目源码 | 文件源码
def _alternative_left_right(term):
    r"""
    Determine and return mapping of left and right arrow keys sequences.

    :arg blessed.Terminal term: :class:`~.Terminal` instance.
    :rtype: dict

    This function supports :func:`get_terminal_sequences` to discover
    the preferred input sequence for the left and right application keys.

    Return dict of sequences ``term._cuf1``, and ``term._cub1``,
    valued as ``KEY_RIGHT``, ``KEY_LEFT`` (when appropriate).  It is
    necessary to check the value of these sequences to ensure we do not
    use ``u' '`` and ``u'\b'`` for ``KEY_RIGHT`` and ``KEY_LEFT``,
    preferring their true application key sequence, instead.
    """
    keymap = dict()
    if term._cuf1 and term._cuf1 != u' ':
        keymap[term._cuf1] = curses.KEY_RIGHT
    if term._cub1 and term._cub1 != u'\b':
        keymap[term._cub1] = curses.KEY_LEFT
    return keymap
项目:tscrnsvr    作者:illinoisjackson    | 项目源码 | 文件源码
def main(win,args):
    SCSP = ScreenSpace(win)
    SNK = Snake(win,args)
    try:
        while True:
            SNK.render(SCSP,args)
            SCSP.render(clear=False,ref=False)
            gc = SCSP.win.getch()
            if gc in [ord("a"),curses.KEY_LEFT]:
                SNK.dir = SNK.turnleft()
            if gc in [ord("d"),curses.KEY_RIGHT]:
                SNK.dir = SNK.turnright()
            if gc == ord("q"):
                SCSP.destroy()
                sys.exit()
            SCSP.win.erase()
            time.sleep(args.delay)
    except KeyboardInterrupt:
        pass
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:getTimer    作者:maxwellgerber    | 项目源码 | 文件源码
def runDay(scr, rollover, topString, bottomString, start=None):
    if(rollover):
        if(start is None):
            day = date.today()
        else:
            day = date(start.year, start.month, start.day)
    else:
        if(start is None):
            day = datetime.date.today()
        else:
            day = datetime.date(start.year, start.month, start.day)

    c = curses.KEY_MAX
    cursor = 3
    while(c != 10):
        displayDay(scr, day, cursor, topString, bottomString)
        c = scr.getch()
        if(c == curses.KEY_RIGHT) and cursor < len(str(day))-1:
            cursor += 1
            if(cursor == 4 or cursor == 7):
                cursor += 1
        elif(c == curses.KEY_LEFT) and cursor > 0:
            cursor -= 1
            if(cursor == 4 or cursor == 7):
                cursor -= 1
        elif(c == curses.KEY_UP):
            day = alterDigitDay(cursor, day, 1)
        elif(c == curses.KEY_DOWN):
            day = alterDigitDay(cursor, day, -1)
        else:
            try:
                i = int(c) - 48
                if(i >= 0 and i < 10):
                    day = updateDigitDay(cursor, day, i)
            except ValueError:
                pass
    return datetime.date(day.year, day.month, day.day)
项目:getTimer    作者:maxwellgerber    | 项目源码 | 文件源码
def runTime(scr, rollover, topString, bottomString, start=None):
    if(rollover):
        if(start is None):
            t = time()
        else:
            t = time(start.hour, start.minute, start.second)
    else:
        if(start is None):
            t = datetime.time()
        else:
            t = datetime.time(start.hour, start.minute, start.second)

    c = curses.KEY_MAX
    cursor = 3
    while(c != 10):
        displayTime(scr, t, cursor, topString, bottomString)
        c = scr.getch()
        if(c == curses.KEY_RIGHT) and cursor < len(str(t))-1:
            cursor += 1
            if(cursor == 2 or cursor == 5):
                cursor += 1
        elif(c == curses.KEY_LEFT) and cursor > 0:
            cursor -= 1
            if(cursor == 2 or cursor == 5):
                cursor -= 1
        elif(c == curses.KEY_UP):
            t = alterDigitTime(cursor, t, 1)
        elif(c == curses.KEY_DOWN):
            t = alterDigitTime(cursor, t, -1)
        else:
            try:
                i = int(c) - 48
                if(i >= 0 and i < 10):
                    t = updateDigitTime(cursor, t, i)
            except ValueError:
                pass
    return datetime.time(t.hour, t.minute, t.second)
项目:loltanks    作者:whentze    | 项目源码 | 文件源码
def processkey(self, key, win):
    h, w = win.getmaxyx()
    if (key == ord(' ')):
      weapon = self.arsenal[self.active_weapon]
      if (weapon[1] != 0):
        self.shoot()
        if(weapon[1] != -1):
          weapon[1] = max(0, weapon[1] - 1)
        return True
      else:
        self.weapon_display_timer = 50
    elif (key == curses.KEY_LEFT):
      if self.angle <= pi/2:
        self.angle = pi - self.angle
      else:
        self.move(-1)
    elif (key == curses.KEY_RIGHT):
      if self.angle >= pi/2:
        self.angle = pi - self.angle
      else:
        self.move(1)
    elif (key == curses.KEY_UP):
      if (self.angle <= pi/2):
        self.angle = min(pi/2.001, self.angle+0.01)
      else:
        self.angle = max(pi/1.999, self.angle-0.01)
    elif (key == curses.KEY_DOWN):
      if (self.angle <= pi/2):
        self.angle = max(0, self.angle-0.01+pi/8)-pi/8
      else:
        self.angle = min(pi*9/8, self.angle+0.01)
    elif (key == ord('+')):
      self.power = min(1.00, self.power+0.01)
    elif (key == ord('-')):
      self.power = max(0.00, self.power-0.01)
    elif (key in map(lambda k : ord(str(k)), range(10))):
      n = int(chr(key))
      self.active_weapon = (n-1) % len(self.arsenal)
      self.weapon_display_timer = 50

    return False
项目:pyfeld    作者:scjurgen    | 项目源码 | 文件源码
def run_main_loop(self):
        self.draw_ui()
        while 1:
            c = self.window.getch()
            if curses.keyname(c) in [b'h', b'H']:
                self.show_help()
            elif curses.keyname(c) in [b'p', b'P']:
                self.play()
            elif curses.keyname(c) in [b'q', b'Q']:
                return None
            elif c == 27:
                self.returnString = self.dir.get_current_path()
                return self.returnString
            elif c == curses.KEY_ENTER or c == 10:
                self.returnString = self.dir.get_current_path()
                return self.returnString
            elif c == curses.KEY_UP:
                if self.selected_index > 0:
                    self.selected_index -= 1
                self.draw_ui()
            elif c == curses.KEY_DOWN:
                if self.selected_index < self.dir.max_entries_on_level()-1:
                    self.selected_index += 1
                self.draw_ui()
            elif c == curses.KEY_LEFT:
                self.leave_dir()
                self.draw_ui()
            elif c == curses.KEY_RIGHT:
                self.enter_dir()
                self.draw_ui()
            elif c == curses.KEY_RESIZE:
                self.draw_ui()
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:sciibo    作者:fdev    | 项目源码 | 文件源码
def on_key(self, ch):
        if ch == curses.KEY_LEFT:
            if self.selected > 0:
                self.selected -= 1

        elif ch == curses.KEY_RIGHT:
            if self.selected + 1 < len(self.items):
                self.selected += 1

        else:
            return False

        self.value = self.items[self.selected]
        self.update()
        return True
项目:sciibo    作者:fdev    | 项目源码 | 文件源码
def on_key(self, ch):
        x = self.pos

        # ascii 32-126 (inclusive)
        if curses.ascii.isprint(ch):
            if len(self.value) < self.max_length:
                self.value = self.value[:x] + chr(ch) + self.value[x:]
                self.pos += 1

        elif ch == curses.KEY_LEFT:
            if x > 0:
                self.pos -= 1

        elif ch == curses.KEY_RIGHT:
            if x < len(self.value):
                self.pos += 1

        elif ch == curses.KEY_BACKSPACE:
            if x > 0:
                self.value = self.value[:x - 1] + self.value[x:]
                self.pos -= 1

        elif ch == curses.KEY_DC:
            if x < len(self.value):
                self.value = self.value[:x] + self.value[x + 1:]

        elif ch == curses.KEY_HOME:
            self.pos = 0

        elif ch == curses.KEY_END:
            self.pos = len(self.value)

        else:
            return False

        self.update()
        return True
项目:sciibo    作者:fdev    | 项目源码 | 文件源码
def on_key(self, ch):
        if not self.active:
            return

        if self.selected:
            if ch in (curses.ascii.ESC, curses.KEY_BACKSPACE):
                self.cancel_selection()

            elif ch == curses.KEY_LEFT:
                if self.selection > 0 and self.selection < 4 or self.selection > 4:
                    self.set_selection(self.selection - 1)

            elif ch == curses.KEY_RIGHT:
                if self.selection < 3 or self.selection > 3 and self.selection < 7:
                    self.set_selection(self.selection + 1)

            elif ch == curses.KEY_UP:
                if self.selection > 3:
                    self.set_selection(self.selection - 4)

            elif ch == curses.KEY_DOWN:
                if self.selection < 4 and self.selected_source == 'hand':
                    self.set_selection(self.selection + 4)

            elif ch in (curses.KEY_ENTER, curses.ascii.SP):
                self.confirm_selection()

        else:
            if ch == curses.KEY_LEFT:
                if self.selection > 0:
                    self.set_selection(self.selection - 1)

            elif ch == curses.KEY_RIGHT:
                if self.selection + 1 < len(self.selectable_sources):
                    self.set_selection(self.selection + 1)

            elif ch in (curses.KEY_ENTER, curses.ascii.SP):
                self.confirm_selection()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:cursebox    作者:Tenchi2xh    | 项目源码 | 文件源码
def poll_event(self):
        """
        Checks if an event happens and returns a string related to the event.

        Returns -1 if nothing happened during self.screen.timeout milliseconds.

        If the event is a normal (letter) key press,
        the letter is returned (case sensitive)

        :return: Event type
        """
        self.mutex.acquire()
        ch = self.screen.getch()
        self.mutex.release()

        if ch == -1:
            return EVENT_SKIP
        elif ch == 27:
            return EVENT_ESC
        elif ch == curses.KEY_RESIZE:
            return EVENT_RESIZE
        elif ch == 10 or ch == curses.KEY_ENTER:
            return EVENT_ENTER
        elif ch == 127 or ch == curses.KEY_BACKSPACE:
            return EVENT_BACKSPACE
        elif ch == curses.KEY_UP:
            return EVENT_UP
        elif ch == curses.KEY_DOWN:
            return EVENT_DOWN
        elif ch == curses.KEY_LEFT:
            return EVENT_LEFT
        elif ch == curses.KEY_RIGHT:
            return EVENT_RIGHT
        elif ch == 3:
            return EVENT_CTRL_C
        elif ch == 409:
            return EVENT_CLICK
        elif 0 <= ch < 256:
            return chr(ch)
        else:
            return EVENT_UNHANDLED
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_move_cursor_left(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put(curses.KEY_LEFT)
        self.assertEqual(0, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_move_cursor_right(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put(curses.KEY_LEFT)
        input.put(curses.KEY_RIGHT)
        self.assertEqual(1, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_not_move_cursor_before_left_boundary(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put(curses.KEY_LEFT)
        input.put(curses.KEY_LEFT)
        self.assertEqual(0, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_put_char_at_beginning(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put(curses.KEY_LEFT)
        input.put('b')
        self.assertEqual('ba', input.text)
        self.assertEqual(1, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_put_backspace_before_end(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put('b')
        input.put(curses.KEY_LEFT)
        input.put(curses.KEY_BACKSPACE)
        self.assertEqual('b', input.text)
        self.assertEqual(0, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_delete_char_at_cursor(self):
        input = TextInput(max_len=10)
        input.put('a')
        input.put('b')
        input.put(curses.KEY_LEFT)
        input.put(curses.KEY_LEFT)
        input.put(curses.KEY_DC)
        self.assertEqual('b', input.text)
        self.assertEqual(0, input.cursor)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def test_should_handle_key_left(self):
        self._parent_window.getmaxyx.return_value = (9, 30)

        win = Datetime(self._manager, 'Date', datetime.datetime.utcnow())
        win.handle_key(curses.KEY_RIGHT)
        win.handle_key(curses.KEY_LEFT)
        win.refresh()

        self._child_window.chgat.assert_called_once_with(2, 2, 4, 0)
项目:logviewer    作者:romuloceccon    | 项目源码 | 文件源码
def handle_key(self, k):
        if k == ord('\n'):
            self.close(True)
        elif k == 27:
            if self._parent.getch() == -1:
                self.close(False)
        elif k == curses.KEY_RIGHT:
            self._datetime_state.move_right()
        elif k == curses.KEY_LEFT:
            self._datetime_state.move_left()
        elif k == curses.KEY_UP:
            self._datetime_state.increment()
        elif k == curses.KEY_DOWN:
            self._datetime_state.decrement()
项目:pygram    作者:RedXBeard    | 项目源码 | 文件源码
def h_scroll_line_up(self, ch):
        if ch == curses.KEY_LEFT:# and self.cursor_line:
            self.h_show_beginning(ch)
            super().h_scroll_line_up(ch)
        else:
            super().h_scroll_line_up(ch)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        noecho()
        cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            echo()
            nocbreak()
            endwin()
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:pysk    作者:ph1l    | 项目源码 | 文件源码
def command(self, char):
        """handle additional page specific commands"""
        if char == curses.KEY_LEFT or char == ord('h'):
            return ('VESSEL_BROWSER', None)
        return (None, None)
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def _create_pocket(self):
        pocket_name = ""
        while True:
            self.screen.clear()

            self._draw_tab_bar()

            self.screen.addstr(2, 2, "Pocket name:")

            self.screen.addstr(4, 4, pocket_name)

            c = self.screen.getch()
            if c == 27:
                self._status = "Cancelled"
                break
            elif c == curses.KEY_ENTER or c == 10 or c == 13:
                ec = await api.Pocket.create(self._ws, pocket_name)
                if ec:
                    self._status = ec.name
                else:
                    self._status = "Created"
                break
            elif c == curses.KEY_BACKSPACE:
                pocket_name = pocket_name[:-1]
            elif c == curses.KEY_LEFT or c == curses.KEY_RIGHT:
                pass
            else:
                pocket_name += chr(c)
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def _enter_password_tab2(self):
        password = ""
        while True:
            self.screen.clear()
            self._draw_tab_bar()
            self.screen.addstr(2, 2, "Password:")
            self.screen.addstr(4, 2, "*" * len(password))
            c = self.screen.getch()
            if c == curses.KEY_BACKSPACE:
                password = password[:-1]
            elif c == curses.KEY_ENTER or c == 10 or c == 13:
                return password
            elif c == curses.KEY_LEFT:
                self._current_tab -= 1
                if self._current_tab < 0:
                    self._current_tab = len(self._account_names) - 1
                await self._activate_account()
                return None
            elif c == curses.KEY_RIGHT:
                self._current_tab += 1
                if self._current_tab >= len(self._account_names):
                    self._current_tab = 0
                await self._activate_account()
                return None
            else:
                password += chr(c)
项目:HPCinstall    作者:NCAR    | 项目源码 | 文件源码
def name(self):
        """String-name of key sequence, such as ``u'KEY_LEFT'`` (str)."""
        return self._name
项目:HPCinstall    作者:NCAR    | 项目源码 | 文件源码
def get_curses_keycodes():
    """
    Return mapping of curses key-names paired by their keycode integer value.

    :rtype: dict

    Returns dictionary of (name, code) pairs for curses keyboard constant
    values and their mnemonic name. Such as code ``260``, with the value of
    its key-name identity, ``u'KEY_LEFT'``.
    """
    _keynames = [attr for attr in dir(curses)
                 if attr.startswith('KEY_')]
    return dict(
        [(keyname, getattr(curses, keyname))
         for keyname in _keynames])
项目:HPCinstall    作者:NCAR    | 项目源码 | 文件源码
def get_keyboard_codes():
    """
    Return mapping of keycode integer values paired by their curses key-name.

    :rtype: dict

    Returns dictionary of (code, name) pairs for curses keyboard constant
    values and their mnemonic name. Such as key ``260``, with the value of
    its identity, ``u'KEY_LEFT'``.  These are derived from the attributes by
    the same of the curses module, with the following exceptions:

    * ``KEY_DELETE`` in place of ``KEY_DC``
    * ``KEY_INSERT`` in place of ``KEY_IC``
    * ``KEY_PGUP`` in place of ``KEY_PPAGE``
    * ``KEY_PGDOWN`` in place of ``KEY_NPAGE``
    * ``KEY_ESCAPE`` in place of ``KEY_EXIT``
    * ``KEY_SUP`` in place of ``KEY_SR``
    * ``KEY_SDOWN`` in place of ``KEY_SF``

    This function is the inverse of :func:`get_curses_keycodes`.  With the
    given override "mixins" listed above, the keycode for the delete key will
    map to our imaginary ``KEY_DELETE`` mnemonic, effectively erasing the
    phrase ``KEY_DC`` from our code vocabulary for anyone that wishes to use
    the return value to determine the key-name by keycode.
    """
    keycodes = OrderedDict(get_curses_keycodes())
    keycodes.update(CURSES_KEYCODE_OVERRIDE_MIXIN)

    # invert dictionary (key, values) => (values, key), preferring the
    # last-most inserted value ('KEY_DELETE' over 'KEY_DC').
    return dict(zip(keycodes.values(), keycodes.keys()))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        noecho()
        cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            echo()
            nocbreak()
            endwin()
项目:soyouhaveanidea    作者:yigitbey    | 项目源码 | 文件源码
def display(self):
        self.window.clear()
        self.showdetail()

        while True:
            self.has_focus = True
            self.next_window.has_focus = False

            self.window.refresh()
            curses.doupdate()

            self.update()

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                return self.position

            if key == curses.KEY_UP:
                if self.position == 0:
                    self.navigate(self.last_item_index)
                else:
                    self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

            elif key == curses.KEY_RIGHT or key == curses.KEY_LEFT:
                self.has_focus = False
                self.update()
                self.next_window.display()
项目:soyouhaveanidea    作者:yigitbey    | 项目源码 | 文件源码
def display(self):
        self.window.clear()
        self.showdetail()

        while True:
            self.has_focus = True
            self.next_window.has_focus = False
            self.window.refresh()
            curses.doupdate()

            self.update()

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                self.action()
                return

            if key == curses.KEY_UP:
                if self.position == 0:
                    self.navigate(self.last_item_index)
                else:
                    self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

            elif key == curses.KEY_RIGHT or key == curses.KEY_LEFT:
                self.has_focus = False
                self.update()
                return


# TODO: scrolling this
项目:functest    作者:opnfv    | 项目源码 | 文件源码
def main():
    environ["TERM"] = 'Eterm'
    initscr()
    curs_set(0)
    try:
        win = newwin(16, 60, 0, 0)
        win.keypad(True)
        win.nodelay(True)
        win.border('|', '|', '-', '-', '+', '+', '+', '+')
        win.addch(4, 44, '@')
        win.addstr(0, 5, ' Eat all the OPNFV bugs by FunTest! ')
        win.addstr(15, 7, ' Left,Right,Up,Down: move; other keys: quit ')
        snake = [[20, 7], [19, 7], [18, 7], [17, 7],
                 [16, 7], [15, 7], [14, 7], [13, 7]]
        key = KEY_RIGHT
        body = '~FUNTEST'
        ind = 0
        while key != 27:
            win.addstr(0, 44, ' Score: ' + str(len(snake) - len(body)) + ' ')
            win.timeout(140 - 2 * len(snake))
            getkey = win.getch()
            key = key if getkey == -1 else getkey
            snake.insert(
                0, [snake[0][0] + (key == KEY_RIGHT and 1 or
                                   key == KEY_LEFT and -1),
                    snake[0][1] + (key == KEY_DOWN and 1 or
                                   key == KEY_UP and -1)])
            win.addch(snake[len(snake) - 1][1], snake[len(snake) - 1][0], ' ')
            if win.inch(snake[0][1], snake[0][0]) & 255 == 32:
                snake.pop()
            elif win.inch(snake[0][1], snake[0][0]) & 255 == ord('@'):
                c = [n for n in [[randrange(1, 58, 1), randrange(1, 14, 1)]
                     for x in range(len(snake))] if n not in snake]
                win.addch(c == [] and 4 or c[0][1],
                          c == [] and 44 or c[0][0], '@')
            else:
                break
            ind += 1
            win.addch(snake[0][1], snake[0][0], body[ind % len(body)])
    finally:
        endwin()

    print('\nSnake.PY-26ines by Kris Cieslak (defaultset.blogspot.com).')
    print('OPNFV adaptation by Functest dream team.')
    score = str(len(snake) - len(body) - 1)
    print ('Thanks for playing, your score: %s.' % score)
    print('Find and fix more bugs in your real OPNFV setup!\n')
项目:notex    作者:adiultra    | 项目源码 | 文件源码
def keys_init(self):
        """Define methods for each key.

        """
        self.keys = {
            curses.KEY_BACKSPACE:           self.backspace,
            CTRL('h'):                      self.backspace,
            curses.ascii.BS:                self.backspace,
            curses.ascii.DEL:               self.backspace,
            curses.ascii.ETX:               self.close,
            curses.KEY_DC:                  self.del_char,
            CTRL('d'):                      self.del_char,
            CTRL('u'):                      self.del_to_bol,
            CTRL('k'):                      self.del_to_eol,
            curses.KEY_DOWN:                self.down,
            CTRL('n'):                      self.down,
            curses.KEY_END:                 self.end,
            CTRL('e'):                      self.end,
            curses.KEY_F1:                  self.help,
            curses.KEY_HOME:                self.home,
            CTRL('a'):                      self.home,
            curses.KEY_ENTER:               self.insert_line_or_quit,
            curses.ascii.NL:                self.insert_line_or_quit,
            curses.ascii.LF:                self.insert_line_or_quit,
            "\n":                           self.insert_line_or_quit,
            curses.KEY_LEFT:                self.left,
            CTRL('b'):                      self.left,
            curses.KEY_NPAGE:               self.page_down,
            curses.KEY_PPAGE:               self.page_up,
            CTRL('v'):                      self.paste,
            CTRL('x'):                      self.quit,
            curses.KEY_F2:                  self.quit,
            curses.KEY_F3:                  self.quit_nosave,
            curses.ascii.ESC:               self.quit_nosave,
            curses.KEY_RESIZE:              self.resize,
            -1:                             self.resize,
            curses.KEY_RIGHT:               self.right,
            CTRL('f'):                      self.right,
            curses.KEY_UP:                  self.up,
            CTRL('p'):                      self.up,
        }
项目:getTimer    作者:maxwellgerber    | 项目源码 | 文件源码
def runDateTime(scr, rollover, topString, bottomString, start=None):
    if(rollover):
        if(start is None):
            d = date.today()
            t = time()
        else:
            d = date(start.year, start.month, start.day)
            t = time(start.hour, start.minute, start.second)
    else:
        if(start is None):
            d = datetime.date.today()
            t = datetime.time()
        else:
            d = datetime.date(start.year, start.month, start.day)
            t = datetime.time(start.hour, start.minute, start.second)

    c = curses.KEY_MAX
    cursor = 3
    while(c != 10):
        displayDateTime(scr, d, t, cursor, topString, bottomString)
        c = scr.getch()
        if(c == curses.KEY_RIGHT) and cursor < 18:
            cursor += 1
            if(cursor in (4, 7, 10, 13, 16)):
                cursor += 1
        elif(c == curses.KEY_LEFT) and cursor > 0:
            cursor -= 1
            if(cursor in (4, 7, 10, 13, 16)):
                cursor -= 1
        elif(c == curses.KEY_UP):
            if(cursor < 10):
                d = alterDigitDay(cursor, d, 1)
            else:
                t = alterDigitTime(cursor - 11, t, 1)
        elif(c == curses.KEY_DOWN):
            if(cursor < 10):
                d = alterDigitDay(cursor, d, -1)
            else:
                t = alterDigitTime(cursor - 11, t, -1)
        else:
            try:
                i = int(c) - 48
                if(i >= 0 and i < 10):
                    if(cursor < 10):
                        d = updateDigitDay(cursor, d, i)
                    else:
                        t = updateDigitTime(cursor - 11, t, i)
            except ValueError:
                pass
    return datetime.datetime(d.year, d.month, d.day,
                             t.hour, t.minute, t.second)