Example #1
0
    def get_and_use_key_press(self):
        curses.raw()
        curses.cbreak()
        curses.meta(1)
        self.form.curses_pad.keypad(1)
        if self.form.keypress_timeout:
            curses.halfdelay(self.form.keypress_timeout)
            ch = self._get_ch()
            if ch == -1:
                log.debug('calling {0}.while_waiting'.format(self.form))
                return self.form.while_waiting()
        else:
            self.form.curses_pad.timeout(-1)
            ch = self._get_ch()
        if ch == curses.ascii.ESC:
            #self.form.curses_pad.timeout(1)
            self.form.curses_pad.nodelay(1)
            ch2 = self.form.curses_pad.getch()
            if ch2 != -1:
                ch = curses.ascii.alt(ch2)
            self.form.curses_pad.timeout(-1)  # back to blocking mode
            #curses.flushinp()

        self.handle_input(ch)
        if self.check_value_change:
            self.when_check_value_changed()
        if self.check_cursor_move:
            self.when_check_cursor_moved()
Example #2
0
 def update_loop(self):
     while self.exit_code is None:
         self.update_screen()
         curses.halfdelay(50)
         v = self.stdscr.getch()
         #print("v=%s" % (v,))
         if v in EXIT_KEYS:
             self.exit_code = 0
         elif v == 258:  #down arrow
             self.position += 1
         elif v == 259:  #up arrow
             self.position = max(self.position - 1, 0)
         elif v == 10 and self.selected_session:
             #show this session:
             cmd = get_nodock_command() + ["top", self.selected_session]
             try:
                 self.cleanup()
                 proc = Popen(cmd)
                 exit_code = proc.wait()
                 #TODO: show exit code, especially if non-zero
             finally:
                 self.stdscr = curses_init()
         elif v in (ord("s"), ord("S")):
             self.run_subcommand("stop")
         elif v in (ord("a"), ord("A")):
             self.run_subcommand("attach")
         elif v in (ord("d"), ord("D")):
             self.run_subcommand("detach")
Example #3
0
 def __init__(self, lives_remaining=3):
     self.stdscr = curses.initscr()
     curses.start_color()
     curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
     curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
     curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_RED)
     curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_GREEN)
     curses.noecho()
     curses.cbreak()
     curses.halfdelay(1)
     self.stdscr.keypad(True)
     self.board = np.zeros((10, 60))
     self.next_spike = 5
     self.board[8][20] = 2
     self.posx = 5
     self.posy = 8
     self.y_move_index = 0
     self.y_move_speeds = [0, -3, -2, -1, 0, 1, 2, 3]
     self.score = 0
     self.difficulty = 0
     self.difficulties = [(1, 1), (1, 2), (1, 3), (1, 4), (2, 4), (2, 5),
                          (3, 5), (4, 5), (4, 6), (5, 6), (6, 6)]
     self.game_over = 0
     self.lives_remaining = lives_remaining
     for j in range(60):
         self.board[9][j] = 1
Example #4
0
 def gather_input(self, win):
     """
     Read and process a part of the available input from stdin, 
     possibly pausing a few ms to wait for additional input.
     Execute all functions enqueued by run_soon() at the end.
     You should call this in a loop.
     """
     curses.halfdelay(7)
     win.nodelay(1)
     while True:
         try:
             key = win.get_wch()
         except curses.error:
             break
         curses.cbreak()
         if key == curses.KEY_MOUSE:
             try:
                 self.input_mouse(*curses.getmouse())
             except curses.error:
                 pass
         else:
             self.input_key(key)
     if self.runqueue:
         rq = self.runqueue
         self.runqueue = []
         for f in rq:
             f()
     return self.key_events != [] or self.mouse_events != []
Example #5
0
 def input_thread(self):
     self.log("input thread: signal handlers=%s" %
              signal.getsignal(signal.SIGINT))
     while self.exit_code is None:
         if not self.paused and self.modified:
             self.stdscr.erase()
             try:
                 self.do_update_screen()
             except Exception as e:
                 self.err(e)
             finally:
                 self.stdscr.refresh()
                 self.modified = False
         try:
             curses.halfdelay(10)
             v = self.stdscr.getch()
         except Exception as e:
             self.log("getch() %s" % e)
             v = -1
         self.log("getch()=%s" % v)
         if v == -1:
             continue
         if v in EXIT_KEYS:
             self.log("exit on key '%s'" % v)
             self.quit(0)
             break
         if v in SIGNAL_KEYS:
             self.log("exit on signal key '%s'" % v)
             self.quit(128 + SIGNAL_KEYS[v])
             break
         if v in PAUSE_KEYS:
             self.paused = not self.paused
Example #6
0
 def _dbg_instr(self): # messy input string (intended for debugging)
     curses.echo()
     self.s.nodelay(0)
     curses.halfdelay(100)
     str = self.s.getstr()
     curses.noecho()
     return str
Example #7
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

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

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

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

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Example #8
0
 def write_prologue(self,string):
     yindex = 20
     xreturn = (self.len_x /2) -25
     xloc = xreturn
     writing_prologue = True
     curses.halfdelay(1)
     for char in string:
         brkchar = self.win.getch()
         if brkchar == ord('Q'):
             curses.nocbreak()
             curses.cbreak()
             return True
             break
         if char == '"':
             time.sleep(2)
             yindex += 1
             xloc = xreturn
         if char != '"':
             txt = ord(char)
             self.win.addch(yindex,xloc,txt)
             self.win.refresh()
             #time.sleep(.1)
             xloc += 1
     time.sleep(4)
     return True
