Example #1
0
 def run(self):
   """Run the editor main loop (read and execute command)"""
   try:
     screen = curses.initscr()
     curses.noecho()
     curses.raw()
     curses.meta(1)
     screen.keypad(1)
     height, width = screen.getmaxyx()
     self._width = width
     self._height = height
     self._window.set_size(width, height-1)
     self.redisplay(screen)
     while 1:
       cmd = self.read_command(screen)
       if cmd is None:
         curses.beep()
         self.message("No command on key '%s'" % self.last_key())
       else:
         self.message(None)
         cmd.run()
       self.redisplay(screen)
   finally:
     screen.keypad(0)
     curses.meta(0)
     curses.noraw()
     curses.endwin()
Example #2
0
 def init(self):
     self.window = curses.initscr()
     self.initted = True
     self.ymax, self.xmax = self.window.getmaxyx()
     terminfo = curses.longname()
     assert '256' in terminfo  # your env TERM must be xterm-256color!
     assert curses.has_colors()
     curses.start_color()
     curses.use_default_colors()
     ctr = 1
     for fg in CLRS:
         for bg in CLRS:
             if ctr <= curses.COLORS-1 and fg != bg:
                 curses.init_pair(ctr, CLRS[fg], CLRS[bg])
                 pairs[(fg,bg)] = curses.color_pair(ctr)
                 ctr += 1
     curses.meta(1)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     curses.delay_output(0)
     curses.mouseinterval(150)
     availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS)
     assert availmask != 0  # mouse must be available!
     self.window.leaveok(1)
     self.window.scrollok(0)
     self.window.keypad(1)
     if NONBLOCKING:
         self.window.nodelay(1)
         self.window.timeout(NONBLOCKING_TIMEOUT)
     else:
         self.window.nodelay(0)
         self.window.timeout(-1)
     self.window.refresh()
Example #3
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 #4
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 #5
0
 def run(self):
     """Run the editor main loop (read and execute command)"""
     try:
         screen = curses.initscr()
         curses.noecho()
         curses.raw()
         curses.meta(1)
         screen.keypad(1)
         height, width = screen.getmaxyx()
         self._width = width
         self._height = height
         self._window.set_size(width, height - 1)
         self.redisplay(screen)
         while 1:
             cmd = self.read_command(screen)
             if cmd is None:
                 curses.beep()
                 self.message("No command on key '%s'" % self.last_key())
             else:
                 self.message(None)
                 cmd.run()
             self.redisplay(screen)
     finally:
         screen.keypad(0)
         curses.meta(0)
         curses.noraw()
         curses.endwin()
Example #6
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 #7
0
    def __enter__(self) -> curses.window:

        locale.setlocale(locale.LC_ALL, '')
        current_locale = locale.getpreferredencoding()
        assert current_locale == 'UTF-8', current_locale

        with DelayedKeyboardInterrupt():

            self.stdscr = curses.initscr()
            curses.start_color()
            if curses.has_colors():
                curses.use_default_colors()
                for i in range(0, curses.COLORS):  # pylint: disable=W8205
                    curses.init_pair(i, i, -1)  # pylint: disable=W8205
                curses.COLOR_BLACK = 8
            else:
                curses.COLORS = 1

            curses.meta(True)
            curses.noecho()
            curses.cbreak()
            with suppress(Exception):
                curses.curs_set(0)

            self.stdscr.keypad(True)
            self.stdscr.leaveok(True)
            self.stdscr.scrollok(False)

            self.stdscr.clear()
            return self.stdscr
Example #8
0
 def start_app(self):
     # start the application
     self.screen = curses.initscr()
     curses.noecho()
     curses.cbreak()
     curses.meta(1)
     self.screen.keypad(1)
Example #9
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 #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 setupcolors(stdscr, f, *args):
    def makeColor(fg, bg):
        global nextColorPair
        if curses.has_colors():
            curses.init_pair(nextColorPair, fg, bg)
            c = curses.color_pair(nextColorPair)
            nextColorPair += 1
        else:
            c = curses.A_NORMAL

        return c

    curses.meta(1)  # allow "8-bit chars"

    colors['red'] = curses.A_BOLD | makeColor(curses.COLOR_RED, curses.COLOR_BLACK)
    colors['blue'] = curses.A_BOLD | makeColor(curses.COLOR_BLUE, curses.COLOR_BLACK)
    colors['green'] = curses.A_BOLD | makeColor(curses.COLOR_GREEN, curses.COLOR_BLACK)
    colors['brown'] = makeColor(curses.COLOR_YELLOW, curses.COLOR_BLACK)
    colors['yellow'] = curses.A_BOLD | colors['brown']
    colors['cyan'] = makeColor(curses.COLOR_CYAN, curses.COLOR_BLACK)
    colors['magenta'] = makeColor(curses.COLOR_MAGENTA, curses.COLOR_BLACK)

    colors['red_bg'] = makeColor(curses.COLOR_WHITE, curses.COLOR_RED)
    colors['blue_bg'] = makeColor(curses.COLOR_WHITE, curses.COLOR_BLUE)
    colors['green_bg'] = makeColor(curses.COLOR_BLACK, curses.COLOR_GREEN)
    colors['brown_bg'] = colors['yellow_bg'] = makeColor(curses.COLOR_BLACK, curses.COLOR_YELLOW)
    colors['cyan_bg'] = makeColor(curses.COLOR_BLACK, curses.COLOR_CYAN)
    colors['magenta_bg'] = makeColor(curses.COLOR_BLACK, curses.COLOR_MAGENTA)

    return f(stdscr, *args)
Example #12
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 #13
0
def _main():  # __main_
    """Program main function."""
    try:
        window = curses.initscr()       # Window object
        window.clear()                  # Erase and repaint on update
        availmask, oldmask = \
                curses.mousemask(curses.BUTTON1_PRESSED | 
                                 curses.BUTTON1_RELEASED)  # Record mouse evnts
        curses.mouseinterval(1)         # Max ms click interval
        curses.start_color()            # To use colors
        curses.use_default_colors()     # Default term colors eg transparency
        curses.meta(1)                  # 8b characters
        curses.noecho()                 # No auto echo keys to window
        curses.cbreak()                 # Don't wait for <Enter>
        window.keypad(1)                # Use special char values
        window.nodelay(1)               # Nonblocking getch/getstr
        window.timeout(0)               # Nonblocking gets, 0 in ms
        window.border()                 # Or box on edges
        window.leaveok(0)               # Virtual screen cursor after update
        curses.curs_set(0)              # Invisible curser
        window.scrollok(0)              # Cursor moves off page don't scroll
        window.bkgd(' ', 0)             # Set background char and attr
        example(window)
    finally:
        window.move(0, 0)
        curses.nocbreak()
        window.keypad(0)
        curses.echo()
        curses.endwin()
