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)
python类KEY_LEFT的实例源码
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)
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)
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)
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 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)
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()
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()
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)
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)
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)
def name(self):
"""String-name of key sequence, such as ``u'KEY_LEFT'`` (str)."""
return self._name
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])
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()))
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()
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 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 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)