Example #9
0
    def run_curses(self, screen):
        # init some curses geometry
        self.screen = screen

        # set up curses colors
        curses.use_default_colors()
        curses.curs_set(0)
        assert len(self.colors) <= 4, 'Too many colors defined'
        assert len(self.colors) > 0, 'Not enough colors defined'
        global ATTRIBUTES
        for i,c in enumerate(self.colors):
            background = getattr(curses, 'COLOR_' + c[0].upper())
            foreground = getattr(curses, 'COLOR_' + c[1].upper())
            curses.init_pair(i + 1, background, foreground)
            ATTRIBUTES[str(i + 1)] = curses.color_pair(i+1)

        # wait for a character for only 0.1s
        curses.halfdelay(1)

        # use the first window as the default window
        self.current_window = self.windows['default']
        self.render()

        while 1:
            input_value = screen.getch()
            # handle non-character input
            try:
                key = chr(input_value)
            except ValueError:
                key = input_value
            # pass the character input to the event loop
            try:
                self.handle(key)
            except Exit:
                return
Example #10
0
    def do_start(self):

        assert not self.started

        if utk._running_from_pytest:
            self._started = True
            return

        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors = True
            except _curses.error:
                self.has_default_colors = False

        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10) # use set_input_timeouts to adjust
        self.s.keypad(0)

        self._started = True
Example #11
0
    def __init__(self, refresh_interval, total_columns):
        """Initialize the window with various settings."""
        self.total_columns = total_columns
        self.window = curses.initscr()

        # Initialize colors with red, green, yellow, blue, and white
        curses.start_color()
        curses.use_default_colors()
        for i in range(1, 5):
            curses.init_pair(i, i, -1)
        curses.init_pair(7, 7, -1)

        # Use the orange color if the terminal supports it, and magenta
        # otherwise
        if curses.COLORS == 256:
            self.COLOR_ORANGE = 208
        else:
            self.COLOR_ORANGE = curses.COLOR_MAGENTA
        curses.init_pair(self.COLOR_ORANGE, self.COLOR_ORANGE, -1)

        # Disable typing echo and hide the cursor
        curses.noecho()
        curses.curs_set(0)

        # Set the refresh interval
        curses.halfdelay(refresh_interval)

        self._update_dimensions()
Example #12
0
def main(stdscr):
    # turn off cursor blinking
    curses.curs_set(0)
    curses.halfdelay(5)
    # color scheme for selected row
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    # specify the current selected row
    current_row = 0
    # print the menu
    print_menu(stdscr, current_row)

    while 1:
        key = stdscr.getch()

        if key == curses.KEY_UP and current_row > 0:
            current_row -= 1
        elif key == curses.KEY_DOWN and current_row < len(menu) - 1:
            current_row += 1
        elif key == curses.KEY_ENTER or key in [10, 13]:
            if current_row == 0:
                get_rice_loop(stdscr)

            if current_row == 1:
                curses.halfdelay(20)
                print_center(stdscr, "Just one question, GotRice?")
                stdscr.getch()
                break

        print_menu(stdscr, current_row)
Example #13
0
def start():
	global READY
	global thr
	global scr
	global win_input
	global pan_input
	global win_status
	global pan_status
	global win_msg
	global pan_msg
	if not READY:
		scr = curses.initscr()
		scr.keypad(1)
		curses.noecho()
		curses.halfdelay(1)

		win_msg = curses.newwin(11,53,0,0)
		win_msg.scrollok(1)
		pan_msg = panel.new_panel(win_msg)
		pan_msg.show()
		win_input = curses.newwin(3,53,12,0)
		pan_input = panel.new_panel(win_input)
		pan_input.show()
		win_status = curses.newwin(3,53,14,0)
		pan_status = panel.new_panel(win_status)
		pan_status.show()
		READY = True

		thr = threading.Thread(target=reading_thread)
		thr.start()
Example #14
0
    def run_curses(self, screen):
        # init some curses geometry
        self.screen = screen

        # set up curses colors
        curses.use_default_colors()
        curses.curs_set(0)
        assert len(self.colors) <= 4, 'Too many colors defined'
        assert len(self.colors) > 0, 'Not enough colors defined'
        global ATTRIBUTES
        for i, c in enumerate(self.colors):
            background = getattr(curses, 'COLOR_' + c[0].upper())
            foreground = getattr(curses, 'COLOR_' + c[1].upper())
            curses.init_pair(i + 1, background, foreground)
            ATTRIBUTES[str(i + 1)] = curses.color_pair(i + 1)

        # wait for a character for only 0.1s
        curses.halfdelay(1)

        # use the first window as the default window
        self.current_window = self.windows['default']
        self.render()

        while 1:
            input_value = screen.getch()
            # handle non-character input
            try:
                key = chr(input_value)
            except ValueError:
                key = input_value
            # pass the character input to the event loop
            try:
                self.handle(key)
            except Exit:
                return
 def _dbg_instr(self): # messy input string (intended for debugging)
     curses.echo()
     self.s.nodelay(0)
     curses.halfdelay(100)
     str = self.s.getstr()
     curses.noecho()
     return str
Example #16
0
def MainLoop(args):
    global errorCount, respawn
    curses.halfdelay(20)
    while 1:
        PollSystem()
        try:
            Display()
        except curses.error:
            0  # destroy the exception.  we're not interested in display errors

        c = stdscr.getch()

        try:

            if c == ord('0'):
                StartStopAll()
            elif c == ord('q'):
                break
            elif c == ord('r'):
                respawn = not respawn
            elif c >= ord('1') and c <= ord('9'):
                StartStop(c - ord('0'))
            elif c >= ord('a') and c <= ord('m'):
                StartStop(c - ord('a') + 10)
        except:
            errorCount = errorCount + 1