Example #14
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 #15
0
    def setup(self):
        if tty:
            self.tcattr = tty.tcgetattr(sys.stdin.fileno())
            tcattr = tty.tcgetattr(sys.stdin.fileno())
            tcattr[0] = tcattr[0] & ~(tty.IXON)
            tty.tcsetattr(sys.stdin.fileno(), tty.TCSANOW, tcattr)

        self.w = curses.initscr()
        curses.cbreak()
        curses.noecho()
        try: curses.meta(1)
        except: pass
        self.cursor(0)
        signal.signal(signal.SIGCHLD, signal.SIG_IGN)
        signal.signal(signal.SIGHUP, self.handler_quit)
        signal.signal(signal.SIGINT, self.handler_quit)
        signal.signal(signal.SIGTERM, self.handler_quit)
        signal.signal(signal.SIGWINCH, self.handler_resize)
        
        self.win_root = RootWindow(None)
        self.win_root.update()

        self.win_status = self.win_root.win_status
        self.status = self.win_status.status
        self.win_podlist = self.win_root.win_tab.win_podlist

        self.timeout = Timeout()
Example #16
0
 def start_app(self):
     # start the application
     self.screen = curses.initscr()
     curses.noecho()
     curses.cbreak()
     curses.meta(1)
     self.screen.keypad(1)
Example #17
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()
Example #18
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()
Example #19
0
def begin_curses():
    win = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.nonl()
    curses.curs_set(0)
    curses.meta(1)
    curses.start_color()
    curses.use_default_colors()
    return win
Example #20
0
def begin_curses():
    win = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.nonl()
    curses.curs_set(0)
    curses.meta(1)
    curses.start_color()
    curses.use_default_colors()
    return win
Example #21
0
File: df.py Project: nikisix/df
def main(stdscr):
	"""main()
	This will be called by curses.wrapper() so 
	that the program will exit properly.
	Be sure to use the stdscr that is sent to this function
	via the wrapper() function or else the keys won't work
	properly.
	"""	
	global g_selected_txt

	# Read command-line options
	# I AM NOT USING COMMAND LINE OPTION YET
	try:
		optlist, args = getopt.getopt(sys.argv[1:] \
			,"vh", ["verbose", "help"])
	except (getopt.GetoptError, err):
		print(str(err))
		usage()
		sys.exit(12)
	#
	for o, a in optlist:
		if (o in ("-h", "--help")):
			usage()
			sys.exit()
		elif (o in ("-v", "--verbose")):
			g_debug_level = 6

	#
	# Load options from ~/.dfconfig
	load_options()
	#
	stdscr.clear()
	curses.noecho()
	stdscr.keypad(1)#allos some escapekeys?
	curses.meta(1)# allow 8-bit characters
	#curses.start_color()# wrapper() should start color
	#
	#
	the_path = posix.getcwd()
	code = 1
	while code in [1, 2]:
		# A code of 1 means to list the new directory
		# and wait for the user to select a file
		# or directory.
		# A code of 2 means to open a shell at the
		# specified directory.
		(l, fmt) = list_files(the_path)
		# Instantiate the main object and then run it
		w = SelectionWindow(stdscr, 0, 1, l, fmt, the_path)
		(code, the_path) = w.key_loop()
	g_selected_txt = the_path

	# Returning a text value to curses.wrapper()
	# does nothing, so just return zero.
	return(0)
Example #22
0
def main(stdscr):
    """main()
	This will be called by curses.wrapper() so 
	that the program will exit properly.
	Be sure to use the stdscr that is sent to this function
	via the wrapper() function or else the keys won't work
	properly.
	"""
    global g_selected_txt

    # Read command-line options
    # I AM NOT USING COMMAND LINE OPTION YET
    try:
        optlist, args = getopt.getopt(sys.argv[1:] \
         ,"vh", ["verbose", "help"])
    except (getopt.GetoptError, err):
        print(str(err))
        usage()
        sys.exit(12)
    #
    for o, a in optlist:
        if (o in ("-h", "--help")):
            usage()
            sys.exit()
        elif (o in ("-v", "--verbose")):
            g_debug_level = 6

    #
    # Load options from ~/.dfconfig
    load_options()
    #
    stdscr.clear()
    curses.noecho()
    stdscr.keypad(1)  #allos some escapekeys?
    curses.meta(1)  # allow 8-bit characters
    #curses.start_color()# wrapper() should start color
    #
    #
    the_path = posix.getcwd()
    code = 1
    while code in [1, 2]:
        # A code of 1 means to list the new directory
        # and wait for the user to select a file
        # or directory.
        # A code of 2 means to open a shell at the
        # specified directory.
        (l, fmt) = list_files(the_path)
        # Instantiate the main object and then run it
        w = SelectionWindow(stdscr, 0, 1, l, fmt, the_path)
        (code, the_path) = w.key_loop()
    g_selected_txt = the_path

    # Returning a text value to curses.wrapper()
    # does nothing, so just return zero.
    return (0)
Example #23
0
def setupcolors(stdscr, f, *args):
    curses.raw()  # get control keys instead of signals
    curses.meta(1)  # allow "8-bit chars"
    curses.mousemask(-1)  # even more than curses.ALL_MOUSE_EVENTS
    curses.mouseinterval(0)  # very snappy but does not allow for [multi]click
    curses.mouseEvents = {}

    for k in dir(curses):
        if k.startswith('BUTTON') or k == 'REPORT_MOUSE_POSITION':
            curses.mouseEvents[getattr(curses, k)] = k

    return f(stdscr, *args)
Example #24
0
def init():
    screen=curses.initscr()
    curses.start_color()
    curses.cbreak()
    curses.meta(1)
    curses.noecho()
    curses.nonl()
    curses.def_prog_mode()
    curses.endwin()
    curses.def_shell_mode()
    curses.reset_prog_mode()
    return Screen(screen)
Example #25
0
def init():
    screen = curses.initscr()
    curses.start_color()
    curses.cbreak()
    curses.meta(1)
    curses.noecho()
    curses.nonl()
    curses.def_prog_mode()
    curses.endwin()
    curses.def_shell_mode()
    curses.reset_prog_mode()
    return Screen(screen)
Example #26
0
def colortest():
    # init
    window = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    print( curses.COLORS )
    # assign 'default' pairs, pairs are assigned +1 MORE than the color value!
    cnt = 1
    for fg in range( curses.COLORS ):
        #curses.init_pair( each + 1, each, -1 )
        for bg in range( curses.COLORS ):
            curses.init_pair( fg << 3 | bg, fg, bg )
            cnt += 1
         # next
    # next
    # custom/non-default pair
    #curses.init_pair( 1 + 2 * curses.COLORS, 0x0F, 0x15 )  # white on cobalt according to colors above ???
    #curses.init_pair( 4321, 0xd5, 0x81 )  # hot pink on violet according to colors above ???

    # setup
    curses.meta(1)
    curses.noecho()
    curses.cbreak()
    window.leaveok(1)
    window.scrollok(0)
    window.keypad(1)
    window.refresh()

    # print all pairs in their colors
    for fg in range( curses.COLORS ):
        for bg in range( curses.COLORS ):
            window.addstr( " %02X " % ( fg << 3 | bg ), curses.color_pair( fg << 3 | bg ) )  # these are all perfect
        # next
        window.addstr("\n")
    # next
    #window.addstr(hex(1 + 2*curses.COLORS).join('  '), curses.color_pair(1 + 2*curses.COLORS))  # nope: this prints 0,-1: black on default ???
    #window.addstr(hex(4321).join('  '), curses.color_pair(4321))  # nope: this prints 0xe1,-1: pinkish on default ???

    # update
    window.noutrefresh()
    curses.doupdate()

    # pause
    window.getch()

    # teardown
    window.leaveok(0)
    window.scrollok(1)
    window.keypad(0)
    curses.echo()
    curses.nocbreak()
    curses.endwin()
