我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.KEY_UP。
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, }
def input_stream(self): """Waiting an input and run a proper method according to type of input""" while True: self.search(self.query) self.display() ch = self.search_window.getch() if curses.ascii.isprint(ch): self.write(ch) self.reset_top() elif ch in (curses.ascii.BS, curses.ascii.DEL, curses.KEY_BACKSPACE): self.delete() self.reset_top() elif ch == curses.KEY_UP: self.scroll(self.UP) elif ch == curses.KEY_DOWN: self.scroll(self.DOWN) elif ch in (curses.ascii.LF, curses.ascii.NL): self.open_link() elif ch == curses.ascii.ESC: break
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()
def _handle_key(self, x): if x == curses.KEY_UP: if self.history_point < len(self.search_history): self.history_point += 1 self.inp.erase() self.inp.addstr(0, 0, self.search_history[-self.history_point]) if x == curses.KEY_DOWN: if self.history_point > 1: self.history_point -= 1 self.inp.erase() self.inp.addstr(0, 0, self.search_history[-self.history_point]) if x == 27: self.canceled = True return 7 if x == 10: return 7 return x
def on_key(self, ch): if ch not in (curses.KEY_UP, curses.KEY_DOWN, curses.KEY_PPAGE, curses.KEY_NPAGE): return if ch == curses.KEY_UP: self.scroll = max(self.scroll - 1, 0) if ch == curses.KEY_DOWN: self.scroll = min(self.scroll + 1, self.maxscroll) if ch == curses.KEY_PPAGE: self.scroll = max(self.scroll - self.perpage, 0) if ch == curses.KEY_NPAGE: self.scroll = min(self.scroll + self.perpage, self.maxscroll) self.update()
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)
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()
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 }
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 }
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()
def main(self): # self.set_banner("14.076.00", "JT65/JT9", "Tx") # # self.thread_flag = True # thread.start_new_thread(self.add_to_window, ()) key = '' while True: key = self.stdscr.getch() if key == ord('q'): # self.thread_flag = False # break pass elif key == curses.KEY_DOWN: # scroll down ? self.main_win.scroll(-1) pass elif key == curses.KEY_UP: # scroll up ? self.main_win.scroll(1) pass self.exit_now()
def loop(self): while True: key = self.left.getkey() if key.lower() == 'q': return elif key.lower() == 'v': status = self.get_selected_status() if status: webbrowser.open(status['url']) elif key.lower() == 'j' or key == curses.KEY_DOWN: self.select_next() elif key.lower() == 'k' or key == curses.KEY_UP: self.select_previous()
def keys_init_noedit(self): """Define methods for each key for non-editing mode. """ self.keys = { curses.ascii.ETX: self.close, curses.KEY_DOWN: self.down_noedit, CTRL('n'): self.down_noedit, 'j': self.down_noedit, curses.KEY_F1: self.help, curses.KEY_NPAGE: self.page_down, 'J': self.page_down, CTRL('f'): self.page_up, curses.KEY_PPAGE: self.page_up, 'K': self.page_up, CTRL('b'): self.page_up, 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_UP: self.up_noedit, CTRL('p'): self.up_noedit, 'k': self.up_noedit, }
def get_user_input(self): # gets the user's input try: user_in = self.screen.getch() # Gets user input except Exception as e: self.__exit__() ## DEBUG KEYS - enable these lines to see curses key codes # self.screen.addstr(1, 1, str(user_in), curses.A_NORMAL) # self.screen.refresh() # Resize sends curses.KEY_RESIZE, update display if user_in == curses.KEY_RESIZE: self.maxy,self.maxx = self.screen.getmaxyx() self.screen.clear() self.screen.refresh() # enter and exit Keys are special cases if user_in == 10: return self.options[self.selected] if user_in == 27: return self.options[-1] # this is a number; check to see if we can set it if user_in >= ord('1') and user_in <= ord(str(min(9,len(self.options)+1))): self.selected = user_in - ord('0') - 1 # convert keypress back to a number, then subtract 1 to get index return # increment or Decrement down_keys = [curses.KEY_DOWN, 14, ord('j')] up_keys = [curses.KEY_UP, 16, ord('k')] if user_in in down_keys: # down arrow self.selected += 1 if user_in in up_keys: # up arrow self.selected -=1 # modulo to wrap menu cursor self.selected = self.selected % len(self.options) return
def display(self): self.panel.top() self.panel.show() self.window.clear() while True: self.window.refresh() curses.doupdate() for index, item in enumerate(self.items): if index == self.position: mode = curses.A_REVERSE else: mode = curses.A_NORMAL msg = '%d. %s' % (index, item[0]) self.window.addstr(1+index, 1, msg, mode) key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: # Handle exit from menu if self.position == len(self.items)-1 or str(self.items[self.position][1]) == "exit": break else: if self.rootmenu.set_selection(self.items[self.position][1]): break elif key == curses.KEY_UP: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
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)
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)
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
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()
def mainloop(self): """ Called after HUD has been set up. Handles rendering and user input. """ # Disable cursor display by default curses.curs_set(0) # Display initial state self.render() while True: # Render before fetching input self.render() # note: call is non-blocking, per __init__ calling nodelay(True) c = self.screen.getch() if c == curses.KEY_RESIZE: # Terminal has been resized # must be called so that curses.LINES, curses.COLS will change curses.update_lines_cols() # in case old data won't be redrawn after resize self.screen.clear() if c == curses.KEY_UP: # Move up as far as the 0th record self.selectpos = max(self.selectpos - 1, 0) if self.selectpos < self.scrollpos: # Handle scrolling if we were at the first record on screen self.scrollpos -= 1 if c == curses.KEY_DOWN: # Move down as far as the Nth record self.selectpos = min(self.selectpos + 1, len(self.records) - 1) if self.selectpos >= (self.scrollpos + curses.LINES - 2 - self.bottom_panel_height) : # Handle scrolling if we were at the last record on screen self.scrollpos += 1
def configure_settings(self, pos=None, key_in=None): """ Perform operations to config settings if `Configure Setting` frame is active, or just draw the `Configure Setting` frame with no items selected while it is inactive. .. note:: Whether the `Configure Setting` frame is inactive is decided by if :attr:`pos` is `None` or not. =========== ======== :attr:`pos` Status =========== ======== None Inactive int Active =========== ======== :param pos: Index of selected item in `Configure Setting` frame. The default value of `pos` is `None`. :type pos: int or None :param key_in: A flag indicating the key pressed by user. The default value of `key_in` is `None`. :type key_in: int or None :return: Index of selected item in `Configure Setting` frame. :rtype: int or None """ id_num = range(len(self.settings)) if pos is not None: if key_in == curses.KEY_DOWN: pos = list(id_num[1:] + id_num[:1])[pos] elif key_in == curses.KEY_UP: pos = list(id_num[-1:] + id_num[:-1])[pos] elif key_in in [10, 32]: self.sub_selection(pos) self.info(pos, 0) self.configure_settings_frame(pos) return pos
def sub_selection(self, pos): """ Let user to choose settings from `Selection Dialog` specified by :attr:`pos`. :param pos: Index of selected item in `Configure Setting` frame. :type pos: int .. warning:: The value of `pos` MUST NOT be `None`. .. seealso:: :meth:`~tui.curses_ui.CursesUI.sub_selection_dialog` in :class:`~tui.curses_ui.CursesUI`. """ screen = self.sub_selection_dialog(pos) i_pos = self.settings[pos][1] # Key Press Operations id_num = range(len(self.settings[pos][2])) key_in = None while key_in != 27: self.sub_selection_dialog_items(pos, i_pos, screen) key_in = screen.getch() if key_in == curses.KEY_DOWN: i_pos = list(id_num[1:] + id_num[:1])[i_pos] elif key_in == curses.KEY_UP: i_pos = list(id_num[-1:] + id_num[:-1])[i_pos] elif key_in in [10, 32]: if pos == 0 and i_pos != self.settings[pos][1]: test = self.settings[pos][2][i_pos]["test_url"] self.check_connection(test) self.settings[pos][1] = i_pos return
def main_loop(): while 1: time.sleep(0.001) c = mainwindow.getch() if c == ord('/'): word = search_window.enter() found = game_menu.find_word(word) game_menu.center(found) if c == ord('j') or c == curses.KEY_DOWN: game_menu.move_down() if c == ord('k') or c == curses.KEY_UP: game_menu.move_up() if c == ord('n'): word = search_window.text.gather().strip() found = game_menu.find_next(word) game_menu.center(found) if c == ord('N'): word = search_window.text.gather().strip() found = game_menu.find_prev(word) game_menu.center(found) if c == ord('\n') or c == ord('l'): cg = game_menu.current_game() launch_game(cg) if c == ord('q'): return if c == curses.KEY_RESIZE: do_resize()
def on_key(self, ch): if not self.items: return False if ch == curses.KEY_UP: self.selected = max(self.selected - 1, 0) elif ch == curses.KEY_DOWN: self.selected = min(len(self.selectable) - 1, self.selected + 1) elif ch == curses.KEY_HOME: self.selected = 0 elif ch == curses.KEY_END: self.selected = len(self.selectable) - 1 elif ch == curses.KEY_ENTER: key, title = self.items[self.selectable[self.selected]] self.select(key) return True # no update necessary else: return False self.update() return True
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()
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
def handle_key_event(self, event): """ Handle edit pad key events :param event: :return: """ logging.info("Key Event:{}".format(event)) if event == curses.KEY_UP: try: cmd = self.lastcmd[0] except IndexError: return event self.edit.clear() self.edit.addstr(0, 0, cmd) self.edit.refresh() try_handle_global_event(event) if event == 9: logging.info("Calling auto complete on TAB key") data = self.pad.gather().strip() cmds = {key[:len(data)]: key for key in commands.keys()} logging.info("Options are") for cmd, fullname in cmds.iteritems(): if cmd == data: logging.info("Grabbed the first match which was {}".format(fullname)) self.edit.clear() self.edit.addstr(0, 0, fullname) self.edit.refresh() break return event
def open_menu(stdscr, items): """Opens a menu containing items and returns the selected item. Blocks until the user selected an item. """ width = max(map(len, items)) + 20 height = len(items*2)-1 + 4 # +2 for frame, +2 for padding curses.curs_set(False) selected = 0 while True: center = (curses.COLS//2, curses.LINES//2) menu_rect = Rect(center[0]-width//2, center[1]-height//2, width, height) menu_rect = draw_frame(stdscr, menu_rect, thick_border=True) for i, item in enumerate(items): attr = curses.A_NORMAL if i == selected: attr = curses.A_STANDOUT stdscr.addstr(menu_rect.y + 1 + i*2, center[0] - len(item)//2, item, attr) c = stdscr.getch() if c == curses.KEY_UP: selected -= 1 if c == curses.KEY_DOWN: selected += 1 if c == curses.KEY_ENTER or c == 10: break selected = clamp(selected, 0, len(items)-1) curses.curs_set(True) return items[selected]
def test_should_handle_key_up(self): self._parent_window.getmaxyx.return_value = (9, 30) win = Select(self._manager, 'Letter', ['a', 'b', 'c']) win.handle_key(curses.KEY_DOWN) win.handle_key(curses.KEY_UP) self.assertEqual(0, win.position)
def test_should_handle_key_up(self): self._parent_window.getmaxyx.return_value = (9, 30) dt = datetime.datetime(2016, 6, 27, 22, 6, 28) win = Datetime(self._manager, 'Date', dt) win.handle_key(curses.KEY_UP) win.refresh() self.assertEqual([((0, 8, '|Date|'),), ((2, 2, '2017-06-27 22:06:28'),)], self._child_window.addstr.call_args_list)
def handle_key(self, k): if k == ord('\n'): self.close(True) elif k == 27: self.close(False) elif k == curses.KEY_DOWN: self.position = min(self._count - 1, self.position + 1) elif k == curses.KEY_UP: self.position = max(0, self.position - 1)
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()
def command(self, char): """handle page specific commands""" if char == curses.KEY_DOWN or char == ord('j'): if self.pad_pos < self.row_count-1: self.pad_pos += 1 elif char == curses.KEY_UP or char == ord('k'): if self.pad_pos > 0: self.pad_pos -= 1 elif char == curses.KEY_NPAGE or char == ord('J'): if self.pad_pos < self.row_count-((self.max_y)/2): self.pad_pos += (self.max_y)/2 else: self.pad_pos = self.row_count-1 elif char == curses.KEY_PPAGE or char == ord('K'): if self.pad_pos > ((self.max_y)/2): self.pad_pos -= (self.max_y)/2 else: self.pad_pos = 0 elif char == curses.KEY_RIGHT or char == ord('l'): if self.row_index[self.pad_pos][0] == 'vessel': vessel = self.row_index[self.pad_pos][1] return ('VESSEL_DETAIL', vessel) if self.row_index[self.pad_pos][0] == 'target': vessel = self.row_index[self.pad_pos][1] path = self.row_index[self.pad_pos][2] return ('TARGET_DETAIL', (vessel, path)) return (None, None)
def _select_account(self): row_len = 20 selected = 0 while True: self.screen.clear() self.screen.addstr(1, 2, "Select an account:") rows = self._account_names + ["New account"] for i, account in enumerate(rows): row_string = " %s" % account row_string += " " * (row_len - len(row_string)) if i == selected: color = self._active_account_color() else: color = self._inactive_account_color() self.screen.addstr(i + 3, 2, row_string, color) self._display_status() self.screen.refresh() c = self.screen.getch() if c == curses.KEY_UP: selected -= 1 if selected < 0: selected = len(rows) - 1 elif c == curses.KEY_DOWN: selected += 1 if selected >= len(rows): selected = 0 elif c == curses.KEY_ENTER or c == 10 or c == 13: if selected == len(rows) - 1: await self._new_account() break else: account_name = rows[selected] password = self._enter_password() ec = await api.Account.set(self._ws, account_name, password) if ec: self.screen.addstr(10, 2, "Error: %s" % ec.name) else: return
def curses_loop(self, stdscr): while 1: self.redraw() c = stdscr.getch() if c == ord('q') or c == ord('Q'): self.aborted = True break elif c == curses.KEY_UP: self.cursor = self.cursor - 1 elif c == curses.KEY_DOWN: self.cursor = self.cursor + 1 # elif c == curses.KEY_PPAGE: # elif c == curses.KEY_NPAGE: elif c == ord(' '): self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["selected"] elif c == 10: break # deal with interaction limits self.check_cursor_up() self.check_cursor_down() # compute selected position only after dealing with limits self.selected = self.cursor + self.offset temp = self.getSelected() self.selcount = len(temp)
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()
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
def display(self): self.window.clear() while True: self.window.refresh() curses.doupdate() for index, item in enumerate(self.items): if index == self.position: mode = curses.A_REVERSE else: mode = curses.A_NORMAL msg = '- %s\n (Features: %s, Design: %s)' % (item, item.features, item.design_need) self.window.addstr(1+index*2, 2, msg, mode) key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: if self.position == len(self.items)-1: return None else: return self.position if key == curses.KEY_UP: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1)
def start(self): """ start iterates the file and paints the text on the screen. exits when q is pressed. """ try: fileptr = 0 key = '' lines = 1 while True: # get the cursor position for further manipulation y, x = self.stdscr.getyx() key = self.stdscr.getch() if key == curses.KEY_BACKSPACE or key == curses.KEY_DC or \ key == curses.KEY_DL or key == 127 : # handle backspace if x == 0 and y == 0: continue # take the file pointer back one step fileptr -= 1 # update the screen if x == 0: lines -= 1 self.stdscr.addstr(y-1, len(self.virtualfile[lines-1]), ' ') self.stdscr.move(y-1, len(self.virtualfile[lines-1])) else: self.stdscr.addstr(y, x-1, ' ') self.stdscr.move(y, x-1) elif key == curses.KEY_UP or key == curses.KEY_DOWN or \ key == curses.KEY_RESIZE or key == -1: # ignore continue else: text = self.get_text(fileptr) # increase the lines if there are "\n" s lines += sum([1 if c == '\n' else 0 for c in text]) fileptr += self.n self.stdscr.addstr(text) self.stdscr.refresh() # graceful exit curses.endwin() except KeyboardInterrupt: curses.endwin() exit()
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')
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, }
def keypress(self, char): # right arrow select a user/group to chat with if char == curses.KEY_RIGHT: self.refresh_body() self.update_chat() self.showing = self.selection current_id = self.slack_client.active[self.showing].id current_name = self.slack_client.active[self.showing].name for m in self.slack_client.last_messages(current_id): self.push_chat(m['user'], m['text']) return # moves to the user/group below current selection elif char == curses.KEY_DOWN: if self.selection < len(self.slack_client.active) - 1: self.set_body_selection(self.selection + 1) self.refresh_body() return # move cursor one position up elif char == curses.KEY_UP: if self.selection > 0: self.set_body_selection(self.selection - 1) self.refresh_body() return # send the content on the textbox elif char == curses.KEY_ENTER or chr(char) == "\n": # Fixme: send message as 'me', should be username self.push_chat('me', self.text) self.send_text() return # delete a character elif chr(char) == self.del_char or chr(char) == "\x7f": self.backspace() return # send the char to textbox area else: self.text += chr(char) self.refresh_textarea(char) return # This method is callable for testing porpuses only
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)
def c_main(stdscr): cargo_cult_routine(stdscr) stdscr.nodelay(0) mydir = factory(start) mydir.expand() curidx = 3 pending_action = None pending_save = False while True: stdscr.clear() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) line = 0 offset = max(0, curidx - curses.LINES + 3) for data, depth in mydir.traverse(): if line == curidx: stdscr.attrset(curses.color_pair(1) | curses.A_BOLD) if pending_action: getattr(data, pending_action)() pending_action = None elif pending_save: global result result = data.name return else: stdscr.attrset(curses.color_pair(0)) if 0 <= line - offset < curses.LINES - 1: stdscr.addstr(line - offset, 0, data.render(depth, curses.COLS)) line += 1 stdscr.refresh() ch = stdscr.getch() if ch == curses.KEY_UP: curidx -= 1 elif ch == curses.KEY_DOWN: curidx += 1 elif ch == curses.KEY_PPAGE: curidx -= curses.LINES if curidx < 0: curidx = 0 elif ch == curses.KEY_NPAGE: curidx += curses.LINES if curidx >= line: curidx = line - 1 elif ch == curses.KEY_RIGHT: pending_action = 'expand' elif ch == curses.KEY_LEFT: pending_action = 'collapse' elif ch == ESC: return elif ch == ord('\n'): pending_save = True curidx %= line ################################################################################
def on_key(self, ch): if not self.items: return False if ch == curses.KEY_UP: if self.selected == 0: return False self.selected -= 1 # Selection is outside view, scroll up if self.selected - self.offset < 0: self.offset = self.selected elif ch == curses.KEY_DOWN: if self.selected == len(self.items) - 1: return False self.selected += 1 # Selection is outside view, scroll down if self.selected - self.offset >= self.h: self.offset = self.selected - self.h + 1 elif ch == curses.KEY_HOME: self.selected = 0 self.offset = 0 elif ch == curses.KEY_END: self.selected = len(self.items) - 1 self.offset = max(0, self.selected - self.h + 1) elif ch == curses.KEY_ENTER: key, title, action = self.items[self.selected] self.select(key) return True # no update necessary else: return False self.update() return True
def on_key(self, ch): if not self.active or self.disabled: return if not self.active.on_key(ch): y, x = self.position(self.active) if ch == curses.KEY_UP: if y > 0: self.set_active(self.rows[y - 1][self.defaults[y - 1]]) elif ch in (curses.KEY_DOWN, curses.KEY_ENTER): if y < len(self.rows) - 1: self.set_active(self.rows[y + 1][self.defaults[y + 1]]) elif ch == curses.KEY_LEFT: if x > 0: self.set_active(self.rows[y][x - 1]) elif ch == curses.KEY_RIGHT: if x < len(self.rows[y]) - 1: self.set_active(self.rows[y][x + 1]) elif ch == curses.ascii.TAB: # Right if x < len(self.rows[y]) - 1: self.set_active(self.rows[y][x + 1]) # Down, ignoring defaults elif y < len(self.rows) - 1: self.set_active(self.rows[y + 1][0]) else: self.set_active(self.rows[0][0]) elif ch == curses.KEY_BTAB: # Left if x > 0: self.set_active(self.rows[y][x - 1]) # Up elif y > 0: col = len(self.rows[y - 1]) - 1 self.set_active(self.rows[y - 1][col]) else: row = len(self.rows) - 1 col = len(self.rows[row]) - 1 self.set_active(self.rows[row][col])
def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr.clear() stdscr_y, stdscr_x = stdscr.getmaxyx() menu_y = (stdscr_y-3)-1 display_menu(stdscr, menu_y) # Allocate a subwindow for the Life board and create the board object subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0) board = LifeBoard(subwin, char=ord('*')) board.display(update_board=False) # xpos, ypos are the cursor's position xpos, ypos = board.X//2, board.Y//2 # Main loop: while (1): stdscr.move(1+ypos, 1+xpos) # Move the cursor c = stdscr.getch() # Get a keystroke if 0<c<256: c = chr(c) if c in ' \n': board.toggle(ypos, xpos) elif c in 'Cc': erase_menu(stdscr, menu_y) stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously ' 'updating the screen.') stdscr.refresh() # Activate nodelay mode; getch() will return -1 # if no keystroke is available, instead of waiting. stdscr.nodelay(1) while (1): c = stdscr.getch() if c != -1: break stdscr.addstr(0,0, '/') stdscr.refresh() board.display() stdscr.addstr(0,0, '+') stdscr.refresh() stdscr.nodelay(0) # Disable nodelay mode display_menu(stdscr, menu_y) elif c in 'Ee': board.erase() elif c in 'Qq': break elif c in 'Rr': board.makeRandom() board.display(update_board=False) elif c in 'Ss': board.display() else: pass # Ignore incorrect keys elif c == curses.KEY_UP and ypos>0: ypos -= 1 elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1 elif c == curses.KEY_LEFT and xpos>0: xpos -= 1 elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1 else: # Ignore incorrect keys pass