Example #17
0
 def get_and_use_key_press(self):
     curses.raw()
     curses.cbreak()
     curses.meta(1)
     self.parent.curses_pad.keypad(1)
     if self.parent.keypress_timeout:
         curses.halfdelay(self.parent.keypress_timeout)
         ch = self._get_ch()
         if ch == -1:
             return self.try_while_waiting()
     else:
         self.parent.curses_pad.timeout(-1)
         ch = self._get_ch()
     # handle escape-prefixed rubbish.
     if ch == curses.ascii.ESC:
         #self.parent.curses_pad.timeout(1)
         self.parent.curses_pad.nodelay(1)
         ch2 = self.parent.curses_pad.getch()
         if ch2 != -1: 
             ch = curses.ascii.alt(ch2)
         self.parent.curses_pad.timeout(-1) # back to blocking mode
         #curses.flushinp()
     
     self.handle_input(ch)
     if self.check_value_change:
         self.when_check_value_changed()
     if self.check_cursor_move:
         self.when_check_cursor_moved()
     
     
     self.try_adjust_widgets()
Example #18
0
 def update_loop(self):
     while self.exit_code is None:
         self.update_screen()
         elapsed = int(1000 * monotonic() - self.last_getch)
         delay = max(100, min(1000, 1000 - elapsed)) // 100
         curses.halfdelay(delay)
         try:
             v = self.stdscr.getch()
         except Exception:
             v = -1
         self.last_getch = int(1000 * monotonic())
         if v in EXIT_KEYS:
             self.exit_code = 0
         if v in SIGNAL_KEYS:
             self.exit_code = 128 + SIGNAL_KEYS[v]
         if v == 258:  #down arrow
             self.position += 1
         elif v == 259:  #up arrow
             self.position = max(self.position - 1, 0)
         elif v == 10 and self.selected_session:
             self.show_selected_session()
         elif v in (ord("s"), ord("S")):
             self.run_subcommand("stop")
         elif v in (ord("a"), ord("A")):
             self.run_subcommand("attach")
         elif v in (ord("d"), ord("D")):
             self.run_subcommand("detach")
Example #19
0
    def start(self):
        """
        Initialize the screen and input mode.
        """
        assert self._started == False

        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors=True
            except _curses.error:
                self.has_default_colors=False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10) # use set_input_timeouts to adjust
        self.s.keypad(0)
        
        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys()

        super(Screen, self).start()
Example #20
0
def setup(curses, session):
    stdscr = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
    curses.init_pair(2, curses.COLOR_CYAN, -1)
    curses.init_pair(3, curses.COLOR_GREEN, -1)
    curses.init_pair(4, curses.COLOR_RED, -1)
    curses.init_pair(10, 166, curses.COLOR_WHITE)
    curses.init_pair(11, curses.COLOR_BLUE, curses.COLOR_WHITE)
    curses.init_pair(12, 23, curses.COLOR_WHITE)

    curses.noecho()
    curses.cbreak()
    # Listing for 1/10th of second at a time
    curses.halfdelay(1)
    stdscr.keypad(True)
    stdscr.clear()
    session.set_current_schema('sys')
    query = session.sql("select @@version, @@version_comment, @@hostname, @@port")
    result = query.execute()
    info = {}
    for row in result.fetch_all():
        info['version'] = row[0]
        info['comment'] = row[1]
        info['hostname'] = row[2]
        info['port'] = row[3]
    return stdscr, info
Example #21
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

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

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

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

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Example #22
0
    def main_cli(self, stdscr):
        # Block each getch() for 10 tenths of a second
        curses.halfdelay(10)
        # Visibility 0 is invisible
        curses.curs_set(0)

        try:
            while True:
                ps_str = self.get_ps_str()
                lines = ps_str.split('\n')

                max_y, max_x = stdscr.getmaxyx()
                stdscr.erase()
                for i, line in enumerate(lines):
                    # We don't want to draw on the last line because the
                    # Press q to exit message goes there
                    if i >= max_y - 1:
                        break
                    stdscr.addstr(i, 0, line[:max_x])
                # Assumes that terminal size is greater than 15 character
                # Will crash otherwise...but who uses terminals 15 characters wide?
                stdscr.addstr(max_y - 1, 0, 'Press q to exit', curses.A_REVERSE)
                stdscr.refresh()

                if stdscr.getch() == ord('q'):
                    break
        except KeyboardInterrupt:
            pass
Example #23
0
def main(stdscr):
    curses.use_default_colors()
    stdscr.clear()
    curses.curs_set(0)
    curses.cbreak()
    stdscr.nodelay(True)
    curses.halfdelay(5)
    curses.start_color()

    O = ((0,0), (0,1), (1,0), (1,1))
    L = ((0,0), (1,0), (2,0), (2,1))
    L1 = ((0,0), (1,0), (2,0), (2,-1))
    I = ((0,0), (1,0), (2,0), (3,0))
    T = ((0,0), (0,1), (0,2), (1,1))
    Z = ((0,0), (0,1), (1,1), (1,2))
    Z1 = ((0,0), (0,1), (1,0), (1,-1))

    pieces = (O, L, L1, I, T, Z, Z1)

    game = Tetris(stdscr)

    #game.set(3, 4, 5, 3)



    prevcol = 1
    random.seed()
    for id in range(1, 1000):
        color = random.choice(range(1, 7))
        game.fall(id, random.choice(pieces), color)
    
    stdscr.refresh()
    while(game.getkey() != "q"):
        pass
Example #24
0
async def motion(lwin: LevelWindow):
    just_grounded = True

    curses.halfdelay(int(TIMER_SEC * 10))

    while True:
        async with level_locker:
            if just_grounded:
                lwin.float_new(any_block())

            undo_move = lwin.float_move('down')
            try:
                lwin.draw()
            except NotDrawable:
                undo_move()
                lwin.make_grounded()
                lwin.draw()
                just_grounded = True
                continue
            just_grounded = False

        try:
            await asyncio.wait_for(interact(lwin), timeout=TIMER_SEC)
        except asyncio.TimeoutError:
            continue