Example #27
0
def main(w):
    curses.raw()
    curses.meta(True)
    w.keypad(True)

    key = None
    w.addstr(_MSG)
    while key != 'Q':
        key, alt = get_key(w)
        w.clear()
        print_key(w, key, alt)

    curses.endwin()
Example #28
0
 def user_input(self):
     while not self.main_future.cancelled():
         curses.raw()
         curses.cbreak()
         curses.meta(1)
         event = yield from asyncio.async(self.get_wch())
         if event is None:
             continue
         if event == curses.KEY_MOUSE:
             self.loop.call_soon(partial(self.mouse_event_handler,
                                         *curses.getmouse()))
         else:
             self.loop.call_soon(partial(self.key_event_handler, event))
def setup_curses():
    '''Initialize the curses module'''
    initscr = curses.initscr()
    if curses.has_colors():
        curses.start_color()
    curses.noecho()
    curses.cbreak()
    curses.meta(1)
    try:
        curses.curs_set(0)
    except curses.error:
        pass
    return initscr
Example #30
0
    def init_screen(self):

        screen = curses.initscr()
        curses.noecho()  # Dont print anything
        curses.cbreak()
        screen.keypad(1)  # Use of arrow keys
        curses.curs_set(0)  # Dont display cursor
        curses.meta(1)  # allow 8bits inputs
        self.init_colors()
        self.maxyx = screen.getmaxyx()

        screen.refresh()
        self.screen = screen
Example #31
0
def setup_curses():
    '''Initialize the curses module'''
    initscr = curses.initscr()
    if curses.has_colors():
        curses.start_color()
    curses.noecho()
    curses.cbreak()
    curses.meta(1)
    try:
        curses.curs_set(0)
    except curses.error:
        pass
    return initscr
Example #32
0
 def __init__(self):
     self.stdscr = c.initscr()
     c.noecho()
     c.cbreak()
     c.curs_set(0)
     c.meta(1)
     c.setupterm()
     if c.has_colors():
         c.start_color()
         c.use_default_colors()
         self.CreatePairs()
     self.stdscr.bkgdset(0,c.color_pair(1))
     self.stdscr.refresh()
     return
