def draw(state,i): screen,windows = state['screen'],state['windows'] topy,topx,bplex = state['topy'],state['topx'],state['buffplex'] current,last = state['current'],state['last'] top_textbox = windows[0] windows[current].bkgd(curses.color_pair(1)) windows[last].bkgd(curses.color_pair(2)) maxy, maxx = bplex.stdscr.getmaxyx() cy, cx = windows[current].getbegyx() # The current window is to far down. Switch the top textbox. if ((topy + maxy - bplex.height) <= cy):top_textbox = windows[current] # The current window is to far up. There is a better way though... if topy >= cy + bplex.height:top_textbox = windows[current] bfcapt = bplex() #screen.clear() for bx in range(bplex.buffcount): bfname = bplex.buffnames[bx] bi,w = bfcapt[bfname],windows[bx] w.box() w.addstr(1,1,'%s:%s' % (bfname,bi)) screen.refresh() topy,topx = bplex.center_view(top_textbox) curses.doupdate()
def init_and_run(self, stdscr): """ called by ncurses.wrapper """ self.stdscr = stdscr try: curses.curs_set(0) except: pass curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK) self.max_y, self.max_x = stdscr.getmaxyx() self.head_win = curses.newwin(4, self.max_x, 0, 0) self.body_win = curses.newwin(self.max_y-4, self.max_x, 4, 0) self.init_head_win() self.init_body_win() curses.doupdate() self.run()
def refresh(self): """ This method just shows each line of the event log """ events = component.get('ConsoleUI').events self.stdscr.erase() self.draw_statusbars() if events: for i, event in enumerate(events): if i - self.offset >= self.rows - 2: more = len(events) - self.offset - self.rows + 2 if more > 0: self.add_string(i - self.offset, ' (And %i more)' % more) break elif i - self.offset < 0: continue try: self.add_string(i + 1 - self.offset, event) except curses.error: pass # This'll just cut the line. Note: This seriously should be fixed in a better way else: self.add_string(1, '{!white,black,bold!}No events to show yet') if not component.get('ConsoleUI').is_active_mode(self): return self.stdscr.noutrefresh() curses.doupdate()
def display(self): self.panel.top() self.panel.show() self.window.clear() # Play keys. play = lambda c: c == ord('p') or c == curses.KEY_ENTER or c == 10 or c == 13 while True: self.window.refresh() curses.doupdate() for index, item in enumerate(self.items): if index == self.position: mode = curses.A_REVERSE else: mode = curses.A_NORMAL self.window.addstr(index, 1, str(item), mode) key = self.window.getch() # Start song if play(key): self.pytify.listen(int(self.position - 1)) # Up elif key == ord('k') or key == curses.KEY_UP: self.navigate(-1) # Down elif key == ord('j') or key == curses.KEY_DOWN: self.navigate(1) # Left elif key == ord('h') or key == curses.KEY_LEFT: self.pytify.prev() # Rights elif key == ord('l') or key == curses.KEY_RIGHT: self.pytify.next() # Play/Pause elif key == ord(' '): self.pytify.play_pause() # Search elif key == ord('s'): break # Search elif key == ord('q'): curses.endwin() sys.exit() self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
def draw_window_apptitle(): window = windows['appTitle'] window.clear() window.bkgd(" ", attrs['appTitleWindow']) window.addstr(1, (cs.COLS/2) - (len(appTitle)/2), appTitle, attrs['appTitle']) window.noutrefresh() cs.doupdate()
def main(scr): h, w = scr.getmaxyx() hghts = [h // 3 + (1 if 3 - h % 3 <= i else 0) for i in range(3)] pr = 0 wins = [] for i in hghts: wins.append(newwin(i, w, pr, 0)) pr += i for i in range(3): wins[i].box(0, 0) panels = [new_panel(i) for i in wins] update_panels() doupdate() x = 0 while x != ord('q'): x = scr.getch() wn = wins[0] wn.addstr(1, 1, "%x" % x) wn.addstr(2, 1, repr([ i for i in dir(wn) if not i.startswith('__')])[:w-3]) def_prog_mode() endwin() print(dir(wn)) reset_prog_mode() wins[0].refresh()
def startup(self): self.mode = CursesVisualizer.Mode.MAIN self.voice = 0 self.scale = 0 Visualizer.startup(self) curses.curs_set(0) curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() self.screen.nodelay(True) self.screen.keypad(True) self.screen.clear() self.screen.refresh() for m in self.modeScreens.itervalues(): m.startup() height = self.screen.getmaxyx()[0] - 1 width = self.screen.getmaxyx()[1] - 1 self.winToolbar = curses.newwin(2, width, height-2, 0) self.old_stdout = sys.stdout self.old_stderr = sys.stderr self.fakeOut = FakeSysOut() sys.stdout = self.fakeOut sys.stderr = self.fakeOut self.paint_toolbar() curses.doupdate()
def display(self): self.panel.top() self.panel.show() self.window.clear() self.window.border(0) self.window.addstr(0,1,self.title) while True: self.refresh() key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: if self.position == len(self.items)-1: break else: self.items[self.position][1]() break elif key == curses.KEY_UP: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
def okbox(mesg,ymax,xmax,y,x): lymax = y lxmax = x ok = "[ OK ]" cancel ="[CANCEL]" y0 = int((ymax-lymax)/2) x0 = int((xmax-lxmax)/2) okb = curses.newwin(lymax,lxmax,y0,x0) okb.keypad(True) okb.border() okb_panel = curses.panel.new_panel(okb) curses.panel.update_panels() curses.doupdate() okb.addstr(int(2*lymax/7),int((lxmax-len(mesg))/2),mesg,curses.A_BOLD) okb.refresh() notDone = True qualities = [curses.A_REVERSE,curses.A_NORMAL,curses.A_REVERSE] i = 0 while notDone: okb.addstr(int(4*lymax/7),int((2*lxmax/4-len(ok))/2),ok,qualities[i]) okb.refresh() okb.addstr(int(4*lymax/7),int((2*3*lxmax/4-len(cancel))/2),cancel,qualities[i+1]) okb.refresh() k = okb.getch() if k == curses.KEY_LEFT and i == 1: i = 0 elif k == curses.KEY_RIGHT and i == 0: i = 1 elif k in [ord('\n'),ord('\r')]: notDone = False return i
def open_editor(data=''): """ Open a temporary file using the system's default editor. The data string will be written to the file before opening. This function will block until the editor has closed. At that point the file will be read and and lines starting with '#' will be stripped. """ with NamedTemporaryFile(prefix='rtv-', suffix='.txt', mode='wb') as fp: fp.write(clean(data)) fp.flush() editor = os.getenv('RTV_EDITOR') or os.getenv('EDITOR') or 'nano' curses.endwin() try: subprocess.Popen([editor, fp.name]).wait() except OSError: raise ProgramError('Could not open file with %s' % editor) curses.doupdate() # Open a second file object to read. This appears to be necessary in # order to read the changes made by some editors (gedit). w+ mode does # not work! with open(fp.name) as fp2: text = ''.join(line for line in fp2 if not line.startswith('#')) text = text.rstrip() return text
def display(self, data): if self.changeflag.isSet(): return inchar = self.mainwin.getch() if inchar == 12: # ^L self._remake_window() self.mainwin.erase() if data: self._display_data(data) else: self.mainwin.addnstr( 1, int(self.mainwinw/2)-5, 'no torrents', 12, curses.A_BOLD ) totalup = 0 totaldn = 0 for ( name, status, progress, peers, seeds, seedsmsg, dist, uprate, dnrate, upamt, dnamt, size, t, msg ) in data: totalup += uprate totaldn += dnrate totalup = '%s/s' % fmtsize(totalup) totaldn = '%s/s' % fmtsize(totaldn) self.totalwin.erase() self.totalwin.addnstr(0, self.mainwinw-27, 'Totals:', 7, curses.A_BOLD) self.totalwin.addnstr(0, self.mainwinw-20 + (10-len(totaldn)), totaldn, 10, curses.A_BOLD) self.totalwin.addnstr(0, self.mainwinw-10 + (10-len(totalup)), totalup, 10, curses.A_BOLD) curses.panel.update_panels() curses.doupdate() return inchar in (ord('q'),ord('Q'))
def Increment(self): # Push snake head self.snakeHead += self.snakeDirection self.snake.insert(0, self.snakeHead) # Check for snake/border collision if self.snakeHead.i == 0 or self.snakeHead.j == 0 or self.snakeHead.i == self.size - 1 or self.snakeHead.j == self.size - 1 or any(segment == self.snakeHead for segment in self.snake[1 : ]): self.alive = False self.PrePaint(self.snakeHead, 'X') else: self.PrePaint(self.snakeHead, 'O') # Check for snake/fruit collision if self.snakeHead == self.fruit: self.NewFruit() self.score += 10 * self.snakeSpeed self.UpdateScore() self.snakeSpeed += 2 self.pad.timeout(self.period // self.snakeSpeed) self.snakeLength += self.snakeSpeed # Pull snake tail? if len(self.snake) >= self.snakeLength: self.PrePaint(self.snake.pop(), ' ') # Paint curses.doupdate() return
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 place_windows(): for window in windows.keys(): wHeight, wWidth, wStartY, wStartX = windows_dimen[window] windows[window] = stdscr.subwin(wHeight, wWidth, wStartY, wStartX) windows[window].box() windows[window].noutrefresh() cs.doupdate()
def open_browser(url, window=None): """ Open the given url using the default webbrowser. The preferred browser can specified with the $BROWSER environment variable. If not specified, python webbrowser will try to determine the default to use based on your system. For browsers requiring an X display, we call webbrowser.open_new_tab(url) and redirect stdout/stderr to devnull. This is a workaround to stop firefox from spewing warning messages to the console. See http://bugs.python.org/issue22277 for a better description of the problem. For console browsers (e.g. w3m), RTV will suspend and display the browser window within the same terminal. This mode is triggered either when 1. $BROWSER is set to a known console browser, or 2. $DISPLAY is undefined, indicating that the terminal is running headless There may be other cases where console browsers are opened (xdg-open?) but are not detected here. """ if config.images and url.endswith(".png"): os.system("curl -s " + url + " > /tmp/rtv.jpg") elif config.images and url.endswith(".jpg"): os.system("curl -s " + url + " > /tmp/rtv.jpg") elif check_browser_display(): command = "import webbrowser; webbrowser.open_new_tab('%s')" % url args = [sys.executable, '-c', command] with open(os.devnull, 'ab+', 0) as null: subprocess.check_call(args, stdout=null, stderr=null) else: curses.endwin() webbrowser.open_new_tab(url) curses.doupdate()
def input_callback(self, prompt, completions=True): # Setup subedit self.curs_set(1) self.callbacks["set_var"]("input_do_completions", completions) self.callbacks["set_var"]("input_prompt", prompt) self.input_box.reset() self.input_box.refresh() curses.doupdate() self.pseudo_input_box.keypad(0) r = raw_readline() if not r: r = "" self.pseudo_input_box.keypad(1) # Only add history for commands, not other prompts if completions: readline.add_history(r) self.callbacks["set_var"]("input_prompt", "") self.input_box.reset() self.input_box.refresh() curses.doupdate() self.curs_set(0) return r
def run_command(name): main_panel.show() status_panel.show() main_window.clear() status_window.clear() wait_for_internet() p = subprocess.Popen(name, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True,executable="/bin/bash") while(True): retcode = p.poll() #returns None while subprocess is running statement=p.stdout.readline() try: main_window.addstr(statement) except: pass if statement.find("Get:")!=-1 or statement.find("Downloading/unpacking")!=-1: status_window.clear() status_window.addstr("Downloading...",curses.A_STANDOUT) elif statement.find("Reading package lists...")!=-1: status_window.clear() status_window.addstr("Starting...",curses.A_STANDOUT) else: status_window.clear() status_window.addstr("Installing...",curses.A_STANDOUT) curses.panel.update_panels() curses.doupdate() if(retcode is not None): break status_window.clear() status_window.addstr("press any key to exit",curses.A_STANDOUT) status_window.getch() main_panel.hide() status_panel.hide() curses.panel.update_panels() curses.doupdate() return
def display(self): self.panel.top() self.panel.show() self.window.clear() while True: self.window.refresh() curses.doupdate() for index, item in enumerate(self.items): if index == self.position: mode = curses.A_REVERSE else: mode = curses.A_NORMAL msg = '%d. %s' % (index, item[0]) self.window.addstr(1+index, 1, msg, mode) key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: if self.position == len(self.items)-1: break else: self.items[self.position][1]() elif key == curses.KEY_UP: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
def run_command(name): main_panel.show() status_panel.show() p = subprocess.Popen(name, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True,executable="/bin/bash") while(True): retcode = p.poll() #returns None while subprocess is running statement=p.stdout.readline() try: main_window.addstr(statement) except: pass if statement.find("Get:")!=-1: status_window.clear() status_window.addstr("Downloading...",curses.A_STANDOUT) elif statement.find("Reading package lists...")!=-1: status_window.clear() status_window.addstr("Starting...",curses.A_STANDOUT) elif statement.find("Setting up"): status_window.clear() status_window.addstr("Completing Installation...",curses.A_STANDOUT) else: status_window.clear() status_window.addstr("Installing...",curses.A_STANDOUT) curses.panel.update_panels() curses.doupdate() if(retcode is not None): break main_panel.hide() status_panel.hide() curses.panel.update_panels() curses.doupdate() raw_input()
def draw(): walls.erase() #obj.erase() for i in objects: if i.objtype=='effect': if i.live==0: killobj(objects, i) continue else: i.live -= 1 if inframe(i.y,i.x): if i.objtype=='plr': walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(1)) elif i.objtype=='bot': walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(2)) elif i.objtype=='blt': walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(3)) elif i.objtype=='effect': walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(4)) else: walls.addch(i.y,i.x,i.mark) panel.update_panels() curses.doupdate() if not blast_panel.hidden(): blast_panel.hide()
def ConnectText(self,window,x,y,colorAttr1,colorAttr2): self._killthread = False m = " Connecting to server " x2 = x + len(m) ndots = 8 temp = 0 tmode = True window.addstr(y,x,m,colorAttr1) while (not(self._killthread)): for i in range(ndots): if (tmode): if (i < temp): window.addstr(y,x2+i,'.',colorAttr1) else: window.addstr(y,x2+i,'.',colorAttr2) else: if (i<temp): window.addstr(y,x2+i,'.',colorAttr2) else: window.addstr(y,x2+i,'.',colorAttr1) temp += 1 if (temp > ndots): temp = 1 tmode = not(tmode) window.noutrefresh() curses.doupdate() time.sleep(.2)
def page(data, use_internal=False): command = get_pager_command() if not command or use_internal: page_internal(data) else: curses.endwin() try: popen = subprocess.Popen(command, stdin=subprocess.PIPE) if py3 or isinstance(data, unicode): data = data.encode(sys.__stdout__.encoding, 'replace') popen.stdin.write(data) popen.stdin.close() except OSError as e: if e.errno == errno.ENOENT: # pager command not found, fall back to internal pager page_internal(data) return except IOError as e: if e.errno != errno.EPIPE: raise while True: try: popen.wait() except OSError as e: if e.errno != errno.EINTR: raise else: break curses.doupdate()
def refresh(self, highligh=True): self.window.clear() for index, item in enumerate(self.items_strings): if index < self.head_position: continue elif index > self.head_position + self.height - 1: continue elif index == self.position: if highligh: mode = curses.color_pair(3) else: mode = curses.color_pair(1) else: mode = curses.color_pair(2) if self.selector_menu: if index in self.selected_items: item = '[x] ' + item else: item = '[ ] ' + item if self.horizontal: x = self.horizontal_padding // 2 + index * self.horizontal_padding y = 0 else: x = 0 y = index - self.head_position self.window.addstr(y, x, item, mode) self.render_scroll_bar() self.window.refresh() self.panel.top() self.panel.show() curses.panel.update_panels() curses.doupdate()
def askString(message, length=40): """Asks the user to enter a string. message: the window title. length: expected maximum length for the string. Returns the inserted string or None if the user canceled the input.""" retval = None winY = screenH / 2 - 2 winWidth = max(len(message), length) + 4 winX = (screenW - winWidth) / 2 panel = CursesPanel(3, winWidth, winY, winX, title=message) panel.focus() window = panel._window subWin = window.derwin(1, length, 1, 1) subWin.keypad(1) textBox = curses.textpad.Textbox(subWin) textBox.stripspaces = True curses.panel.update_panels() curses.doupdate() done = False while not done: c = subWin.getch() if c == curses.ascii.NL: retval = textBox.gather() done = True elif c == curses.ascii.ESC: done = True # so that we return None else: textBox.do_command(c) del textBox del subWin del window return retval
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()
def redraw(seconds=1): """ Redraws the screen periodically. """ while True: curses.doupdate() time.sleep(seconds)
def __liveActually(self, stdscr): """live() calls this function inside a curses wrapper.""" global screenH, screenW self.__stdscr = stdscr (screenH, screenW) = self.__stdscr.getmaxyx() self.__stdscr.addstr(0, 0, "Custom Burner " + common.version) self.__stdscr.addstr(screenH - 1, 0, "a: add ISO q: Quit") self.__stdscr.noutrefresh() isoWindowHeight = ((screenH - 2) * 2)/ 3 self.__isoWindow = IsoWindow(isoWindowHeight, screenW, 1, 0) self.__isoWindow.timeout(1000) # msec self.__logWindow = LogWindow(screenH - 2 - isoWindowHeight, screenW, isoWindowHeight + 1, 0) self.__focus = 0 self.__focusedWindow = self.__isoWindow self.__isoWindow.focus() quitting = False while not quitting: self.__updateLog() curses.panel.update_panels() curses.doupdate() c = self.__focusedWindow.getch() if c == curses.ascii.TAB: self.__switchFocus() elif c == ord('a'): self.__askForIso() elif c == ord('q'): quitting = True
def addkey(self, ch): if ch in (ascii.STX, curses.KEY_LEFT): if self.x > self.minx: self.x -= 1 elif ch in (ascii.BS, curses.KEY_BACKSPACE, ascii.DEL): if self.x > self.minx: idx = self.x - self.minx self.result = self.result[:idx - 1] + self.result[idx:] self.x -= 1 elif ch == curses.KEY_DC: # Delete if self.x < self.minx + len(self.result): idx = self.x - self.minx self.result = self.result[:idx] + self.result[idx + 1:] elif ch in (ascii.ACK, curses.KEY_RIGHT): # C-f self.x += 1 if len(self.result) + self.minx < self.x: self.result += " " elif ch in (ascii.ENQ, curses.KEY_END): # C-e self.x = self.minx + len(self.result) elif ch in (ascii.SOH, curses.KEY_HOME): # C-a self.x = self.minx elif ch == ascii.NL: # C-j return 0 elif ch == ascii.BEL: # C-g self.result = "" return 0 else: idx = self.x - self.minx self.result = self.result[:idx] + chr(ch) + self.result[idx:] self.x += 1 self.refresh() curses.doupdate() return 1
def inputbox(y,x,y0,x0,doEcho): box = curses.newwin(y,x,y0,x0) box.keypad(True) box_panel = curses.panel.new_panel(box) curses.panel.update_panels() curses.doupdate() box.bkgd('_') val = "" length = 0 enter = False while not enter: c = box.getch() if c in [ord('\n'),ord('\t'),ord(' ')]: enter = True elif chr(c) in string.printable and length < x-1: if doEcho: box.addch(chr(c)) else: box.addch("*") length+=1 val+=chr(c) elif (c in [8,127] or c == curses.KEY_BACKSPACE) and length > 0: # BACKSPACE/DELETE curry,currx = box.getyx() box.delch(curry,currx-1) box.addch('_') box.move(curry,currx-1) length-=1 val=val[:-1] return val
def die_callback(self, window): sync_lock.acquire_write() # Remove window from both window_types and the general window list try: idx = self.windows.index(window) except: pass else: # Call the window's die function window.die() del self.windows[idx] del self.window_types[idx] # Regenerate layout with remaining windows. self.subwindows() self.refresh() # Force a doupdate because refresh doesn't, but we have possibly # uncovered part of the screen that isn't handled by any other window. curses.doupdate() sync_lock.release_write()
def draw(self): """ Refresh all windows """ self.stdscr.clear() for name in self.windows: window = self.windows[name].window window.overwrite(self.stdscr) window.noutrefresh() # Also refresh extra stuff (e.g. SelectableList) for instance in self.extra_draws: instance.draw() curses.doupdate()
def enter(self): self.history_point = 0 curses.curs_set(1) curses.setsyx(2, 2) curses.doupdate() self.inp.erase() self.canceled = False res = self.text.edit(self._handle_key).strip() curses.curs_set(0) if self.canceled: self.inp.erase() self.inp.refresh() return '' elif (not (self.search_history) or self.search_history[-1] != res): self.search_history.append(res) return res
def start(self): self.state = State(self.version) self.state.version = self.version self.state.calc() self.load() if DEVMODE > 0: self.state.gold = 5000000000000000 self.state.level = 30000 self.state.rebirth.value = 100 self.state.evolve.value = 100 self.state.transform.value = 0 curses.doupdate() self.penalties = 0 self.init_level()
def drawGoal(current, goal): """ draws the game goal and current words counts on the screen :param current: int - the current words counts :param goal: int - the game goal in order to pass the level :return: panel - the panel that contains game goal and current words counts """ goal_win = curses.newwin(3, 18, 3, 90) goal_win.addstr(1, 2, "CURRENT: " + str(current) + "/" + str(goal)) goal_win.box() goal_pan = curses.panel.new_panel(goal_win) curses.panel.update_panels() goal_win.noutrefresh() curses.doupdate() return goal_pan
def print_to_screen(self, output_win): while 1: if not self.output_q.empty(): # take note of where cursor is at y, x = curses.getsyx() # get latest message from output_q msg = self.output_q.get() # msg = 'message' output_win.addstr(msg.rstrip() + "\n") output_win.refresh() # place cursor back where it was. curses.setsyx(y, x) curses.doupdate() time.sleep(.05)
def loop(self): cWin = self.windows[0] cWin.draw() curses.doupdate() while True: try: c = cWin.win.getch() # cWin.win.addstr(1,30, " ") # cWin.win.addstr(1,30, str(focus)) # cWin.win.refresh() except KeyboardInterrupt: self.__signal = 2 break cWin.key_pressed(c) if self.__signal != 0: break
def print_verb_adj_window(win, lverbs, ladjs): h, w = win.getmaxyx() len_x = w//2 pos_y = (h - 5)//2 color = win.getbkgd() tab = len_x//4 win.clear() for i in range(0, w): win.addch(0, i, curses.ACS_HLINE) for i in range(0, 5): if i < len(lverbs): win.addstr(pos_y+i, tab, lverbs[i][0], color) if i < len(ladjs): win.addstr(pos_y+i, len_x+tab, ladjs[i][0], color) win.noutrefresh() curses.doupdate()
def display(self, title, content): curses.curs_set(0) self.infowin.clear() y, x = self.infowin.getmaxyx() self.infowin.bkgd(" ", curses.color_pair(6)) self.infowin.box() self.infowin.addstr(0, 0, title, curses.A_UNDERLINE | curses.A_BOLD) for count, line in enumerate(content.split('\n'), start=1): self.infowin.addstr(count, 1, line) self.infopanel.show() curses.panel.update_panels() curses.doupdate() while self.infowin.getch() != 27: pass curses.curs_set(1)
def _run_loop(self, stdscr): self.stdscr = stdscr self.init() while (True): try: if (not self.views): break self.proc() try: self.key(SCKey(self.stdscr.get_wch())) except curses.error: if (time.time() < self.lastframe+self.frame_delay): continue self.key(SCKey(-1)) self.draw() curses.doupdate() self.lastframe = time.time() except KeyboardInterrupt: break self.stdscr = None
def main_page(scr: window): curses.curs_set(0) scr.noutrefresh() callbacks = {} def command_callback(command: str, **kwargs: Any): if command in callbacks: callbacks[command](**kwargs) setup_colours() max_rows, max_cols = scr.getmaxyx() views: dict[str, AbstractView] = { 'header': HeaderView(max_cols), 'footer': FooterView(max_rows, max_cols), 'a2z': A2ZView(max_rows, command_callback), 'tabs': TabView(max_cols, command_callback), 'content': ContentView(max_rows, max_cols, command_callback) } keypress_table: dict[str, Callable[[int], None]] = {name: view.process_keystroke for name, view in views.items()} focus: list[str] = ['a2z'] dispatch_to: list[Callable[[int], None]] = [keypress_table[focus[0]]] full_render_current_state(scr, views, focus[0]) curses.doupdate() callbacks = setup_callbacks(views, focus, dispatch_to) command_callback('LOAD_PAGE', page='HOMEPAGE') keep_going = True while keep_going: update_render_current_state(scr, views) curses.doupdate() key: int = scr.getch() if key == ord('q'): keep_going = False elif key == ord('\t'): focus[0] = next_focus(focus[0]) update_focuses(views, focus[0]) dispatch_to[0] = keypress_table[focus[0]] elif key == curses.KEY_RESIZE: curses.resizeterm(*scr.getmaxyx()) scr.erase() scr.noutrefresh() resize_all(focus[0], views, scr) else: dispatch_to[0](key)
def inputbox(stdscr, window, value="", title="", prompt="Please enter a value"): menu_bar = MenuBar(["Ok"]) cursor_pos = len(value) while True: draw_prompt(stdscr, window, menu_bar, prompt, input_box=value, title=title, cursor_pos=cursor_pos) stdscr.noutrefresh() window.noutrefresh() curses.doupdate() c = stdscr.getch() if c == 10: return (True, value) elif c == 27: return (False, None) elif c == curses.KEY_BACKSPACE: if cursor_pos > 0: cursor_pos -= 1 value = value[:cursor_pos] + value[cursor_pos + 1:] elif c == curses.KEY_DC: value = value[:cursor_pos] + value[cursor_pos + 1:] elif 32 <= c < 256: value = value[:cursor_pos] + chr(c) + value[cursor_pos:] cursor_pos += 1 elif c == curses.KEY_LEFT: if cursor_pos > 0: cursor_pos -= 1 elif c == curses.KEY_RIGHT: if cursor_pos < len(value): cursor_pos += 1 elif c == curses.KEY_HOME: cursor_pos = 0 elif c == curses.KEY_END: cursor_pos = len(value)
def show(self, title, text, downtext, percent, percent2=0, txtFrom='', txtTo=''): try: win = self.pwin.window() win.erase() #win.box(0, 0) win.border(curses.ACS_VLINE, curses.ACS_VLINE, curses.ACS_HLINE, curses.ACS_HLINE, curses.ACS_ULCORNER, curses.ACS_URCORNER, curses.ACS_LLCORNER, curses.ACS_LRCORNER) hpos = 0 win.addstr(hpos, int((self.w - len(title) - 2) / 2), ' ' + title + ' ', self.bd_att) hpos += 2 win.addstr(hpos, 2, text) if self.copy_move: hpos += 1 win.addstr(hpos, 2, 'From: %s' % txtFrom, color.DIR) hpos += 1 win.addstr(hpos, 2, 'To: %s' % txtTo, color.SEL_FLS) hpos += 2 win.addstr(hpos, self.w - 8, '[%3d%%]' % percent) if self.nprogress >= 2: hpos += 2 win.addstr(hpos, self.w - 8, '[%3d%%]' % percent2) win.addstr(self.h - 1, int((self.w - len(downtext) - 2) / 2), ' ' + downtext + ' ') win.noutrefresh() self.progress.refresh(percent) if self.nprogress >= 2: self.progress2.refresh(percent2) curses.doupdate() except: return
def refresh(self): # Resize the pad to make room for text self.output_p.resize(self.max_y, curses.COLS) # If at the bottom of the window, remain at the bottom of the window when more text is added if self.current_y == self.max_y - self.output_h: self.current_y += 1 # Ensure we are scrolling somewhere within the scrollable area if self.current_y < 0: self.current_y = 0 if self.current_y > self.max_y - self.output_h: self.current_y = self.max_y - self.output_h # Refresh the contents of the window, scrolling to current scroll position self.screen.noutrefresh() self.output_p.noutrefresh(self.current_y, 0, 1, 0, self.output_h, curses.COLS) curses.doupdate()
def drawProgressLine(self, screen, mixer): board_size = len(self.board) for i in range(0, board_size): max_len = board_size - 1 if i == 0: low = max_len else: low = i - 1 self.setProgressColor(low, "LOW", None) self.setProgressColor(i, "HIGH", mixer) curses.doupdate() newKey = screen.getch() if self.key != newKey: self.keyMap.handleKey(self.key, self.board, screen) self.key = newKey time.sleep(0.25)
def update(self,now=0,redraw=0): self.lock.acquire() try: if not self.active: return if redraw: self.scr.clear() self.scr.noutrefresh() if self.content: self.content.update(0,redraw) elif not redraw: self.scr.erase() if now: curses.doupdate() self.screen.cursync() finally: self.lock.release()
def setup_draw(self): """ Draws all of the windows for the curses interface """ # get screen dimensions self.maxY, self.maxX = self.stdscr.getmaxyx() # n_lines, n_cols, begin_y, begin_x self.head_win = curses.newwin(1, self.maxX, 0, 0) # left panel, contacts self.body_win = curses.newwin(self.maxY - 1, int(self.maxX * self.body_proportion), 1, 0) # chat frame self.chat_win = curses.newwin( self.maxY - 1 - int(self.maxY * self.text_area_proportion), self.maxX - int(self.maxX * self.body_proportion), 1, int(self.maxX * self.body_proportion)) self.chatareaHeight = self.maxY - 1 - int( self.maxY * self.text_area_proportion) - 2 # chat window (displays text) self.chatarea = curses.newwin( self.chatareaHeight, self.maxX - int(self.maxX * self.body_proportion) - 2, 2, int(self.maxX * self.body_proportion) + 1) # bottom frame window self.text_win = curses.newwin( int(self.maxY * self.text_area_proportion), self.maxX - int(self.maxX * self.body_proportion), self.maxY - int(self.maxY * self.text_area_proportion), int(self.maxX * self.body_proportion)) # bottom textarea self.textarea = curses.newwin( int(self.maxY * self.text_area_proportion) - 2, self.maxX - int(self.maxX * self.body_proportion) - 2, self.maxY - int(self.maxY * self.text_area_proportion) + 1, int(self.maxX * self.body_proportion) + 1) self.init_head() self.init_body() self.init_chat() self.init_chatarea() self.init_textbox() self.init_textarea() self.body_win.keypad(1) curses.doupdate()
def _get_input(self, wait_tenths): # this works around a strange curses bug with window resizing # not being reported correctly with repeated calls to this # function without a doupdate call in between curses.doupdate() key = self._getch(wait_tenths) resize = False raw = [] keys = [] while key >= 0: raw.append(key) if key == KEY_RESIZE: resize = True elif key == KEY_MOUSE: keys += self._encode_mouse_event() else: keys.append(key) key = self._getch_nodelay() processed = [] try: while keys: run, keys = escape.process_keyqueue(keys, True) processed += run except escape.MoreInputRequired: key = self._getch(self.complete_tenths) while key >= 0: raw.append(key) if key == KEY_RESIZE: resize = True elif key == KEY_MOUSE: keys += self._encode_mouse_event() else: keys.append(key) key = self._getch_nodelay() while keys: run, keys = escape.process_keyqueue(keys, False) processed += run if resize: processed.append('window resize') return processed, raw
def display_err(self, text): '''Display error 'text'. Will also flash the error text if this box was already visible, to draw the user's attention to the new (or existing) error Restores cursor location after updating ''' cursor_loc = curses.getsyx() self.clear() self.add_text(text) self.make_active() curses.setsyx(cursor_loc[0], cursor_loc[1]) curses.doupdate() if self.visible: self.flash() self.visible = True
def input(self): try: key = self.stdscr.getkey(0, 0) except CursesError: key = '' #while key == -1: # key = self.stdscr.getkey(0, 0) if key == ' ': self.report('testing', 5) if key == 'u': self.update_all() if key == 'q': self.quit() if key == 'r': if self.mode == 'resize': self.leave_resize() else: self.enter_resize() if key == 'm': if self.mode == 'monocle': self.leave_monocle() else: self.enter_monocle() if self.mode in {'normal', 'monocle'}: if key in self.scroll_keys: if self.focused == self.entry_pane: self.scroll_move(self.scroll_keys[key]) else: self.select_move(self.scroll_keys[key]) if key in self.focus_keys: self.focus(self.next_pane(self.focus_keys[key])) # Catching exceptions doesn't work because by the time the # exception is raised, the size has already been changed. if self.mode == 'resize': if key in self.resize_keys: self.resize_funcs[self.resize_keys[key]]() curses.doupdate()
def refresh(self): with self.curseslock: curses.endwin() self.stdscr.noutrefresh() self.y, self.x = self.stdscr.getmaxyx() self.mainwin.erase() curses.resizeterm(self.y, self.x) self.modewin.erase() self.modewin.resize(MODEWIN_LINES, self.x) self.modewin.box() self.modewin.noutrefresh() self.mainwin.resize(MAINWIN_LINES, self.x) self.mainwin.mvwin(MODEWIN_LINES, 0) self.mainwin.box() self.mainwin.noutrefresh() self.logwin.erase() self.logwin.resize( self.y - MODEWIN_LINES - MAINWIN_LINES - HELPWIN_LINES, self.x) self.logwin.mvwin(MODEWIN_LINES + MAINWIN_LINES, 0) self.logwin.box() self.logwin.noutrefresh() self.helpwin.erase() self.helpwin.resize(HELPWIN_LINES, self.x) self.helpwin.mvwin(self.y - HELPWIN_LINES, 0) try: self.helpwin.addstr( 0, 0, 's - set strobo_duration, b - set max_brightness, r - refresh screen, l - list clients, Ctrl-C - quit' ) except Exception: pass self.helpwin.noutrefresh() curses.doupdate() self.update_mainwin() self.update_modewin() self.update_log()
def show_window(self): y = self.y x = self.x self.shadowpanel.top() self.contentpanel.top() self.textpanel.top() self.shadowpanel.move(y + 1, x + 1) self.contentpanel.move(y, x) self.textpanel.move(y + 2, x + 2) self.shadowpanel.show() self.contentpanel.show() self.textpanel.show() curses.panel.update_panels() curses.doupdate()
def fillAddress(self, pan, height): sAddr = self.addrView win = pan.window() for i in range(1, height): win.move(i, 1) startAddr = hex(sAddr) startAddr = startAddr[2:] s = "0x" for i in range(self.addrWidth - len(startAddr) - 2): s = s + "0" startAddr = s + startAddr win.addstr(startAddr[0:self.addrWidth]) sAddr += 16 win.border(0, 0, 0, 0, 0, curses.ACS_TTEE, curses.ACS_LTEE, 0) curses.doupdate() panel.update_panels()
def redraw(self): window = curses.newwin(self._height, self._width, self._y, self._x) window.refresh() if self.pos < 0: for idx, child in enumerate(self.children): if isinstance(child, ItemWidget): self.pos = idx break if self.pos >= 0: self.children[self.pos].select() extra_padding = int(0.5 * self._height) start = max(min(len(self.children) - self._height, self.pos - extra_padding), 0) for idx, child in enumerate(self.children[start:start+self._height]): child.compute_dimensions(1, self._width, self._x, idx + self._y) child.redraw() curses.doupdate()
def noteMissingPage(screen, filename, x): print_str = "|" + filename + "| is missing. Perhaps you should add it?" for i in range(3): screen.clear() screen.attrset(curses.A_BOLD) screen.hline(0, 0, ' ', x) screen.addnstr(0, 0, print_str, x - 1) screen.noutrefresh() curses.doupdate() time.sleep(0.5) screen.clear() screen.attrset(curses.A_NORMAL) screen.hline(0, 0, ' ', x) screen.addnstr(0, 0, print_str, x - 1) screen.noutrefresh() curses.doupdate() time.sleep(0.5)
def print_year(window, now): year = now disp_array = ["" for i in range(0, 7)] one = True if now[0] == '1' else False for char in year: char_array = config.glyph[char] for row in range(0, len(char_array)): disp_array[row] += char_array[row] window.clear() for y in range(0, len(disp_array)): for x in range(0, len(disp_array[y])): a = x-1 if now[0] == '1' else x char = disp_array[y][x] color = curses.A_REVERSE if char == " " else 4 addstr(window, y, a, " ", curses.color_pair(color), len(disp_array), len(disp_array[y])) window.noutrefresh() curses.doupdate()
def display(self): self.panel.top() self.panel.show() self.window.clear() while True: self.window.refresh() curses.doupdate() for index, item in enumerate(self.items): if index == self.position: mode = curses.A_REVERSE else: mode = curses.A_NORMAL self.window.addstr(index, 1, str(item), mode) key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: self.pytify.listen(int(self.position - 1)) elif key == curses.KEY_UP: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) elif key == curses.KEY_LEFT: self.pytify.prev() elif key == curses.KEY_RIGHT: self.pytify.next() # spacebar elif key == 32: self.pytify.play_pause() # escape elif key == 27: break self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
def process_dialog(self): self.diag_win.keypad(1) while True: self.key = self.diag_win.getch() # Debug fieldwin.addnstr(3, 0, str(self.key), fieldw, curses.A_BOLD) fieldwin.addnstr(4, 0, str(self.valid_keys.keys()), fieldw, curses.A_BOLD) curses.panel.update_panels() curses.doupdate() if self.key == ord('\n'): break if self.key in self.valid_keys.keys(): self.valid_keys[self.key]() self.refresh()
def start(self): self.panel.top() self.panel.show() self.window.clear() while True: self.draw() if self.wait_for_input() is False: break if not self.resp["done"]: self.resp["code"] = self.items[self.position].tid self.resp["item"] = self.items[self.position] self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate()
def drawscreen(scr, story, node, page): height, width = scr.getmaxyx() if height < 24 or width < 80: scr.move(0, 0) scr.erase() curses.doupdate() return scr.clear() pagecount = 0 for pages in story[current]['text']: pagecount += 1 pagenumber = str(page + 1) + "/" + str(pagecount) pagenumber = (80 - len(pagenumber)) * " " + pagenumber scr.addstr(0, 80 - len(pagenumber), pagenumber, curses.A_REVERSE) commands = [["^C: Quit", "^R: Restart story", "^L: Load story"], ["1-3: Select choice"]] if (page != len(story[current]['text']) - 1): scr.hline(21, 0, '-', width) for r in range(2): ct = 0 for cmd in commands[r]: scr.addstr(22 + r, ct * 20 + 5, cmd, curses.A_REVERSE) ct += 1 if (page == len(story[current]['text']) - 1): options = story[current]['options'] r = 0 for key in story[current]['options']: if key in story: scr.addstr(21 + r, 0, str(r + 1) + ". " + story[current]['options'][key], curses.A_UNDERLINE) r += 1 if width > 80: #if we need to fill in the excess space to the right of the document... for row in range(height - 4): scr.addstr(row, 80, " " * (width - 80), curses.A_REVERSE) scr.move(0, 0) c = 1 for line in story[node]['text'][page]: scr.addstr(c, 0, line) c += 1 pos_r, pos_c = curses.getsyx() scr.move(pos_r, pos_c)
def update_screen(self): self._drawevent.wait() self._drawevent.clear() with self.map_ as m: m.draw() if self.chunkmap_active: self.chunkmap.draw() curses.curs_set(False) else: curses.curs_set(True) #m.update_cursor() #m.noutrefresh() curses.doupdate()