def close(self): if self._old_signal_handler: signal.signal(signal.SIGWINCH, self._old_signal_handler) self._core.io_selector.unregister_async(TERMINAL_RESIZE_EVENT) self._core.io_selector.unregister(sys.stdin) curses.resetty() curses.endwin()
def _start_hearts(win, names): curses.use_default_colors() curses.init_pair(1, curses.COLOR_RED, -1) curses.init_pair(2, curses.COLOR_BLACK, -1) curses.nonl() curses.resetty() curses.curs_set(0) curses.halfdelay(1) game = HeartsGame(names) #game.force_first_card() game.render(win) curses.doupdate() while True: try: c = win.getch() if c == -1: idle(game, win) continue if c == ord('q'): break win.clear() if c in bindings: bindings[c](game) else: win.addstr(0, 0, "Unhandled input: %d" % c) game.render(win) curses.doupdate() except Exception: idle(game, win)
def main(stdscr): curses.savetty() try: module_funcs(stdscr) window_funcs(stdscr) finally: curses.resetty()
def __exit__(self: App, type, value, traceback) -> None: # Monitor destruction, restore terminal state curses.nocbreak() # Re-enable line-buffering curses.noecho() # Enable user-input echo curses.curs_set(True) # Enable the cursor curses.resetty() # Restore the terminal state curses.endwin() # Destroy the virtual screen
def main(argv): def __call__(self): pass dlog = DebugLog("debug.log") dlog.msg("Logging started\n") stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.start_color() try: wl = WindowLogic(stdscr) wl.start() ci = CommandInterpreter(stdscr, wl) ci.start() except Exception as e: dlog.excpt(e) raise ci.join() dlog.msg("Command Interpreter joined.\n") wl.stop() wl.join() dlog.msg("Thread Fetcher joined.\n") curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() curses.resetty() dlog.msg("Terminal restored.\n")
def reset_mode(self): """Restore to the previously saved terminal mode.""" # Apparently this doesn't work? # curses.reset_prog_mode() if self.mode else self.set_mode() if self.mode: curses.resetty() else: raise DisplayError("There is no previously saved mode.")
def main(stdscr): curses.savetty() try: logo(stdscr) w = xmms_main_window(stdscr) w.main_keyloop() finally: curses.resetty()
def main(stdscr): curses.savetty() try: logo(stdscr) w = cxmms_window_manager(stdscr) w.keyloop() finally: curses.resetty()
def main(stdscr): curses.savetty() try: module_funcs(stdscr) window_funcs(stdscr) test_userptr_without_set(stdscr) finally: curses.resetty()
def window(self, window): self._window = window try: self.dimensions = Point(*reversed(self.window.getmaxyx())) self.position = Point(*reversed(self.window.getbegyx())) except: curses.resetty() curses.endwin() raise
def end_ui(stdscreen): """ End ncurses. """ # Restore default curses.echo() # Enable user input echo curses.nocbreak() # Enable line buffering curses.curs_set(True) # Enable the cursor display curses.resetty() # Restore terminal state stdscreen.keypad(False) curses.endwin() # Destroy virtual screen
def run(user, cmd, interactive=False): ''' Run ``cmd`` as ``user``. If ``interactive`` is True, save any curses status and synchronously run the command in foreground. Otherwise, run the command in background, discarding any output. special user -2 means: current user ''' prefix = [] cur_uid = os.getuid() try: cur_user = pwd.getpwuid(cur_uid).pw_name except: cur_user = cur_uid if user != cur_user and user != -2: if cur_uid == 0: prefix = ['su', user] if user == 'root': prefix = ['sudo'] else: prefix = ['sudo', '-u', user] if interactive: # Prepare screen for interactive command curses.savetty() curses.nocbreak() curses.echo() curses.endwin() # Run command pty.spawn(prefix + cmd) # Restore screen curses.start_color() # load colors curses.use_default_colors() curses.noecho() # do not echo text curses.cbreak() # do not wait for "enter" curses.curs_set(0) # hide cursor curses.mousemask(curses.ALL_MOUSE_EVENTS) curses.resetty() else: with open('/dev/null', 'w') as dev_null: subprocess.Popen( prefix + cmd, stdout=dev_null, stderr=dev_null, close_fds=True, )
def run(user, cmd, interactive=False): ''' Run ``cmd`` as ``user``. If ``interactive`` is True, save any curses status and synchronously run the command in foreground. Otherwise, run the command in background, discarding any output. special user -2 means: current user ''' prefix = [] cur_uid = os.getuid() try: cur_user = pwd.getpwuid(cur_uid).pw_name except: cur_user = cur_uid if user != cur_user and user != -2: if cur_uid == 0: prefix = ['su', user] if user == 'root': prefix = ['sudo'] else: prefix = ['sudo', '-u', user] if interactive: # Prepare screen for interactive command curses.savetty() curses.nocbreak() curses.echo() curses.endwin() # Run command pty.spawn(prefix+cmd) # Restore screen curses.start_color() # load colors curses.use_default_colors() curses.noecho() # do not echo text curses.cbreak() # do not wait for "enter" curses.curs_set(0) # hide cursor curses.mousemask(curses.ALL_MOUSE_EVENTS) curses.resetty() else: with open('/dev/null', 'w') as dev_null: subprocess.Popen( prefix+cmd, stdout=dev_null, stderr=dev_null, close_fds=True, )
def editor(self, i): # logger.debug("Before invoking editor") self.stdscr.keypad(0) curses.savetty() curses.echo() curses.nocbreak() curses.endwin() super().editor(i) curses.cbreak() curses.noecho() curses.resetty() self.stdscr.keypad(True) # keys processed by curses (again) self.stdscr.clear() self.stdscr.refresh() # logger.debug("After invoking editor") return
def __exit__(self: App, type, value, traceback) -> None: """ Exit the runtime context related to this object. Cleanup any curses settings to allow the terminal to return to normal :param type: exception type or None :param value: exception value or None :param traceback: exception traceback or None :return: None """ # Monitor destruction, restore terminal state curses.nocbreak() # Re-enable line-buffering curses.echo() # Enable user-input echo curses.curs_set(True) # Enable the cursor curses.resetty() # Restore the terminal state curses.endwin() # Destroy the virtual screen
def initGpio(firstrun=0): curses.savetty() #Save screen #Init GPIO if not firstrun: GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setwarnings(0) #Init GPIO pins, set event_detect callbacks, save initial states etc. for i,channel in enumerate(gpio_ch): if not gpio_inout[i]: GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if gpio_pud[i] == 0 else GPIO.PUD_UP) GPIO.add_event_detect(channel, GPIO.BOTH, callback = gpio_callback, bouncetime = debounce) gpio_state[i] = GPIO.input(channel) # Primary state curses.resetty() # Restore screen
def main(argv): def __call__(self): pass stdscr = curses.initscr() curses.noecho() # @UndefinedVariable curses.cbreak() # @UndefinedVariable stdscr.keypad(1) curses.start_color() try: wl = WindowLogic(stdscr) #wl.start() except Exception as e: raise try: dlog = wl.dlog dlog.msg("Logging debug output to " + str(dlog.outputFile)) dlog.msg("Images will be cached in " + wl.cfg.get('file.image.directory')) ci = CommandInterpreter(stdscr, wl) ci.start() updater = Updater(stdscr, wl) updater.start() except Exception as e: dlog.excpt(e) raise ci.join() dlog.msg("Command Interpreter joined.") updater.stop() updater.join() dlog.msg("Updater joined.") #wl.stop() #wl.join() dlog.msg("Thread Fetcher joined.") curses.nocbreak() # @UndefinedVariable stdscr.keypad(0) curses.echo() # @UndefinedVariable curses.endwin() # @UndefinedVariable curses.resetty() # @UndefinedVariable dlog.msg("Terminal restored.")
def showCommand(self, force): if self._results == None: return FeedCmdResult.error('No results to show yet (use \'search\' command first).') if self._resultsFresh == False and not force: return FeedCmdResult.error('The query has been changed. To show the previous '+\ 'results, use \'show!\' command.') mbox = mailbox.Maildir('.tmp.mail.dir', None, True) mbox.clear() for message in self._results: mbox.add(message) mbox.close() self._mainLayout.save() curses.savetty() os.system('mutt -f .tmp.mail.dir') self._mainLayout.restore() curses.resetty() return FeedCmdResult()
def initGpio(): curses.savetty() #Init GPIO GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setwarnings(0) for i in range(gpio_num): if (not gpio_inout[i]): GPIO.setup(gpio_ch[i], GPIO.IN, pull_up_down=GPIO.PUD_DOWN if gpio_pud[i] == 0 else GPIO.PUD_UP) GPIO.add_event_detect(gpio_ch[i], GPIO.BOTH, callback=gpio_callback, bouncetime=debounce) gpio_state[i] = GPIO.input(gpio_ch[i]) curses.resetty()
def showCommand(self, force): if self._results == None: return FeedCmdResult.error( 'No results to show yet (use \'search\' command first).') if self._resultsFresh == False and not force: return FeedCmdResult.error('The query has been changed. To show the previous '+\ 'results, use \'show!\' command.') mbox = mailbox.Maildir('.tmp.mail.dir', None, True) mbox.clear() for message in self._results: mbox.add(message) mbox.close() self._mainLayout.save() curses.savetty() os.system('mutt -f .tmp.mail.dir') self._mainLayout.restore() curses.resetty() return FeedCmdResult()
def main(stdscr): curses.echo() stdscr.keypad(True) #initial parameters cols = -1 rows = -1 while cols < 0 or cols > max_cols: try: stdscr.addstr("Input width (max " + str(max_cols) + "): ") cols = int(stdscr.getstr()) except ValueError: stdscr.addstr("Not a number.") continue if cols > max_cols: stdscr.addstr("Too much. One more time.") while rows < 0 or rows > max_rows: try: stdscr.addstr("Input height (max " + str(max_rows) + "): ") rows = int(stdscr.getstr()) except ValueError: stdscr.addstr("Not a number.") continue if rows > max_rows: stdscr.addstr("Too much. One more time.") stdscr.clear() try: generate_table(rows, cols) except KeyboardInterrupt: stdscr.addstr(rows, 0, "Ctrl+C detected, Program Stopping") stdscr.refresh() time.sleep(2) curses.endwin() curses.nocbreak() stdscr.addstr("\nPress any key to quit.") stdscr.getkey() curses.endwin() curses.nocbreak() curses.resetty()
def rename_file(self, file): renamefile = self.tmpfile + "renamefile" with open(renamefile, 'w') as rnfile: rnfile.write(file) with open(renamefile, 'r') as rnfile: oldname = rnfile.readlines()[0] curses.endwin() curses.savetty() with open(renamefile, 'r') as rnfile: subprocess.run(["vim", renamefile]) curses.resetty() self.stdscr.refresh() curses.curs_set(0) newname = rnfile.read().splitlines()[0] if newname in self.dir_contents: self.print_contents(newname + " already exists") elif oldname != newname and newname != "x": os.rename(oldname, newname) self.dir_contents[self.curr_pos] = newname self.print_contents(newname)
def main(scr): reset(scr) init_colors() display_logo(scr) drawing = Drawing(scr) tutor = Tutor(scr) save_dir = directory_setup() pen_tips = " ~`!@#$%^&*()-_+=vvxxoo|\/[]{}'.:<>\"" while True: c = scr.getch() if c == ord("q"): # QUIT break elif c == curses.KEY_RESIZE: drawing.recenter() continue elif c == curses.KEY_UP: drawing.move_by(-1, 0) elif c == curses.KEY_DOWN: drawing.move_by(1, 0) elif c == curses.KEY_RIGHT: drawing.move_by(0, 1) elif c == curses.KEY_LEFT: drawing.move_by(0, -1) elif c == ord("c"): # CHANGE COLORS drawing.color_pair = (drawing.color_pair + 1) % 8 tutor.change_color() elif c == ord("n"): # NEW DRAWING reset(scr) drawing = Drawing(scr) tutor.new() continue # skip drawing: the new drawing should be empty elif c == ord("p"): # PEN UP/DOWN drawing.pen_down = not drawing.pen_down tutor.pen() elif c == ord("e"): # ERASE tutor.erase() drawing.erase_last() continue # skip drawing: that would negate the erase elif c == ord("r"): # REPLAY CURRENT DRAWING tutor.message("OK, now it's my turn!") drawing.replay() continue # skip drawing: that would add to it elif c == ord("s"): # SAVE CURRENT DRAWING try: drawing.save(save_dir) tutor.message("I saved your drawing!") except IOError: tutor.message( "Sorry, something went wrong.\nI couldn't save this drawing." ) elif c == ord("l"): # LOAD SAVED DRAWING try: drawing = Drawing(scr) tutor.message( "Here's a drawing you made!\n(Or someone made for you!)") drawing.load_random(save_dir) except IndexError: tutor.message( "There are no drawings to load!\nYou should save one first." ) continue # skip drawing: the cursor hasn't moved elif c == ord("D"): # DELETE if drawing.fname: os.remove(drawing.fname) tutor.message("Deleted %s" % drawing.fname) reset(scr) drawing = Drawing(scr) elif c == ord("?") or c == ord("h"): # HELP tutor.help() elif c in map(ord, pen_tips): # PEN TIP drawing.pen_tip = chr(c) elif c in map(ord, "01234567"): # COLOR SELECTION drawing.color_pair = int(chr(c)) elif c == curses.KEY_F3: # DEBUG # save terminal state for later: curses.savetty() # return to shell mode for debug session: scr.move(0, 0) curses.reset_shell_mode() scr.refresh() import pdb pdb.set_trace() # when debugging is finished, restore the previous state: curses.resetty() reset(scr) drawing.recenter() # draw a new 'pixel' at the current location with the current pen tip, # if the pen is down: drawing.draw()
def reset_term(): curses.resetty()
def __init__(self, debug=True): locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() self.debug = debug if debug : print "Hello there! deubg is ", debug # Setup Player self.setScore(0) # Setup Screen stdscr = curses.initscr() curses.savetty() #make sure we can put the screen back the way we found it curses.noecho() #prevent keypresses appearing on screen curses.cbreak() #interpret input with out return stdscr.keypad(1) #everyone loves the keypad stdscr.clearok(1) #allow the screen to be cleared curses.curs_set(0) #hide the caret self.minX = minX = 0 #how far to the right we can go. #Leaving room for messages. self.maxX = maxX = stdscr.getmaxyx()[1] -15 self.minY = minY = 0 ##how far down we can go #leaving room for messages self.maxY = maxY = stdscr.getmaxyx()[0] -5 self.maze = {} self.minY = self.minX = 0 self.visited = 0 for row in range(maxY): self.maze[row] = {} for col in range(maxX): self.maze[row][col] = {} self.maze[row][col]["visited"] = False self.maze[row][col]["contains"] = {} self.visited += 1 self.maze[row][col]["wall"] = True self.__get_start__() self.__generate_maze__(self.startY,self.startX) stdscr.clear() stdscr.refresh() # print self.maze # item = "0" # for y in range(maxY): # for x in range(maxX): # stdscr.addstr(y,x,item.encode("utf-8")) # stdscr.refresh() # time.sleep(0.001) # # stdscr.clear() moveTest = True charPos = {'y':0,'x':0} while moveTest: move = stdscr.getch() if move == 113 : moveTest = False elif move == curses.KEY_RIGHT: charPos['x'] += 1 elif move == curses.KEY_LEFT: charPos['x'] -= 1 elif move == curses.KEY_UP: charPos['y'] -= 1 elif move == curses.KEY_DOWN: charPos['y'] += 1 stdscr.clear() stdscr.addstr(charPos['y'],charPos['x']-1,item.encode("utf-8")) stdscr.refresh() time.sleep(1) ##put it all back curses.resetty() curses.endwin() return None
def run(self): try: while True: #print 'Is the queue empty?: {}'.format(self.qscreen.empty()) if not self.qscreen.empty(): order = self.qscreen.get() #self.logfile.write('Receiving the order'+order+'\n') if order == 'Start': stdscr = curses.initscr() curses.savetty() curses.start_color() curses.use_default_colors() self.screen = stdscr curses.init_pair(1, curses.COLOR_GREEN, -1) curses.init_pair(2, curses.COLOR_RED, -1) curses.init_pair(3, curses.COLOR_BLUE, -1) curses.init_pair(4, curses.COLOR_WHITE, -1) self.screen.bkgd(' ', curses.color_pair(1)) self.screen.bkgd(' ') curses.noecho() curses.cbreak() self.screen.keypad(1) # curses.curs_set. 0 means invisible cursor, 1 visible, 2 very visible curses.curs_set(0) self.screen.addstr(0,0, 'Live Stream', curses.A_BOLD) self.screen.refresh() self.qscreen.task_done() elif order == 'Stop': self.screen.addstr(0,0, 'Press any key to go back to stf screen... ', curses.A_BOLD) self.screen.getstr(0,0, 15) curses.nocbreak() self.screen.keypad(0) curses.echo() curses.curs_set(1) stdscr.refresh() # close self.qscreen.task_done() curses.resetty() self.f.close() return else: #self.screen.addstr(0,50, 'Receiving Data') self.screen.refresh() # Get the screen size (x_max, y_max) = self.screen.getmaxyx() # The order orig_tuple = order tuple_id = orig_tuple.get_id() # Get the amount of letters that fit on the screen state = orig_tuple.get_state()[-(y_max-self.y_min):] tuple = self.get_tuple(tuple_id) # Update the status bar if int(tuple['x_pos']) < x_max - 3: self.screen.addstr(0,20,tuple_id + " ", curses.A_BOLD) self.screen.refresh() #self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'] | curses.A_BOLD) #if int(tuple['x_pos']) <= xmax: self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color']) #tuple['y_pos'] += len(state) self.screen.refresh() self.qscreen.task_done() except KeyboardInterrupt: curses.nocbreak() self.screen.keypad(0) curses.echo() curses.curs_set(1) curses.resetty() self.screen.refresh() except Exception as inst: print '\tProblem with Screen()' print type(inst) # the exception instance print inst.args # arguments stored in .args print inst # __str__ allows args to printed directly sys.exit(1)
def __init__(self, score=0,debug=False): """ admm started out as JUST the maze maker (ADvanced Maze Maker) but it sort of spiraled out of control. It is currently the main game loop as well. I am not sure if I will ever change that. It takes a score and a debug value. I noticed that debug was, possibly, leading to segfaults... Inputs: int: score boolean: debug Output: Not really much """ self.debug = debug self.log = logger.Logger("admm.log") maze = {} # self.maxY = y-1 # self.maxX = x-1 # self.minY = self.minX = 0 self.visited = 0 locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() self.debug = debug if debug : print "Hello there! deubg is ", debug # Setup Player # pizza # player = u"\U0001f355" # p1 = { # 'player':player, # 'inventory':{}, # 'items':{}, # 'sight': 3 # } self.score = score p1 = player.Player() p1.addItem('bombs',3) self.__setScore__(self.score,p1) self.log._log(p1) # exit icon #red circle? # self.exit =u"\U00002B55" #hot springs # self.exit =u"\U00002668" #house # self.exit = u"\U0001f3e0" #blue thing self.exit = u"\U0001f4a0" # arrow? # self.exit = u"\U000023eb" #wall Icon self.wall = "#" # self.wall = u"\U00002B1C" # Setup Screen stdscr = curses.initscr() curses.savetty() #make sure we can put the screen back the way we found it curses.noecho() #prevent keypresses appearing on screen curses.cbreak() #interpret input with out return stdscr.keypad(1) #everyone loves the keypad stdscr.clearok(1) #allow the screen to be cleared curses.curs_set(0) #hide the caret stdscr.border(0) curses.start_color() keypresses = { 'bomb' : 'b' ,'quit' : 'q' ,'North': 'w' ,'East' : 'd' ,'West' : 'a' ,'South': 's' # ,'menu':'m' } self.items= { 'health':{'icon':u"\U0001f493",'position':1,'max':100,'current':100}, 'money':{'icon':u"\U0001f4b0",'position':4,'max':100000,'current':0}, 'food':{'icon':u"\U0001f371",'position':7,'max':10,'current':0}, 'bomb':{'icon':u"\U0001F4a3",'position':10,'max':10,'current':3,'timer':4,'action':self.__get_bomb__,'score':5} } # p1['items'] = self.items self.enemies = {} # used for placing on screen bombs sbomb = {} rem_bomb = [] stdscr.clear() stdscr.refresh() self.minX = minX = 0 #how far to the right we can go. #Leaving room for messages. self.maxX = maxX = stdscr.getmaxyx()[1] -15 self.minY = minY = 0 ##how far down we can go #leaving room for messages self.maxY = maxY = stdscr.getmaxyx()[0] # Room stuff self.maxRoomSize = 4 self.roomY = [] self.roomX = [] for rooms in range(int((self.maxX*.25))): self.roomY += [random.choice(range(self.maxY))] self.roomX += [random.choice(range(self.maxX))] if debug: self.log._log("setting room up\nroomY numbers",getframeinfo(currentframe()).lineno,"low") self.log._log(json.dumps(self.roomY),getframeinfo(currentframe()).lineno,"low") # setup maze # for cols in range(maxY): maze[cols] = {} for rows in range(maxX): maze[cols][rows] = {} maze[cols][rows]['wall'] = True maze[cols][rows]['visited'] = False maze[cols][rows]['checked'] = False maze[cols][rows]['contains'] = {} self.visited += 1 self.maze = maze self.__get_start__() self.maze[self.startY][self.startX]['contains'] = "exit" self.__generate_maze__(self.startY,self.startX) self.__make_room__(self.startY,self.startX,3) self.__get_player_start__() charPos = [self.lastY,self.lastX] self.__make_room__(charPos[0],charPos[1],3) self.__place_items__() # self.__hider__() #self.__reveal__(charPos[0],charPos[1],p1['sight']) stdscr.clear() stdscr.refresh() # begin main while # OH my goodness this is such a hack # this started life as a way to test character movement... # it is currently the main game loop... >_< self.moveTest = True # charPos = {'y':0,'x':0} while self.moveTest: stdscr.clear() for cols in self.maze: for rows in self.maze[cols]: if self.maze[cols][rows]['wall'] : stdscr.addstr(cols,rows,self.wall.encode("utf-8"),curses.A_DIM) else: if self.maze[cols][rows]['checked']: stdscr.addstr(cols,rows,".",curses.A_DIM) else : stdscr.addstr(cols,rows," ",curses.A_DIM) for inv in self.maze[cols][rows]['contains']: try: if inv in self.items and self.maze[cols][rows]['contains'][inv]: stdscr.addstr(cols,rows,self.items[inv]['icon'].encode("utf-8"),curses.A_NORMAL) except Exception as e: # print self.maze[cols][rows]['contains'] msg = "inventory is {0}".format(self.maze[cols][rows]['contains']) self.log._err(e,msg,"219","medium") # Drawing the player character. # eventually the charPos should PROBABLY be contained in the # player object... I will add it to the list. stdscr.addstr(charPos[0],charPos[1]-1,p1.icon.encode("utf-8")) # display side items stdscr.addstr(self.minY,self.maxX+2,"Score") stdscr.addstr(self.minY+1,self.maxX +2,str(p1.score)) for item in items.getItems(): posY = self.minY + items.getItems()[item]['position'] + 3 posX = self.maxX + 2 #guh magic number # Ditching this log statement because I think I fixed it... # msg = "Trying to get the inventory to display properly...\n" # msg += " p1.inventory == {0}".format(p1.inventory) # self.log._log(msg,226) values = str(p1.inventory[item]['quantity']) values += "/" values += str(items.getItems()[item]['max']) name = item name += " " name += items.getItems()[item]['icon'] stdscr.addstr(posY,posX,name.encode("utf-8")) stdscr.addstr(posY+1,posX,values.encode("utf-8")) # okay here we are getting the list of keypresses. # one day I might add standard wasd keys for movement... # note the offset for maxY... instOffset = len(keypresses)+1 stdscr.addstr(self.maxY-instOffset,self.maxX+1, "Controls:") # self.log._log("offset = {0}".format(instOffset)) for k in keypresses: instOffset -= 1 cy = self.maxY-instOffset cx = self.maxX+2 ctrl = "{0} = {1}".format(keypresses[k],k) # self.log._log(ctrl) stdscr.addstr(cy,cx,ctrl.encode("utf-8")) # Draw the exit stdscr.addstr(self.startY,self.startX,self.exit.encode("utf-8"), curses.A_NORMAL) # this should probably be its own functions # Currently this is how to calculate bomb detonations.. # it is REALLY hacky. for b in sbomb: sbomb[b]['counter'] -= 1 if sbomb[b]['counter'] < 0: rem_bomb +=[b] if rem_bomb: for b in rem_bomb: self.__det_bomb(sbomb[b],stdscr) del sbomb[b] rem_bomb = [] if sbomb: for b in sbomb: stdscr.addstr(sbomb[b]['y'],sbomb[b]['x'],self.items['bomb']['icon'].encode("utf-8"), curses.A_BLINK) stdscr.addstr(sbomb[b]['y'],sbomb[b]['x']+1,str(sbomb[b]['counter'])) # okay we have drawn everything, time to make it show up. stdscr.refresh() # this is the movement loop. # I suspect there is a prettier way to do this but... move = stdscr.getch() if move == ord('q') or move == ord('Q') : self.moveTest = False elif move == ord('b') or move == ord('B') : self.__place_bomb__(charPos[0],charPos[1],sbomb,p1) elif move == curses.KEY_RIGHT or move == ord('d'): if self.maze[charPos[0]][charPos[1]+1]['wall'] == False : charPos[1] += 1 elif move == curses.KEY_LEFT or move == ord('a'): if self.maze[charPos[0]][charPos[1]-1]['wall'] == False : charPos[1] -= 1 elif move == curses.KEY_UP or move == ord('w'): if self.maze[charPos[0]-1][charPos[1]]['wall'] == False : charPos[0] -= 1 elif move == curses.KEY_DOWN or move == ord('s'): if self.maze[charPos[0]+1][charPos[1]]['wall'] == False : charPos[0] += 1 elif move == ord('c'): window = self.__get_window__('medium') combat.Combat(p1,enemy.Enemy(-1,p1.level),window) # This is currently disabled. # there was a time where I had sight radius implemented. # that time may come again. # self.__reveal__(charPos[0],charPos[1],p) # check to see if there is anything in our cell. # I might make this check adjacent cells.. I might not. self.__cell_check__(charPos[0],charPos[1],p1) self.score = p1.score # end main while # time.sleep(1) ##put it all back # The resetty() returns the terminal to standard curses.resetty() # kill the window. curses.endwin()
def restore(self): curses.resetty() self._stdscr.redrawwin()
def __end_gui(): """Quit the ncurses GUI and execute 'stty sane' to bring the terminal into a sane state.""" curses.resetty() curses.endwin() os.system('stty sane')
def doQuitEvent(key): c.resetty() # set terminal settings c.endwin() # end curses session raise SystemExit
def __init__(self, y=15, x=15, debug=True): if debug: self.log = open("admm.log", 'a+') maze = {} self.maxY = y - 1 self.maxX = x - 1 self.minY = self.minX = 0 self.visited = 0 locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() self.debug = debug if debug: print "Hello there! deubg is ", debug # Setup Player self.setScore(0) # pizza player = u"\U0001f355" #house self.exit = u"\U0001f3e0" # Setup Screen stdscr = curses.initscr() curses.savetty( ) #make sure we can put the screen back the way we found it curses.noecho() #prevent keypresses appearing on screen curses.cbreak() #interpret input with out return stdscr.keypad(1) #everyone loves the keypad stdscr.clearok(1) #allow the screen to be cleared curses.curs_set(0) #hide the caret stdscr.clear() stdscr.refresh() self.minX = minX = 0 #how far to the right we can go. #Leaving room for messages. self.maxX = maxX = stdscr.getmaxyx()[1] - 15 self.minY = minY = 0 ##how far down we can go #leaving room for messages self.maxY = maxY = stdscr.getmaxyx()[0] - 5 # setup maze for cols in range(maxY): maze[cols] = {} for rows in range(maxX): maze[cols][rows] = {} maze[cols][rows]['visited'] = False self.visited += 1 maze[cols][rows]['wall'] = True self.maze = maze self.__get_start__() self.__generate_maze__(self.startY, self.startX) charPos = [self.lastY, self.lastX] stdscr.clear() stdscr.refresh() # begin main while moveTest = True # charPos = {'y':0,'x':0} while moveTest: stdscr.clear() for cols in self.maze: for rows in self.maze[cols]: if self.maze[cols][rows]['wall']: stdscr.addstr(cols, rows, "#") stdscr.addstr(charPos[0], charPos[1] - 1, player.encode("utf-8")) stdscr.addstr(self.startY, self.startX, self.exit.encode("utf-8")) stdscr.refresh() move = stdscr.getch() if move == 113: moveTest = False elif move == curses.KEY_RIGHT: if self.maze[charPos[0]][charPos[1] + 1]['wall'] == False: charPos[1] += 1 elif move == curses.KEY_LEFT: if self.maze[charPos[0]][charPos[1] - 1]['wall'] == False: charPos[1] -= 1 elif move == curses.KEY_UP: if self.maze[charPos[0] - 1][charPos[1]]['wall'] == False: charPos[0] -= 1 elif move == curses.KEY_DOWN: if self.maze[charPos[0] + 1][charPos[1]]['wall'] == False: charPos[0] += 1 # end main while time.sleep(1) ##put it all back curses.resetty() curses.endwin() if debug: self.log.close()
def __init__(self, debug=True): locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() self.debug = debug if debug: print "Hello there! deubg is ", debug # Setup Player self.setScore(0) # Setup Screen stdscr = curses.initscr() curses.savetty( ) #make sure we can put the screen back the way we found it curses.noecho() #prevent keypresses appearing on screen curses.cbreak() #interpret input with out return stdscr.keypad(1) #everyone loves the keypad stdscr.clearok(1) #allow the screen to be cleared curses.curs_set(0) #hide the caret self.minX = minX = 0 #how far to the right we can go. #Leaving room for messages. self.maxX = maxX = stdscr.getmaxyx()[1] - 15 self.minY = minY = 0 ##how far down we can go #leaving room for messages self.maxY = maxY = stdscr.getmaxyx()[0] - 5 self.maze = {} self.minY = self.minX = 0 self.visited = 0 for row in range(maxY): self.maze[row] = {} for col in range(maxX): self.maze[row][col] = {} self.maze[row][col]["visited"] = False self.maze[row][col]["contains"] = {} self.visited += 1 self.maze[row][col]["wall"] = True self.__get_start__() self.__generate_maze__(self.startY, self.startX) stdscr.clear() stdscr.refresh() # print self.maze # item = "0" # for y in range(maxY): # for x in range(maxX): # stdscr.addstr(y,x,item.encode("utf-8")) # stdscr.refresh() # time.sleep(0.001) # # stdscr.clear() moveTest = True charPos = {'y': 0, 'x': 0} while moveTest: move = stdscr.getch() if move == 113: moveTest = False elif move == curses.KEY_RIGHT: charPos['x'] += 1 elif move == curses.KEY_LEFT: charPos['x'] -= 1 elif move == curses.KEY_UP: charPos['y'] -= 1 elif move == curses.KEY_DOWN: charPos['y'] += 1 stdscr.clear() stdscr.addstr(charPos['y'], charPos['x'] - 1, item.encode("utf-8")) stdscr.refresh() time.sleep(1) ##put it all back curses.resetty() curses.endwin() return None
def execute(self, args): files = args.files if not files: files = find_files_of_type(os.path.realpath('.'), 'tex') ignoredb = self.config.get('acronyms', 'ignoredb') ignored = set() if os.path.exists(ignoredb): with open(ignoredb) as fh: for line in fh: line = line.strip() if line: ignored.add(line) stdscr = curses.initscr() curses.savetty() curses.noecho() curses.cbreak() curses.curs_set(0) for f in files: with open(f) as fh: self.replacements = [] contents = fh.read() for m in re.finditer(self.acronym_regex, contents): ms, me = m.start(1), m.end(1) token = contents abbr = token[ms:me] if abbr.endswith('s'): abbr = abbr[:-1] if abbr in ignored: continue line = contents.count("\n", 0, ms) max_context = 20 prefix = postfix = '' # Isolate a single line cs = contents.rfind("\n", 0, ms) + 1 ce = contents.find("\n", me) if ms - cs > max_context: cs = ms - max_context cs = contents.rfind(" ", 0, cs) + 1 prefix = '...' if ce - me > max_context: ce = me + max_context ce = contents.find(" ", ce) postfix = '...' char = ms - cs ms -= cs me -= cs token = token[cs:ce] self.print_token_color(stdscr, f, token, line, char, ms, me, prefix, postfix) callbacks = { 'l': self.replace_lower, 'u': self.replace_upper, 'p': self.replace_lower_plural, 'j': self.replace_upper_plural, } try: c = stdscr.getch() try: callback = callbacks[chr(c)] except (KeyError, ValueError): if c == ord('f'): break else: continue else: callback(contents, m.start(1), m.end(1)) except KeyboardInterrupt: curses.resetty() curses.nocbreak() curses.echo() curses.endwin() return if self.replacements: for s, e, string in reversed(self.replacements): contents = contents[:s] + string + contents[e:] with open(f, 'w') as fh: fh.write(contents)
#
pp('%20s\t%10d\t%10.2f' % ('Total', total, total_rate)) else: pp('%20s\t%10d' % ('Total', total)) interval = time.time() - ts if interval < sleep_time: time.sleep(sleep_time - interval) last_ts = ts if soopretty: myscreen.refresh() curses.flash() except KeyboardInterrupt: sys.exit(0) finally: if soopretty: curses.resetty() if __name__ == '__main__': if options.show_indices_status: indices_status() sys.exit(0) if options.show_indices_nodes: indices_nodes(indice_pattern) sys.exit() if options.show_indices_routing: indices_routing(indice_pattern) sys.exit() if options.show_unassigned: