예제 #1
0
파일: __init__.py 프로젝트: anmitsu/pyful
def start_curses():
    try:
        curses.noecho()
        curses.cbreak()
        curses.raw()
    except curses.error:
        base.StandardScreen()
예제 #2
0
def go():
    
    locale.setlocale(locale.LC_ALL, '')
  
    a = curses.initscr()
    curses.raw()
    y = []
    try:
        a.keypad(1)
#        y = xla(a)
        a.addstr(1, 0, str(a.getch(0,0)))
        a.addstr(2, 0, str(a.getch(0,0)))
        a.addstr(3, 0, str(a.getch(0,0)))
        a.addstr(4, 0, str(a.getch(0,0)))
        a.addstr(5, 0, str(a.getch(0,0)))
        a.addstr(6, 0, str(a.getch(0,0)))
        a.addstr(7, 0, str(a.getch(0,0)))
       

    finally:
        a.nodelay(1)
        curses.endwin()
        a.keypad(0)
        curses.echo()
        print y
        print 'end'
예제 #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()
예제 #4
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()
예제 #5
0
    def __init__(self, screen, data):
        self.stdscr = screen
        self.WIDTH = 0
        self.HEIGHT = 0
        self.PROMPT = 'QUERY> '
        self.has_default_colors = False
        self.selected = 0

        self.data = data
        self.filter_data = data

        self.stdscr.keypad(True)
        curses.raw()
        curses.noecho()
        curses.cbreak()
        curses.nonl()

        curses.start_color()
        curses.use_default_colors()
        FG_COLORS["default"] = -1
        BG_COLORS["on_default"] = -1
        self.init_color_pairs()
        self.HEIGHT, self.WIDTH = self.stdscr.getmaxyx()
        self.MAX_DISPLAY_COUNT = self.HEIGHT - 2

        self.keyword_style = self.attrs_to_style(keyword_style)
        self.keyword_highlight_style = self.attrs_to_style(keyword_style +
                                                           highlight_style)
        self.highlight_style = self.attrs_to_style(highlight_style)
        self.leader_style = self.attrs_to_style(leader_style)

        self.return_result = None
    def __init__(self, parentScreen):
        # Make it green
        #curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        curses.raw()
        #stdscrDim = stdscr.getmaxyx()
        self.height = 9
        self.width = 50
        self.ypos = (self.parentHeight - self.height) / 2
        self.xpos = (self.parentWidth - self.width) / 2

        self.win = curses.newwin(self.height, self.width, self.ypos, self.xpos)

        #self.win.attron(curses.color_pair(1))
        self.win.keypad(1)
        strHeader =   ' Welcome to My Application '
        strExplain =  'Press key in [] to enter:'
        strLogin =    '******'
        strRegester = '[R]      - Registration'
        strQuit =     '[CTRL-X] - Exit'
        self.win.box()
        self.win.addstr(1, (self.width-len(strHeader))/2,
                        strHeader, curses.A_REVERSE)
        self.win.addstr(3, (self.width-len(strExplain))/2,
                        strExplain, curses.A_BOLD)
        self.win.addstr(5, 5, strLogin, curses.A_NORMAL)
        self.win.addstr(6, 5, strRegester, curses.A_NORMAL)
        self.win.addstr(7, 5, strQuit, curses.A_NORMAL)
        self.win.refresh()
예제 #7
0
	def _init_input(self):
		curses.raw()
		self.results = []
		self.input_position = 0
		self.selected = 0
		self.results_scroll = 0
		self.set_query("")
예제 #8
0
def init_curses():
    curses.noecho()
    curses.raw()
    #curses.cbreak()

    stdscr = curses.initscr()
    return stdscr
예제 #9
0
파일: pyview.py 프로젝트: langner/lfm
 def init_curses(self):
     curses.cbreak()
     curses.raw()
     curses.curs_set(0)
     try:
         self.win_title = curses.newwin(1, app.maxw, 0, 0)
         self.win_body = curses.newwin(app.maxh-2, app.maxw, 1, 0)     # h, w, y, x
         self.win_status = curses.newwin(1, app.maxw, app.maxh-1, 0)
     except curses.error:
         print 'Can\'t create windows'
         sys.exit(-1)
     if curses.has_colors():
         self.win_title.bkgd(curses.color_pair(1),
                             curses.color_pair(1) | curses.A_BOLD)
         self.win_body.bkgd(curses.color_pair(2))
         self.win_status.bkgd(curses.color_pair(1))
     self.win_body.leaveok(1)
     self.win_body.keypad(1)
     self.win_title.erase()
     self.win_status.erase()
     title = self.title
     if len(title) - 4 > app.maxw:
         title = title[:app.maxw-12] + '~' + title[-7:]
     self.win_title.addstr(0, int((app.maxw-len(title))/2), title)
     if self.large:
         status = ''
     else:
         status = 'Press any key to continue'
         self.win_status.addstr(0, int((app.maxw-len(status))/2), status)
     self.win_title.refresh()
     self.win_status.refresh()
예제 #10
0
def main_app(screen, server, debugging):
  """Main command-loop, to be run within curses.wrapper."""
  curses.raw()
  screen.nodelay(0)
  info_layout(screen)
  stale = False
  while True:
    ch = screen.getch()
    if stale or debugging:
      info_layout(screen)
      stale = False
    if ch in (-1, 3, 4, ord('q')):
      # We forcibly use ^C and ^D, even if stty has remapped intr & eof
      break
    if ch == 12:  # ^L
      screen.refresh()
      continue
    if ch == ord('D'):
      debugging = False if debugging else True
      screen.addstr(1, 10, 'Debugging %s' % ('enabled' if debugging else 'disabled'))
      screen.move(0, 0)
      stale = True
      continue
    handled = process_command(ch, server, screen, debugging)
    if debugging and not handled:
      screen.addstr(1, 10, 'Character %d  %s' % (ch, curses.keyname(ch)))
      screen.move(0, 0)
      stale = True