Example #33
0
 def __init__(self, cursesScreen):
     self.debugMouseEvent = (0, 0, 0, 0, 0)
     self.exiting = False
     self.cursesScreen = cursesScreen
     self.ch = 0
     curses.mousemask(-1)
     curses.mouseinterval(0)
     # Enable mouse tracking in xterm.
     sys.stdout.write('\033[?1002;h')
     #sys.stdout.write('\033[?1005;h')
     curses.meta(1)
     # Access ^c before shell does.
     curses.raw()
     # Enable Bracketed Paste Mode.
     sys.stdout.write('\033[?2004;h')
     # Push the escape codes out to the terminal. (Whether this is needed seems
     # to vary by platform).
     sys.stdout.flush()
     try:
         curses.start_color()
         if not curses.has_colors():
             userMessage("This terminal does not support color.")
             self.quitNow()
         else:
             curses.use_default_colors()
     except curses.error as e:
         app.log.error(e)
     app.log.startup(u"curses.COLORS", curses.COLORS)
     if 0:
         assert curses.COLORS == 256
         assert curses.can_change_color() == 1
         assert curses.has_colors() == 1
         app.log.detail("color_content:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
         for i in range(16, curses.COLORS):
             curses.init_color(i, 500, 500, i * 787 % 1000)
         app.log.detail("color_content, after:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
     if 1:
         #rows, cols = self.cursesScreen.getmaxyx()
         cursesWindow = self.cursesScreen
         cursesWindow.leaveok(1)  # Don't update cursor position.
         cursesWindow.scrollok(0)
         cursesWindow.timeout(10)
         cursesWindow.keypad(1)
         app.window.mainCursesWindow = cursesWindow
     self.zOrder = []
Example #34
0
 def __init__(self, cursesScreen):
     self.clicks = 0
     self.debugMouseEvent = (0, 0, 0, 0, 0)
     self.exiting = False
     self.modalUi = None
     self.modeStack = []
     self.priorClick = 0
     self.savedMouseButton1Down = False
     self.savedMouseWindow = None
     self.savedMouseX = -1
     self.savedMouseY = -1
     self.cursesScreen = cursesScreen
     self.ch = 0
     curses.mousemask(-1)
     curses.mouseinterval(0)
     # Enable mouse tracking in xterm.
     sys.stdout.write('\033[?1002;h\n')
     #sys.stdout.write('\033[?1005;h\n')
     curses.meta(1)
     # Access ^c before shell does.
     curses.raw()
     # Enable Bracketed Paste Mode.
     sys.stdout.write('\033[?2004;h\n')
     #curses.start_color()
     curses.use_default_colors()
     if 0:
         assert (curses.COLORS == 256)
         assert (curses.can_change_color() == 1)
         assert (curses.has_colors() == 1)
         app.log.detail("color_content:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
         for i in range(16, curses.COLORS):
             curses.init_color(i, 500, 500, i * 787 % 1000)
         app.log.detail("color_content, after:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
     self.setUpPalette()
     if 1:
         #rows, cols = self.cursesScreen.getmaxyx()
         cursesWindow = self.cursesScreen
         cursesWindow.leaveok(1)  # Don't update cursor position.
         cursesWindow.scrollok(0)
         cursesWindow.timeout(10)
         cursesWindow.keypad(1)
         self.top, self.left = cursesWindow.getyx()
         self.rows, self.cols = cursesWindow.getmaxyx()
         app.window.mainCursesWindow = cursesWindow
     self.zOrder = []
Example #35
0
    def init_screen(self):

        self.screen = curses.initscr()
        curses.noecho()  # Dont print anything
        # curses.cbreak()
        self.screen.timeout(500)
        self.screen.keypad(1)  # Use of arrow keys
        try:
            curses.curs_set(0)  # Dont display cursor
        except curses.error:
            pass
        curses.meta(1)  # allow 8bits inputs
        self.init_colors()
        self.maxyx = self.screen.getmaxyx()

        self.screen.refresh()
Example #36
0
 def get_and_use_key_press(self):
     global TEST_SETTINGS
     if TEST_SETTINGS['TEST_INPUT'] 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()
     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
     
     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 #37
0
    def get_and_use_key_press(self):
        global TEST_SETTINGS
        if TEST_SETTINGS['TEST_INPUT'] 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()
        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

        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 #38
0
def agwInitCurses(): # initialize the curses environment                                                                           
    if (not curses.has_colors()):
        print("UH OH, this terminal does not support color! Quitting.")
        sys.exit(1)
        pass
    curses.start_color()
    ## Initialize some colors below. The first number is an ID and must be UNIQUE.
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    ## Done initializing some colors
    CURSES_INVISIBLE_CURSOR = 0
    CURSES_VISIBLE_CURSOR = 1
    CURSES_HIGHLIGHTED_CURSOR = 2
    try:
        curses.curs_set(CURSES_INVISIBLE_CURSOR) # Don't show a blinking cursor                                                  
    except(curses.error):
        print("Unable to set cursor state to \"invisible\"")
        pass
    curses.meta(1)  # Allow 8-bit chars
    return
Example #39
0
def tui_main(scr):
    curses.raw()
    curses.meta(1)
    curses.mousemask(-1)
    curses.curs_set(False)

    with contextlib.suppress(curses.error):
        curses.curs_set(0)
    scr.timeout(30)

    inputfns = []

    for arg in sys.argv[1:]:
        if arg in ['-d', '--debug']: options.debug = True
        else:
            inputfns.append(arg)

    global app
    app = DarkDraw(*(Tile(fn) for fn in inputfns))
    app.run(scr)
Example #40
0
def init_screen():
    screen = curses.initscr()  # Window object
    screen.clear()  # Erase and repaint on update
    availmask, oldmask = curses.mousemask(
            curses.BUTTON1_PRESSED | curses.BUTTON1_RELEASED | \
                    curses.BUTTON1_DOUBLE_CLICKED)  # Record mouse evnts
    curses.mouseinterval(0)  # Max ms click interval
    curses.start_color()  # To use colors
    curses.use_default_colors()  # Default term colors eg transparency
    curses.init_pair(COLOR_RED, curses.COLOR_RED, -1)
    curses.init_pair(COLOR_BLUE, curses.COLOR_BLUE, -1)
    curses.meta(1)  # 8b characters
    curses.noecho()  # No auto echo keys to window
    curses.cbreak()  # Don't wait for <Enter>
    screen.keypad(1)  # Use special char values
    screen.nodelay(1)  # Nonblocking getch/getstr
    screen.timeout(1)  # Nonblocking gets, 0 in ms
    screen.leaveok(0)  # Virtual screen cursor after update
    curses.curs_set(0)  # Invisible curser
    screen.scrollok(0)  # Cursor moves off page don't scroll
    return screen
Example #41
0
    def __exit__(self, _exc_type: Optional[Type[BaseException]],
                 exc_value: Optional[BaseException],
                 _traceback: Optional[TracebackType]) -> None:

        if exc_value is not None:
            with suppress(Exception):
                self.show_error(exc_value)

        with DelayedKeyboardInterrupt():

            self.stdscr.scrollok(True)
            self.stdscr.leaveok(False)
            self.stdscr.keypad(False)

            with suppress(Exception):
                curses.curs_set(1)
            curses.nocbreak()
            curses.echo()
            curses.meta(False)

            curses.endwin()
Example #42
0
	def start(self):
		self.running = True
	
		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:
				self.has_default_colors=False
		self._setup_colour_pairs()
		curses.noecho()
		curses.meta(1)
		curses.halfdelay(10) # don't wait longer than 1s for keypress
		self.s.keypad(0)
		self.s.scrollok(1)

		Thread.start(self)
Example #43
0
 def __init__(self, cursesScreen):
     self.debugMouseEvent = (0, 0, 0, 0, 0)
     self.exiting = False
     self.modalUi = None
     self.modeStack = []
     self.priorClick = 0
     self.savedMouseWindow = None
     self.savedMouseX = -1
     self.savedMouseY = -1
     self.stdscr = cursesScreen
     self.ch = 0
     curses.mousemask(-1)
     curses.mouseinterval(0)
     # Enable mouse tracking in xterm.
     print '\033[?1002;h'
     #print '\033[?1005;h'
     curses.meta(1)
     # Access ^c before shell does.
     curses.raw()
     #curses.start_color()
     curses.use_default_colors()
     if 0:
         assert (curses.COLORS == 256)
         assert (curses.can_change_color() == 1)
         assert (curses.has_colors() == 1)
         app.log.detail("color_content:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
         for i in range(16, curses.COLORS):
             curses.init_color(i, 500, 500, i * 787 % 1000)
         app.log.detail("color_content, after:")
         for i in range(0, curses.COLORS):
             app.log.detail("color", i, ": ", curses.color_content(i))
     self.showPalette = 0
     self.shiftPalette()
     self.zOrder = []
Example #44
0
 def __init__(self, parent, name, height, width, children, y = -1, x = -1 ):
     Component.__init__(self,name,0)
     self.height = height
     self.width = width
     self.children = children
     max_y,max_x = parent.getmaxyx()
     curses.raw()                                           
     if x < 0:
         self.win = parent.subwin(height,width,(max_y/2)-(height/2),(max_x/2)-(width/2))
     else:
         self.win = parent.subwin(height,width,y,x)
         
     self.win.clear()
     self.win.keypad(1)
     curses.meta(1)
     self.max_y,self.max_x = self.win.getmaxyx()
     self.setparent(parent)
     for c in self.children:
         c.setparent(self.win)
     self.current = 0
     self.focus_list = []
     self.hist_idx = 0
     self.enable_history = True
     self.focus()
Example #45
0
						newStart = random.randint(start+1,start+length-(portalSize+1))
						#
						boxR.join( (adjR[0],newStart,portalSize) )
						boxL.join( (adjL[0],newStart,portalSize) )
						hasjoined = True
						break
			if hasjoined:
				break;
		return L + R



if __name__ == '__main__':
	scr = curses.initscr()
	curses.curs_set(0)
	curses.meta(True)
	maxYX = scr.getmaxyx()
	minYX = scr.getbegyx()
	
	#maxYX = (20,20)
	#minYX = (0,0)
	
	width = maxYX[1] - minYX[1]-5
	height = maxYX[0] - minYX[0]-5
	boxes = [ box(3,3,width,height) ]
	#print "DIM ",width,height
	boxes = split(boxes[0],8,4)
	for b in boxes:
		b.draw()
		#print "box: ",`b.x`,`b.y`,`b.width`,`b.height`
	scr.refresh()
Example #46
0
                                        stdscr.getmaxyx()[1])), arxiv.data)) +
        1, y_stdscr)
    # the lenght of pad (since stdscr and stdpad will have the same width
    # we can use stdscr to comute its lenght)
    # XXX: without +1: last line is repeated till the end of stdscr. Why?
    stdpad = curses.newpad(ypad, x_stdscr)
    (ytop, xtop) = (0, 0)  # stdpad
    curses.start_color()
    curses.use_default_colors()
    # use this for transparency (then -1 can be used as the default background
    # color)
    curses.noecho()  # turn off automatic echoing of keys to the screen
    curses.cbreak()  # react to keays instantly (without requireing Enter)
    stdscr.keypad(1)
    curses.curs_set(0)
    curses.meta(1)

    curses.init_pair(0, -1, -1)
    # no hightlight
    curses.init_pair(1, curses.COLOR_RED, -1)
    # it is used when the author matches a pattern.
    # also used to hightligh that the entry is in the sqlite3 database
    # also to hightlight the title in the detailed view.
    curses.init_pair(2, curses.COLOR_GREEN, -1)
    # it is used when the title or abstract matches a pattern.
    # also used to highlight numbers of entries on the left
    curses.init_pair(3, curses.COLOR_RED, -1)
    curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)
    curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_GREEN)

    def clear_status():