Example #25
0
    def setScreen(self, scr):
        """
		Set the screen and create the different windows 
		"""
        log(self.__class__.__name__, sys._getframe().f_code.co_name)
        self.stdscr = scr
        if self.stdscr != None:
            curses.curs_set(0)
            curses.start_color()
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.halfdelay(2 * 10)

            # setup all windows
            self.mainWindow = MainDisplay(0, self.stdscr)

            # self.stdscr.hline(self.WinPositions.headerBlock+self.headerWindow.getmaxyx()[0], 0, '-', 130)
            self.jobWindow = JobDisplay(0, self.stdscr)
            # self.stdscr.hline(self.WinPositions.summaryBlock+self.jobsWindow.getmaxyx()[0], 0, '-', 130)
            ##self.stdscr.hline(self.WinPositions.submitBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)

            ##self.erroWindow = curses.newwin(5, self.stdscr.getmaxyx()[1], self.WinPositions.debugBlock, 0)
            ##self.finalWindow = curses.newwin(3, self.stdscr.getmaxyx()[1], self.WinPositions.finalizeBlock, 0)
            ##self.finalWindow.addstr(0, 50, "Finalization job result")
            ##self.stdscr.hline(self.WinPositions.finalizeBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)
            ##
            ##self.stdscr.nooutrefresh()
            ##self.repaint()

            self.mainWindow.generate()
            self.jobWindow.generate()
            self.stdscr.refresh()
            self.activateMainWindow()
Example #26
0
def _start_hearts(win, names):
	curses.use_default_colors()
	curses.init_pair(1, curses.COLOR_RED,   -1)
	curses.init_pair(2, curses.COLOR_BLACK, -1)
	curses.nonl()
	curses.resetty()
	curses.curs_set(0)
	curses.halfdelay(1)
	game = HeartsGame(names)
	#game.force_first_card()
	game.render(win)
	curses.doupdate()
	while True:
		try:
			c = win.getch()
			if c == -1:
				idle(game, win)
				continue
			if c == ord('q'): break
			win.clear()
			if c in bindings:
				bindings[c](game)
			else:
				win.addstr(0, 0, "Unhandled input: %d" % c)
			game.render(win)
			curses.doupdate()
		except Exception:
			idle(game, win)
    def _start(self):
        """
        Initialize the screen and input mode.
        """
        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors = True
            except _curses.error:
                self.has_default_colors = False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10)  # use set_input_timeouts to adjust
        self.s.keypad(0)

        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys()

        super(Screen, self)._start()
Example #28
0
def main(window=curses.initscr()):
    curses.curs_set(0)
    curses.halfdelay(2)

    direction = {
        'w': Direction.UP,
        'a': Direction.LEFT,
        's': Direction.DOWN,
        'd': Direction.RIGHT
    }
    height = 10
    width = 20
    window.resize(height + 2, width + 2)
    game = Game(width=width,
                height=height,
                snake=Snake(cells=[Cell(3, 1),
                                   Cell(2, 1),
                                   Cell(1, 1)],
                            direction=Direction.RIGHT),
                apples=Apples(width=width,
                              height=height,
                              cells=frozenset(
                                  [Cell.get_random(width - 1, height - 1)])))
    input_ch = 0
    pause = False
    while chr(input_ch) != 'q':
        draw(window, game)
        input_ch = max(window.getch(), 0)
        if chr(input_ch) == 'p':
            pause = not pause
        if not pause:
            game = game.update(direction.get(chr(input_ch)))
Example #29
0
def run(stdscr):
    def paint(b):
        board = b.get_board()
        for i, r in enumerate(board.T):
            for j, c in enumerate(r):
                stdscr.addstr(j, i, c)

    k = 0
    b = Board(20, 40)

    curses.start_color()
    stdscr = curses.initscr()
    stdscr.clear()
    curses.halfdelay(2)
    stdscr.keypad(True)

    MOVE_KEYS = {
        curses.KEY_LEFT: b.move_left,
        curses.KEY_RIGHT: b.move_right,
        curses.KEY_UP: b.move_up,
        curses.KEY_DOWN: b.move_down
    }

    while k != ord('q'):
        paint(b)
        k = stdscr.getch()
        if k in MOVE_KEYS:
            MOVE_KEYS.get(k)()
        b.play()
Example #30
0
 def get_and_use_key_press(self):
     curses.raw()
     curses.cbreak()
     curses.meta(1)
     self.parent.curses_pad.keypad(1)
     if self.parent.keypress_timeout:
         curses.halfdelay(self.parent.keypress_timeout)
         ch = self._get_ch()
         if ch == -1:
             return self.try_while_waiting()
     else:
         self.parent.curses_pad.timeout(-1)
         ch = self._get_ch()
     # handle escape-prefixed rubbish.
     if ch == curses.ascii.ESC:
         #self.parent.curses_pad.timeout(1)
         self.parent.curses_pad.nodelay(1)
         ch2 = self.parent.curses_pad.getch()
         if ch2 != -1: 
             ch = curses.ascii.alt(ch2)
         self.parent.curses_pad.timeout(-1) # back to blocking mode
         #curses.flushinp()
     
     self.handle_input(ch)
     if self.check_value_change:
         self.when_check_value_changed()
     if self.check_cursor_move:
         self.when_check_cursor_moved()
         
     self.try_adjust_widgets()
Example #31
0
File: fe.py Project: jamwt/pyker
def _main(stdscr):
    curses.use_default_colors()
    curses.halfdelay(2)
    setup_colors()
    stdscr.clear()
    establish_base_size(stdscr)
    loop(stdscr)