예제 #11
0
 def __init__(self, this_plant, this_data):
     '''Initialization'''
     self.initialized = False
     self.screen = curses.initscr()
     curses.noecho()
     curses.raw()
     curses.start_color()
     try:
         curses.curs_set(0)
     except curses.error:
         # Not all terminals support this functionality.
         # When the error is ignored the screen will look a little uglier, but that's not terrible
         # So in order to keep botany as accesible as possible to everyone, it should be safe to ignore the error.
         pass
     self.screen.keypad(1)
     self.plant = this_plant
     self.user_data = this_data
     self.plant_string = self.plant.parse_plant()
     self.plant_ticks = str(self.plant.ticks)
     self.exit = False
     self.infotoggle = 0
     self.maxy, self.maxx = self.screen.getmaxyx()
     # Highlighted and Normal line definitions
     self.define_colors()
     self.highlighted = curses.color_pair(1)
     self.normal = curses.A_NORMAL
     # Threaded screen update for live changes
     screen_thread = threading.Thread(target=self.update_plant_live, args=())
     screen_thread.daemon = True
     screen_thread.start()
     self.screen.clear()
     self.show(["water","look","garden","instructions"], title=' botany ', subtitle='options')
예제 #12
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()
예제 #13
0
def init_ncurses():
    stdscr = curses.initscr()
    curses.raw()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    return stdscr
예제 #14
0
파일: pyview.py 프로젝트: ryanbekabe/lfm
 def init_curses(self):
     curses.cbreak()
     curses.raw()
     curses.curs_set(0)
     try:
         self.win_title = curses.newwin(1, app.maxw, 0, 0)
         self.win_body = curses.newwin(app.maxh - 2, app.maxw, 1,
                                       0)  # h, w, y, x
         self.win_status = curses.newwin(1, app.maxw, app.maxh - 1, 0)
     except curses.error:
         print 'Can\'t create windows'
         sys.exit(-1)
     if curses.has_colors():
         self.win_title.bkgd(curses.color_pair(1),
                             curses.color_pair(1) | curses.A_BOLD)
         self.win_body.bkgd(curses.color_pair(2))
         self.win_status.bkgd(curses.color_pair(1))
     self.win_body.leaveok(1)
     self.win_body.keypad(1)
     self.win_title.erase()
     self.win_status.erase()
     title = self.title
     if len(title) - 4 > app.maxw:
         title = title[:app.maxw - 12] + '~' + title[-7:]
     self.win_title.addstr(0, int((app.maxw - len(title)) / 2), title)
     if self.large:
         status = ''
     else:
         status = 'Press any key to continue'
         self.win_status.addstr(0, int((app.maxw - len(status)) / 2),
                                status)
     self.win_title.refresh()
     self.win_status.refresh()
예제 #15
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()
예제 #16
0
    def __enter__(self):
        locale.setlocale(locale.LC_ALL, '')
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.nonl()
        curses.raw()

        termstate = termios.tcgetattr(0)
        termstate[6][termios.VINTR] = bytes([self.INTCHAR])
        nope = bytes([0])  # to disable a character
        termstate[6][termios.VQUIT] = nope
        termstate[6][termios.VSUSP] = nope
        if hasattr(termios, 'VDSUSP'):
            termstate[6][termios.VDSUSP] = nope  # pragma: nocover
        termstate[3] |= termios.ISIG
        termios.tcsetattr(0, termios.TCSANOW, termstate)

        self.stdscr.keypad(1)
        self.stdscr.nodelay(1)
        self.color_assigner = ttycolor.get_assigner()
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.orig_sigtstp = signal.signal(signal.SIGTSTP, self.sigtstp)
        self.main_pid = os.getpid()
        loop = asyncio.get_event_loop()
        loop.add_signal_handler(signal.SIGWINCH, self.sigwinch, loop)

        with mock.patch('asyncio.unix_events._sighandler_noop',
                        self.sighandler_op):
            loop.add_signal_handler(signal.SIGINT, self.sigint)

        return self
예제 #17
0
파일: term.py 프로젝트: gnar/pyhack
def init():
  import os
  os.environ["ESCDELAY"] = "25"

  global wnd
  wnd = c.initscr()

  c.noecho()
  c.nocbreak()
  c.raw()
  c.curs_set(False)

  wnd.keypad(True)

  c.start_color()
  #c.init_pair(0, c.COLOR_BLACK, c.COLOR_BLACK)
  c.init_pair(1, c.COLOR_BLUE, c.COLOR_BLACK)
  c.init_pair(2, c.COLOR_GREEN, c.COLOR_BLACK)
  c.init_pair(3, c.COLOR_CYAN, c.COLOR_BLACK)
  c.init_pair(4, c.COLOR_RED, c.COLOR_BLACK)
  c.init_pair(5, c.COLOR_MAGENTA, c.COLOR_BLACK)
  c.init_pair(6, c.COLOR_YELLOW, c.COLOR_BLACK)
  c.init_pair(7, c.COLOR_WHITE, c.COLOR_BLACK)

  c.init_pair(8, c.COLOR_BLACK, c.COLOR_BLACK)
  c.init_pair(9, c.COLOR_BLUE, c.COLOR_BLACK)
  c.init_pair(10, c.COLOR_GREEN, c.COLOR_BLACK)
  c.init_pair(11, c.COLOR_CYAN, c.COLOR_BLACK)
  c.init_pair(12, c.COLOR_RED, c.COLOR_BLACK)
  c.init_pair(13, c.COLOR_MAGENTA, c.COLOR_BLACK)
  c.init_pair(14, c.COLOR_YELLOW, c.COLOR_BLACK)
  c.init_pair(15, c.COLOR_WHITE, c.COLOR_BLACK)
예제 #18
0
def main():
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_YELLOW)
    curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_GREEN)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_CYAN)
    curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
    curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_RED)
    curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE)
    curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.raw()
    curses.noecho()
    curses.cbreak()
    stdscr.nodelay(True)
    stdscr.keypad(True)
    curses.curs_set(0)
    maxyx = stdscr.getmaxyx()
    if(maxyx[0]<44 or maxyx[1]<110):
        screenTooSmall(stdscr)
        curses.endwin()
        exit(1)
    drawTable(stdscr)
    stdscr.refresh()
    while(stdscr.getch()==curses.ERR):
        time.sleep(0.01)
    curses.endwin()
예제 #19
0
def main():
    """Main game loop"""
    stdscr = curses.initscr()
    # TODO: add title
    curses.noecho()
    # initialize curses color
    curses.start_color()
    # TODO: initialize array of color pairs?
    # turn off cursor
    curses.curs_set(0)
    # begin game loop
    stdscr.keypad(1)
    curses.raw()

    bigletters, newstops, newspic = loadgraphics()

    loadinitfile() # does nothing yet, possible deprecated

    # load site map data
    oldMapMode = readConfigFile('sitemaps.txt')
    if not oldMapMode:
        stdscr.addstr('Failed to load sitemaps.txt! Reverting to old map mode.')
        stdscr.refresh()
        stdscr.getch()

    # quit game
    quit(stdscr)