Example #47
0
def cursessetup():
    # Initialize curses library
    stdscr = curses.initscr()

    # Turn off echoing of keys
    curses.noecho()

    # 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)

    # allow 8-bit characters to be input
    curses.meta(1)

    # enter raw mode, thus disabling interrupt, quit, suspend and flow-control keys
    curses.raw()

    # wait at maximum for 1/10th of seconds for keys pressed by user
    curses.halfdelay(1)

    if config.general.colorsupport == "auto":
        # Try to enable color support
        try:
            curses.start_color()
        except:
            log.warning(
                "terminal does not support colors: disabling color support")

        # now check whether color support really has been enabled
        if curses.has_colors():
            config.configcolor._colorenabled = 1
    elif config.general.colorsupport == "on":
        curses.start_color()
        config.configcolor._colorenabled = 1

    # Check for transparency support of terminal
    # use_default_colors(), which will be integrated in python 2.4.
    # Before that happens we try to use our own cursext c-extension
    try:
        curses.use_default_colors()
        config.configcolor._colors["default"] = -1
    except:
        log.warning("terminal does not support transparency")

    # try disabling cursor
    try:
        curses.curs_set(0)
    except:
        log.warning("terminal does not support disabling of cursor")

    if config.general.mousesupport:
        # enable all mouse events
        curses.mousemask(curses.ALL_MOUSE_EVENTS)

    # redirect stderr to /dev/null (to prevent spoiling the screen
    # with libalsa messages). This is not really nice but at the moment there
    # is no other way to get rid of this nuisance.
    dev_null = open("/dev/null", 'w')
    os.dup2(dev_null.fileno(), sys.stderr.fileno())

    return stdscr
