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)
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()
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")
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 refresh(self): # cfg.dbg("hexscreen.py refresh tw:" + str(self.tableWidth) + " ppadCurX:" + str(self.ppadCurX) + " maxX:" + str(self.maxX)) if(curses.is_term_resized(self.maxY, self.maxX)): cfg.dbg("Caught resize event. Consider using immedok()") self.tearDown() self.drawHeader() self.drawFooter() # Handle the mini-buffer if(self.mBufFocus): eStr = self.mBuf.exe() if(eStr): self.toggleMBuf() self.stdscr.move(self.cY, self.cX) self.genericTry(eStr) else: self.printToMBuf(self.mBuf.out()) self.stdscr.move(self.maxY - 1, self.mBuf.cX) else: self.printToMBuf(self.mBufMsg) self.mBufMsg = '' self.stdscr.move(self.cY, self.cX) self.refreshBoldPacket() self.headPpad.refresh(0, self.ppadCurX, 0, 0, self.headerHeight, self.maxX - 1) self.ppad.refresh(self.ppadCurY, self.ppadCurX, self.ppadTopY, 0, self.ppadBottomY, self.maxX - 1) self.stdscr.refresh() curses.doupdate()
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
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)
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: if curses.is_term_resized(self.height, self.width): curses.resizeterm(self.height, self.width) self.bannerwin.resize(1, self.width) self.logwin.resize(self.logheight, self.width) self.stdscr.clear() self.stdscr.noutrefresh() 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()
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 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
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
def process_q_events(self): #print "*** process q_events ***\r\n" # return true signifies end of main event loop while True: if curses.is_term_resized(self.maxy, self.maxx) is True: self.resize_curses() if self.input_q.empty_p(): break msg = self.input_q.delete_head_nowait() print "*** process msg %s ***\r\n" % msg.to_string() if msg.type() == -4: return self.process_json(msg.to_string()) return False
def resize_handler(self, signum: Optional[int], frame) -> None: # type: ignore # pylint: disable=unused-argument """Handles terminal window resizing events. This method gets exploited to trigger a refresh of the entire TUI window. In such a case it will be called as `resize_handler(None, None)`. Args: signum: signal number. frame: unused argument, required by the function template. """ LOGGER.debug("Handling resize event.") if signum == signal.SIGWINCH: # update total dimension data buf = struct.pack("HHHH", 0, 0, 0, 0) # We use f_d = 0 as this redirects to STDIN under the hood, regardless of whether the # application is actually running in the foreground or in a pseudo terminal. buf = fcntl.ioctl(0, TIOCGWINSZ, buf) self.height, self.width = struct.unpack("HHHH", buf)[0:2] if signum is not None and not curses.is_term_resized( self.height, self.width): # when no signal number was given, this was a manually triggered event with the purpose # of completely refreshing the screen LOGGER.debug("Resize event did not have any effect: %dx%d", self.width, self.height) return LOGGER.debug("New stdscr dimension determined to be %dx%d", self.width, self.height) # actually resize the terminal curses.resize_term(self.height, self.width) # clear and refresh for a blank canvas self.stdscr.keypad(True) self.stdscr.clear() self.stdscr.refresh() # update top statusbar self.topbar.resize(1, self.width) self.statusbar(self.topbar, STATE.topstatus) self.topbar.refresh() # update bottom statusbar self.botbar.resize(1, self.width) self.botbar.mvwin(self.height - 2, 0) self.statusbar(self.botbar, self.infoline()) self.botbar.refresh() # update prompt self.prompt.resize(1, self.width) self.prompt.refresh(0, 0, self.height - 1, 0, self.height, self.width - 1) # update viewport self.viewport.resize(self.height - 3, self.width)
def _resize_term(self): if curses.is_term_resized(self.nlines, self.ncols): self.nlines = self.window.getmaxyx()[0] self.ncols = self.window.getmaxyx()[1] if not SPACING: self.drawable_cols = self.ncols else: self.drawable_cols = int(self.ncols / 2) self.window.clear() curses.resize_term(self.nlines, self.ncols) self.window.refresh() self._init_lines()
def process_terminal_events(self): # return true signifies end of main event loop if curses.is_term_resized(self.maxy, self.maxx) is True: self.resize_curses() _ORD_S = ord('s') _ORD_L = ord('l') _ORD_H = ord('h') COMMANDS = {_ORD_S: 'skip', _ORD_L: 'lockout', _ORD_H: 'hold'} c = self.stdscr.getch() if c == ord('u') or self.do_auto_update(): self.send_command('update', 0) if c in COMMANDS.keys(): self.send_command(COMMANDS[c], 0) elif c == ord('q'): return True elif c == ord('t'): if self.current_nac: self.send_command('add_default_config', int(self.current_nac)) elif c == ord('f'): self.prompt.addstr(0, 0, 'Frequency') self.prompt.refresh() self.text_win.erase() response = self.textpad.edit() self.prompt.erase() self.prompt.refresh() self.text_win.erase() self.text_win.refresh() self.title_help() try: freq = float(response) if freq < 10000: freq *= 1000000.0 except: freq = None if freq: self.send_command('set_freq', freq) elif c == ord(','): self.send_command('adj_tune', -100) elif c == ord('.'): self.send_command('adj_tune', 100) elif c == ord('<'): self.send_command('adj_tune', -1200) elif c == ord('>'): self.send_command('adj_tune', 1200) elif (c >= ord('1') ) and (c <= ord('5')): self.send_command('toggle_plot', (c - ord('0'))) elif c == ord('x'): assert 1 == 0 return False
def wait_for_enter(stdscr, dialog_id): # Resize before waiting for enter try: stdscr.addstr("\nPress enter\n", curses.color_pair(15)) except curses.error: pass if curses.is_term_resized(height, width): redraw_on_resize(stdscr, dialog_id) k = 0 while (k != 10) and (k != 110): k = stdscr.getch() if (k == curses.KEY_RESIZE): # Resize if window resized waiting for enter redraw_on_resize(stdscr, dialog_id)
def tui_loop(rc_path): ch = None menu = Menu(rc_path) check_term_size(menu) menu.draw_statics() menu.draw_datetime() menu.draw_all_pads() menu.draw_active() while (ch != ord('q')): ch = menu.screen.getch() if ch == ord('\t'): menu.draw_active(highlight=False) menu.active = (menu.active + 1) % len(menu.pads) menu.draw_active() if ch == curses.KEY_DOWN: menu.pads[menu.active].selection = ( (menu.pads[menu.active].selection + 1) % len(menu.pads[menu.active].item_list)) menu.draw_active() if ch == curses.KEY_UP and menu.pads[menu.active].selection == 0: menu.pads[menu.active].selection = len( menu.pads[menu.active].item_list) menu.draw_active() if ch == curses.KEY_UP and menu.pads[menu.active].selection != 0: menu.pads[menu.active].selection = ( menu.pads[menu.active].selection - 1) menu.draw_active() if ch == 10: menu.pads[menu.active].spawn() menu.draw_active() if ch == ord('s'): # curses.echo() menu.search_pad.enter_search() curses.noecho() sleep(0.01) menu.draw_datetime() if curses.is_term_resized(menu.rows, menu.cols): menu.screen.erase() menu.get_dimensions() check_term_size(menu) menu.draw_statics() menu.draw_datetime() menu.search_pad.set_dimensions( menu.rows // 2 - menu.largest_list // 2 - 2, menu.cols // 5, 3 * menu.cols // 5) menu.draw_all_pads() menu.draw_active() menu.screen.erase() curses.endwin() exit()
def draw(img): for col in range(output_cols): for row in range(output_rows): if curses.is_term_resized(rows, columns): return try: pixel = img[row * compression_factor][col * compression_factor_x] char = pixel_to_char(pixel) win.addch(row + padding_rows, col + padding_cols, char) win.refresh() except: # win.addch() causes an exception if we try to draw beyond # the boundaries of the window. We can just ignore it. pass
def resize_curses(self, force=False): """ Check if terminal is resized and adapt screen """ # Check difference between self.screen_height and self.app.screen_height resize = curses.is_term_resized(self.screen_height, self.screen_width) if resize or force: # save also these value locally to check if self.screen_height, self.screen_width = self.app.stdscr.getmaxyx() # Update display self.app.stdscr.clear() self.gwin.clear() self.gwin.resize(self.app.panel_height, self.app.screen_width) curses.resizeterm(self.app.screen_height, self.app.screen_width) self.app.stdscr.refresh() self.gwin.refresh()
def _refresh_winsize(self, screen=None): old_winsize = self._winsize self._winsize = self.window.getmaxyx() if (screen is not None or old_winsize != self._winsize or curses.is_term_resized(*old_winsize)): curses.resize_term(*self._winsize) if screen: screen.pre_display(self) self.screen = screen self.screen.resize(self) if screen: self._render(time.time())
def update(self): if self._playing: modified = self.update_messages() else: modified = False if self._modified: self._modified = False modified = True if curses.is_term_resized(self._nrows, self._ncols): self._nrows, self._ncols = self._stdscr.getmaxyx() modified = True return modified
def main(arg): # Initialize curses curses.initscr() curses.curs_set(0) curses.use_default_colors() # Create the window rows, columns = get_winsize() win = curses.newwin(rows, columns, 0, 0) # Initialize the capture device cap = cv2.VideoCapture(0) win.refresh() # Get the initial compression_factor ret, img = cap.read() compression_factor = max(len(img) / rows, len(img[0]) / columns) # Function for drawing the image as characters def draw(img): output_rows = len(img) / compression_factor output_cols = len(img[0]) / compression_factor * 2 padding_rows = (rows - output_rows) / 2 padding_cols = (columns - output_cols) / 2 for row in range(output_rows): for col in range(output_cols): if curses.is_term_resized(rows, columns): return try: pixel = img[row * compression_factor][col // 2 * compression_factor] char = pixel_to_char(pixel) win.addch(row + padding_rows, col + padding_cols, char) except: # win.addch() causes an exception if we try to draw beyond # the boundaries of the window. We can just ignore it. pass # Loop forever, handling terminal resizes while True: ret, img = cap.read() draw(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)) if curses.is_term_resized(rows, columns): rows, columns = get_winsize() win = curses.newwin(rows, columns, 0, 0) compression_factor = max(len(img) / rows, len(img[0]) / columns) win.refresh()
def refresh(window: Window): if not window.screen: return y, x = window.screen.getmaxyx() resize = curses.is_term_resized(curses.LINES, curses.COLS) if resize is True: logger.debug(f"resizing to {y}x{x}") window.screen.clear() curses.resizeterm(y, x) window.screen.refresh() window.root_component.set_rect(Rect(0, 0, curses.COLS, curses.LINES)) window.root_component.mark_for_update()
def main(arg): # Initialize curses curses.initscr() curses.curs_set(0) curses.use_default_colors() # Create the window rows, columns = get_winsize() win = curses.newwin(rows, columns, 0, 0) # Initialize the capture device cap = cv2.VideoCapture(0) win.refresh() # Get the initial compression_factor ret, img = cap.read() compression_factor = max(len(img)/rows, len(img[0])/columns) # Function for drawing the image as characters def draw(img): output_rows = len(img)/compression_factor output_cols = len(img[0])/compression_factor * 2 padding_rows = (rows - output_rows) / 2 padding_cols = (columns - output_cols) / 2 for row in range(output_rows): for col in range(output_cols): if curses.is_term_resized(rows, columns): return try: pixel = img[row * compression_factor][col // 2 * compression_factor] char = pixel_to_char(pixel) win.addch(row + padding_rows, col + padding_cols, char) except: # win.addch() causes an exception if we try to draw beyond # the boundaries of the window. We can just ignore it. pass # Loop forever, handling terminal resizes while True: ret, img = cap.read() draw(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)) if curses.is_term_resized(rows, columns): rows, columns = get_winsize() win = curses.newwin(rows, columns, 0, 0) compression_factor = max(len(img)/rows, len(img[0])/columns) win.refresh()
def draw(img): output_rows = len(img)/compression_factor output_cols = len(img[0])/compression_factor * 2 padding_rows = (rows - output_rows) / 2 padding_cols = (columns - output_cols) / 2 for row in range(output_rows): for col in range(output_cols): if curses.is_term_resized(rows, columns): return try: pixel = img[row * compression_factor][col // 2 * compression_factor] char = pixel_to_char(pixel) win.addch(row + padding_rows, col + padding_cols, char) except: # win.addch() causes an exception if we try to draw beyond # the boundaries of the window. We can just ignore it. pass
def curses_loop(self, stdscr): while 1: resize = curses.is_term_resized(self.window_width, self.window_height) if resize == True: self.resize_window() self.redraw() c = stdscr.getch() if c == ord('q') or c == ord('Q'): self.aborted = True break elif c == ord('a') or c == ord('A'): set_to = self.mostly_checked() for option in self.all_options: option["selected"] = not set_to elif c == curses.KEY_UP: self.cursor = self.cursor - 1 self.check_cursor_up() elif c == curses.KEY_DOWN: self.cursor = self.cursor + 1 self.check_cursor_down() elif c == curses.KEY_PPAGE: self.offset -= self.entry_height self.check_page_up() elif c == curses.KEY_NPAGE: self.offset += self.entry_height self.check_page_down() elif c == ord(' '): self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["selected"] elif c == 10: break elif c in self.hotkeyOptions: self.cursor = self.hotkeyOptions[c] self.selected = self.hotkeyOptions[c] self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["selected"] # compute selected position only after dealing with limits self.selected = self.cursor + self.offset temp = self.getSelected() self.selcount = len(list(temp))
def curmain(stdscr): stdscr = curses.initscr() stdscr.clear() stdscr.keypad(True) # Sppport keypad functional keys #curses.noecho() #curses.cbreak() # Clear screen win_log = curses.newwin(curses.LINES - 3, curses.COLS - 2, 1, 1) win_log.addstr(0, 0, "Current mode: Typing mode\n", curses.A_REVERSE) rectangle(stdscr, 0, 0, curses.LINES - 2, curses.COLS - 1) win_com = curses.newwin(1, curses.COLS - 1, curses.LINES - 1, 1) stdscr.addstr(curses.LINES - 1, 0, ">") stdscr.refresh() win_log.refresh() #stdscr.getkey() #log = Textbox(win_log) com = Textbox(win_com) #log.edit() y = 0 x = 0 while (True): # Let the user edit until Ctrl-G is struck. com.edit() # Get resulting contents message = com.gather() #curses.nocbreak() win_log.addstr(message, curses.A_REVERSE) win_log.addstr("\n", curses.A_REVERSE) win_log.refresh() win_com.clear() resize = curses.is_term_resized(y, x) if resize: y, x = stdscr.getmaxyx() stdscr.clear() curses.resizeterm(y, x) stdscr.refresh() stdscr.keypad(False) #curses.echo() curses.endwin()
def __getattr__(self, attr): def wrapped(*args, **kwargs): try: return getattr(self.pad, attr)(*args, **kwargs) except Exception: try: mtrraw.show_msg(traceback.format_exc()) except Exception: pass if attr in ("addch", 'addnstr', 'addstr'): return wrapped if attr == "refresh": if curses.is_term_resized(scr.y, scr.x): scr._resize() self.resize() mtrraw.show_msg('Auto Window resize.') return wrapped else: return getattr(self.pad, attr)
def Redraw(self): self.stdscr.clear() if curses.is_term_resized(self.h, self.w): self.h, self.w = self.stdscr.getmaxyx() curses.resizeterm(self.h, self.w) i = 0 i += self._titleyx(i, 0, "CONTROLLER") lines = str(self.controller).split("\n") i += self._printyx(i, 0, lines) def render_node(n): if n == self.controller.GetNodeId(): return"node %d CONTROLLER" % n elif n in self.controller.failed_nodes: return"node %d FAILED" % n elif n in self.nodeset.nodes: node = self.nodeset.nodes[n] return "%s %s" % (node.Name(), node.state) else: return "Node %d UNKNOWN" % n i += self._titleyx(i, 0, "NODES") nodes = set(self.controller.nodes) | self.nodeset.nodes.keys() lines = [render_node(n) for n in nodes] i += self._printyx(i, 0, lines) i += self._titleyx(i, 0, "QUEUE") lines = self.driver.OutQueueString().split("\n") i += self._printyx(i, 0, lines) i += self._titleyx(i, 0, "STATS") lines = MessageStatsString(self.driver.History()).split("\n") i += self._printyx(i, 0, lines) i = 1 lines = [self.format(r) for r in self.messages[-self.h + 2:]] self._printyx(i, 81, lines) i += len(lines) + 1 self.stdscr.refresh()
def myaddstr(self, r, c, txt): w = 0 h = 0 if curses.is_term_resized(h, w): # self.height, self.width= self.term.getmaxyx() # self.term.clear() curses.resizeterm(self.height, self.width) self.write_head() self.term.refresh() #slice first part until screen width is reached # if len(str)>self.width-c if len(txt) > self.width - c: t = txt[:self.width - c] else: t = txt try: self.term.addstr(r, c, t) except: return
def fitScreen(self, height, width, stdscr): # Check if screen was re-sized (True or False) resize = curses.is_term_resized(height, width) # Action in loop if resize is True: if resize is True: self.height, self.width = stdscr.getmaxyx() stdscr.clear() curses.resizeterm(self.height, self.width) stdscr.refresh() self.window = curses.newwin(self.height, self.width, 0, 0) self.map = Map(parent=self.window) self.controls = Controls(parent=self) self.info = Info(parent=self) return self.height, self.width return height, width
def dynamic_window_gen(self): while (self.L < H_MIN) or (self.C < W_MIN): try: self.screen.addstr(self.L // 2 - 1, (self.C - len(DY_MSG_1)) // 2, DY_MSG_1) self.screen.addstr(self.L // 2, (self.C - len(DY_MSG_2)) // 2, DY_MSG_2) self.screen.refresh() if curses.is_term_resized(self.L, self.C): self.L, self.C = self.screen.getmaxyx() curses.resizeterm(self.L, self.C) self.screen.clear() except: self.cleanup() raise IOError( "Terminal window too small to use.\nResize to atleast " + str(W_MIN) + "x" + str(H_MIN)) self.w_reg = curses.newwin(WIN_REG_H, WIN_REG_W, 0, self.C - WIN_REG_W) self.w_instr = curses.newwin(self.L - WIN_REG_H, WIN_INSTR_W, WIN_REG_H, self.w_reg.getbegyx()[1]) self.w_stack = curses.newwin(self.L - WIN_REG_H, WIN_STACK_W, WIN_REG_H, self.w_instr.getbegyx()[1] + WIN_INSTR_W) self.w_logo = curses.newwin(self.L - WIN_REG_H, WIN_LOGO_W, WIN_REG_H, self.w_stack.getbegyx()[1] + WIN_STACK_W) self.w_menu = curses.newwin(WIN_MENU_H, self.w_reg.getbegyx()[1], self.L - WIN_MENU_H, 0) self.w_game = None self.w_console = None if (self.L < DISPLAY_MIN_H) or (self.C < DISPLAY_MIN_W): self.w_console = curses.newwin(self.L - WIN_MENU_H, self.w_reg.getbegyx()[1], 0, 0) else: self.w_game = curses.newwin(DISPLAY_H, DISPLAY_W, 0, (self.C - WIN_REG_W - DISPLAY_W) // 2) self.w_console = curses.newwin(self.L - DISPLAY_H - WIN_MENU_H, self.w_reg.getbegyx()[1], DISPLAY_H, 0)
def mainloop(self): for station_boards in self.__boards.values(): for platform_board in station_boards.values(): platform_board.draw_box() platform_board.update_time() for station_data in self.__station_data.values(): station_data.check_updates( lambda station_code: self.__on_station_update(station_code)) self.__setup_schedules() while True: # Check if screen was re-sized (True or False) resize = curses.is_term_resized(self.__rows, self.__cols) if resize is True: self.__handle_resize() schedule.run_pending() time.sleep(0.1)
def handle_input(self): c = stdscr.getch() if curses.is_term_resized(*stdscr.getmaxyx()) == True: self.resize_screen() if c == 258: # Down Arrow if self.pos < self.display_range - 1: self.pos += 1 else: self.pos = 0 elif c == 259: #Up arrow if self.pos > 0: self.pos -= 1 else: self.pos = self.display_range - 1 elif c == ord('\n'): self.open_t( self.pos ) elif c == ord('n') or c == ord('N'): self.new_search() self.pos = 0 elif c == ord('q') or c == ord('Q'): sys.exit()
def ui_main(self, stdscr): global screen # Instantiate a screen, so we can play with it later. screen = Screen(stdscr) while not self.shutdown_flag.is_set(): screen.getkey(stdscr) # Check if screen has been resized. Handle it. y, x = stdscr.getmaxyx() resized = curses.is_term_resized(y, x) if resized is True: y, x = stdscr.getmaxyx() screen.update_size(stdscr, y, x) # Draw the window screen.draw(stdscr, lines, y, x) stdscr.refresh() sleep(1)
def update_size(self): if self.stdscr == None: return self.max_y, self.max_x = self.stdscr.getmaxyx() self.display_width = self.max_x - 1 - len(self.prompt) - 1 if curses.is_term_resized(self.max_y, self.max_x): curses.resizeterm(self.max_y, self.max_x) if self.logwin != None: self.logwin.resize(self.max_y - 1, self.max_x) if self.promptwin != None: if self.max_x <= len(self.prompt): self.promptwin.erase() self.promptwin.resize(1, 1) self.promptwin.addstr(0, 0, '$') self.promptwin.refresh() else: self.promptwin.erase() self.promptwin.resize(1, len(self.prompt) + 1) self.promptwin.addstr(0, 0, self.prompt) self.promptwin.refresh() return
def curses_loop(self, stdscr): while 1: resize = curses.is_term_resized(self.window_width, self.window_height) if resize == True: self.resize_window() self.redraw() c = stdscr.getch() print c if c == ord('q') or c == ord('Q'): self.aborted = True break elif c == ord('a') or c == ord('A'): set_to = self.mostly_checked() for option in self.all_options: option["selected"] = not set_to elif c == curses.KEY_UP: self.cursor = self.cursor - 1 self.check_cursor_up() elif c == curses.KEY_DOWN: self.cursor = self.cursor + 1 self.check_cursor_down() elif c == curses.KEY_PPAGE: self.offset -= self.entry_height self.check_page_up() elif c == curses.KEY_NPAGE: self.offset += self.entry_height self.check_page_down() elif c == ord(' '): self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["selected"] elif c == 10: break # compute selected position only after dealing with limits self.selected = self.cursor + self.offset temp = self.InterGetSelected() self.selcount = len(list(temp))
def curses_main(screen, model: int) -> None: curses.curs_set(0) # Set the cursor to off. screen.timeout(0) # Turn blocking off for screen.getch(). # curses.init_pair() height, width = screen.getmaxyx() if height <= 15 or width <= 15: raise RoombaError("Error window size should be greater than 15") room = setup_room_list(width, height) roomba = Roomba(5, 0, width, height, roomba_option(model)) room[5][0] = BASE reset = False running = True while running: resize = curses.is_term_resized(height, width) if resize or reset: height, width = screen.getmaxyx() if height <= 15 or width <= 15: raise RoombaError( "Error window size should be greater than 15") room = setup_room_list(width, height) roomba = Roomba(5, 0, width, height, roomba_option(model)) room[5][0] = BASE screen.clear() add_dust(room, height, width) reset = roomba.operate(room) for y, row in enumerate(room): for x, d in enumerate(row): if d == ROOMBA: screen.addstr(y, x, d, curses.A_BOLD) else: screen.addstr(y, x, d) battery, state = roomba.get_statues() msg = f" Model: {model} Battery: {battery:.1f}% {state}" screen.addstr(height - 1, 0, msg, curses.A_BOLD) screen.refresh() ch = screen.getch() if ch in [81, 113]: running = False sleep(0.25)
def render(self): """ handles resize and displays the data in "data" """ self._getSize() self.screen.clear() if self.width < 60 or self.height < 20: self.wts(1, 1, "Windows too small to render!", 1) else: # check if resized if curses.is_term_resized(self.height, self.width): curses.resizeterm(self.height, self.width) self._getSize() # render border if self.screenBorder: self.drawBorder() # render lines self.drawLines() # render status self.wts(self.height - 1, 1, self.status, 1) # render objects self.drawObjects(self.objects) # render menus self.drawObjects(self.menus) self.screen.refresh()
def refresh(self, fetch_data): """ Redraw the display """ self.win.erase() height, width = getmaxyx() if curses.is_term_resized(height, width): self.win.clear() curses.resizeterm(height, width) self.win.addstr(0, 0, datetime.now().strftime('%H:%M:%S')) y = 1 x = 0 for table in self._tables: desc = self.engine.describe(table, fetch_data, True) cap = desc.consumed_capacity['__table__'] col_width = min(width - x, self._max_width) rows = 2 * len(desc.consumed_capacity) + 1 if y + rows > height: if x + 1 + 2 * col_width < width: x = col_width + 1 y = 1 col_width = min(width - x, self._max_width) else: break self.win.addstr(y, x, table, curses.color_pair(1)) y += 1 y = self._add_throughput(y, x, col_width, 'R', '', desc.read_throughput, cap['read']) y = self._add_throughput(y, x, col_width, 'W', '', desc.write_throughput, cap['write']) for index_name, cap in six.iteritems(desc.consumed_capacity): if index_name == '__table__': continue index = desc.global_indexes[index_name] y = self._add_throughput(y, x, col_width, 'R', index_name, index.read_throughput, cap['read']) y = self._add_throughput(y, x, col_width, 'W', index_name, index.write_throughput, cap['write']) self.win.refresh()
def get_screen(self): self.screen = curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) if self.x == 0: starty, startx = self.screen.getmaxyx() self.x = startx self.y = starty resize = curses.is_term_resized(self.y, self.x) # Action in loop if resize is True: if resize is True: y, x = self.screen.getmaxyx() self.screen.clear() curses.resizeterm(self.y, self.x) self.screen.refresh() self.show_header() return self.screen
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: if curses.is_term_resized(self.height, self.width): curses.resizeterm(self.height, self.width) self.bannerwin.resize(1, self.width) self.logwin.resize(self.logheight, self.width) self.stdscr.clear() self.stdscr.noutrefresh() 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() # TODO: Sort the accounts using their name self.accounts = 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()
def pager(stdscr): key = 0 curses.halfdelay(5) stdscr.clear() stdscr.refresh() lines = curses.LINES - 1 cols = curses.COLS - 1 topline = 0 intacc = 0 file = sys.argv longline = 0 colsMove = 0 stdinacc = '' if options.p: for i in sys.stdin: stdinacc += i #using sys.stdin interferes with curses input functions #so to work around this problem, this will reopen the terminal #since there is no more input through the stdin #for reference see the following url #https://stackoverflow.com/questions/3999114/linux-pipe-into-python-ncurses-script-stdin-and-termios f = open("/dev/tty") os.dup2(f.fileno(), 0) if options.f or options.p: if options.f: file = options.f elif options.p: file = '-' if options.p or options.f: if options.f: infile = open(file, "r") else: infile = stdinacc.split("\n") keystr = [] for i in infile: keystr.append(i) # determine the longest line in keystr for i in keystr: if len(i) > longline: longline = len(i) # make each line the same length for num, i in enumerate(keystr): if len(i) < longline: tmp = "" iterations = longline - len(i) for i in range(0, iterations): tmp += " " keystr[num] += tmp #due to a bug where the longest line would be displayed from stdinput, and paging right, would result in seeing duplicate characters as the #last character of the line, like the example below #if this was the last lineeeeeee #add a space to the end of the already processed lines for num, i in enumerate(keystr): keystr[num] += " " #press the 'q' key to quit the pager # still have an issue where ptty size change causes curses to exit with an exception while key != ord('q'): if intacc != len(keystr) - 1: if key == curses.KEY_DOWN: if topline <= len(keystr) - 1: topline += 1 if key == curses.KEY_UP: if topline > 0: topline -= 1 if key == curses.KEY_LEFT: if colsMove > 0: colsMove -= 1 if ((cols - 5) + colsMove) != longline: if key == curses.KEY_RIGHT: colsMove += 1 # key detection for left and right to view document left and right # if keystr[line] shorter than longest line in document, add spaces to line until equal len of longest line # if left key is pressed, move document by slicing left # if right key is pressed, move document by slicing right # in the event that the terminal is resized, get the right dimensions resize = curses.is_term_resized(lines + 1, cols + 1) if resize == True: lines, cols = stdscr.getmaxyx() lines = lines cols = cols stdscr.clear() curses.resizeterm(lines, cols) stdscr.refresh() cols = cols - 1 lines = lines - 1 colsMove = 0 for i in range(0, lines): intacc = i + topline # in the event of terminal resize, the code will drop to an except so that a terminal redraw can be performed try: if intacc <= len(keystr) - 1: stdscr.addstr( i, 0, keystr[i + topline][colsMove:int(cols - 5) + colsMove]) #stdscr.addstr(i,0,str(topline)+":"+str(key)) except: break #stdscr.addstr(0,0,str(lines)) stdscr.addstr(lines, 0, file, curses.A_BOLD) stdscr.refresh() key = stdscr.getch() else: return "please see -h/--help"
def visualize(device): chunk = 2048 # Change if too fast/slow, never less than 1024 scale = 200 # Change if bars too short/long exponent = .5 # Change if too little/too much difference between loud and quiet sounds sample_rate = 44100 p = pyaudio.PyAudio() stream = p.open(format = pyaudio.paInt16, channels = 1, rate = sample_rate, input = True, frames_per_buffer = chunk, input_device_index = device) print "Starting, use Ctrl+C to stop" screen = curses.initscr() curses.start_color() curses.use_default_colors() curses.curs_set(0) # invisible cursor curses.init_pair(1, -1, curses.COLOR_BLUE) curses.init_pair(2, -1, -1) term_height = screen.getmaxyx()[0] term_width = screen.getmaxyx()[1] min_bar_height = 1 bar_width = 4 bar_spacing = 2 vertical_offset = 2 bins = term_width / (bar_width + bar_spacing) bars = [] for i in range(bins): xcoord = bar_spacing + i*(bar_width + bar_spacing) bars.append(curses.newwin(min_bar_height, bar_width, term_height - vertical_offset , xcoord)) try: while True: # handle terminal resizing if curses.is_term_resized(term_height, term_width): screen.clear() screen.refresh() term_height = screen.getmaxyx()[0] term_width = screen.getmaxyx()[1] bins = term_width / (bar_width + bar_spacing) bars = [] for i in range(bins): xcoord = bar_spacing + i*(bar_width + bar_spacing) bars.append(curses.newwin(min_bar_height, bar_width, term_height - vertical_offset, xcoord)) data = stream.read(chunk) levels = analyze(data, chunk, sample_rate, bins) for i in range(bins): height = max(min((levels[i]*1.0)/scale, 1.0), 0.0) height = height**exponent height = int(height*term_height*1.5) prev_coords = bars[i].getbegyx() prev_bar_height = bars[i].getmaxyx()[0] bars[i].bkgd(' ', curses.color_pair(2)) # recolor to default bars[i].erase() bars[i].refresh() new_bar_height = max(height, min_bar_height) bars[i] = curses.newwin(new_bar_height, bar_width, prev_coords[0] - (new_bar_height - prev_bar_height) , prev_coords[1]) bars[i].bkgd(' ', curses.color_pair(1)) # set color bars[i].refresh() except KeyboardInterrupt: pass finally: print "\nStopping" stream.close() p.terminate() curses.endwin()
def main(win): optionSel=0 pos=0 dirty = False zeroL=True fourL = True fiveL=True while 1: curses.curs_set(0) stdscr = curses.initscr() curses.cbreak() curses.noecho() curses.init_pair(1,curses.COLOR_RED,curses.COLOR_WHITE) stdscr.clear() sh,sw = stdscr.getmaxyx() if curses.is_term_resized(sh,sw): sh,sw = stdscr.getmaxyx() stdscr.clear() curses.resizeterm(sh,sw) stdscr.refresh() rows = sh/8. cols = sw/4. x = 0 hPanel = stdscr.subwin(2,int(sw),x,0) x+=2 topMid = stdscr.subwin(int(rows*2),int(sw),x,0) x+=int(rows*2) bottomMid = stdscr.subwin(int(rows*2),int(sw),x,0) x+=int(rows*2) leftFooter= stdscr.subwin(int(rows*2),30,x,0) rightFooter= stdscr.subwin(int(rows*2),int(sw)-30,x,29) topMid.border(1,1,0,1,1,1,1,1) bottomMid.border(1,1,0,1,1,1,1,1) leftFooter.border(1,0,0,1,1,0,1,1) rightFooter.border(0,1,0,1,0,1,1,1) dt = datetime.datetime.now() hPanel.addstr(0,0,dt.strftime("%m/%d/%y %H:%m")) hPanel.addstr(0,sw/2,"Sys Interface") hPanel.addstr(1,sw/2," Version 1.0") upTime = os.popen("uptime -p").read() if len(upTime) > 15: hPanel.addstr(0,sw-30,upTime) else: hPanel.addstr(0,sw-15,upTime) topMid.addstr(1,sw/2,"VPN Status",curses.A_BOLD) #need to run checks...see if tun is connected state topMid.addstr(2,(sw/2)-1, "Not Connected") bottomMid.addstr(1,sw/2,"Interfaces",curses.A_BOLD) interfaces = os.popen("nmcli d").read().split('\n')[1::] i1 = interfaces[0].split() i2 = interfaces[1].split() i3 = interfaces[2].split() ipcmd = "ip addr show " ipaddr1=[ i for i in os.popen(ipcmd+i1[0]).read().split("\n") if "inet" in i] ipaddr1=ipaddr1[0].strip().split(' ')[1] if len(ipaddr1)>0 else "DOWN" ipaddr2=[ i for i in os.popen(ipcmd+i2[0]).read().split("\n") if "inet" in i] ipaddr2=ipaddr2[0].strip().split(' ')[1] if len(ipaddr2)>0 else "DOWN" ipaddr3=[ i for i in os.popen(ipcmd+i3[0]).read().split("\n") if "inet" in i] ipaddr3=ipaddr3[0].strip().split(' ')[1] if len(ipaddr3)>0 else "DOWN" gwcmd = os.popen("netstat -r").read().split('\n')[2::] ifgw1=[ i.split(' ') for i in gwcmd if i1[0] in i][0] ifgw2=[ i.split(' ') for i in gwcmd if i2[0] in i][0] ifgw3=[ i.split(' ') for i in gwcmd if i3[0] in i][0] ifgw1 = [ i for i in ifgw1 if len(i) >=1 ][1] ifgw2 = [ i for i in ifgw2 if len(i) >=1 ][1] ifgw3 = [ i for i in ifgw3 if len(i) >=1 ][1] bottomMid.addstr(2,3,i1[0]) bottomMid.addstr(3,1,displayIP(ipaddr1)) bottomMid.addstr(4,1,displayGW(ifgw1)) bottomMid.addstr(5,1,displayNS(ipaddr1)) bottomMid.addstr(2,(sw/2)+5,i2[0]) bottomMid.addstr(3,sw/2,displayIP(ipaddr2)) bottomMid.addstr(4,sw/2,displayGW(ifgw2)) bottomMid.addstr(5,sw/2,displayNS(ipaddr2)) bottomMid.addstr(2,(sw-20)+2,i3[0]) bottomMid.addstr(3,sw-20,displayIP(ipaddr3)) bottomMid.addstr(4,sw-20,displayGW(ifgw3)) bottomMid.addstr(5,sw-20,displayNS(ipaddr3)) hl = curses.color_pair(1) norm = curses.A_NORMAL leftFooter.addstr(1,10,"Admin Options") if pos == 0: leftFooter.addstr(2,1,"Set IP Address",hl) else: leftFooter.addstr(2,1,"Set IP Address",norm) if pos == 1: leftFooter.addstr(3,1,"Set DNS",hl) else: leftFooter.addstr(3,1,"Set DNS",norm) if pos == 2: leftFooter.addstr(4,1,"Ping",hl) else: leftFooter.addstr(4,1,"Ping",norm) if pos == 3: leftFooter.addstr(5,1,"Login",hl) else: leftFooter.addstr(5,1,"Login",norm) if pos == 4: leftFooter.addstr(6,1,"Reboot",hl) else: leftFooter.addstr(6,1,"Reboot",norm) if pos == 5: leftFooter.addstr(7,1,"Shutdown",hl) else: leftFooter.addstr(7,1,"Shutdown",norm) rightFooter.addstr(1,(sw/2)-30,"Input area") if dirty: if pos == 0 and zeroL: rightFooter.addstr(5,(sw/2)-30,"DHCP",hl) rightFooter.addstr(5,(sw/2)-10,"Static",norm) elif pos == 0 and not zeroL: rightFooter.addstr(5,(sw/2)-30,"DHCP",norm) rightFooter.addstr(5,(sw/2)-10,"Static",hl) if pos == 4 and fourL: rightFooter.addstr(5,(sw/2)-30,"Reboot",hl) rightFooter.addstr(5,(sw/2)-10,"Abort",norm) elif pos == 4 and not fourL: rightFooter.addstr(5,(sw/2)-30,"Reboot",norm) rightFooter.addstr(5,(sw/2)-10,"Abort",hl) if pos == 5 and fiveL: rightFooter.addstr(5,(sw/2)-30,"ShutDown",hl) rightFooter.addstr(5,(sw/2)-10,"Abort",norm) elif pos == 5 and not fiveL: rightFooter.addstr(5,(sw/2)-30,"ShutDown",norm) rightFooter.addstr(5,(sw/2)-10,"Abort",hl) hPanel.refresh() topMid.refresh() bottomMid.refresh() leftFooter.refresh() rightFooter.refresh() stdscr.refresh() optionSel=stdscr.getch() def curSel(): output="" if pos == 0: if zeroL: output= os.popen("dhclient-script BOUND").read() dirty=False else: curses.textpad.Textbox(stdscr).edit() staticIP(txtReturn) elif pos == 1: curses.textpad.Textbox(stdscr).edit() elif pos == 2: curses.textpad.Textbox(stdscr).edit() elif pos == 3: pass elif pos == 4: if fourL: os.popen("shutdown -r") else: dirty=False elif pos == 5: if fiveL: os.popen("shutdown -h") else: dirty=False else: output="Input area" rightFooter.addstr(1,sw/2,output[0]) if optionSel == 258 and not dirty: if pos<5: pos+=1 elif optionSel == 259 and not dirty: if pos>0: pos-=1 elif optionSel == ord('\n') and not dirty: dirty=True curses.flash() elif optionSel == ord('\n') and dirty: curSel() dirty=False elif optionSel == ord('q') and dirty: optionSelected = False dirty=False if optionSel == 260 and dirty: if pos == 0: zeroL=True rightFooter.addstr(5,(sw/2)-30,"DHCP",hl) rightFooter.addstr(5,(sw/2)-10,"Static",norm) elif pos == 4: fourL = True rightFooter.addstr(5,(sw/2)-30,"Reboot",hl) rightFooter.addstr(5,(sw/2)-10,"Abort",norm) elif pos == 5: fiveL = True rightFooter.addstr(5,(sw/2)-30,"ShutDown",hl) rightFooter.addstr(5,(sw/2)-10,"Abort",norm) if optionSel == 261 and dirty: if pos == 0: zeroL=False rightFooter.addstr(5,(sw/2)-30,"DHCP",norm) rightFooter.addstr(5,(sw/2)-10,"Static",hl) elif pos == 4: fourL = False rightFooter.addstr(5,(sw/2)-30,"Reboot",norm) rightFooter.addstr(5,(sw/2)-10,"Abort",hl) elif pos == 5 : fiveL = False rightFooter.addstr(5,(sw/2)-30,"ShutDown",norm) rightFooter.addstr(5,(sw/2)-10,"Abort",hl) hPanel.refresh() topMid.refresh() bottomMid.refresh() leftFooter.refresh() rightFooter.refresh() stdscr.refresh()
os.system("clear") signal.signal(signal.SIGINT, signal_handler) scr = curses.initscr() curses.cbreak() curses.echo() inputline = printlist(scr) scr.border(0) scr.refresh() y, x = scr.getmaxyx() while True: try: n = scr.getstr(inputline,8, 7) except EOFError: ctrlExit() if n.isdigit(): connect2host(n, inputline) elif n.lower() == 'q': ctrlExit() elif n.lower() == 'exit': ctrlExit() resized = curses.is_term_resized(y, x) if resized is True: y, x = scr.getmaxyx() scr.clear() curses.resizeterm(y, x) inputline = printlist(scr) scr.border(0) scr.refresh()
def visualize(device): global bins, chunk, sample_rate, exponent scale = 300 p = pyaudio.PyAudio() stream = p.open( format=pyaudio.paInt16, channels=1, rate=sample_rate, input=True, frames_per_buffer=chunk, input_device_index=device, ) screen = curses.initscr() curses.start_color() curses.use_default_colors() curses.curs_set(0) curses.init_pair(1, -1, curses.COLOR_BLUE) curses.init_pair(2, -1, -1) term_height = screen.getmaxyx()[0] term_width = screen.getmaxyx()[1] min_bar_height = 1 bar_width = 4 bar_spacing = 2 vertical_offset = 2 bars = [] for i in range(bins): xcoord = bar_spacing + i * (bar_width + bar_spacing) bars.append(curses.newwin(min_bar_height, bar_width, term_height - vertical_offset, xcoord)) screen.nodelay(1) height = 0 try: while True: catch_data = False c = screen.getch() if c != -1: screen.addstr(0, 0, str(c) + " ") f_d = open(save_file_data, "a") f_t = open(save_file_target, "a") catch_data = True if curses.is_term_resized(term_height, term_width): screen.clear() screen.refresh() term_height = screen.getmaxyx()[0] term_width = screen.getmaxyx()[1] bars = [] for i in range(bins): xcoord = bar_spacing + i * (bar_width + bar_spacing) bars.append(curses.newwin(min_bar_height, bar_width, term_height - vertical_offset, xcoord)) data = stream.read(chunk) levels = get_coeffs(data, chunk, sample_rate, bins) if catch_data: data = ", ".join([x.astype("str") for x in levels]) f_d.write(data + "\n") f_t.write(str(c) + "\n") for i in range(bins): height = max(min((levels[i] * 1.0) / scale, 1.0), 0.0) height = height ** exponent height = int(height * term_height * 1.5) prev_coords = bars[i].getbegyx() prev_bar_height = bars[i].getmaxyx()[0] bars[i].bkgd(" ", curses.color_pair(2)) bars[i].erase() bars[i].refresh() new_bar_height = max(height, min_bar_height) bars[i] = curses.newwin( new_bar_height, bar_width, prev_coords[0] - (new_bar_height - prev_bar_height), prev_coords[1] ) bars[i].bkgd(" ", curses.color_pair(1)) bars[i].refresh() except KeyboardInterrupt: pass finally: print "\nStopping to record" stream.close() p.terminate() curses.endwin()
def run(self): # Clear the terminal and draw the header self.draw_header() while 1: # Do not read the CAN-Bus when in paused mode if not self.paused: # Read the CAN-Bus and draw it in the terminal window msg = self.bus.recv(timeout=1. / 1000.) if msg is not None: self.draw_can_bus_message(msg) else: # Sleep 1 ms, so the application does not use 100 % of the CPU resources time.sleep(1. / 1000.) # Read the terminal input key = self.stdscr.getch() # Stop program if the user presses ESC or 'q' if key == KEY_ESC or key == ord('q'): break # Clear by pressing 'c' elif key == ord('c'): self.ids = {} self.start_time = None self.scroll = 0 self.draw_header() # Sort by pressing 's' elif key == ord('s'): # Sort frames based on the CAN-Bus ID self.draw_header() for i, key in enumerate(sorted(self.ids.keys())): # Set the new row index, but skip the header self.ids[key]['row'] = i + 1 # Do a recursive call, so the frames are repositioned self.draw_can_bus_message(self.ids[key]['msg'], sorting=True) # Pause by pressing space elif key == KEY_SPACE: self.paused = not self.paused # Scroll by pressing up/down elif key == curses.KEY_UP: # Limit scrolling, so the user do not scroll passed the header if self.scroll > 0: self.scroll -= 1 self.redraw_screen() elif key == curses.KEY_DOWN: # Limit scrolling, so the maximum scrolling position is one below the last line if self.scroll <= len(self.ids) - self.y + 1: self.scroll += 1 self.redraw_screen() # Check if screen was resized resized = curses.is_term_resized(self.y, self.x) if resized is True: self.y, self.x = self.stdscr.getmaxyx() if hasattr(curses, 'resizeterm'): # pragma: no cover curses.resizeterm(self.y, self.x) self.redraw_screen() # Shutdown the CAN-Bus interface self.bus.shutdown()
def main(): """Create Curses display of FFT""" args = parse_args() usrp = uhd.usrp.MultiUSRP(args.args) # Set the USRP rate, freq, and gain usrp.set_rx_rate(args.rate, args.channel) usrp.set_rx_freq(uhd.types.TuneRequest(args.freq), args.channel) usrp.set_rx_gain(args.gain, args.channel) # Initialize the curses screen screen = cs.initscr() cs.curs_set(0) cs.noecho() cs.cbreak() screen.keypad(1) height, width = screen.getmaxyx() # Create a pad for the y-axis y_axis_width = 10 y_axis = cs.newwin(height, y_axis_width, 0, 0) # Create the buffer to recv samples num_samps = max(args.nsamps, width) samples = np.empty((1, num_samps), dtype=np.complex64) st_args = uhd.usrp.StreamArgs("fc32", "sc16") st_args.channels = [args.channel] metadata = uhd.types.RXMetadata() streamer = usrp.get_rx_stream(st_args) buffer_samps = streamer.get_max_num_samps() recv_buffer = np.zeros((1, buffer_samps), dtype=np.complex64) stream_cmd = uhd.types.StreamCMD(uhd.types.StreamMode.start_cont) stream_cmd.stream_now = True streamer.issue_stream_cmd(stream_cmd) db_step = float(args.dyn) / (height - 1.0) db_start = db_step * int((args.ref - args.dyn) / db_step) db_stop = db_step * int(args.ref / db_step) try: while True: # Resize the frequency plot on screen resize screen.clear() if cs.is_term_resized(height, width): height, width = screen.getmaxyx() cs.resizeterm(height, width) db_step = float(args.dyn) / (height - 1.0) db_start = db_step * int((args.ref - args.dyn) / db_step) db_stop = db_step * int(args.ref / db_step) y_axis.clear() # Create the vertical (dBfs) axis y_axis.addstr(0, 1, "{:> 6.2f} |-".format(db_stop)) for i in range(1, height - 1): label = db_stop - db_step * i y_axis.addstr(i, 1, "{:> 6.2f} |-".format(label)) try: y_axis.addstr(height - 1, 1, "{:> 6.2f} |-".format(db_start)) except cs.error: pass y_axis.refresh() # Receive the samples recv_samps = 0 while recv_samps < num_samps: samps = streamer.recv(recv_buffer, metadata) if metadata.error_code != uhd.types.RXMetadataErrorCode.none: print(metadata.strerror()) if samps: real_samps = min(num_samps - recv_samps, samps) samples[:, recv_samps:recv_samps + real_samps] = recv_buffer[:, 0:real_samps] recv_samps += real_samps # Get the power in each bin bins = psd(width, samples[args.channel][0:width]) for i in range(y_axis_width, width): vertical_slot = clip(height, 0, np.int(bins[i] / db_step)) try: for j in range(vertical_slot, height): screen.addch(j, i, '*') except cs.error: pass screen.refresh() except KeyboardInterrupt: pass stream_cmd = uhd.types.StreamCMD(uhd.types.StreamMode.stop_cont) streamer.issue_stream_cmd(stream_cmd) cs.curs_set(1) cs.nocbreak() screen.keypad(0) cs.echo() cs.endwin()
def __init__(self): self.running = True self.paused = False self.DATA_Y = 1 self.DATA_X = 0 self.DATA_H = 29 self.DATA_W = 32 self.PLAYERS_Y = 1 self.PLAYERS_X = self.DATA_X + self.DATA_W + 2 self.PLAYERS_H = 21 self.PLAYERS_W = 66 self.MAP_Y = 1 self.MAP_X = self.PLAYERS_X + self.PLAYERS_W + 2 self.MAP_H = 0 self.MAP_W = 0 self.PATH_Y = self.PLAYERS_Y + self.PLAYERS_H + 3 self.PATH_X = self.DATA_X + self.DATA_W + 2 self.PATH_H = 5 self.PATH_W = 66 self.LOG_Y = self.DATA_Y + self.DATA_H + 2 self.LOG_X = 0 self.LOG_H = 12 self.LOG_W = self.DATA_W + self.PLAYERS_W + 2 self.HELP_Y = self.LOG_Y + self.LOG_H - 2 self.HELP_X = 1 self.HELP_H = 1 self.HELP_W = self.LOG_W - 2 self.TIME_Y = self.LOG_Y + self.LOG_H + 2 self.TIME_X = 0 self.TIME_H = 0 self.TIME_W = 0 self.MENU_Y = 0 self.MENU_X = 0 self.MENU_H = 24 self.MENU_W = 0 self.SUMMARY_Y = self.LOG_Y + 5 self.SUMMARY_X = self.LOG_X + self.LOG_W + 2 self.SUMMARY_H = 7 self.SUMMARY_W = 20 self.data_win = None self.map_win = None self.path_win = None self.log_win = None self.help_win = None self.players_win = None self.time_win = None self.menu_win = None self.time_win = None self.summary_win = None self.log_entries = [] self.stdscr = curses.initscr() curses.start_color() # Basic color set curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(7, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_YELLOW) # check for minimal screen size screen_y, screen_x = self.stdscr.getmaxyx() if screen_y < MIN_LINES or screen_x < MIN_COLS: # Try resizing terminal curses.resizeterm(MIN_LINES, MIN_COLS) if not curses.is_term_resized(MIN_LINES, MIN_COLS): self.quit_ui() print ("Unable to change your terminal size. Your terminal must be at least", \ MIN_LINES, "lines and", MIN_COLS, "columns and it actually has", \ screen_y, "lines and", screen_x, "columns.") quit(1) # Screen is up curses.noecho() curses.cbreak() curses.curs_set(0) self.stdscr.keypad(1)
def keyborad_processor(main_screen): def clear_cursor(): visible_lines[cursor_position]['screen'].chgat(visible_lines[cursor_position]['y'], 1, int(width / 2) - 3, curses.color_pair(3)) if visible_lines[cursor_position]['findit']: visible_lines[cursor_position]['screen'].addstr(visible_lines[cursor_position]['y'], visible_lines[cursor_position]['findit_position'], visible_lines[cursor_position]['findit'][1], curses.color_pair(4) | curses.A_BOLD) visible_lines[cursor_position]['screen'].refresh() def draw_cursor(): if visible_lines: visible_lines[cursor_position]['screen'].chgat(visible_lines[cursor_position]['y'], 1, int(width / 2) - 3, curses.color_pair(5)) if visible_lines[cursor_position]['findit']: visible_lines[cursor_position]['screen'].addstr(visible_lines[cursor_position]['y'], visible_lines[cursor_position]['findit_position'], visible_lines[cursor_position]['findit'][1], curses.color_pair(6) | curses.A_BOLD) visible_lines[cursor_position]['screen'].refresh() def move_cursor_down(): nonlocal current_page nonlocal cursor_position nonlocal visible_lines if cursor_position + 1 == len(visible_lines) and len(visible_lines) == max_lines * 2: current_page += 1 cursor_position = 0 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) else: cursor_position = cursor_position + 1 if cursor_position + 1 < len(visible_lines) else cursor_position def move_cursor_up(): nonlocal current_page nonlocal cursor_position nonlocal visible_lines if current_page > 0 and cursor_position == 0: current_page -= 1 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) cursor_position = len(visible_lines) - 1 else: cursor_position = cursor_position - 1 if cursor_position > 0 else cursor_position def call_search_dialog(): nonlocal search_string sid = edit_box(70, 5, 5, ' Searching for... ') while True: key = sid.getch() if key == 10: break if key == 27: curses.curs_set(0) return False edit_box_keyborad_processor(sid, key, search_string) return True def new_cert_dialog(): nonlocal obj_set obj_set = [{'win_id': edit_box(70, 5, 5, ' Name '), 'buffer': [], 'onlydigit': False}, {'win_id': edit_box(70, 8, 5, ' E-mail '), 'buffer': [], 'onlydigit': False}, {'win_id': edit_box(70, 11, 5, ' Expired in ... '), 'buffer': [], 'onlydigit': True}] for obj in reversed(obj_set): obj['win_id'].refresh() cur_object = 0 while True: key = obj_set[cur_object]['win_id'].getch() if key == 9: cur_object = cur_object + 1 if cur_object + 1 < len(obj_set) else 0 if key == 10: break if key == 27: curses.curs_set(0) return False edit_box_keyborad_processor(obj_set[cur_object]['win_id'], key, obj_set[cur_object]['buffer'], obj_set[cur_object]['onlydigit']) return True def menu(): offset = 0 for item in ['Q: Exit ', 'S: Search ', 'Ctrl+V: show valid ', 'Ctrl+R: show revoked ', 'Ctrl+A: show all ', 'C: Gen CRL ', 'N: New ', 'P: p12 gen ', 'R: Revoke ']: menu_item = item.split(':') try: main_screen.addstr(height - 1, offset, menu_item[0], curses.color_pair(2) | curses.A_BOLD) main_screen.addstr(height - 1, offset + len(menu_item[0]) + 1, '%s' % menu_item[1], curses.color_pair(1)) except: pass offset = offset + len(item) + 2 def show_me_screen(): nonlocal left, right, height, width, max_lines, visible_lines height, width = main_screen.getmaxyx() left, right = create_main_window(main_screen, height, width) max_lines = min([left[0].getmaxyx()[0], right[0].getmaxyx()[0]]) max_lines -= 2 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) draw_cursor() main_screen.refresh() curses.panel.update_panels() menu() cursor_position = 0 current_page = 0 left, right, height, width = None, None, 0, 0 max_lines = 0 visible_lines = [] show_me_screen() while True: pressed_key = main_screen.getch() try: main_screen.move(height - 3, 1) except: pass main_screen.clrtoeol() if pressed_key == curses.KEY_RESIZE: if curses.is_term_resized(height, width): main_screen.clear() main_screen.refresh() del left del right show_me_screen() if pressed_key == 258: clear_cursor() move_cursor_down() draw_cursor() if pressed_key == 99: generate_crl() visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) if pressed_key == 259: clear_cursor() move_cursor_up() draw_cursor() if pressed_key == 338: clear_cursor() cursor_position = len(visible_lines) - 1 move_cursor_down() draw_cursor() if pressed_key == 339: clear_cursor() cursor_position = 0 move_cursor_up() draw_cursor() if pressed_key == 114: if visible_lines[cursor_position]['Status'] == 'V': revoke_cert(visible_lines[cursor_position]) or generate_crl() visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) else: main_screen.addstr(height - 3, 1, 'Already revoked', curses.color_pair(7) | curses.A_BOLD | curses.A_BLINK) if pressed_key == 113 or pressed_key == 81: break if pressed_key == 112 or pressed_key == 80: try: p12_file_size = os.path.getsize('%s/Certs/%s.p12' % (os.environ['PKI_ROOT'], visible_lines[cursor_position]['CN'])) except FileNotFoundError: p12_file_size = -1 if p12_file_size <= 0 and visible_lines[cursor_position]['Status'] == 'V': generate_p12(visible_lines[cursor_position]['CN']) visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) else: main_screen.addstr(height - 3, 1, 'Already exist', curses.color_pair(7) | curses.A_BOLD | curses.A_BLINK) if pressed_key == 22: cursor_position = 0 current_page = 0 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines, findit=('Status', 'V')) draw_cursor() if pressed_key == 18: cursor_position = 0 current_page = 0 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines, findit=('Status', 'R')) draw_cursor() if pressed_key == 1: cursor_position = 0 current_page = 0 visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) draw_cursor() if pressed_key == 115 or pressed_key == 83: search_string = [] cursor_position = 0 find_str = None if call_search_dialog(): find_str = ('CN', ''.join(search_string)) visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines, findit=find_str) draw_cursor() if pressed_key == 110: obj_set = [] new_cert_dialog() if len(obj_set[0]['buffer'] and obj_set[1]['buffer'] and obj_set[2]['buffer']): (create_request(''.join(obj_set[0]['buffer']), ''.join(obj_set[1]['buffer'])) or sign_cert(''.join(obj_set[0]['buffer']), ''.join(obj_set[1]['buffer']), ''.join(obj_set[2]['buffer'])) or generate_p12(''.join(obj_set[0]['buffer']))) visible_lines = show_lines(left[0], right[0], page=current_page, max_lines=max_lines) draw_cursor()
def main(self, screen, irc_print_queue, irc_flood_timeout_queue, ui_print_queue, ui_status_queue): try: curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLUE) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN) curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_YELLOW) curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_RED) curses.curs_set(0) curses.nocbreak() screen.bkgd(curses.color_pair(1)) screen.refresh() con_buf = [] win_size = screen.getmaxyx() console_width=(((win_size[1]/2)+(win_size[1]/6))) status_position=(((win_size[1]/2)+(win_size[1]/6))) status_width=(win_size[1]-status_position) con_win = curses.newwin(win_size[0], console_width, 0, 0) stat_win = curses.newwin((win_size[0]/2), status_width, 0, status_position) con_win.keypad(0) con_win.notimeout(0) con_win.bkgd(curses.color_pair(2)) con_win.move(1,1) con_line = 1 con_max_line_len = (console_width-16) con_max_lines = (win_size[0]-2) PINGS=0 PING_TIME=datetime.datetime.now() IRC_MESSAGES=0 while True: if curses.is_term_resized(win_size[0], win_size[1]): win_size = screen.getmaxyx() screen.clear() curses.resizeterm(win_size[0], win_size[1]) console_width=(((win_size[1]/2)+(win_size[1]/6))) status_position=(((win_size[1]/2)+(win_size[1]/6))) status_width=(win_size[1]-status_position) con_win.resize(win_size[0], console_width) con_win.mvwin(0,0) con_win.redrawwin() con_win.erase() con_win.move(1,1) con_line = 1 con_max_line_len = (console_width-16) con_max_lines = (win_size[0]-2) buffer_size = len(con_buf) lines = min(buffer_size, con_max_lines) for line in range(0,lines): con_win.move(1,2) con_win.deleteln() con_win.move(con_max_lines,1) con_win.deleteln() con_win.insstr(con_max_lines, 2, con_buf[(buffer_size-lines)+line]) con_win.noutrefresh() stat_win.resize((win_size[0]/2), status_width) stat_win.mvwin(0,status_position) stat_win.redrawwin() stat_win.clear() screen.refresh() con_win.box() con_win.insstr(0, ((console_width/2)-6), "Bot Console") if ui_print_queue.empty() == False: line=ui_print_queue.get() if line is None: break #bad queue item con_buf.append(line) if len(con_buf) > 512: con_buf.pop(0) con_win.move(1,2) con_win.deleteln() con_win.move(con_max_lines,1) con_win.deleteln() con_win.insstr(con_max_lines, 2, (line)) con_win.noutrefresh() else: time.sleep(0.004) if ui_status_queue.empty() == False: status=ui_status_queue.get() if status[0] == STAT['ping']: PINGS=status[1] elif status[0] == STAT['ping_time']: PING_TIME=status[1] elif status[0] == STAT['irc_messages']: IRC_MESSAGES=status[1] else: time.sleep(0.004) uptime = (datetime.datetime.now() - self.loadDateTime) stat_win.move(1,2) stat_win.clrtoeol() stat_win.insstr(1,2, ("LoadTime " + self.loadDateTime.strftime('%d/%m/%Y %H:%M:%S'))) stat_win.move(2,2) stat_win.clrtoeol() stat_win.insstr(2,2, ("Uptime " + str(uptime))) stat_win.move(3,2) stat_win.clrtoeol() stat_win.insstr(3,2, "IRC Flood ") stat_win.move(3,15) flood_bar_len = float(min(((FLOOD['flood_messages']), (status_width-21)))) for x in range(0,min(int(irc_flood_timeout_queue.qsize()*(float(flood_bar_len)/float(FLOOD['flood_messages']))),flood_bar_len)): if irc_flood_timeout_queue.qsize() >= FLOOD['flood_messages']: stat_win.addch(' ',curses.color_pair(5)) elif irc_flood_timeout_queue.qsize() >= (FLOOD['flood_messages']/2): stat_win.addch(' ',curses.color_pair(4)) else: stat_win.addch(' ',curses.color_pair(3)) stat_win.insstr(3, int(15+flood_bar_len), (" : " + str(irc_flood_timeout_queue.qsize()))) stat_win.move(4,2) stat_win.clrtoeol() stat_win.insstr(4,2, "IRC MSG Q " + str(irc_print_queue.qsize())) stat_win.move(5,2) stat_win.clrtoeol() stat_win.insstr(5,2, "#IRC MSGS " + str(IRC_MESSAGES)) stat_win.move(6,2) stat_win.clrtoeol() stat_win.insstr(6,2, "PINGs " + str(PINGS)) stat_win.move(7,2) stat_win.clrtoeol() if PINGS==0: stat_win.insstr(7,2, "Last PING Never") else: stat_win.insstr(7,2, "Last PING " + PING_TIME.strftime('%d/%m/%Y %H:%M:%S')) stat_win.vline(1,14,'|',(((win_size[1]/2)+(win_size[1]/6)))) stat_win.box() stat_win.insstr(0, ((status_width/2)-5), "Bot Stats") con_win.box() con_win.insstr(0, ((console_width/2)-6), "Bot Console") curses.doupdate() con_win.refresh() stat_win.refresh() except Exception as e: print e exit()
import curses import time screen = curses.initscr() # Get current size y, x = screen.getmaxyx() # See if a resize would succeed y = 30 x = 100 can_resize = curses.is_term_resized(y, x) # Action in loop if resize is True: if can_resize: screen.clear() curses.resizeterm(y, x) screen.refresh() time.sleep(3) else: screen.endwin() print("Unable to resize window")
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS - 1) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) # availmask indicates that mouse stuff not available. if availmask != 0: curses.mouseinterval(10) # just verify these don't cause errors m = curses.getmouse() curses.ungetmouse(*m) if hasattr(curses, 'is_term_resized'): curses.is_term_resized(*stdscr.getmaxyx()) if hasattr(curses, 'resizeterm'): curses.resizeterm(*stdscr.getmaxyx()) if hasattr(curses, 'resize_term'): curses.resize_term(*stdscr.getmaxyx())
def main(stdscr): # initialize window curses.use_default_colors() curses.curs_set(0) curses.init_pair(1, curses.COLOR_GREEN, -1) curses.init_pair(2, curses.COLOR_RED, -1) curses.init_pair(3, curses.COLOR_MAGENTA, -1) curses.init_pair(4, curses.COLOR_BLUE, -1) # generate text for the user to type tuple_list = generateRedditText() text, source = getText(tuple_list) word_list = splitText(text) # initialize variables so_far = "" so_far_word = "" position = 0 word_index = 0 start_time = None quit = False y, x = stdscr.getmaxyx() while True: displayText(stdscr, text, position, y, x) # handle screen resizes if curses.is_term_resized(y, x): stdscr.clear() y, x = stdscr.getmaxyx() displayText(stdscr, text, position, y, x) if quit: break stdscr.addstr((len(text) // x) + 2, 0, "> ") if start_time is None: stdscr.addstr((len(text) // x) + 4, 0, "Start typing to begin. Hit ESC to quit.", curses.A_BOLD) c = stdscr.getch() # quit on ESC if c == 27 or quit: break # start a timer after the first key is pressed if c < 256 and start_time is None: stdscr.clear() start_time = time.time() # detect and handle 'delete' key if c == 127: if len(so_far_word) > 0: so_far = so_far[:-1] so_far_word = so_far_word[:-1] stdscr.clear() # handle user character input elif c < 256 and c != 10: so_far += chr(c) so_far_word += chr(c) position = len(so_far) # keep track of the current word the user is typing current_word = word_list[word_index] # display red if typo if so_far_word != current_word[:len(so_far_word)]: stdscr.addstr((len(text) // x) + 2, 2, so_far_word, curses.color_pair(2)) # otherwise, green else: stdscr.addstr((len(text) // x) + 2, 2, so_far_word, curses.color_pair(1)) # clear the input section when words are typed correctly if so_far_word == current_word and word_index < len(word_list) - 1: stdscr.clear() word_index += 1 so_far_word = "" # detect when the text is finished being typed if so_far == text: end_time = time.time() # calculate and display wpm and source wpm = calculateWPM(text, start_time, end_time) stdscr.addstr((len(text) // x) + 2, 2, "WPM: ", curses.A_BOLD) stdscr.addstr((len(text) // x) + 2, 7, str(wpm), curses.color_pair(3)) stdscr.addstr( (len(text) // x) + 4, 0, "Press Enter to continue playing or 'r' to redo. Hit ESC to quit.", curses.A_BOLD) stdscr.addstr((len(text) // x) + 6, 0, "Source: ", curses.A_BOLD) stdscr.addstr((len(text) // x) + 6, 8, source, curses.color_pair(4)) # reset the game valid_option = False while True: d = stdscr.getch() # ESC (27) pressed if d == 27: quit = True break # enter key (10) or 'r' key (114) pressed elif d == 10 or d == 114: if d == 10: text, source = getText(tuple_list) word_list = splitText(text) # re-initialize variables and clear screen stdscr.clear() so_far = "" so_far_word = "" position = 0 word_index = 0 start_time = None done = False quit = False y, x = stdscr.getmaxyx() break