예제 #20
0
def _init(stdscr):
    curses.start_color()
    curses.use_default_colors()

    curses.raw()
    curses.nonl()
    stdscr.leaveok(1)
예제 #21
0
파일: icl.py 프로젝트: canute24/icl
    def __init__(self):
        self.input_string = ""
        self.all_entries = get_entries_from_file()
        self.matches = []
        self.selected_option_index = 0

        self.screen = curses.initscr()
        self.screen.clear()
        # signal.signal(signal.SIGINT, lambda signum, frame: None)
        self.screen.keypad(True)
        curses.raw()
        curses.noecho()
        curses.cbreak()
        curses.nonl()

        curses.start_color()
        curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_MAGENTA)
        curses.newwin(0, 0)
        self.screen.keypad(1)
        self.screen.addstr(0, 0, "QUERY>")

        try:
            self.process_new_input()
            while True:
                pressed_key = self.screen.getch()
                self._handle_keypress(pressed_key)
                self.process_new_input()
        except:
            #TODO: maybe catch only keyboard interrupt????
            curses.nocbreak()
            self.screen.keypad(False)
            curses.echo()
            curses.nl()
            curses.endwin()
예제 #22
0
 def handle_input(self, key=None):
     if not key:
         self.pad.keypad(True)
         curses.raw(True)
         key = self.pad.getch()
     # TODO: check for min/max
     if key == ord('s') or key == curses.KEY_DOWN:
         self.contents[self.pos_x][self.pos_y].highlight()
         self.pos_y += 1
     elif key == ord('w') or key == curses.KEY_UP:
         self.contents[self.pos_x][self.pos_y].highlight()
         self.pos_y -= 1
     elif key == ord('d') or key == curses.KEY_RIGHT:
         self.contents[self.pos_x][self.pos_y].highlight()
         self.pos_x += 1
     elif key == ord('a') or key == curses.KEY_LEFT:
         self.contents[self.pos_x][self.pos_y].highlight()
         self.pos_x -= 1
     elif key == curses.KEY_PPAGE or key == ord('k'):  # page up
         self.win_pos_y += 1
     elif key == curses.KEY_NPAGE or key == ord('j'):  # page down
         self.win_pos_y -= 1
     elif key == curses.KEY_ENTER or key in [10, 13]:
         self.contents[self.pos_x][self.pos_y].edit_entry()
         txt = self.contents[self.pos_x][self.pos_y].get_text()
         self.csv_data.update_data(self.contents)
     elif key == curses.KEY_DC or key == curses.KEY_DL:
         self.contents[self.pos_x][self.pos_y].clear_text()
     elif key == 19:  # CTRL + S
         self.csv_data.update_data(self.contents)
         self.csv_data.save()
     elif key == ord('q'):
         raise Exception("App closed")
예제 #23
0
 def _setup_curses(self):
     self.screen.keypad(True)
     curses.raw()
     curses.noecho()
     curses.cbreak()
     curses.nonl()
     curses.curs_set(0)
예제 #24
0
 def __init__(self, this_plant, this_data):
     '''Initialization'''
     self.initialized = False
     self.screen = curses.initscr()
     curses.noecho()
     curses.raw()
     curses.start_color()
     curses.curs_set(0)
     self.screen.keypad(1)
     self.plant = this_plant
     self.user_data = this_data
     self.plant_string = self.plant.parse_plant()
     self.plant_ticks = str(self.plant.ticks)
     self.exit = False
     self.infotoggle = 0
     self.maxy, self.maxx = self.screen.getmaxyx()
     # Highlighted and Normal line definitions
     self.define_colors()
     self.highlighted = curses.color_pair(1)
     self.normal = curses.A_NORMAL
     # Threaded screen update for live changes
     screen_thread = Thread(target=self.update_plant_live, args=())
     screen_thread.daemon = True
     screen_thread.start()
     self.screen.clear()
     self.show(["water", "look", "garden", "instructions"],
               title=' botany ',
               subtitle='options')
예제 #25
0
    async def __aenter__(self):
        locale.setlocale(locale.LC_ALL, '')
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.nonl()
        curses.raw()

        termstate = termios.tcgetattr(0)
        termstate[6][termios.VINTR] = bytes([self.INTCHAR])
        nope = bytes([0])  # to disable a character
        termstate[6][termios.VQUIT] = nope
        termstate[6][termios.VSUSP] = nope
        if hasattr(termios, 'VDSUSP'):  # pragma: nocover
            termstate[6][termios.VDSUSP] = nope
        termstate[3] |= termios.ISIG
        termios.tcsetattr(0, termios.TCSANOW, termstate)

        self.stdscr.keypad(1)
        self.stdscr.nodelay(1)
        self.color_assigner = ttycolor.get_assigner()
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.main_pid = os.getpid()
        self.supervisor = await imbroglio.get_supervisor()
        self.orig_sigtstp = signal.signal(signal.SIGTSTP, self.sigtstp)
        self.orig_sigwinch = signal.signal(signal.SIGWINCH, self.sigwinch)
        self.orig_sigint = signal.signal(signal.SIGINT, self.sigint)

        self.running = True

        return self
예제 #26
0
파일: __init__.py 프로젝트: roceys/percol
    def __enter__(self):
        # init curses and it's wrapper
        self.screen  = curses.initscr()
        self.display = Display(self.screen, self.encoding)

        # create keyhandler
        self.keyhandler = key.KeyHandler(self.screen)

        # create view
        self.view = SelectorView(percol = self)

        # create command
        self.command_candidate = SelectorCommand(self.model_candidate, self.view)
        self.command_action = SelectorCommand(self.model_action, self.view)

        # suppress SIGINT termination
        signal.signal(signal.SIGINT, lambda signum, frame: None)

        # handle special keys like <f1>, <down>, ...
        self.screen.keypad(True)

        curses.raw()
        curses.noecho()
        curses.cbreak()
        # Leave newline mode. Make percol distinguish between "C-m" and "C-j".
        curses.nonl()

        return self