Example #48
0
def module_funcs(stdscr):
    "Test module-level functions"

    for func in [curses.baudrate, curses.beep, curses.can_change_color,
                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
                 curses.filter, curses.flash, curses.flushinp,
                 curses.has_colors, curses.has_ic, curses.has_il,
                 curses.isendwin, curses.killchar, curses.longname,
                 curses.nocbreak, curses.noecho, curses.nonl,
                 curses.noqiflush, curses.noraw,
                 curses.reset_prog_mode, curses.termattrs,
                 curses.termname, curses.erasechar, curses.getsyx]:
        func()

    # Functions that actually need arguments
    if curses.tigetstr("cnorm"):
        curses.curs_set(1)
    curses.delay_output(1)
    curses.echo() ; curses.echo(1)

    f = tempfile.TemporaryFile()
    stdscr.putwin(f)
    f.seek(0)
    curses.getwin(f)
    f.close()

    curses.halfdelay(1)
    curses.intrflush(1)
    curses.meta(1)
    curses.napms(100)
    curses.newpad(50,50)
    win = curses.newwin(5,5)
    win = curses.newwin(5,5, 1,1)
    curses.nl() ; curses.nl(1)
    curses.putp('abc')
    curses.qiflush()
    curses.raw() ; curses.raw(1)
    curses.setsyx(5,5)
    curses.tigetflag('hc')
    curses.tigetnum('co')
    curses.tigetstr('cr')
    curses.tparm('cr')
    curses.typeahead(sys.__stdin__.fileno())
    curses.unctrl('a')
    curses.ungetch('a')
    curses.use_env(1)

    # Functions only available on a few platforms
    if curses.has_colors():
        curses.start_color()
        curses.init_pair(2, 1,1)
        curses.color_content(1)
        curses.color_pair(2)
        curses.pair_content(curses.COLOR_PAIRS - 1)
        curses.pair_number(0)

        if hasattr(curses, 'use_default_colors'):
            curses.use_default_colors()

    if hasattr(curses, 'keyname'):
        curses.keyname(13)

    if hasattr(curses, 'has_key'):
        curses.has_key(13)

    if hasattr(curses, 'getmouse'):
        (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
        # availmask indicates that mouse stuff not available.
        if availmask != 0:
            curses.mouseinterval(10)
            # just verify these don't cause errors
            m = curses.getmouse()
            curses.ungetmouse(*m)
Example #49
0
#
Example #50
0
    def runui(self):
        #
        # This is the loop for user input polling and for mud output.
        #
        global HELP_TEXT

        exported.add_help("cursesui", HELP_TEXT)

        stdscr = curses.initscr()
        try:

            if curses.has_colors():
                curses.start_color()
                for i in xrange(1, 64):
                    curses.init_pair(i, i % 8, i / 8)
            curses.raw()
            curses.noecho()
            curses.nonl()
            curses.meta(1)

            out = None
            edit = None
            scrollback = None

            lines = self.lines_

            exported.write_message(
                "For Cursesui help, type \"#help cursesui\".")
            exported.write_message(
                "For some commands help, type \"#help curses\".")

            dirty_count = 0
            timestamp = 0
            output_count = 0

            hotkey_buffer = ''
            keyboard_buffer = []

            select_timeout = 100
            keyboard_fd = sys.stdin.fileno()
            output_pipe_fd = self.output_[0]
            select_input_list = [keyboard_fd, output_pipe_fd]

            while self.running_:

                #
                # set output windows:
                #
                if not out:
                    stdscr = curses.initscr()
                    (screen_h, screen_w) = stdscr.getmaxyx()
                    win = curses.newwin(1, screen_w, screen_h - 1, 0)
                    if edit:
                        edit.attach(win)
                    else:
                        edit = inputbox(self, win)
                    if not scrollback:
                        out = scroller(
                            curses.newwin(screen_h - 1, screen_w, 0, 0), lines)
                    else:
                        scroll_h = screen_h / 3 * 2
                        out_h = (screen_h - 2) - scroll_h
                        scrollback = scroller(
                            curses.newwin(scroll_h, screen_w, 0, 0), lines[:])
                        scrollback.redraw()
                        wborder = curses.newwin(1, screen_w, scroll_h, 0)
                        wborder.bkgd(curses.ACS_HLINE)
                        wborder.erase()
                        wborder.noutrefresh()
                        out = scroller(
                            curses.newwin(out_h, screen_w, scroll_h + 1, 0),
                            lines)
                    out.redraw()

                edit._align()

                if keyboard_buffer and not hotkey_buffer:
                    ch = keyboard_buffer.pop()
                else:
                    ch = win.getch()
                    if ch == curses.ERR:

                        # drop the hotkey buffer when the keyboard goes idle
                        hotkey_buffer = ''

                        # enter idle mode:
                        try:
                            (i, o, x) = select.select(select_input_list, [],
                                                      [], select_timeout)
                        except:
                            # It's probably stray EINTR - further investigation is needed
                            (i, o, x) = (None, None, None)

                        if not i:
                            # timeout was hit:
                            out.redraw(self.cfg_maxscrollback_)
                            select_timeout = 100
                            dirty_count = 0
                            continue
                        else:

                            if keyboard_fd in i:
                                ch = win.getch()

                            if output_pipe_fd in i:
                                line = os.read(output_pipe_fd, 1024)
                                dirty_count += len(line)

                            if ch == curses.ERR:
                                timestamp_now = time()
                                if ((timestamp_now - timestamp) >
                                        0.2) or (dirty_count > self.cfg_lazy_):
                                    out.redraw(self.cfg_maxscrollback_)
                                    select_timeout = 100
                                    dirty_count = 0
                                    output_count = 0
                                else:
                                    select_timeout = 0.2
                                    output_count += 1
                                timestamp = timestamp_now
                                continue

                    keyboard_buffer.insert(0, ch)
                    if ch < 256:
                        keycodename = chr(ch)
                        hotkey_buffer += keycodename

                        if self.cfg_keydebug_:
                            if is_a_char(keycodename):
                                exported.write_message(keycodename)
                            elif ch == 0x1b:
                                exported.write_message("<ESC>")

                        binding = bindings.get(hotkey_buffer)
                        if binding:
                            hotkey_buffer = ''
                            keyboard_buffer = []
                            self.handleinput(binding[1], internal=1)
                            continue
                        elif not filter(lambda x: x.startswith(hotkey_buffer),
                                        bindings.keys()):
                            hotkey_buffer = ''
                        continue
                    else:
                        keycodename = keytext.get(ch)
                        if keycodename:
                            if self.cfg_keydebug_:
                                exported.write_message(keycodename)
                            binding = bindings.get(keycodename)
                            if binding:
                                self.handleinput(binding[1], internal=1)
                                keyboard_buffer.pop()  # get it back
                        hotkey_buffer = ''
                        continue

                if ch == curses.KEY_PPAGE:
                    if not scrollback:
                        scrollback = 1  # create scrollback window at next iteration
                        out = None
                    else:
                        scrollback.redraw(scroll=-(scroll_h / 2 + 1))
                    continue
                if ch == curses.KEY_NPAGE:
                    if scrollback:
                        scrollback.redraw(scroll=scroll_h / 2 + 1)
                    continue

                if ch == curses.ascii.ESC and scrollback:
                    scrollback = None
                    out = None
                    continue

                ch = edit.do_command(ch)

                if ch in (curses.ascii.CR, curses.ascii.LF):
                    edit_string = edit.get_string()
                    if edit_string.strip() == "#end":
                        break
                    self.handleinput(edit_string)
                    edit.set("")

                elif ch in (curses.KEY_RESIZE,
                            curses.ascii.FF):  # force screen redraw
                    out = None
                    continue

                elif ch == curses.ascii.ETX:  # Ctrl-C
                    break

        finally:
            endcurses()
Example #51
0
  def runui(self):
    # 
    # This is the loop for user input polling and for mud output.
    #
    global HELP_TEXT
    
    exported.add_help("cursesui", HELP_TEXT)

    stdscr = curses.initscr()
    try:
    
      if curses.has_colors():
        curses.start_color()
        for i in xrange(1,64):
          curses.init_pair(i, i%8, i/8)
      curses.raw()
      curses.noecho()
      curses.nonl()
      curses.meta(1)

      out = None
      edit = None
      scrollback = None

      lines = self.lines_

      exported.write_message("For Cursesui help, type \"#help cursesui\".")
      exported.write_message("For some commands help, type \"#help curses\".")

      dirty_count = 0
      timestamp = 0
      output_count = 0

      hotkey_buffer = ''
      keyboard_buffer = []

      select_timeout = 100
      keyboard_fd = sys.stdin.fileno()
      output_pipe_fd = self.output_[0]
      select_input_list = [ keyboard_fd, output_pipe_fd ]

      while self.running_:

        #
        # set output windows:
        #
        if not out:
          stdscr = curses.initscr()
          (screen_h, screen_w) = stdscr.getmaxyx()
          win = curses.newwin(1, screen_w, screen_h-1, 0)
          if edit:
            edit.attach(win)
          else:  
            edit = inputbox(self, win)
          if not scrollback:
            out = scroller(curses.newwin(screen_h-1, screen_w, 0, 0), lines)
          else:
            scroll_h = screen_h/3*2
            out_h = (screen_h - 2) - scroll_h 
            scrollback = scroller(curses.newwin(scroll_h, screen_w, 0, 0),
                                  lines[:])
            scrollback.redraw()
            wborder = curses.newwin(1, screen_w, scroll_h, 0)
            wborder.bkgd(curses.ACS_HLINE)
            wborder.erase()
            wborder.noutrefresh()
            out = scroller(curses.newwin(out_h, screen_w, scroll_h+1, 0), lines)
          out.redraw()

        edit._align()

        if keyboard_buffer and not hotkey_buffer:
          ch = keyboard_buffer.pop()
        else: 
          ch = win.getch()
          if ch == curses.ERR:
          
            # drop the hotkey buffer when the keyboard goes idle
            hotkey_buffer = ''

            # enter idle mode:
            try:
                (i, o, x) = select.select(select_input_list, [], [], select_timeout)
            except:
                # It's probably stray EINTR - further investigation is needed
                (i, o, x) = (None, None, None)

            if not i:
              # timeout was hit:
              out.redraw(self.cfg_maxscrollback_)
              select_timeout = 100
              dirty_count = 0
              continue
            else:    
              
              if keyboard_fd in i:
                ch = win.getch()
 
              if output_pipe_fd in i:  
                line=os.read(output_pipe_fd, 1024)
                dirty_count += len(line)
                
              if ch == curses.ERR:
                timestamp_now = time()
                if ((timestamp_now - timestamp) > 0.2) or (dirty_count > self.cfg_lazy_):
                  out.redraw(self.cfg_maxscrollback_)
                  select_timeout = 100
                  dirty_count = 0
                  output_count = 0
                else:  
                  select_timeout = 0.2
                  output_count += 1
                timestamp = timestamp_now
                continue

          keyboard_buffer.insert(0, ch)
          if ch < 256:
            keycodename = chr(ch)
            hotkey_buffer += keycodename
            
            if self.cfg_keydebug_:
              if is_a_char(keycodename):
                exported.write_message(keycodename)
              elif ch==0x1b:
                exported.write_message("<ESC>")

            binding = bindings.get(hotkey_buffer)
            if binding:
              hotkey_buffer = ''
              keyboard_buffer = []
              self.handleinput(binding[1], internal=1)
              continue
            elif not filter(lambda x: x.startswith(hotkey_buffer), bindings.keys()):
              hotkey_buffer = ''
            continue
          else:
            keycodename = keytext.get(ch)
            if keycodename:
              if self.cfg_keydebug_:
                exported.write_message(keycodename)
              binding = bindings.get(keycodename)
              if binding:
                self.handleinput(binding[1], internal=1)
                keyboard_buffer.pop() # get it back
            hotkey_buffer = ''
            continue

        if ch == curses.KEY_PPAGE:
          if not scrollback:
            scrollback = 1 # create scrollback window at next iteration
            out = None
          else: 
            scrollback.redraw( scroll = -(scroll_h/2+1) )
          continue
        if ch == curses.KEY_NPAGE:
          if scrollback:
            scrollback.redraw( scroll = scroll_h/2+1 )
          continue

        if ch == curses.ascii.ESC and scrollback:
          scrollback = None
          out = None
          continue

        ch = edit.do_command(ch)    

        if ch in (curses.ascii.CR, curses.ascii.LF):
          edit_string = edit.get_string()
          if edit_string.strip() == "#end":
            break
          self.handleinput( edit_string )
          edit.set("")

        elif ch in (curses.KEY_RESIZE, curses.ascii.FF): # force screen redraw
          out = None
          continue

        elif ch == curses.ascii.ETX:    # Ctrl-C
          break

    finally:
      endcurses()
Example #52
0
    def __init__(self, stdscr):
        maxy, maxx = stdscr.getmaxyx()
        self.msg = curses.newwin(1, maxx - 16, 0, 0)
        self.inv = curses.newwin(maxy - 1, 16, 1, maxx - 16)
        self.stat = curses.newwin(1, 16, 0, maxx - 16)
        self.map = curses.newwin(maxy - 1, maxx - 16, 1, 0)
        self.map.keypad(1)
        self.map.immedok(0)
        self.inv.immedok(0)
        self.stat.immedok(0)
        self.msg.immedok(0)
        self.stat.scrollok(0)
        self.msg.scrollok(1)
        self.xmap = 0
        self.ymap = 0
        self.maxmapy, self.maxmapx = self.map.getmaxyx()
        curses.meta(1)
        self.map.leaveok(1)
        curses.curs_set(0)
        self.effects = []
        self.eff_back = []
        if curses.has_colors():
            #curses.use_default_colors()
            curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLACK)
            curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(3, curses.COLOR_YELLOW, 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_CYAN, curses.COLOR_BLACK)

            tiles[0]['visible'] = ord('.')
            tiles[0]['explored'] = ord('.') | curses.color_pair(4)
            tiles[0]['shadow'] = ord('.') | curses.color_pair(
                1) | curses.A_BOLD

            tiles[1]['visible'] = ord('#')
            tiles[1]['explored'] = ord('#') | curses.color_pair(4)

            tiles[2]['visible'] = ord('%') | curses.color_pair(
                5) | curses.A_BOLD
            tiles[2]['explored'] = ord('%') | curses.color_pair(
                4) | curses.A_BOLD

            tiles[3]['visible'] = ord('=') | curses.color_pair(5)
            tiles[3]['explored'] = ord('=') | curses.color_pair(4)

            tiles[4]['visible'] = ord(':') | curses.color_pair(3)
            tiles[4]['explored'] = ord(':') | curses.color_pair(4)

            tiles[5]['visible'] = ord('#') | curses.color_pair(
                1) | curses.A_BOLD
            tiles[5]['explored'] = ord('#') | curses.color_pair(4)

            tiles[6]['visible'] = ord(';') | curses.color_pair(5)
            tiles[6]['explored'] = ord(';') | curses.color_pair(4)

            tiles[7]['visible'] = ord('.') | curses.color_pair(5)
            tiles[7]['explored'] = ord('.') | curses.color_pair(4)

            tiles[8]['visible'] = ord('#') | curses.color_pair(
                5) | curses.A_BOLD
            tiles[8]['explored'] = ord('#') | curses.color_pair(4)

            tiles[9]['visible'] = ord('&') | curses.color_pair(
                3) | curses.A_BOLD
            tiles[9]['explored'] = ord('&') | curses.color_pair(
                4) | curses.A_BOLD

            tiles[10]['visible'] = ord('>') | curses.color_pair(
                3) | curses.A_BOLD
            tiles[10]['explored'] = ord('>') | curses.color_pair(
                4) | curses.A_BOLD

            tiles[11]['visible'] = ord('<') | curses.color_pair(
                3) | curses.A_BOLD
            tiles[11]['explored'] = ord('<') | curses.color_pair(
                4) | curses.A_BOLD

            tiles[12]['visible'] = ord('+') | curses.color_pair(6)
            tiles[12]['explored'] = ord('+') | curses.color_pair(4)

            tiles[13]['visible'] = ord("'") | curses.color_pair(6)
            tiles[13]['explored'] = ord("'") | curses.color_pair(4)
