Example #1
0
 def resize(self, yx=None):
     """Resize UI to yx."""
     if yx is None:
         yx = self.screen.getmaxyx()
     self.screen.erase()
     curses.resizeterm(yx[0], yx[1])
     self.setup_windows(resize=True)
Example #2
0
    def setupwindows(self, resize=False):
        """Setup and draw bannerwin and logwin

        If `resize`, don't create new windows, just adapt size. This
        function should be invoked with CursesUtils.locked()."""
        self.height, self.width = self.stdscr.getmaxyx()
        self.logheight = self.height - len(self.accframes) - 1
        if resize:
            curses.resizeterm(self.height, self.width)
            self.bannerwin.resize(1, self.width)
            self.logwin.resize(self.logheight, self.width)
        else:
            self.bannerwin = curses.newwin(1, self.width, 0, 0)
            self.logwin = curses.newwin(self.logheight, self.width, 1, 0)

        self.draw_bannerwin()
        self.logwin.idlok(True)  # needed for scrollok below
        self.logwin.scrollok(True)  # scroll window when too many lines added
        self.draw_logwin()
        self.accounts = reversed(sorted(self.accframes.keys()))
        pos = self.height - 1
        index = 0
        self.hotkeys = []
        for account in self.accounts:
            acc_win = curses.newwin(1, self.width, pos, 0)
            self.accframes[account].setwindow(acc_win, index)
            self.hotkeys.append(account)
            index += 1
            pos -= 1
        curses.doupdate()
Example #3
0
 def initialize(self):
     self.stdscr = curses.initscr()
     curses.resizeterm(self.screen_y, self.screen_x)
     self.stdscr.keypad(True)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(False)