예제 #27
0
def hook(stdscr):
    # curses.wrapper uses cbreak, but I rather want raw so things
    # don't get utterly f****d when I hit ctrl-s
    curses.raw()
    curses.curs_set(0)  # Hide cursor
    x = 5
    y = 10
    w = 5
    h = 10
    # Wow, I already want to punch the writer of this library.
    #win = curses.newwin(h, w, y, x)
    pad = curses.newpad(50, 50)
    for y in range(0, 50):
        for x in range(0, 50):
            try:
                pad.addch(y, x, ord('a') + (x * x + y * y) % 26)
            except curses.error:
                pass
    # Displays a pad in the middle of the screen.
    pad.refresh(0, 0, 5, 5, 20, 75)
    # Wait for input
    pad.getch()
    # Set up a color pair
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    stdscr.addstr(5, 0, "Current mode: Your mom", \
                  curses.A_REVERSE | curses.color_pair(1))
    stdscr.refresh()
    stdscr.getch()
    def _render(self):
        self.stdscr = curses.initscr()
        curses.raw()
        curses.noecho()
        curses.cbreak()

        self.show_settings()
예제 #29
0
    def load(self, *args):
        """Setup curses."""
        # Log the terminal type
        termname = curses.termname().decode("utf-8")
        self.logger.debug("Loading UI for terminal: {0}".format(termname))

        self.screen = curses.initscr()
        self.setup_colors()

        # curses.cbreak()
        # TODO: Raw mode seems to work ok. Should probably
        # switch to it from cbreak to get Ctrl+Z to work etc.
        curses.raw()

        curses.noecho()
        try:
            # Might fail on vt100 terminal emulators
            curses.curs_set(0)
        except:
            self.logger.warning("curses.curs_set(0) failed!")

        self.screen.keypad(1)

        self.current_yx = self.screen.getmaxyx()  # For checking resize
        self.setup_mouse()
        self.setup_windows()
예제 #30
0
    def exec_script(self, wnd):
        f, t = self.document.marks['current_script']
        s = wnd.document.gettext(f, t).lstrip().rstrip(' \t')
        with self._redirect_output(wnd):
            curses.cbreak()
            try:
                start = time.time()
                ret = self.interp.runsource(s)
                end = time.time()
            finally:
                curses.raw()

            if not ret:
                kaa.app.messagebar.set_message(
                    'Execued in {} secs'.format(end - start))
                wnd.document.undo.clear()
                if s.strip():
                    hist = kaa.app.config.hist(
                        'pyconsole_script',
                        self.MAX_HISTORY)
                    hist.add(s)

                self.document.append('>>>', self.get_styleid('ps'))
                self.document.append('\n', self.get_styleid('default'))
                p = self.document.endpos()
                self.document.marks['current_script'] = (p, p)
                wnd.cursor.setpos(p)
            else:
                self.on_commands(wnd, ['edit.newline'])
                return
예제 #31
0
파일: ten.py 프로젝트: code4tots/ten
def main(window):
  curses.curs_set(0)
  curses.raw()
  curses.use_default_colors()
  curses.init_pair(DEFAULT_COLOR_PAIR, -1, -1)
  e = Editor(attrs=curses.color_pair(DEFAULT_COLOR_PAIR)|curses.A_NORMAL)
  e.draw(window, 0)
  while True:
    c = window.getch()
    if c == 3:  # break on '^c'
      break
    elif c == 127:  # backspace
      e.backspace()
    elif c == curses.KEY_LEFT:
      e.move_left()
    elif c == curses.KEY_RIGHT:
      e.move_right()
    elif c == curses.KEY_UP:
      e.move_up()
    elif c == curses.KEY_DOWN:
      e.move_down()
    elif c in PRINTABLE:
      e.add(chr(c))
    else:
      raise Exception('Bad code: ' + repr(c))
    e.draw(window, 0)
    window.refresh()
예제 #32
0
    def start(self):
        self.stdscr = curses.initscr()
        self.stdscr.immedok(True)
        curses.noecho()
        curses.raw()
        self.stdscr.clear()
        rows, cols = self.stdscr.getmaxyx()
        self.header = curses.newwin(1, cols, 0, 0)
        self.screen = VMConsole.CursesScreen(self, cols, rows - 2)
        self.stream.attach(self.screen)
        self.window = curses.newwin(rows - 1, cols, 1, 0)
        self.window.immedok(True)
        self.header.immedok(True)
        self.header.bkgdset(' ', curses.A_REVERSE)
        self.header.addstr(0, 0, self.header_msg[:cols - 1])
        signal(SIGWINCH, self.resize)
        self.connect()
        while True:
            ch = self.stdscr.getch()
            if ch == 29:
                curses.endwin()
                self.disconnect()
                break

            self.conn.write(chr(ch))
예제 #33
0
def wrappred_main(stdscr, args):
    curses.use_default_colors()
    curses.noecho()
    curses.cbreak()
    curses.raw()
    stdscr.keypad(True)
    stdscr.clearok(False)
    stdscr.immedok(False)

    editor = Editor()
    rows, cols = stdscr.getmaxyx()
    screen = Screen(rows, cols)
    editor.screen = screen

    if args.file is not None:
        editor.open(args.file)

    while not editor.exiting:

        for row in range(screen.rows):
            # curses throws error when addch() writes to the last column
            lastcol = screen.cols - 1
            for col in range(lastcol):
                stdscr.addch(row, col, screen[row,col])
            stdscr.insch(row, lastcol, screen[row,lastcol])
        stdscr.move(screen.cursor.row, screen.cursor.col)

        editor.input_buffer.put(stdscr.getch())
        editor.refresh()
예제 #34
0
def draw(scr):
    curses.raw() #disable certain keybindings
    #set up colors
    curses.use_default_colors()
    white = -1
    curses.init_pair(1, 0, white)
    curses.init_pair(2, 4, white)
    curses.init_pair(3, 0, 2)
    curses.init_pair(4, 7, 0)
    curses.init_pair(5, 6, white)
    curses.init_pair(6, 4, 7)
    curses.init_pair(7, 7, 4)
    curses.init_pair(8, 6, 7) 
    curses.init_pair(9, 5, white) 
    scr.erase()
    scr.refresh()
    height, width = scr.getmaxyx()
    for i in range(height-1):
        scr.addstr(i, 0, ' ' * (width), curses.color_pair(1))
    if not os.path.isfile(filename) : open(filename, 'a').close()
    e = editor(scr, filename)
    while e.key != 27: #quit on escape
        e.refresh()
        e.doinput()
    #save before quitting
    file = open(e.filename, 'w')
    file.write('\n'.join(e.lines))
    file.close()