Example #53
0
def main(stdscr):
    curses.curs_set(0) # hide cursor
    curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLACK) # Ubuntu (Yellow?)
    curses.init_pair(2,curses.COLOR_BLUE,curses.COLOR_BLACK) # Kubuntu Blue on Black
    curses.init_pair(3,curses.COLOR_RED,curses.COLOR_BLACK) # Edubuntu
    curses.init_pair(4,curses.COLOR_CYAN,curses.COLOR_BLACK) # Xubuntu
    curses.init_pair(5,curses.COLOR_BLACK,curses.COLOR_GREEN) # Pass
    curses.init_pair(6,curses.COLOR_BLACK,curses.COLOR_RED) # Fail (This could be reverse edubuntu)

    """while (1):
        try:
            server.connect((HOST, PORT))
            break
        except socket.error:
            # Since non-blocking, if it doesn't work immediately, EINPROGRESS
            # Subsequent calls (while in progress) give EALREADY
            # There are other errors (actual errors), we may want to check them
            pass"""

    stdscr.bkgd('*', curses.A_REVERSE )
    win_sidebar = curses.newwin(21,15,0,0)
    # Set up sidebar (static stuff) UGLY CHANGE!!!!!!!!!!!!! - JB
    win_sidebar.border(' ','|',' ',' ',' ',curses.ACS_VLINE,' ',curses.ACS_VLINE) # Righthand Line
    win_sidebar.addstr(0,0,"    Queue     ", curses.A_UNDERLINE)
    win_sidebar.addstr(1,3,"F V A T P")
    for i in range(1,10):
        win_sidebar.addstr(i+1,1,str(i))
    for i in range(10,20):
        win_sidebar.addstr(i+1,0,str(i))
    # done with sidebar static stuff

    win_topbar = curses.newwin(4,65,0,15)
    # set up top bar (static stuff)
    win_topbar.border(' ',' ',' ','-',' ',' ','-','-') # Bottom Line
    for i in range(1,6):
        for j in range(0,3):
            win_topbar.addstr(j,i*11-1,'|') # Dividers between clients
        win_topbar.addstr(0,i*11,' ******** ') # blank client names (2-6)
    win_topbar.addstr(0,0,' ******** ') # blank client name (1)
    # done with top bar static stuff

    # Now we set up the four (up to five) tabs
    tabs.append(curses.newwin(17,65,4,15))  # These panel references are
    tabs.append(curses.newwin(17,65,4,15))  # important, without them
    tabs.append(curses.newwin(17,65,4,15))  # our panels get GC'd
    tabs.append(curses.newwin(17,65,4,15))  # Using Win instead?

    # Put some test stuff in the tabs
    draw_menu_order(tabs[0])
    draw_menu_packages(tabs[1])
    draw_menu_clients(tabs[2])
    draw_menu_queue(tabs[3])

    # initial updates
    #get_queue()
    #get_clients()
    update_package_names()
    

    global active_tab
    global is_running
    global keysdown
    global blankkeys
    global frame_count
    keysdown = blankkeys
    active_tab = 0
    stale_queue = True
    stale_client = True
    stdscr.nodelay(1)
    curses.meta(1)
    while(is_running):
        
        
        stdscr.noutrefresh()
        win_sidebar.noutrefresh()
        win_topbar.noutrefresh()
        tabs[active_tab].touchwin() # Have to make them think this is modified
        tabs[active_tab].noutrefresh()
        curses.doupdate()
        

        """# begin socket stuff
        try: #try RX
            if len(server.recv(1024,socket.MSG_PEEK)) == 0:
                server.close() # Bad connection, We likely want to reconnect
                continue
            # otherwise: do stuff with inbuf
            inbuf = inbuf + server.recv(1024)
        except socket.error: # Excepion (no data RX, but connection still there)
            pass

        if len(outbuf) > 0: # if we have stuff to send
            try: # try TX
                sent = server.send(outbuf)
                outbuf = outbuf[sent:]
            except socket.error: # We only want to catch SIGPIPE (server disconnect)
                pass
        # done with socket stuff"""


        # Handle Communication
        if stale_queue:
            update_display_queue(win_sidebar)
            stale_queue = False
        if stale_client:
            update_display_clients(win_topbar)
            stale_client = False


        handle_input(stdscr)
        update_tab(active_tab)
        
        #clear keys
        clear_keys()
        frame_count += 1
Example #54
0
    def __init__(self, window, report_cols, col_minmax, buff, formats,
                 the_path):
        # parms:
        # window = a curses screen object--usually a full screen or nearly full.
        # report_cols = number of report columns to display (same
        #        idea as newspaper columns). Zero means automatic.
        # col_minmax = a list that contains a min/max list
        #   for each colum (min/max charcter_col width; NOT USED YET)
        # buff = a list of strings to display
        # formats = a list of 0 for regular files or 1 for directories.
        # the_path = a path that is the starting basis for the file list.
        #
        global HEADER_LINES, SPACE_BETWEEN_COLUMNS
        self.window = window
        self.ibuff = buff
        self.ibuff_idx = 0
        # Check the maximum width of the input buffer
        self.max_txt_width = 0
        for j in range(len(self.ibuff)):
            if len(buff[j]) > self.max_txt_width:
                self.max_txt_width = len(buff[j])
        if report_cols == 0:
            # zero means auto-detect the number of report
            # columns.
            (max_y, max_x) = self.window.getmaxyx()
            tmp = int(self.max_txt_width + 5 + \
             SPACE_BETWEEN_COLUMNS) / max_x
            if tmp < 1:
                self.report_cols = 1
            else:
                self.report_cols = tmp

        # top_ibuff_idx is the ibuff_idx of the
        # first line displayed on the screen (used
        # to manage scrolling of the text)
        self.top_ibuff_idx = 0
        self.formats = formats
        self.frames = []
        #
        # Window setup
        # disable the normal echo of characters to the screen
        curses.noecho()
        # the cbreak command helps to process key strokes instantly
        curses.cbreak()
        # attemp to allow arrow keys (didn't work):
        curses.meta(1)
        # activate the mouse (X-Term) and listen
        # for mouse click only:
        oldmouse = curses.mousemask(curses.BUTTON1_CLICKED)
        #self.displayscreen(self.startbuffrow_idx)
        if curses.has_colors():
            curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_YELLOW)
            curses.init_pair(2, curses.COLOR_CYAN, 0)
            curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_MAGENTA)
            curses.init_pair(4, curses.COLOR_MAGENTA, 0)
            curses.init_pair(5, curses.COLOR_RED, 0)
            curses.init_pair(6, curses.COLOR_YELLOW, 0)
            curses.init_pair(7, curses.COLOR_WHITE, 0)

        self.window.clear()
        self.window.refresh()
        # header/status bar frame:
        self.frames.append(WinHeader(self.window, 0, 0, HEADER_LINES, \
         self.window.getmaxyx()[1] - 1))
        self.frames[0].set_header_txt(1, the_path)
        #self.frames[0].refresh()
        #
        # frame 1 will be the main display area. Others might
        # be used for menus, status line, debug info, etc
        (max_y, max_x) = self.window.getmaxyx()
        if report_cols == 0:
            # Calculate the number of 'newspaper columns' allowing for
            # some space between columns
            self.report_cols = int(max_x / (self.max_txt_width \
             + 5 + SPACE_BETWEEN_COLUMNS))
            if self.report_cols < 1:
                self.report_cols = 1
        self.frames.append(WinFrame(self.window,HEADER_LINES, 0, \
         max_y, max_x, report_cols=self.report_cols ))
        #
        #
        self.display_buff()
        #self.frames[1].move(0,0)
        self.goto_buff_idx(0)
Example #55
0
def cursessetup():
    # Initialize curses library
    stdscr = curses.initscr()

    # Turn off echoing of keys
    curses.noecho()

    # 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)

    # allow 8-bit characters to be input
    curses.meta(1)

    # enter raw mode, thus disabling interrupt, quit, suspend and flow-control keys
    curses.raw()

    # wait at maximum for 1/10th of seconds for keys pressed by user
    curses.halfdelay(1)

    if config.general.colorsupport == "auto":
        # Try to enable color support
        try:
            curses.start_color()
        except:
            log.warning("terminal does not support colors: disabling color support")

        # now check whether color support really has been enabled
        if curses.has_colors():
            config.configcolor._colorenabled = 1
    elif config.general.colorsupport == "on":
        curses.start_color()
        config.configcolor._colorenabled = 1

    # Check for transparency support of terminal
    # use_default_colors(), which will be integrated in python 2.4.
    # Before that happens we try to use our own cursext c-extension
    try:
        curses.use_default_colors()
        config.configcolor._colors["default"] = -1
    except:
        try:
            import cursext
            if cursext.useDefaultColors():
                config.configcolor._colors["default"] = -1
            else:
                log.warning("terminal does not support transparency")
        except:
            log.warning("transparency support disabled because cursext module is not present")

    # try disabling cursor
    try:
        curses.curs_set(0)
    except:
        log.warning("terminal does not support disabling of cursor")

    if config.general.mousesupport:
        # enable all mouse events
        curses.mousemask(curses.ALL_MOUSE_EVENTS)

    # redirect stderr to /dev/null (to prevent spoiling the screen
    # with libalsa messages). This is not really nice but at the moment there
    # is no other way to get rid of this nuisance.
    dev_null = file("/dev/null", 'w')
    os.dup2(dev_null.fileno(), sys.stderr.fileno())

    return stdscr
Example #56
0
#