Example #4
0
def draw_player_selection_screen(stdscr, players, option):
    """
    Draws a screen where the user can select two players to play a game. The
    user can select themselves as a player or a bot.
    """
    # Clear the screen before drawing anything.
    stdscr.clear()

    # Get the height and width of the window and resize the screen if either
    # go below a certain threshold.
    height, width = stdscr.getmaxyx()
    if width < 64:
        width = 64
        curses.resizeterm(height, width)
    if height < 26:
        height = 26
        curses.resizeterm(height, width)

    # Centering calculation.
    centre_x = int(width // 2)
    top_y = 4

    # Draw two rectangles, the first to encompass the player options and the
    # second to encompass the selected players.
    draw_panel_border(stdscr, centre_x - 29, top_y, 58, 13)
    draw_panel_border(stdscr, centre_x - 29, top_y + 15, 58, 3)

    # Print a header in the first rectangle detailing which side is being
    # selected for.
    if len(players) < 2:
        side_name = "white" if len(players) == 1 else "black"
        header = "Select a player to play as {0}:".format(side_name)
    elif len(players) == 2:
        header = " Press Enter to start the game."
    stdscr.attron(curses.A_BOLD)
    stdscr.addstr(top_y + 1, centre_x - 16, header)
    stdscr.attroff(curses.A_BOLD)
    stdscr.addstr(top_y + 13, centre_x - 28, "Press backspace to undo.")

    # Print the available options with the current option highlighted.
    x = centre_x - 28
    y = top_y + 2
    for op, option_string in enumerate(PLAYERS):
        colour = 3 if option == op else 1
        stdscr.attron(curses.color_pair(colour))
        stdscr.addstr(y + 3 + 3 * op, x, option_string)
        stdscr.attroff(curses.color_pair(colour))
        stdscr.addstr(y + 3 + 3 * op, x + 13, PLAYER_DESCRIPTIONS[op])

    # Print which options have been selected so far in the second rectangle.
    b = PLAYERS[players[0]] if len(players) > 0 else "__"
    w = PLAYERS[players[1]] if len(players) > 1 else "__"
    currently_selected = "{0} as black - vs - {1} as white".format(b, w)
    x = int((width // 2) - (len(currently_selected) // 2))
    stdscr.attron(curses.A_BOLD)
    stdscr.addstr(top_y + 17, x, currently_selected)
    stdscr.attroff(curses.A_BOLD)

    # Refresh the screen
    stdscr.refresh()
Example #5
0
    def update(self):
        if self._query_reshape < 0 and time.time() > -self._query_reshape:
            self._query_reshape = 0.0

        if self._query_reshape > 0 and time.time() > self._query_reshape + 0.5:
            height, width = self._stdscr.getmaxyx()

            self._stdscr.clear()
            curses.resizeterm(height, width)

            for k, view in self._views.items():
                # reshape any views
                view.reshape(height, width)

            self._views.get('info').redraw()
            self._views.get('help').redraw()
            self._views.get('default').redraw()
            self._views.get('command').redraw()
            self._views.get('status').redraw()
            self._views.get('notice').redraw()
            self._views.get('panel').redraw()
            self._views.get('panel-head').redraw()

            if self._active_content:
                view = self._views.get(self._active_content)
                if view:
                    view.redraw()

            self._stdscr.refresh()
            self._query_reshape = -time.time() - 0.5

        for k, view in self._views.items():
            view.refresh()
Example #6
0
    def display(self):
        # Display event loop
        while True:
            y, x = self.stdscr.getmaxyx()
            if( y != self._height ) or ( x != self._width ):
                self._height = y
                self._width = x
                curses.resizeterm(y, x)
                self.update()

            c = self.stdscr.getch()
            

            # TODO - Handle various keystrokes here
            if c == curses.KEY_RIGHT:
                self.tab_shift_right()
#            elif c == curses.KEY_RESIZE:
#                self.resize()
            elif c == curses.KEY_LEFT:
                self.tab_shift_left()
            elif c == ord('q') or c == ord('Q'):
                break

            # Refresh subwindow
            self._active_tab.subwindow.clear()
            self._active_tab.subwindow.refresh()

            # Refresh the windows from the bottom up
            self.update()
Example #7
0
def loop(screen, update_delay):
    redraw(screen)
    #print('Please wait. The display is updated every {sleep:.0f} seconds.'
    #         .format(sleep=sleep))
    #print('Starting up...')

    # Main loop
    y, x = screen.getmaxyx()
    while True:
        try:
            signal.alarm(int(update_delay))
            in_char = screen.getch()  # Input
            signal.alarm(0)
        except TimedOutException:
            in_char = IN_TIMEOUT

        # Handle resize
        resized = curses.is_term_resized(y, x)
        if resized is True:
            y, x = screen.getmaxyx()
            screen.clear()
            curses.resizeterm(y, x)
            redraw(screen)

        if in_char in [ord(' '), IN_TIMEOUT]:
            redraw(screen)
        elif in_char is ord('q'):
            raise SystemExit()
        else:
            pass  # ignore
def main(stdscr, max_y, max_x):
    # set up screen for standard terminal size
    global screen
    screen = stdscr.subwin(max_y,max_x,0,0)
    screen.box()
    screen.hline(2, 1, curses.ACS_HLINE, max_x-2)
    screen.addstr(30, 10, str(max_y))
    screen.addstr(31, 10, str(max_x))
    screen.refresh()

    # define menus
    file_menu = ("File", file_func) 
    exit_menu = ("Exit", exit_func) # EXIT

    # add topbar menu
    menus_setup((file_menu, exit_menu))

    #topbar menu loop
    while topbar_key_handler():
        screen.move(1,1)
        new_y, new_x = stdscr.getmaxyx()
        if (new_y, new_x) != (max_y, max_x):
            if new_x > max_x:
                rm_col(max_y, max_x)
            if new_y > max_y:
                rm_row(max_y, max_x)
        max_y, max_x = new_y, new_x
        curses.resizeterm(max_y, max_x)
        screen.box()
        screen.hline(2, 1, curses.ACS_HLINE, max_x-2)
        screen.refresh()
Example #9
0
 def resize(self):
     '''resize the screen'''
     # move to the renderer
     y, x = self.scr.getmaxyx()
     curses.resizeterm(y, x)
     self.render.entire_buffer(self.buff)
     self.scr.refresh()
Example #10
0
 def setup_curses(self):
     curses.resizeterm(24, 80)
     curses.start_color()
     curses.use_default_colors()
     curses.curs_set(False)
     self.window_size = self.stdscr.getmaxyx()
     self.stdscr.nodelay(True)
Example #11
0
def check_screen_resize(screen):

    if screen.getch() == curses.KEY_RESIZE:
        curses.resizeterm(*screen.getmaxyx())
        screen.clear()
        screen.border()
        screen.refresh()
Example #12
0
def test_resize_term(stdscr):
    if hasattr(curses, 'resizeterm'):
        lines, cols = curses.LINES, curses.COLS
        curses.resizeterm(lines - 1, cols + 1)

        if curses.LINES != lines - 1 or curses.COLS != cols + 1:
            raise RuntimeError, "Expected resizeterm to update LINES and COLS"
Example #13
0
 def sigwch(signum, stackframe):
     screen_size = struct.pack("HHHH", 0, 0, 0, 0)
     screen_size = fcntl.ioctl(0, termios.TIOCGWINSZ, screen_size)
     rows, cols, xpixels, ypixels = struct.unpack('HHHH', screen_size)
     if curses.is_term_resized(rows, cols):
         curses.resizeterm(rows, cols)
         raise TerminalResized("Terminal size changed")
Example #14
0
    def BatchRun(cls, Command=None, BatchSize=multiprocessing.cpu_count(), TimeOut=3, MaxTime=604800):
        print('Running batch of GITR simulations. Batchsize={}. TimeOut={}'.format(
            BatchSize, TimeOut))
        assert BatchSize > 0, "BatchSize<1"
        Tstart = time.time()
        TimeElapsed = 0
        cls.Screen = curses.initscr()
        cls.Screen.resize(len(cls.CurrentSimu)+10, 150)
        curses.resizeterm(len(cls.CurrentSimu)+10, 150)
        cls.Nprocess = 0
        while TimeElapsed < MaxTime and cls.Nprocess <= len(cls.CurrentSimu):
            TimeElapsed = time.time()-Tstart
            while cls.CheckRunningSim() < BatchSize and cls.Nprocess < len(cls.CurrentSimu):
                for S in cls.CurrentSimu:
                    if S.Process is None:
                        #print('Time elapsed: {:.1f} - Running simulations: {}'.format(TimeElapsed, cls.CheckRunningSim()))
                        S.Start(Command)
                        cls.Nprocess = cls.Nprocess + 1
                        break

            cls.Screen.clear()
            cls.Screen.addstr(0, 0, cls.DisplayOutput(TimeElapsed=TimeElapsed), curses.A_PROTECT)
            cls.Screen.refresh()
            if cls.CheckRunningSim() == 0:
                break

            time.sleep(TimeOut)

        #curses.endwin()
        cls.Screen.clear()
        cls.Screen.addstr(0, 0, cls.DisplayOutput(TimeElapsed=TimeElapsed), curses.A_PROTECT)
        cls.Screen.refresh()
        cls.StopBatch()
Example #15
0
    def resize(self):
        """Handles a resized terminal."""
        self.screen.redraw = True

        max_y, max_x = self.screen.window.getmaxyx()
        self.screen.clear()

        # Check if we have the resizeterm ncurses extension
        if hasattr(curses, "resizeterm"):
            curses.resizeterm(max_y, max_x)
            # An ungetch for KEY_RESIZE will be sent to let others handle it.
            # We'll just pop it off again to prevent endless loops.
            self.screen.get_key()

        self.screen.set_quote(self.quote)

        if self.start is not None and self.stop is None:
            # Resize during typing requires redrawing quote.
            self.screen.update_quote(Screen.COLOR_QUOTE)
            self.screen.update_author()

            if self.position + self.incorrect <= len(self.quote.text):
                for pos in range(self.position + 1):
                    self.screen.highlight_progress(pos, 0)
                for inc in range(self.incorrect + 1):
                    self.screen.highlight_progress(self.position, inc)
Example #16
0
def print_status(status_message=""):
    global ypos
    global maxyx

    ypos = 0
    stdscr.clear()
    if curses.is_term_resized(*maxyx):
        maxyx = stdscr.getmaxyx()
        curses.resizeterm(*maxyx)

    print_autoy(datetime.now().strftime("%c"))
    print_autoy("")

    if status_message:
        for msg in status_message.split('\n'):
            print_autoy(msg)


    ws = Worker.all(connection=conn)
    print_autoy("WORKERS (%s): " % len(ws), yadd=1)
    if ws:
        for w in sorted(ws, key=lambda x: x.name):
            print_autoy("worker %s: %s" % (w.name, job_string(w.get_current_job())), xadd=2)
    else:
        print_autoy("no workers", xadd=2)

    qs = Queue.all(connection=conn)
    print_autoy("QUEUES: ", yadd=1)
    for q in sorted(qs, key=lambda x: x.name):
        print_autoy("%s (%s):" % (q.name, len(q)), xadd=2)

        for j in sorted(q.get_jobs(), key=lambda x: x.enqueued_at):
            print_autoy(job_string(j), xadd=4)

    stdscr.refresh()
Example #17
0
 def _handle_resize(self):
    curx, cury = get_terminal_size()
    if self.screen_size != (cury, curx):
       self.screen_size = (cury, curx)
       curses.resizeterm(cury, curx)
       self.layout._resize(0, 0, curx, cury)
       self.refresh_event.set()
Example #18
0
 def resize(self):
     """Handle window resizing."""
     if curses.is_term_resized(self.max_win_size_y, self.max_win_size_x):
         self.win_init()
         self.box_init()
         self.text = [self._text_wrap(i) for i in self.text]
         curses.resizeterm(self.max_win_size_y, self.max_win_size_x)
def checkIfresize(win,x,y):
		# Check if screen was re-sized (True or False)
		resize = curses.is_term_resized(y, x)
		# Action in loop if resize is True:
		if resize == True:
			ry,rx = win.getmaxyx()
			win.clear()
			curses.resizeterm(ry,rx)
			drowList(win,config,iterator,ry-4)
			#try:
			for i in range(0,rx):	# 窗口缩放过快可能导致窗口大小变化,导致出错
									# 即便是做了这个保险也是会出错......
				ty,tx = win.getmaxyx()
				#if(rx == tx):
				win.addstr(ry-3,i,"=")
			#except:
			'''	with open("log","a") as f:#debug
					t = win.getmaxyx()
					f.write(str(t))
					f.write("---")
					f.write(str(rx))
					f.write("-----")
					f.write(str(i))
					f.write("-------")
					f.write(str(ry)+"\n")
			'''
			catThing(win,"resize to:"+str(ry)+":"+str(rx))
			return (ry,rx)
		return (y,x)
Example #20
0
    def __init__(self):
        print("\x1b[8;"+str(HEIGHT)+";"+str(WIDTH)+"t")
        self.stdscr = curses.initscr()
        curses.start_color()
        curses.use_default_colors()

        # @ in title and credits
        curses.init_pair(1, -1, curses.COLOR_RED)
        # ^ in title and credits
        curses.init_pair(2, -1, curses.COLOR_GREEN)
        # = in title and credits
        curses.init_pair(3, -1, curses.COLOR_BLUE)
        # menu unselected
        curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_YELLOW)
        # menu selected
        curses.init_pair(5, -1, curses.COLOR_RED)
        # A in title
        curses.init_pair(6, curses.COLOR_RED, -1)
        # V in title
        curses.init_pair(7, curses.COLOR_GREEN, -1)
        # E in title
        curses.init_pair(8, curses.COLOR_BLUE, -1)
        # inventory
        curses.init_pair(9, -1, curses.COLOR_BLUE)
        # gameover
        curses.init_pair(10, -1, curses.COLOR_BLUE)

        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.stdscr.keypad(1)
        curses.resizeterm(HEIGHT,WIDTH)
        self.stdscr.refresh()
def main(stdscr):
  global screen
  text = "This is a test"
  screen = stdscr.subwin(0, 0)
  screen.box() # Wrap screen window in box
  # Get window diminsions
  y, x = screen.getmaxyx()
  global cur_x, cur_y;
  # Sets the cursor to center the text on screen
  cur_x = (x/2)-(len(text))/2
  cur_y = (y/2)
  # Add string to screen
  screen.addstr( cur_y, cur_x, text) 
  screen.refresh() # Refresh to populate screen with data

  c = screen.getch() # Get char
  while c != ord('q'): # Exit loop if char caught is 'q'
    screen.addstr(1,1,str(c))
    screen.refresh()
    if c == 65: # ARROW_UP
      move_up(text, screen) 
    elif c == 66: # ARROW_DOWN
      move_down(text, screen)
    elif c == 68: # ARROW_LEFT
      move_left(text, screen)
    elif c == 67: # ARROW_RIGHT
      move_right(text, screen) 
    elif c == 410:
      y, x = screen.getmaxyx()
      curses.resizeterm(y, x) # Resize curses boundaries
      move_center(text,screen)

    c = screen.getch()
  
  return
Example #22
0
    def __init__(self, stdscr):
        META_DATA_FILE = os.path.join(os.path.dirname(__file__), 'meta.data')
        self.stdscr = stdscr
        # topic
        self.messages = []

        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
        self.stdscr.nodelay(1)
        curses.curs_set(0)
        """
        Workaround for issuse #1774, since we know the exactly number of the
        columns that we used, so if the default terminal width <= 80, we just
        resize the terminal to ensure it is bigger enough for the addstr() call.
        Otherwise, addstr() may not happy: "error: addstr() returned ERR".
        """
        maxY, maxX = self.stdscr.getmaxyx()
        if maxY <= 80:
            curses.resizeterm(maxX, 90)  #80+10, 10 for the "Delay" column

        self.lock = threading.Lock()
        with open(META_DATA_FILE) as f:
            for line in f:
                line = line.strip()
                # Skip empty lines, header and comments.
                if not line or line.startswith('#'):
                    continue
                module_name, proto_name, topic, period = line.split()
                self.messages.append(
                    Message(module_name, proto_name, topic, period,
                            self.stdscr, self.lock))
        self.selection = 0
        self.current_index = 0
        self.MENU = True
Example #23
0
 def update_size(self, width, height):
     curses.resizeterm(height, width)
     self.screen.refresh()
     logger.logInformation(f'Terminal size updated to `{[width, height]}`')
     tui.layout.cols = width
     tui.layout.lines = height
     tui.layout.__update_size__()
Example #24
0
    def __init__(self):
        print("\x1b[8;" + str(HEIGHT) + ";" + str(WIDTH) + "t")
        self.stdscr = curses.initscr()
        curses.start_color()
        curses.use_default_colors()

        # @ in title and credits
        curses.init_pair(1, -1, curses.COLOR_RED)
        # ^ in title and credits
        curses.init_pair(2, -1, curses.COLOR_GREEN)
        # = in title and credits
        curses.init_pair(3, -1, curses.COLOR_BLUE)
        # menu unselected
        curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_YELLOW)
        # menu selected
        curses.init_pair(5, -1, curses.COLOR_RED)
        # A in title
        curses.init_pair(6, curses.COLOR_RED, -1)
        # V in title
        curses.init_pair(7, curses.COLOR_GREEN, -1)
        # E in title
        curses.init_pair(8, curses.COLOR_BLUE, -1)
        # inventory
        curses.init_pair(9, -1, curses.COLOR_BLUE)
        # gameover
        curses.init_pair(10, -1, curses.COLOR_BLUE)

        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.stdscr.keypad(1)
        curses.resizeterm(HEIGHT, WIDTH)
        self.stdscr.refresh()
 def set_up_curses(self):
     # Instantiate standard screen object.
     self.stdscr = curses.initscr()
     # Properly initialize screen.
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     # Check for and begin color support.
     if curses.has_colors():
         curses.start_color()
     # Optionally enable the F-1 etc. keys, which are multi-byte.
     self.stdscr.keypad(1)
     # Declare colors.
     curses.use_default_colors()
     for i in range(0, curses.COLORS):
         curses.init_pair(i + 1, i, -1)
     # Create and configure window.
     curses.resizeterm(30, 80)
     self.window = curses.newwin(curses.LINES, curses.COLS)
     self.window.nodelay(1)
     # Create and configure main half-screen subwindows.
     half_screen = curses.COLS//2
     self.attacks = curses.newwin(curses.LINES-3, half_screen, 1, 0)
     self.attacks.attrset(curses.color_pair(198))
     self.attacks.addstr(1, 0, 'ATTACK STRINGS (KILL THESE)'.
             center(half_screen, ' '))
     self.attacks.box()
     self.noncomb = curses.newwin(
             curses.LINES-3, half_screen, 1, half_screen)
     self.noncomb.attrset(curses.color_pair(47))
     self.noncomb.addstr(1, 0, '''NON-COMBATANT STRINGS (DO NOT KILL)'''.
             center(half_screen, ' '))
     self.noncomb.box()
Example #26
0
 def on_resize(self, *args):
     log.debug("on_resize_from_signal")
     # Get the new rows and cols value
     self.rows, self.cols = struct.unpack(
         "hhhh", ioctl(0, termios.TIOCGWINSZ, "\000" * 8))[0:2]
     curses.resizeterm(self.rows, self.cols)
     self.refresh()
Example #27
0
 def __handle_resize(self):
     self.__update_size()
     self.__stdscr.clear()
     curses.resizeterm(self.__rows, self.__cols)
     self.__stdscr.addstr(
         0, 0, "Rows: {} Cols: {}".format(self.__rows, self.__cols))
     self.__redraw()
Example #28
0
def main(stdscr):
    cursor_x = START_CURSOR_X
    cursor_y = curses.LINES-1
    global spot, input_string, finish_winch, g_lines, g_cols
    global input_string, g_hashtags, g_encoded_hashtags, tweet_arr

    draw_scr(stdscr)

    while True:
        ch_code = stdscr.getch()
        if ch_code == curses.KEY_UP:
            spot = min(len(tweet_arr)-1, curses.LINES-2, spot + 1)
        elif ch_code == curses.KEY_DOWN:
            spot = max(0, spot - 1)
        elif ch_code == 8 or ch_code == 127:
            cursor_x = max(START_CURSOR_X, cursor_x - 1)
            input_string = input_string[:-1]
        elif ch_code == 10:
            # enter key
            break
        elif ch_code in char_codes and cursor_x < curses.COLS-1:
            cursor_x += 1
            input_string += chr(ch_code)
        elif ch_code == curses.KEY_RESIZE:
            # Assume WINCH
            input_string = ""
            cursor_x = START_CURSOR_X
            spot = 0
            l, c = stdscr.getmaxyx()
            if g_lines != l or g_cols != c:
                curses.resizeterm(l, c)
                g_lines, g_cols = l, c

        draw_scr(stdscr)
def main(stdscr):
    global LINES
    global COLS
    pad = curses.newpad(curses.LINES, curses.COLS)
    curses.use_default_colors()
    thread.start_new_thread(readInput,(stdscr,pad))
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLUE)
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
    COLS=curses.COLS
    LINES=curses.LINES
    while 1:
        resize = curses.is_term_resized(LINES, COLS)
        if resize is True:
            LINES, COLS = stdscr.getmaxyx()
            stdscr.clear()
            curses.resizeterm(LINES, COLS)
            pad.resize(LINES,COLS)
            stdscr.refresh()
        try:
            for i in range(0,LINES-1):
                pad.move(i,0)
                pad.clrtoeol()
                pad.addstr(i,0,prevChatLines[i], curses.color_pair(1))
                pad.addstr(i,math.floor(COLS/2), prevEdLines[i], curses.color_pair(3))
            pad.move(LINES-1,0)
            pad.clrtoeol()
            global ed
            if (ed):
                pad.addstr(LINES-1,0,currentmessage, curses.color_pair(3))
            else:
                pad.addstr(LINES-1,0,currentmessage, curses.color_pair(1))
            pad.refresh(0,0,0,0,LINES,COLS)
        except _curses.error:
            pass