Example #32
0
    def run(self, scr):
        """ Initialize and run the application """
        m = AsciiMap()
        curses.halfdelay(self.sleep)
        while True:
            now = int(time.time())
            refresh = self.fetch_data(now)
            m.set_data(self.data)
            try:
                m.draw(scr)
            except curses.error:
                raise Exception('Terminal window too small')
            scr.addstr(0, 1, 'Shodan Radar', curses.A_BOLD)
            scr.addstr(0, 40,
                       time.strftime("%c UTC", time.gmtime(now)).rjust(37),
                       curses.A_BOLD)

            # Key Input
            # q     - Quit
            event = scr.getch()
            if event == ord('q'):
                break

            # redraw window (to fix encoding/rendering bugs and to hide other messages to same tty)
            # user pressed 'r' or new data was fetched
            if refresh:
                m.window.redrawwin()
Example #33
0
    def run(self, scr):
        """ Initialize and run the application """
        m = AsciiMap()
        curses.halfdelay(self.sleep)
        while True:
            now = int(time.time())
            refresh = self.fetch_data(now)
            m.set_data(self.data)
            try:
                m.draw(scr)
            except curses.error:
                raise Exception('Terminal window too small')
            scr.addstr(0, 1, 'Shodan Radar', curses.A_BOLD)
            scr.addstr(0, 40, time.strftime("%c UTC", time.gmtime(now)).rjust(37), curses.A_BOLD)

            # Key Input
            # q     - Quit
            event = scr.getch()
            if event == ord('q'):
                break

            # redraw window (to fix encoding/rendering bugs and to hide other messages to same tty)
            # user pressed 'r' or new data was fetched
            if refresh:
                m.window.redrawwin()
Example #34
0
def init():
    # Don't display user input
    curses.noecho()
    # React to keys without pressing enter (700ms delay)
    curses.halfdelay(7)
    # Enumerate keys
    stdscr.keypad(True)
Example #35
0
def MainLoop(args):
  global errorCount, respawn
  curses.halfdelay(20)
  while 1:
    PollSystem()
    try:
      Display()
    except curses.error:
      0 # destroy the exception.  we're not interested in display errors

    c = stdscr.getch()
  
    try:

      if c == ord('0'):
        StartStopAll()
      elif c == ord('q'):
        break
      elif c == ord('r'):
        respawn = not respawn
      elif c >= ord('1') and c <= ord('9'):
        StartStop(c - ord('0'))
      elif c >= ord('a') and c <= ord('m'):
        StartStop(c - ord('a')+10)
    except:
      errorCount = errorCount + 1
Example #36
0
    def __init__(self, stdscr, state):
        self.state = state
        self.scr = stdscr
        curses.mousemask(curses.BUTTON1_CLICKED)
        curses.init_pair(1, WHITE_PIECES,
                         DARK_SQUARES)  # White piece on dark square
        curses.init_pair(2, WHITE_PIECES, LIGHT_SQUARES)  # White on bright
        curses.init_pair(3, BLACK_PIECES, DARK_SQUARES)  # Black on dark
        curses.init_pair(4, BLACK_PIECES, LIGHT_SQUARES)  # Black on bright
        curses.init_pair(5, 0, 12)  # Status bar
        curses.init_pair(6, 15, 9)  # [FAIL]
        curses.init_pair(7, 15, 2)  # [OK]
        curses.init_pair(8, 9, 0)  # Logo
        curses.init_pair(9, 14, 0)  # Bright white on black
        curses.init_pair(10, 10, 0)  # Past move from/to marker, move text
        curses.init_pair(11, 9, 4)  # Move selector from/to marker

        curses.halfdelay(1)
        self.scr.clear()

        self.widgets = [
            MoveReady(stdscr, state),
            Logo(stdscr, state),
            HelpPane(stdscr, state),
            Status(stdscr, state),
            ChessBoard(stdscr, state),
            StatusBar(stdscr, state),
            Engine(stdscr, state),
            Timer(stdscr, state),
            Info(stdscr, state),
            MoveList(stdscr, state),
            Promotions(stdscr, state),
            MoveInput(stdscr, state),
        ]
Example #37
0
    def start(self):
        """
		Initialize the screen and input mode.
		"""
        assert self._started == False

        self.s = curses.initscr()
        self._started = True
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors = True
            except _curses.error:
                self.has_default_colors = False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10)  # use set_input_timeouts to adjust
        self.s.keypad(0)
Example #38
0
    def appInit(self):
        # Init curses mode
        self._mainWin = curses.initscr()
        curses.noecho()  # turn off key echo
        curses.cbreak()  # turn of input buffering
        self._mainWin.keypad(
            1)  # Process function key escape sequences as single key events
        curses.curs_set(0)
        if curses.has_colors():
            curses.start_color()
            curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)
            curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
            curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLACK)
            curses.init_pair(7, curses.COLOR_YELLOW, curses.COLOR_BLACK)
            curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_BLUE)

        self._ttyCols = curses.COLS
        self._ttyRows = curses.LINES

        curses.halfdelay(30)

        self._mainWin.clear()
        self._mainWin.refresh()
Example #39
0
def main():
    a = CarControl()
    screen = curses.initscr()
    screen.keypad(True)
    curses.noecho()
    curses.cbreak()
    curses.halfdelay(5)

    try:
        while True:
            char = screen.getch()
            screen.clear()
            if char == curses.KEY_RIGHT:
                a.turn_right()
            elif char == curses.KEY_LEFT:
                a.turn_left()
            elif char == curses.KEY_UP:
                a.forward()
            elif char == curses.KEY_DOWN:
                a.backward()
            elif char == ord(' '):
                a.stop()
            elif char == ord('w'):
                a.speed_up(30)
            elif char == ord('s'):
                a.speed_down(30)
            elif char == -1:
                a.straight()
                a.stop()
    except KeyboardInterrupt:
        a.exit()