예제 #35
0
    def exec_script(self, wnd):
        self.document.undo.clear()
        f, t = self.document.marks['current_script']
        s = wnd.document.gettext(f, t).lstrip()
        with self._redirect_output(wnd):
            curses.cbreak()
            try:
                ret = self.interp.runsource(s)
            finally:
                curses.raw()

            if not ret:
                if s.strip():
                    hist = kaa.app.config.hist(
                        'pyconsole_script',
                        self.MAX_HISTORY)
                    hist.add(s)

                self.document.append('>>>', self.get_styleid('ps'))
                self.document.append('\n', self.get_styleid('default'))
                p = self.document.endpos()
                self.document.marks['current_script'] = (p, p)
                wnd.cursor.setpos(p)
            else:
                self._show_inputline(wnd, s + '\n')
예제 #36
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()
예제 #37
0
파일: guiTree.py 프로젝트: icedwater/clifox
 def __call__(self, screen):
  self.screen = screen
  self.screen.nodelay(1)
  self.screen.keypad(1)
  curses.raw(1)
  curses.noecho()
  self.maxy,self.maxx=self.screen.getmaxyx()
  self.screen.addstr(self.maxy-1,0,"-"*(self.maxx-2))
  self.maxy-=2
  self.maxx-=1
  self.show()
  while 1:
   time.sleep(0.001)
   k=self.screen.getch()
#we're using nodelay, so -1 means no keystroke.
   if k==-1:
    continue
#each time a key is pressed, it should be shown here.
#write spaces to top line of window for clear line
   if k==ord('q'):
    return None
   if k==curses.KEY_LEFT:
    self.collapse()
   if k==curses.KEY_RIGHT:
    self.expand()
   if k==curses.KEY_UP:
    self.up()
   if k==curses.KEY_DOWN:
    self.down()
   if k in (curses.KEY_ENTER,10):
    if self.canReturn(self.cur):
     self.collapseEntireList()
     return self.getReturnable(self.cur)
   continue
예제 #38
0
def hackertype(file):
    w = curses.initscr()

    curses.noecho()
    curses.raw()
    curses.cbreak()

    def signal_handler(signal, frame):
        curses.noraw()
        curses.endwin()
        print("OHSHITEXPLODE")
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    file = open(file)
    w.leaveok(0)
    while True:
        if w.getch() != -1:
            char = file.read(1)
            sys.stdout.write(char)
            w.move(0, 0)
            if char == '\n':
                sys.stdout.write('\r')
            sys.stdout.flush()
예제 #39
0
def main():
    """ Entry point for example 2
    """
    screen = curses.initscr()  # Start curses mode
    curses.raw()  # Line buffering disabled
    screen.keypad(True)  # We get F1, F2 etc..
    curses.noecho()  # Don't echo() while we do getch

    # The Python API doesn't have printw, so use addstr
    screen.addstr("Type any character to see it in bold\n")

    # If raw() hadn't been called we have to press enter
    # before it gets to the program
    # Note that this is a C-character (an integer between 0 and 255)
    char = screen.getch()

    # Without keypad enabled this will not get to us either
    if char == curses.KEY_F2:
        # Without noecho() some ugly escape charachters might
        # have been printed on screen
        screen.addstr("F2 Key pressed")
    else:
        screen.addstr("The pressed key is ")
        screen.attron(curses.A_BOLD)
        screen.addstr("%s" % (chr(char), ))
        screen.attroff(curses.A_BOLD)

    screen.refresh()  # Print it on to the real screen
    screen.getch()  # Wait for user input
    curses.endwin()  # End curses mode

    sys.exit(0)
예제 #40
0
 def __enter__(self):
     """Open ANSI interface."""
     VideoPlugin.__enter__(self)
     self.screen = curses.initscr()
     curses.noecho()
     curses.cbreak()
     curses.nonl()
     curses.raw()
     self.orig_size = self.screen.getmaxyx()
     self.underlay = curses.newwin(
         self.height + self.border_y*2, self.width + self.border_x*2, 0, 0
     )
     self.window = curses.newwin(self.height, self.width, self.border_y, self.border_x)
     self.window.nodelay(True)
     self.window.keypad(True)
     self.window.scrollok(False)
     curses.start_color()
     # curses mistakenly believes changing palettes works on macOS's Terminal.app
     self.can_change_palette = (not MACOS) and (
         curses.can_change_color() and curses.COLORS >= 16 and curses.COLOR_PAIRS > 128
     )
     sys.stdout.write(SET_TITLE % self.caption.encode('utf-8', 'replace'))
     sys.stdout.flush()
     self._set_default_colours(16)
     bgcolor = self._curses_colour(7, 0, False)
     # text and colour buffer
     self.text = [[[(u' ', bgcolor)]*self.width for _ in range(self.height)]]
     self.set_border_attr(0)
     self.screen.clear()
예제 #41
0
def main(stdscr):
    curses.raw()

    height, width = stdscr.getmaxyx()
    beg = (4, 10)
    end = (height - 4, width - 10)

    textpad.rectangle(stdscr, beg[0], beg[1], end[0], end[1])
    box_width = end[1] - beg[1]

    stdscr.move(beg[0] + 1, beg[1] + 1)

    line = str()
    lines = list()

    while True:
        key = stdscr.getch()
        cursor = stdscr.getyx()

        if key == 3:
            break

        elif key == 10:
            if cursor[0] + 1 == end[0]:
                continue

            lines.append(line + "\n")
            line = str()
            stdscr.move(cursor[0] + 1, beg[1] + 1)
            continue

        elif key == 263:
            if cursor[1] - 1 == beg[1]:
                continue
                # if len(lines) == 0:
                #     continue

                # else:
                #     stdscr.move(cursor[0] - 1, beg[1] + len(lines[-1]))
                #     lines.pop()
                #     continue
    
            stdscr.addstr(cursor[0], cursor[1] - 1, " ")
            stdscr.move(cursor[0], cursor[1] - 1)
            line = line[:-1]
            continue

        if len(line) + 1 == box_width:
            continue

        line += chr(key)
        stdscr.addstr(chr(key))

    if len(lines) == 0:
        lines = [line]

    buf = "".join(lines)

    with open("test_file", "w") as f:
        f.write(buf)
예제 #42
0
파일: ttyfe.py 프로젝트: kcr/snipe
    def __enter__(self):
        locale.setlocale(locale.LC_ALL, '')
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.nonl()
        curses.raw()

        termstate = termios.tcgetattr(0)
        termstate[6][termios.VINTR] = bytes([self.INTCHAR])
        nope = bytes([0])  # to disable a character
        termstate[6][termios.VQUIT] = nope
        termstate[6][termios.VSUSP] = nope
        if hasattr(termios, 'VDSUSP'):
            termstate[6][termios.VDSUSP] = nope  # pragma: nocover
        termstate[3] |= termios.ISIG
        termios.tcsetattr(0, termios.TCSANOW, termstate)

        self.stdscr.keypad(1)
        self.stdscr.nodelay(1)
        self.color_assigner = ttycolor.get_assigner()
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.orig_sigtstp = signal.signal(signal.SIGTSTP, self.sigtstp)
        self.main_pid = os.getpid()
        loop = asyncio.get_event_loop()
        loop.add_signal_handler(signal.SIGWINCH, self.sigwinch, loop)

        with mock.patch(
                'asyncio.unix_events._sighandler_noop', self.sighandler_op):
            loop.add_signal_handler(signal.SIGINT, self.sigint)

        return self
예제 #43
0
    def __init__(self, coloring, colorMap=None):
        # check and set singleton object
        if Screen.__obj is not None:
            raise RuntimeError(_('Duplicate "Screen" object.'))
        Screen.__obj = self

        # initialize
        self.__scr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.raw()
        self.__scr.keypad(1)
        self.__scr.timeout(Screen.__TIMEOUT)

        # for self.__h, self.__w
        self.__updateSize()

        # settings
        self.__coloring = coloring and curses.has_colors()

        # color settings
        if self.__coloring:
            curses.start_color()

            # default color mapping
            for val in Screen.__COLORNUM.values():
                if val == 0:
                    continue
                curses.init_pair(val, val, val)

            # optional color mapping
            if colorMap is not None:
                for key, val in colorMap.items():
                    if key in Screen.__COLORNUM:
                        curses.init_pair(Screen.__COLORNUM[key], val, val)
예제 #44
0
파일: phnb_curses.py 프로젝트: Agyar/phnb
    def init_ui(self):
        self._screen = curses.initscr()
        curses.noecho()
        curses.raw()
        curses.curs_set(0)
        self._screen.keypad(1)

        self._create_pad()
        self._define_colors()

        self.SCR_HEIGHT, self.SCR_WIDTH = self._screen.getmaxyx()
        if self.SCR_WIDTH < self.MIN_SIZE_CVIEW:
            self._mode = 'vanilla'
        else:
            self._active_panel = '_main'
            self._panels = {
                # win name : {( start x, start y, end x, end y) : win obj}
                '_main': {
                    (1, 0, self.SCR_HEIGHT, 46): None
                },
                '_c_one': {
                    (1, 47, self.SCR_HEIGHT, 129): None
                },
                '_c_two': {
                    (1, 130, self.SCR_HEIGHT, 212): None
                }
            }
            self._make_textboxes()
        self._screen.refresh()
예제 #45
0
파일: main_02.py 프로젝트: voxelv/glopnet
def run():
    ch = -1
    count = 0
    event = None

    os.environ['TERM'] = "xterm-1003"

    screen = curses.initscr()
    curses.raw()
    screen.keypad(True)
    curses.noecho()

    screen.clear()
    curses.cbreak()

    curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)

    while ch != ord('q'):
        count += 1
        # screen.addstr(1, 1, "Has mouse {}".format(curses.has_mouse()))
        screen.addstr(
            2, 1, "Key code: {}; mouse code:{}".format(ch, curses.KEY_MOUSE))
        if ch == curses.KEY_MOUSE:
            event = curses.getmouse()
            screen.addstr(
                3, 3,
                "Mouse Event: x={}, y={}, z={}".format(event[1], event[2],
                                                       event[3]))
            screen.addstr(4, 3, "Mouse device id: {}".format(event[0]))
            screen.addstr(5, 3, "Mouse button mask: {}".format(event[4]))
        screen.addstr(6, 1, "Event number: {}".format(count))
        screen.refresh()
        ch = screen.getch()
    curses.endwin()
예제 #46
0
파일: psplit.py 프로젝트: ammongit/scripts
    def run(self, win):
        curses.raw()
        curses.nonl()
        curses.noecho()

        while True:
            self.redraw(win)

            ch = win.getch()
            if ch in NEXT:
                self.blockno = min(self.blockno + 1, len(self.blocks) - 1)
            elif ch in PREV:
                self.blockno = max(self.blockno - 1, 0)
            elif ch in FIRST:
                self.blockno = 0
            elif ch in LAST:
                self.blockno = len(self.blocks) - 1
            elif ch in RANDOM:
                self.blockno = random.randint(0, len(self.blocks) - 1)
            elif ch in EDIT:
                self.edit(win)
            elif ch in HELP:
                self.print_help(win)
            elif ch in QUIT:
                return 0
예제 #47
0
파일: pyview.py 프로젝트: langner/lfm
 def init_curses(self):
     self.maxh, self.maxw = self.win.getmaxyx()
     curses.cbreak()
     curses.raw()
     curses.curs_set(0)
     try:
         self.win_title = curses.newwin(1, self.maxw, 0, 0)
         self.win_file = curses.newwin(self.maxh-2, self.maxw, 1, 0)
         self.win_status = curses.newwin(1, self.maxw, self.maxh-1, 0)
     except curses.error:
         print 'Can\'t create windows'
         sys.exit(-1)
     if curses.has_colors():
         curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLUE)    # title
         curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)    # files
         curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_CYAN)      # current file
         curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_CYAN)   # messages
         curses.init_pair(5, curses.COLOR_GREEN, curses.COLOR_BLACK)    # help
         curses.init_pair(6, curses.COLOR_RED, curses.COLOR_BLACK)      # file info
         curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_RED)      # error messages
         curses.init_pair(8, curses.COLOR_BLACK, curses.COLOR_RED)      # error messages
         curses.init_pair(9, curses.COLOR_YELLOW, curses.COLOR_RED)     # button in dialog
         curses.init_pair(10, curses.COLOR_YELLOW, curses.COLOR_BLACK)  # file selected
         curses.init_pair(11, curses.COLOR_YELLOW, curses.COLOR_CYAN)   # file selected and current
         self.win_title.bkgd(curses.color_pair(1),
                             curses.color_pair(1) | curses.A_BOLD)
         self.win_file.bkgdset(curses.color_pair(2))
         self.win_status.bkgdset(curses.color_pair(1))
     self.win_file.leaveok(1)
     self.win_file.keypad(1)
예제 #48
0
파일: curses.py 프로젝트: clandgraf/cui
    def initialize(self):
        self._color_index_map = DEFAULT_COLOR_INDEX_MAP.copy()
        self._old_signal_handler = None

        # Init Curses
        self._screen = curses.initscr()
        curses.savetty()
        curses.raw(1)
        curses.nonl()
        curses.noecho()
        curses.curs_set(0)
        self._screen.keypad(1)
        self._screen.timeout(0)
        self._core.add_exit_handler(self.close)

        # Init Colors
        curses.start_color()
        self._init_colors()

        # Init Symbols
        self.symbols = {
            symbols.SYM_VLINE: curses.ACS_VLINE,
            symbols.SYM_HLINE: curses.ACS_HLINE,
            symbols.SYM_LTEE: curses.ACS_LTEE,
            symbols.SYM_LLCORNER: curses.ACS_LLCORNER,
            symbols.SYM_RARROW: curses.ACS_RARROW,
            symbols.SYM_DARROW: curses.ACS_DARROW,  #ord('v'),
        }

        # Init Event Handling
        self._core.io_selector.register(sys.stdin, self._read_input)
        self._core.io_selector.register_async(TERMINAL_RESIZE_EVENT,
                                              self._handle_resize)
        self._old_signal_handler = signal.getsignal(signal.SIGWINCH)
        signal.signal(signal.SIGWINCH, self._handle_resize_sig)
예제 #49
0
 def __enter__(self):
     """Open ANSI interface."""
     VideoPlugin.__enter__(self)
     try:
         self.screen = curses.initscr()
         curses.noecho()
         curses.cbreak()
         curses.nonl()
         curses.raw()
         self.orig_size = self.screen.getmaxyx()
         self.window = curses.newwin(self.height + self.border_y * 2,
                                     self.width + self.border_x * 2, 0, 0)
         self.window.nodelay(True)
         self.window.keypad(True)
         self.window.scrollok(False)
         curses.start_color()
         # curses mistakenly believes changing palettes works on macOS's Terminal.app
         self.can_change_palette = (not MACOS) and (
             curses.can_change_color() and curses.COLORS >= 16
             and curses.COLOR_PAIRS > 128)
         self._set_default_colours(16)
         bgcolor = self._curses_colour(7, 0, False)
         self.set_border_attr(0)
         self._resize(self.height, self.width)
         self.screen.clear()
     except Exception as e:
         # if setup fails, don't leave the terminal raw
         self._close()
         raise
예제 #50
0
파일: hexscreen.py 프로젝트: hexcap/hexcap
  def __init__(self):
    locale.setlocale(locale.LC_ALL, '')
    self.code = locale.getpreferredencoding()
    self.stdscr = curses.initscr()
    curses.noecho()
    curses.raw()
    self.stdscr.keypad(1)

    self.headerHeight = 2 # Section / Column names
    self.footerHeight = 2 # Includes blank line

    # Our stack of hidden sections
    self.hiddenSectIDs = []

    # Are we in insert mode?
    self.insert = False

    # Is the mark set?
    self.markSet = False

    # Packet ID of marked packet. Zero based.
    self.mark = 0

    # Flag is True if mini-buffer has focus
    self.mBufFocus = False

    # Message to be printed to mBuf for one cycle and then cleared
    self.mBufMsg = ''
예제 #51
0
파일: screen.py 프로젝트: odashi/ganglist
	def __init__(self, coloring, colorMap=None):
		# check and set singleton object
		if Screen.__obj is not None:
			raise RuntimeError(_('Duplicate "Screen" object.'))
		Screen.__obj = self

		# initialize
		self.__scr = curses.initscr()
		curses.noecho()
		curses.cbreak()
		curses.raw()
		self.__scr.keypad(1)
		self.__scr.timeout(Screen.__TIMEOUT)

		# for self.__h, self.__w
		self.__updateSize()

		# settings
		self.__coloring = coloring and curses.has_colors()

		# color settings
		if self.__coloring:
			curses.start_color()
			
			# default color mapping
			for val in Screen.__COLORNUM.values():
				if val == 0:
					continue
				curses.init_pair(val, val, val)

			# optional color mapping
			if colorMap is not None:
				for key, val in colorMap.items():
					if key in Screen.__COLORNUM:
						curses.init_pair(Screen.__COLORNUM[key], val, val)
예제 #52
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()
예제 #53
0
    def exec_script(self, wnd):
        f, t = self.document.marks['current_script']
        s = wnd.document.gettext(f, t).lstrip().rstrip(' \t')
        with self._redirect_output(wnd):
            curses.cbreak()
            try:
                start = time.time()
                ret = self.interp.runsource(s)
                end = time.time()
            finally:
                curses.raw()

            if not ret:
                kaa.app.messagebar.set_message(
                    'Execued in {} secs'.format(end - start))
                wnd.document.undo.clear()
                if s.strip():
                    hist = kaa.app.config.hist('pyconsole_script',
                                               self.MAX_HISTORY)
                    hist.add(s)

                self.document.append('>>>', self.get_styleid('ps'))
                self.document.append('\n', self.get_styleid('default'))
                p = self.document.endpos()
                self.document.marks['current_script'] = (p, p)
                wnd.cursor.setpos(p)
            else:
                self.on_commands(wnd, ['edit.newline'])
                return