Example #30
0
 def resize(self):
     y, x = self.screen.getmaxyx()
     self.screen.clear()
     curses.resizeterm(y, x)
     self.WIDTH = x
     self.HEIGHT = y
     self.refresh()
Example #31
0
 def resize(self):
     """Handle window resizing."""
     if curses.is_term_resized(self.max_win_size_y, self.max_win_size_x):
         self.win_init()
         self.box_init()
         self.text = [self._text_wrap(i) for i in self.text]
         curses.resizeterm(self.max_win_size_y, self.max_win_size_x)
Example #32
0
 def WatchJobs(cls):
     cls.Screen = curses.initscr()
     cls.Screen.resize(len(cls.CurrentSimu)+10, 150)
     curses.resizeterm(len(cls.CurrentSimu)+10, 150)
     cls.Screen.clear()
     cls.Screen.addstr(0, 0, cls.DisplayOutput(0), curses.A_PROTECT)
     cls.Screen.refresh()
Example #33
0
    async def clear(self, height, width):
        if curses.is_term_resized(height, width):
            curses.resizeterm(
                height,
                width)  # FIXME: Crash if less characters in new window size

        self.stdscr.clear()
Example #34
0
def main(stdscr):
    global screen
    text = "This is a test"
    screen = stdscr.subwin(0, 0)
    screen.box()  # Wrap screen window in box
    # Get window diminsions
    y, x = screen.getmaxyx()
    global cur_x, cur_y
    # Sets the cursor to center the text on screen
    cur_x = (x / 2) - (len(text)) / 2
    cur_y = (y / 2)
    # Add string to screen
    screen.addstr(cur_y, cur_x, text)
    screen.refresh()  # Refresh to populate screen with data

    c = screen.getch()  # Get char
    while c != ord('q'):  # Exit loop if char caught is 'q'
        screen.addstr(1, 1, str(c))
        screen.refresh()
        if c == 65:  # ARROW_UP
            move_up(text, screen)
        elif c == 66:  # ARROW_DOWN
            move_down(text, screen)
        elif c == 68:  # ARROW_LEFT
            move_left(text, screen)
        elif c == 67:  # ARROW_RIGHT
            move_right(text, screen)
        elif c == 410:
            y, x = screen.getmaxyx()
            curses.resizeterm(y, x)  # Resize curses boundaries
            move_center(text, screen)

        c = screen.getch()

    return
Example #35
0
 def isResized(self):
     if curses.is_term_resized(self.y, self.x):
         self.y, self.x = self.screen.getmaxyx()
         curses.resizeterm(self.y, self.x)
         self.screen.clear()
         return True
     return False
Example #36
0
 def sigwch(signum, stackframe):
     screen_size = struct.pack("HHHH", 0, 0, 0, 0)
     screen_size = fcntl.ioctl(0, termios.TIOCGWINSZ, screen_size)
     rows, cols, xpixels, ypixels = struct.unpack('HHHH', screen_size)
     if curses.is_term_resized(rows, cols):
         curses.resizeterm(rows, cols)
         raise TerminalResized("Terminal size changed")
Example #37
0
def test_resize_term(stdscr):
    if hasattr(curses, 'resizeterm'):
        lines, cols = curses.LINES, curses.COLS
        curses.resizeterm(lines - 1, cols + 1)

        if curses.LINES != lines - 1 or curses.COLS != cols + 1:
            raise RuntimeError, "Expected resizeterm to update LINES and COLS"
Example #38
0
 def on_terminal_size(self, *args):
     # Get the new rows and cols value
     rows, cols = struct.unpack('hhhh',
                                ioctl(0, termios.TIOCGWINSZ,
                                      b'\000' * 8))[0:2]
     curses.resizeterm(rows, cols)
     return rows, cols
Example #39
0
 def resize(self):
     """Handle terminal resizing"""
     # Check if screen was re-sized (True or False)
     resize = self.max_x == 0 or curses.is_term_resized(self.max_y, self.max_x)
     if resize is True:
         self.recalculate_layout()
         curses.resizeterm(self.max_y, self.max_x)
Example #40
0
def curses_program(screen: curses.window):
    y, x = screen.getmaxyx()
    o = Ocean(x - 1, y - 1)
    screen.clear()
    curses.resizeterm(y, x)

    for instruct in data:
        screen.clear()
        curr_north, curr_east = c.north, c.east
        c.execute_instruction(instruct)
        new_north, new_east = c.north, c.east

        if new_north < curr_north:
            for i in range(abs(curr_north - new_north)):
                o.move_ocean_south()
                o.draw(screen)
        else:
            for i in range(abs(curr_north - new_north)):
                o.move_ocean_north()
                o.draw(screen)

        if new_east < curr_east:
            for i in range(abs(curr_east - new_east)):
                o.move_ocean_west()
                o.draw(screen)
        else:
            for i in range(abs(curr_east - new_east)):
                o.move_ocean_east()
                o.draw(screen)
Example #41
0
    def setupwindows(self, resize=False):
        """Setup and draw bannerwin and logwin

        If `resize`, don't create new windows, just adapt size. This
        function should be invoked with CursesUtils.locked()."""
        self.height, self.width = self.stdscr.getmaxyx()
        self.logheight = self.height - len(self.accframes) - 1
        if resize:
            curses.resizeterm(self.height, self.width)
            self.bannerwin.resize(1, self.width)
            self.logwin.resize(self.logheight, self.width)
        else:
            self.bannerwin = curses.newwin(1, self.width, 0, 0)
            self.logwin = curses.newwin(self.logheight, self.width, 1, 0)

        self.draw_bannerwin()
        self.logwin.idlok(True)    # needed for scrollok below
        self.logwin.scrollok(True) # scroll window when too many lines added
        self.draw_logwin()
        self.accounts = reversed(sorted(self.accframes.keys()))
        pos = self.height - 1
        index = 0
        self.hotkeys = []
        for account in self.accounts:
            acc_win = curses.newwin(1, self.width, pos, 0)
            self.accframes[account].setwindow(acc_win, index)
            self.hotkeys.append(account)
            index += 1
            pos -= 1
        curses.doupdate()