def main(window):
    next_key = None
    while True:
        curses.halfdelay(1)
        if next_key is None:
            key = window.getch()
        else:
            key = next_key
            next_key = None
            sleep(0.2)
        if key != -1:
            # KEY DOWN
            curses.halfdelay(3)
            action = actions.get(key)
            if action is not None:
#                action()
                pos = mc.player.getPos()
                x = pos.x
                y = pos.y
                z = pos.z
                mc.setBlock(x,y,z block,1)

            next_key = key
            while next_key == key:
                next_key = window.getch()
            # KEY UP
            robot.stop()
Example #41
0
File: ui.py Project: gwash/ranger
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

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

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

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
        self.update_size()
        self.is_on = True
Example #42
0
    def get_input(self, word: str, timeout: float, stdscr: Window) -> str:
        stdscr.addstr(INPUT_ROW, 0, f"{word} > ")
        stdscr.refresh()

        result = ""
        ch = 0
        while True:
            start = time.time()
            curses.halfdelay(int(timeout * 10))
            ch = stdscr.getch()
            if ch in (curses.KEY_BACKSPACE, 8, 127):
                result = result[:-1]
                stdscr.delch(INPUT_ROW, len(f"{word} > ") + len(result))
            else:
                result += chr(ch)
                if not word.startswith(result):
                    curses.beep()
                    stdscr.attron(curses.color_pair(1))
                stdscr.addch(INPUT_ROW,
                             len(f"{word} > ") + len(result) - 1, ch)
                if not word.startswith(result):
                    stdscr.attroff(curses.color_pair(1))
            stdscr.refresh()
            elapsed = time.time() - start
            timeout -= elapsed

            if result == word:
                return
Example #43
0
    def __init__(self, stdscr, args):
        self.stdscr = stdscr
        self.num_leds = args.number_leds
        self.server = args.SERVER

        self.ddp = DDP(args.SERVER, self.num_leds, args.lpc)

        self.assign_color_index = 0
        self.red = self.assign_color(curses.COLOR_BLACK, curses.COLOR_RED)
        self.green = self.assign_color(curses.COLOR_BLACK, curses.COLOR_GREEN)
        self.blue = self.assign_color(curses.COLOR_BLACK, curses.COLOR_BLUE)
        self.white = self.assign_color(curses.COLOR_BLACK, curses.COLOR_WHITE)
        self.off = self.assign_color(curses.COLOR_WHITE, curses.COLOR_BLACK)
        self.status_text = self.assign_color(curses.COLOR_WHITE,
                                             curses.COLOR_BLUE, curses.A_BOLD)
        self.error_text = self.assign_color(curses.COLOR_WHITE,
                                            curses.COLOR_RED, curses.A_BOLD)

        self.box = Box
        self.box_color = self.off
        self.box_index = 0

        curses.curs_set(False)
        curses.halfdelay(10)
        self.set_all_leds(self.off)
        self.resize()

        while True:
            self.send()
            self.draw()
            self.handle_input()
Example #44
0
    def setup_curses(self):
        self.stdscr = curses.initscr()
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        if (self.maxy < 6) or (self.maxx < 60):
            sys.stderr.write("Terminal window too small! Minimum size [70 x 6], actual [%d x %d]\n" % (self.maxx, self.maxy))
            print ("Terminal window too small! Minimum size [70 x 6], actual [%d x %d]\n" % (self.maxx, self.maxy))
            self.keep_running = False
            return

        curses.noecho()
        curses.halfdelay(1)

        self.title_bar = curses.newwin(1, self.maxx, 0, 0)
        self.help_bar = curses.newwin(1, self.maxx, self.maxy-1, 0)
        self.top_bar = curses.newwin(1, self.maxx, 1, 0)
        self.freq_list = curses.newwin(self.maxy-5, self.maxx, 2, 0)
        self.active1 = curses.newwin(1, self.maxx-15, self.maxy-3, 0)
        self.active2 = curses.newwin(1, self.maxx-15, self.maxy-2, 0)
        self.status1 = curses.newwin(1, 15, self.maxy-3, self.maxx-15)
        self.status2 = curses.newwin(1, 15, self.maxy-2, self.maxx-15)
        self.prompt = curses.newwin(1, 10, self.maxy-1, 0)
        self.text_win = curses.newwin(1, 11, self.maxy-1, 10)
        self.textpad = curses.textpad.Textbox(self.text_win)
        self.stdscr.refresh()

        self.title_help()
Example #45
0
def mifunc(stdscr):
    curses.halfdelay(1)
    w = curses.newwin(3, 20, 10, 1)
    ac = open("/dev/actuator", "rw")
    while 1:
        c = stdscr.getch()
        if c == ord('q'):
            break
        elif c == ord(' '):
            # stop
            ioctl(ac, AC_MSTOP)
        elif c == curses.KEY_RIGHT:
            ioctl(ac, AC_MWEST)
        elif c == curses.KEY_LEFT:
            ioctl(ac, AC_MEAST)
        elif c == ord('g'):
            newpos = int(curses.textpad.Textbox(w).edit())
            ioctl(ac, AC_WTARGET, struct.pack("i", newpos))
        elif c == ord('p'):
            newpos = int(curses.textpad.Textbox(w).edit())
            ioctl(ac, AC_WPOS, struct.pack("i", newpos))
        stat = ioctl(ac, AC_RSTATUS, "                ")
        mode = struct.unpack("I", stat[0:4])[0]
        state = struct.unpack("I", stat[4:8])[0]
        target = struct.unpack("i", stat[8:12])[0]
        position = struct.unpack("i", stat[12:16])[0]
        stdscr.addstr(2, 1, str(position))
        stdscr.clrtoeol()
        stdscr.addstr(3, 1, str(target))
        stdscr.clrtoeol()
        stdscr.addstr(4, 1, modes[mode])
        stdscr.clrtoeol()
        stdscr.addstr(5, 1, states[state])
        stdscr.clrtoeol()
Example #46
0
    def __init__(self, refresh_interval, total_columns):
        """Initialize the window with various settings."""
        self.total_columns = total_columns
        self.window = curses.initscr()

        # Initialize colors with red, green, yellow, blue, and white
        curses.start_color()
        curses.use_default_colors()
        for i in range(1, 5):
            curses.init_pair(i, i, -1)
        curses.init_pair(7, 7, -1)

        # Use the orange color if the terminal supports it, and magenta
        # otherwise
        if curses.COLORS == 256:
            self.COLOR_ORANGE = 208
        else:
            self.COLOR_ORANGE = curses.COLOR_MAGENTA
        curses.init_pair(self.COLOR_ORANGE, self.COLOR_ORANGE, -1)

        # Disable typing echo and hide the cursor
        curses.noecho()
        curses.curs_set(0)

        # Set the refresh interval
        curses.halfdelay(refresh_interval)

        self._update_dimensions()
Example #47
0
	def init(self):
		self.screen = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.screen.keypad(1)

		try:
			curses.curs_set(0)
		except:
			logging.warning("Cursor hiding is not supported")

		curses.halfdelay(1) # block for 0.1s

		if curses.has_colors():
			self.colors = True
			curses.start_color()

			curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
			curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
			curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
			curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
			curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)
		else:
			self.colors = False
			logging.warning("Colors are not supported")

		logging.info("Console I/O initialized")
Example #48
0
    def __init__(self, stdscr, clock_args=None):
        self.stdscr = stdscr
        curses.halfdelay(10)
        curses.curs_set(0)
        curses.use_default_colors()

        self.clock = PyClock(self.stdscr, clock_args)
        self.running = False
Example #49
0
def restore_state():
    global play_process
    if play_process != None:
        return

    draw_help()
    draw_results()
    curses.halfdelay(10)
Example #50
0
 def setup_screen(self):
   self.screen = curses.initscr()
   curses.noecho()       # no echo, we will render it
   curses.cbreak()       #
   curses.curs_set(0)    # hide cursor, we will fake it with inverted space
   curses.halfdelay(1)   # wait for 1/10 second when waiting for input
   self.screen.keypad(1)
   self.setup()
Example #51
0
 def __init__(self,screen,options):
  self.screen = screen 
  curses.halfdelay(1)
  self.infolines=['no port open']
  self.mode='main'
  self.options=options
  self.currcur=-1
  self.dlog=open('gui.log','w')