예제 #54
0
파일: viewLogFrames.py 프로젝트: Bike/clasp
 def mainloop(self):
     curses.raw()
     self.updateFrames()
     self.redrawAll("viewLog","startup")
     while (1):
         c = self._Window.getch()
         extraMessage = ""
         if ( c == curses.KEY_UP ):
             self.currentFrame().cursorUp()
         elif (c == curses.KEY_DOWN ):
             self.currentFrame().cursorDown()
         elif (c == ord("t") or c == ord(" ") ):
             self.currentFrame().toggleCurrentNode()
         elif (c == ord("o") ):
             self.currentFrame().openCurrentNode()
         elif (c == ord("c") ):
             self.currentFrame().closeCurrentNode()
         elif (c == 22 ): # C-v
             self.currentFrame().pageDown()
         elif (c == 118 ): # M-v
             self.currentFrame().pageUp()
         elif ( c == ord("C") ):
             self.currentFrame().nodeCrawlerCursor().node().closeAllChildren()
         elif ( c == ord("u") ):
             self.currentFrame().parentNode()
         elif (c == 19 ): # C-s
             self.enterSearchString("Forward search")
             extraMessage = self.currentFrame().forwardSearch(self._LastSearch)
         elif (c == 18 ): # C-r
             self.enterSearchString("Reverse search")
             extraMessage = self.currentFrame().reverseSearch(self._LastSearch)
         elif ( c == ord("m") ):
             m = self._Window.getch()
             self._Locations[m] = self.currentFrame().nodeCrawlerCursor()
             extraMessage = "Saved location in register <%c>" % m
         elif ( c == ord("'") ):
             m = self._Window.getch()
             if ( m in self._Locations ):
                 self.currentFrame().setNodeCrawlerCursor(self._Locations[m])
                 self.currentFrame().nodeCrawlerCursor().node().openAllParents()
                 extraMessage = "Restored location in register <%c>" % m
             else:
                 extraMessage = "Unknown register <%c>" % m
         elif ( c == 24 ):
             m = self._Window.getch()
             if ( m == ord("2") ):
                 self.insertFrameBeforeCurrent()
             elif ( m == ord("o") ):
                 self.nextFrame()
             elif ( m == ord("0") ):
                 self.deleteCurrentFrame()
         elif (c == ord("Q") or ( c == 3 ) ):
             return
         elif (curses.keyname(c) == "^v" ):
             self.pageDown()
         statusLine = self.cursorStatus(extraMessage)
         self._Window.erase()
         self.updateFrames()
         self.redrawAll(statusLine,"last key: %d" % c)
예제 #55
0
 def __init__(self, **kwargs):
     """ Initialise the text interface. """
     video.VideoPlugin.__init__(self)
     self.curses_init = False
     if not curses:
         raise video.InitFailed()
     # set the ESC-key delay to 25 ms unless otherwise set
     # set_escdelay seems to be unavailable on python curses.
     if not os.environ.has_key('ESCDELAY'):
         os.environ['ESCDELAY'] = '25'
     self.curses_init = True
     self.screen = curses.initscr()
     self.orig_size = self.screen.getmaxyx()
     curses.noecho()
     curses.cbreak()
     curses.nonl()
     curses.raw()
     curses.start_color()
     self.screen.clear()
     self.height, self.width = 25, 80
     # border width percentage
     border_width = kwargs.get('border_width', 0)
     self.border_y = int(round((self.height * border_width)/200.))
     self.border_x = int(round((self.width * border_width)/200.))
     self.underlay = curses.newwin(
         self.height + self.border_y*2, self.width + self.border_x*2, 0, 0)
     self.window = curses.newwin(self.height, self.width, self.border_y, self.border_x)
     self.window.nodelay(True)
     self.window.keypad(True)
     self.window.scrollok(False)
     self.can_change_palette = (curses.can_change_color() and curses.COLORS >= 16
                           and curses.COLOR_PAIRS > 128)
     self.caption = kwargs.get('caption', '')
     sys.stdout.write(ansi.esc_set_title % self.caption)
     sys.stdout.flush()
     self._set_default_colours(16)
     # cursor is visible
     self.cursor_visible = True
     # 1 is line ('visible'), 2 is block ('highly visible'), 3 is invisible
     self.cursor_shape = 1
     # current cursor position
     self.cursor_row = 1
     self.cursor_col = 1
     # last colour used
     self.last_colour = None
     # text and colour buffer
     self.num_pages = 1
     self.vpagenum, self.apagenum = 0, 0
     bgcolor = self._curses_colour(7, 0, False)
     self.text = [[[(u' ', bgcolor)]*self.width for _ in range(self.height)]]
     self.f12_active = False
     self.set_border_attr(0)
     # set codepage
     try:
         self.codepage = kwargs['codepage']
     except KeyError:
         logging.error('No codepage supplied to text-based interface.')
         raise video.InitFailed()
예제 #56
0
 def __init__(self, screen):
     curses.noecho()
     curses.cbreak()
     curses.raw()
     self.tweet_database = TweetDatabase()
     self.screen = Screen(screen, self)
     self._create_user_dir()
     self._auth = None
     self._stream_thread = UserStreamThread(self)
예제 #57
0
파일: ui.py 프로젝트: jsbronder/fzsl
def ncurses():
    """
    Context manager for curses applications.  This does a number of
    things beyond what curses.wrapper() does.

    - Redirect stdout to stderr.  This is done so that we can still
      use the ncurses interface from within a pipe or subshell.
    - Drop the escape delay down to 25ms, similar to vim.
    - Remove newline mode.

    An ncurses screen is returned by the manager.  If any exceptions
    occur, all of the setup performed by the manager is undone before
    raising the original exception.  This should guarantee that any
    bugs in the code will not leave the user with a messed up shell.
    """
    # Push stdout to stderr so that we still get the curses
    # output while inside of a pipe or subshell
    old_stdout = sys.__stdout__
    old_stdout_fd = os.dup(sys.stdout.fileno())
    os.dup2(sys.stderr.fileno(), sys.stdout.fileno())

    # Reduce the timeout after receiving an escape character, there
    # doesn't seem to be a way to do this via curses so we have to
    # set the environment variable before creating the screen.
    if 'ESCDELAY' not in os.environ:
        os.environ['ESCDELAY'] = '25'

    scr = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    for i in range(curses.COLORS):
        curses.init_pair(i + 1, i, -1)

    curses.noecho()
    curses.cbreak()
    curses.raw()
    curses.nonl()
    curses.curs_set(2)
    scr.keypad(1)

    exc = None
    try:
        yield scr
    except Exception:
        exc = sys.exc_info()

    scr.keypad(0)
    curses.nl()
    curses.nocbreak()
    curses.echo()
    curses.endwin()

    os.dup2(old_stdout_fd, sys.stdout.fileno())
    sys.stdout = old_stdout

    if exc is not None:
        exc[0].with_traceback(exc[1], exc[2])
예제 #58
0
    def pause_interface_callback(self):
        log.debug("Pausing interface.")
        sync_lock.acquire_write()

        curses.raw()

        self.input_lock.acquire()

        curses.endwin()