Example #42
0
 def resize(self, yx=None):
     """Resize UI to yx."""
     if yx is None:
         yx = self.screen.getmaxyx()
     self.screen.erase()
     curses.resizeterm(yx[0], yx[1])
     self.setup_windows(resize=True)
Example #43
0
  def draw(self, world):
    self.screen.clear()

    self.draw_pos(world.ship, 'W')

    for b in world.all_bunkers:
      self.draw_pos(b, str(b.bunk.health))

    for b in world.bombs:
      self.draw_pos(b, 'o')

    for e in world.enemies:
      self.draw_pos(e, '!')

    for b in world.bullets:
      self.draw_pos(b, '^')

    if self.debug:
      self.screen.addstr(0, 0, f'h{self.cols}')
      self.screen.addstr(0, 3, f'w{self.rows}')

    self.screen.refresh()
    if curses.is_term_resized(self.rows, self.cols):
      self.rows, self.cols = self.screen.getmaxyx()
      curses.resizeterm(self.rows, self.cols)
Example #44
0
 def commandLoop(self):
     window = self.inputWindow
     window.focus()
     self.focusedWindow = window
     self.mainLoopTime = 0
     self.mainLoopTimePeak = 0
     start = time.time()
     while not self.exiting:
         self.refresh()
         self.mainLoopTime = time.time() - start
         if self.mainLoopTime > self.mainLoopTimePeak:
             self.mainLoopTimePeak = self.mainLoopTime
         cmdList = []
         mouseEvents = []
         while not len(cmdList):
             for i in range(5):
                 ch = window.cursorWindow.getch()
                 #if ch != -1:
                 #  app.log.info('ch', ch)
                 if ch == curses.ascii.ESC:
                     keySequence = []
                     n = window.cursorWindow.getch()
                     while n != curses.ERR:
                         keySequence.append(n)
                         n = window.cursorWindow.getch()
                     #app.log.info('sequence\n', keySequence)
                     ch = tuple(keySequence)
                     if not ch:
                         # The sequence was empty, just forward the esc.
                         ch = curses.ascii.ESC
                 if ch != curses.ERR:
                     self.ch = ch
                     if ch == curses.KEY_MOUSE:
                         # On Ubuntu, Gnome terminal, curses.getmouse() may only be called
                         # once for each KEY_MOUSE. Subsequent calls will throw an
                         # exception.
                         self.debugMouseEvent = curses.getmouse()
                         mouseEvents.append(
                             (self.debugMouseEvent, time.time()))
                         #app.log.info('mouse event\n', mouseEvents[-1])
                     cmdList.append(ch)
         start = time.time()
         if len(cmdList):
             for cmd in cmdList:
                 if cmd == curses.KEY_RESIZE:
                     if sys.platform == 'darwin':
                         rows, cols = app.curses_util.terminalSize()
                         curses.resizeterm(rows, cols)
                     self.layout()
                     window.controller.onChange()
                     self.refresh()
                     app.log.debug(self.stdscr.getmaxyx(), time.time())
                     continue
                 window.controller.doCommand(cmd)
                 if cmd == curses.KEY_MOUSE:
                     self.handleMouse(mouseEvents[0])
                     mouseEvents = mouseEvents[1:]
                 window = self.focusedWindow
                 window.controller.onChange()