Example #52
0
def main():
    global stdscr
    global pause
    global toggle_digital
    global window_is_too_small

    stdscr = curses.initscr()
    curses.start_color()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)
    
    stdscr.nodelay(1)
    curses.halfdelay(1)
    
    curses.init_pair(10, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(11, curses.COLOR_BLACK, curses.COLOR_BLACK)
    curses.init_pair(12, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(13, curses.COLOR_BLUE, curses.COLOR_BLACK)
    
    fetch_screensize()
    recalc_coords(my_width, my_height)
    if window_is_too_small:
	curses.echo()
	curses.endwin()
	print "Screen too small."
	sys.exit(1)

    cas = time.time()

    while 1:
	try:
	    c = stdscr.getch()
	except KeyboardInterrupt:
	    break
	if c in [-1, curses.KEY_RESIZE]:
	    if c == -1:
		pass
	    elif c == curses.KEY_RESIZE:
		resize_handler()
	else:
	    if c == ord('d'):
		toggle_digital = not toggle_digital
		recalc_coords(my_width, my_height)
	    elif c == ord('q'): break
	    elif c == ord('p'):
		pause = not pause
	    else:
		pass
	if not pause:
	    cas = time.time()
	cas2 = time.localtime(cas)
        year, month, day, hour, minute, second, weekday = cas2[:7]
	hds = int(math.fmod(math.floor(cas * 100), 100))
        draw_watch(year, month, day, hour, minute, second, weekday, hds)

    curses.echo()
    curses.endwin()
Example #53
0
 def _getch(self, wait_tenths):
     if wait_tenths==0:
         return self._getch_nodelay()
     if wait_tenths is None:
         curses.cbreak()
     else:
         curses.halfdelay(wait_tenths)
     self.s.nodelay(0)
     return self.s.getch()
Example #54
0
File: gui.py Project: Kun-Qu/petsc
 def Welcome(self,stdscr):
   bootstrap.CursesInstall.CenterAddStr(stdscr,1,'Welcome to the ASE Project Installer')
   bootstrap.CursesInstall.CenterAddStr(stdscr,3,'The SIDL Language and compiler included were developed')
   bootstrap.CursesInstall.CenterAddStr(stdscr,4,'by the LLNL Babel Team (http://www.llnl.gov/CASC/components)')
   bootstrap.CursesInstall.CenterAddStr(stdscr,5,'(hit any key to continue)')
   stdscr.refresh()
   curses.halfdelay(50)
   c = stdscr.getch()
   curses.nocbreak()
Example #55
0
def notWrapperInit(): 
	screen = curses.initscr()
	curses.noecho()
	curses.cbreak()
	screen.keypad(1)
	# set custom tenths of a second to wait before giving up on waiting for input
	curses.start_color() 
	curses.halfdelay(5)
	return screen
Example #56
0
def init_window():
    "initialize the curses window"

    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    curses.halfdelay(delay)
    return stdscr
Example #57
0
def main(scr):    
    
    #scr.nodelay(1)
    scr.keypad(1)

    try:

        width = 90

        data = sp.check_output(['nvidia-smi', '-q', '-x'])
        root = ET.fromstring(data)
        
        timestamp = root.find('timestamp').text
        driver = root.find('driver_version').text
        n = int(root.find('attached_gpus').text)
        
        scr.addstr(0, 0, 'nvidia-top' + '%*s' % (width-10, 'ESC to quit'))
        scr.addstr(1, 0, 'Timestamp:\t' + timestamp)
        scr.addstr(2, 0, 'Driver Version:\t' + driver)
        scr.addstr(3, 0, 'Number of GPUs:\t' + repr(n))

        gpus = root.findall('gpu')
        for ind in range(len(gpus)):
            memt = gpus[ind].find('fb_memory_usage').find('total').text
            scr.addstr(3+ind*2, 0, 'GPU %d Memory:  ' % ind + memt)
            powt = gpus[ind].find('power_readings').find('power_limit').text
            scr.addstr(4+ind*2, 0, 'GPU %d Power Limit:  ' % ind + powt)

        n*=2
        # Drawing header
        scr.addstr(5+n, 0, '-' * width)
        scr.addstr(6+n, 0, '%3s' % '#' + '%23s' % 'Name' + '%13s' % 'Mem. Use' + '%10s' % '% Mem.' + '%13s' % 'GPU Util.' +'%12s' % 'Power Use' + '%9s' % 'Temp.')
        scr.addstr(7+n, 0, '-' * width)
        
        # 10 tenths = 1 sec <- this is the polling frequency
        crs.halfdelay(8)
        #t0 = 0
        while (1):
            #if (time.clock() - t0) > 1.0:
            data = sp.check_output(['nvidia-smi', '-q', '-x'])
            root = ET.fromstring(data)
            
            timestamp = root.find('timestamp').text
            scr.addstr(1, 0, 'Timestamp:\t' + timestamp)
            
            display_info(root, scr)
            #t0 = time.clock()
            scr.refresh()
                
            
            if scr.getch() == 27:
                break

    except:

        print 'Something went wrong! Exception handling is pretty basic right now.'
Example #58
0
def main():
    arg_parser = argparse.ArgumentParser(description="ifstat - network interface statistics utility")
    arg_parser.add_argument(dest='device', help='The device name to get stats for')
    arg_parser.add_argument('--interval', '-i', dest='interval', default=1.0, type=float, help='Interval to gather and display stats')

    args = arg_parser.parse_args()

    if args.device not in pcap.findalldevs():
        sys.stderr.write('Error: No such device %s \n' % (args.device, ))
        return

    collector = getstats.StatCollector(args.device)
    collector.start()
    raw_stats = collector.get_stats()
    stat_processor = StatProcessor(raw_stats)

    locale.setlocale(locale.LC_ALL, '')
    window = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    window.keypad(1)
    # XXX: halfdelay is in tenths of seconds
    curses.halfdelay(int(args.interval * 10))
    colors = _init_colors()
    last_time = time.time()
    sessions_pad = SessionsPad(colors=colors)
    device_pad = DevicePad(args.device, args.interval, colors=colors, ylocation=sessions_pad.get_y_size())
    current_stats = {"device": {}, "sessions": []}
    try:
        running = True
        while running:
            # XXX: Get & process new stats only when the intervals have passed
            current_time = time.time()
            if current_time - last_time >= args.interval:
                raw_stats = collector.get_stats()
                current_stats = stat_processor.process_new_stats(raw_stats, args.interval)
                last_time = current_time

                maxy, maxx = window.getmaxyx()
                sessions_pad.display(maxy, maxx, current_stats["sessions"])
                device_pad.display(maxy, maxx, current_stats["device"])

            key = window.getch()

            if key != -1:
                sessions_pad.key(key)
                device_pad.key(key)
            if key == ord('q'):
                collector.stop()
                running = False

    finally:
        curses.nocbreak()
        curses.echo()
        curses.endwin()
Example #59
0
    def get_and_use_key_press(self):
        global TEST_SETTINGS
        trace = False

        if (TEST_SETTINGS['TEST_INPUT'] is None) and (TEST_SETTINGS['INPUT_GENERATOR'] is None):
            curses.raw()
            curses.cbreak()
            curses.meta(1)
            self.parent.curses_pad.keypad(1)
            if self.parent.keypress_timeout:
                curses.halfdelay(self.parent.keypress_timeout)
                ch = self._get_ch()
                if ch == -1:
                    return self.try_while_waiting()
            else:
                self.parent.curses_pad.timeout(-1)
                ch = self._get_ch()
            # handle escape-prefixed rubbish.
            if ch == curses.ascii.ESC:
                #self.parent.curses_pad.timeout(1)
                self.parent.curses_pad.nodelay(1)
                ch2 = self.parent.curses_pad.getch()
                if ch2 != -1:
                    ch = curses.ascii.alt(ch2)
                self.parent.curses_pad.timeout(-1) # back to blocking mode
                #curses.flushinp()
        elif (TEST_SETTINGS['INPUT_GENERATOR']):
            self._last_get_ch_was_unicode = True
            try:
                ch = next(TEST_SETTINGS['INPUT_GENERATOR'])
            except StopIteration:
                if TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT']:
                    TEST_SETTINGS['INPUT_GENERATOR'] = None
                    return
                else:
                    raise ExhaustedTestInput
        else:
            self._last_get_ch_was_unicode = True
            try:
                ch = TEST_SETTINGS['TEST_INPUT'].pop(0)
                TEST_SETTINGS['TEST_INPUT_LOG'].append(ch)
            except IndexError:
                if TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT']:
                    TEST_SETTINGS['TEST_INPUT'] = None
                    return
                else:
                    raise ExhaustedTestInput

        # if trace: g.trace('Widget', self.__class__.__name__, ch, chr(ch))
        if trace: g.pr('Widget', self.__class__.__name__, 'get_and_use_key_press', ch, chr(ch))
        self.handle_input(ch)
        if self.check_value_change:
            self.when_check_value_changed()
        if self.check_cursor_move:
            self.when_check_cursor_moved()
        self.try_adjust_widgets()