Example #45
0
 def resize_screen(self):
     y, x = stdscr.getmaxyx()
     screen.clear()
     stdscr.clear()
     curses.resizeterm(y, x)
     self.height, self.width = screen.getmaxyx()
     stdscr.refresh()
     self.draw_topbar()
Example #46
0
File: XConio.py Project: non/ld21
def resize(h, w):
    y,x = W.getmaxyx()
    if y < h or x < w:
        raise Exception("Your window is x=%s, y=%s. Minimum required is x=%s, y=%s" % (x, y, w, h))
    curses.resizeterm(h, w)
    W.resize(h, w)
    curses.nocbreak()
    curses.echo()
Example #47
0
	def handle_resize(self, *args):
		w,h = self.getTerminalSize_linux()
		self.win_log.win.resize(h,w)
		self.screen.resize(h,w)
		curses.resizeterm(h,w)
		self.win_log.height = h - 1
		self.win_log.width = w - 1
		self.win_log.refr()
Example #48
0
	def __init__(self, size):
		if CursesWindow.__single:
			raise CursesWindow.__single
		CursesWindow.__single = self
		self.xsize, self.ysize = size
		self.screen = curses.initscr()
		curses.resizeterm(self.ysize, self.xsize)
		curses.cbreak()
Example #49
0
def redraw_scr(window):
    screen_write_sema.acquire()
    height, width = get_win_size()
    if is_term_resized(height, width):
        curses.resizeterm(height, width)
        window.erase()
        window.box()
        window.addstr(2, 2, "{0} - {1}".format(height, width))
    screen_write_sema.release()
Example #50
0
def change_screen_size():
    # quite literal
    global SPLIT_X
    SPLIT_X = int(MAX_X/5)
    curses.resizeterm(MAX_Y, MAX_X)
    screen.box()
    screen.hline(2, 1, curses.ACS_HLINE, MAX_X-2)
    screen.refresh()
    refresh_hits()
def handle_window_resize(stdscr, y, x):
    if curses.is_term_resized(y, x):
        maxy, maxx = stdscr.getmaxyx()
        stdscr.clear()
        curses.resizeterm(y, x)
        stdscr.refresh()
    else:
        maxy = y
        maxx = x
    return maxy, maxx
Example #52
0
def init(scrn):
	curses.resizeterm(32,62)
	scrn.box()
	scrn.addstr(1,1,"For best results maximize/fullscreen the terminal.")
	scrn.addstr(5,1,"Press Any Arrow Key to continue.")
	scrn.addstr(3,1,"Pressing 'q' at any time will close the game")
	c = scrn.getch()
	
	while c not in (curses.KEY_UP, curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_DOWN):
		c = scrn.getch()
Example #53
0
File: main.py Project: telmich/ceof
    def refresh_windows(self):
        """Called on SIGWINCH"""
        self.height, self.width = self.window.getmaxyx()
        curses.resizeterm(self.height, self.width)

        # (Re-)define scroll region
        self.window.setscrreg(2, self.height-2)

        self.draw_title()
        self.window.refresh()
Example #54
0
	def __init__(self, refresh_time = 1):
		# Global information to display
		self.__version = __version__

		# Init windows positions
		self.term_h = 		24 ; 		self.term_w = 		80
		self.host_x = 		0 ; 		self.host_y = 		0
		self.system_x = 	0 ; 		self.system_y = 	1
		self.cpu_x = 		0 ; 		self.cpu_y = 		3
		self.load_x = 		20; 		self.load_y = 		3
		self.mem_x = 		41; 		self.mem_y = 		3
		self.network_x = 	0 ; 		self.network_y = 	9
		self.diskio_x = 	0 ; 		self.diskio_y = 	16
		self.process_x = 	30;			self.process_y = 	9
		self.now_x = 		79;			self.now_y = 		23	 # Align right
		self.caption_x = 	0 ;			self.caption_y = 	23

		# Init the curses screen
		self.screen = curses.initscr() 
		if not self.screen:
			print "Error: Can not init the curses library.\n"
		curses.resizeterm( self.term_h, self.term_w )
		curses.start_color()
		curses.use_default_colors()
		curses.noecho() ; curses.cbreak() ; curses.curs_set(0)
		
		# Init colors
		self.hascolors = False
		if curses.has_colors():
			self.hascolors = True
			#Init				FG color				BG color
			curses.init_pair(1, curses.COLOR_WHITE, 	curses.COLOR_BLACK)
			curses.init_pair(2, curses.COLOR_WHITE, 	curses.COLOR_RED)
			curses.init_pair(3, curses.COLOR_WHITE, 	curses.COLOR_GREEN)
			curses.init_pair(4, curses.COLOR_WHITE, 	curses.COLOR_BLUE)
			curses.init_pair(5, curses.COLOR_WHITE, 	curses.COLOR_MAGENTA)
			curses.init_pair(6, curses.COLOR_WHITE, 	curses.COLOR_CYAN)
			curses.init_pair(7, curses.COLOR_BLACK, 	curses.COLOR_YELLOW)

			# Text colors/styles
			self.title_color = curses.A_BOLD|curses.A_UNDERLINE
			self.no_color = curses.color_pair(1)
			self.default_color = curses.color_pair(3)|curses.A_BOLD
			self.if50pc_color = curses.color_pair(4)|curses.A_BOLD
			self.if70pc_color = curses.color_pair(5)|curses.A_BOLD
			self.if90pc_color = curses.color_pair(2)|curses.A_BOLD

		# Init window		
		self.term_window = curses.newwin(self.term_h, self.term_w, 0, 0)

		# Init refresh time
		self.__refresh_time = refresh_time

		# Catch key pressed with non blocking mode
		self.term_window.keypad(1) ; self.term_window.nodelay(1) ; self.pressedkey = -1
Example #55
0
    def start_view(self, screen):
        self.screen = screen
        screen.keypad(False)
        refr = True

        (last_h, last_w) = screen.getmaxyx()

        while 1:
            (h, w) = screen.getmaxyx()

            if h != last_h or w != last_w:
                screen.erase()
                curses.resizeterm(h, w)
                last_h = h
                last_w = w
                refr = True
                if self.cursor_y > h:
                    self.cursor_y = h - 5
                    if self.cursor_y < 0:
                        self.cursor_y = 0
                if self.cursor_x > w:
                    self.cursor_x = w - 3

            if self.has_statusbar:
                h -= 1

            if refr:
                self.redraw(h, w)
                refr = False

            size_line = len(self.output.lines[self.win_y + self.cursor_y])
            if size_line == 0:
                x = 0
            elif self.cursor_x >= size_line:
                x = size_line - 1
            else:
                x = self.cursor_x

            screen.move(self.cursor_y, x)

            k = self.read_escape_keys()

            if k in self.mapping:
                refr = self.mapping[k](h, w)
            elif k.startswith(b"\x1b[M"):
                refr = self.mouse_event(k, h, w)
            elif k == b"q" or k == b"\x1b":
                break

            if self.should_stop:
                screen.erase()
                return True

        screen.erase()
        return False
Example #56
0
    def _update_win(self):
        if curses.is_term_resized(self.win_height, self.win_width):
            self.win_height, self.win_width = self.stdscr.getmaxyx()
            curses.resizeterm(self.win_height, self.win_width)

            self.status_win.resize(self.state_win_height, self.win_width)
            self.status_win.mvwin(self.win_height-self.state_win_height, 0)

            self.textblock.set_width(self.win_width, reflow=False)

            self.win_changed = True
Example #57
0
    def set_screen_size(self):
        """ Setup screen size and padding

        We have need 2 free lines at the top and 2 free lines at the bottom

        """
        height, width = self.getheightwidth()
        curses.resizeterm(height, width)
        self.pad_x = 0
        self.max_y, self.max_x = (height-1, width-1)
        self.pad_h = height-3
        self.pad_w = width-2*self.pad_x
Example #58
0
File: ui.py Project: hoyho/musicbox
 def update_size(self):
     # get terminal size
     size = terminalsize.get_terminal_size()
     self.x = max(size[0], 10)
     self.y = max(size[1], 25)
     
     # update intendations
     curses.resizeterm(self.y, self.x)
     self.startcol = int(float(self.x)/5)
     self.indented_startcol = max(self.startcol - 3, 0)
     self.update_space()
     self.screen.clear()
     self.screen.refresh()
Example #59
0
    def doresize(self, signum, frame):
        self.log.debug('doresize: in_redisplay=%s', self.in_redisplay)
        if os.getpid() != self.main_pid:
            return # sigh
        winsz = array.array('H', [0] * 4) # four unsigned shorts per tty_ioctl(4)
        fcntl.ioctl(0, termios.TIOCGWINSZ, winsz, True)
        curses.resizeterm(winsz[0], winsz[1])

        oldy = self.maxy
        self.maxy, self.maxx = self.stdscr.getmaxyx()

        new = []
        orphans = []
        remaining = self.maxy
        for (i, victim) in enumerate(self.windows):
            if hasattr(victim.window, 'height'):
                height = victim.window.height()
            elif victim.window.noresize:
                height = victim.height
            else:
                # should get proportional chunk of remaining? think harder later.
                height = max(1, int(victim.height * (self.maxy / oldy)))
                height = min(height, remaining)
            if height > remaining:
                orphans.append(victim)
            else:
                new.append([
                    victim.window,
                    self.maxy - remaining,
                    height,
                    i == self.active,
                    ])
            remaining -= height
        if remaining:
            new[-1][2] += remaining

        for victim in orphans: # it sounds terrible when you put it that way
            with contextlib.suppress(ValueError):
                self.popstack.remove(victim)
            victim.window.destroy()

        self.active = 1
        self.windows = []
        for (i, (window, y, height, active)) in enumerate(new):
            self.windows.append(TTYRenderer(self, y, height, window))
            if active:
                self.active = i

        self.windows[i].window.focus()
        self.log.debug('RESIZED %d windows', len(self.windows))
        self.redisplay()