def draw_header(screen): maxyx = screen.getmaxyx() localtime = time.localtime() mini_format = False # Decide whether to draw the mini-format if we have less than 98 columns header1 = "NETWORK " header2 = "IP ADDRESS RECVD SENT TOTAL AVG/s " if maxyx[1] < (len(header1) + 1): header1 = "NETWORK " header2 = "IP ADDRESS RECVD SENT TOTAL AVG/s " mini_format = True screen.addstr(0, 0, "iptap v{0} - {1:0>2}:{2:0>2}:{3:0>2} {4}".format( __version__, localtime.tm_hour, localtime.tm_min, localtime.tm_sec, "(mini-format)" if mini_format else "" )) screen.addstr(1, 0, "Press 'h' for help") if curses.has_colors(): curses.start_color() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) screen.attron(curses.color_pair(1)) # If we can't fit the header and text in the screen, exit and error format_header1 = "{0:<" + str(maxyx[1] - len(header1)) + "}" format_header2 = "{0:<" + str(maxyx[1] - len(header2)) + "}" try: screen.attron(curses.A_BOLD); screen.addstr(3, 0, header1) screen.addstr(3, len(header1), format_header1.format(" ")) screen.attroff(curses.A_BOLD); screen.addstr(4, 0, header2) screen.addstr(4, len(header2), format_header2.format(" ")) except: end_curses() print "Could not draw curses window, please check terminal is at least 80 columns wide" exit(1) if curses.has_colors(): screen.attroff(curses.color_pair(1)) curses.use_default_colors() return mini_format
def __set_time_win(self, remain_minutes, prompt, prompt_color=None): self.__time_win.erase() if curses.has_colors(): curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) self.__time_win.attrset(curses.color_pair(4)) time_str = 'BLOCKING TIME: {time}min'.format(time=self.__blocking_minutes) self.__time_win.insstr(0, 0, time_str) remain_str = 'Time Remaining: {remain_time}min'.format(remain_time=remain_minutes) self.__time_win.insstr(1, 0, remain_str) if len(prompt) > 0: if curses.has_colors(): self.__time_win.attrset(prompt_color) self.__time_win.insstr(4, 0, prompt) self.__time_win.refresh()
def curses_gui(screen): curses.use_default_colors() curses.start_color() # Start colour mode if not curses.has_colors(): sys.exit('Terminal does not support colors!') # TODO: Fall back to text mode else: old_colors = renderer.init_colors() curses.curs_set(0) # Hide cursor # TODO: @rubiks_colors decorator. Coooool. main_loop(screen) if curses.has_colors(): renderer.reset_colors(old_colors)
def set_attr(self,name,fg,bg,attr,fallback): if attr is None: self.attrs[name]=None self.attr_defs[name]=(None,)*4 return if not curses.has_colors(): self.attrs[name]=fallback self.attr_defs[name]=(fg,bg,attr,fallback) return if fg is None: self.attrs[name]=attr self.attr_defs[name]=(fg,bg,attr,fallback) return self.__logger.debug("for attr %r need pair: (%r,%r)",name,fg,bg) if self.pairs.has_key((fg,bg)): pair=self.pairs[fg,bg] self.__logger.debug("already got it: %r",pair) elif self.next_pair>=curses.COLOR_PAIRS: self.attrs[name]=fallback self.__logger.debug("too many color pairs used, falling back to:" " %r",fallback) self.attr_defs[name]=(fg,bg,attr,fallback) return else: self.__logger.debug("creating new pair #%i...",self.next_pair) curses.init_pair(self.next_pair,fg,bg) pair=self.next_pair self.pairs[fg,bg]=pair self.next_pair+=1 attr|=curses.color_pair(pair) self.attrs[name]=attr self.attr_defs[name]=(fg,bg,attr,fallback)
def init(self): self.window = curses.initscr() self.initted = True self.ymax, self.xmax = self.window.getmaxyx() terminfo = curses.longname() assert '256' in terminfo # your env TERM must be xterm-256color! assert curses.has_colors() curses.start_color() curses.use_default_colors() ctr = 1 for fg in CLRS: for bg in CLRS: if ctr <= curses.COLORS-1 and fg != bg: curses.init_pair(ctr, CLRS[fg], CLRS[bg]) pairs[(fg,bg)] = curses.color_pair(ctr) ctr += 1 curses.meta(1) curses.noecho() curses.cbreak() curses.curs_set(0) curses.delay_output(0) curses.mouseinterval(150) availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS) assert availmask != 0 # mouse must be available! self.window.leaveok(1) self.window.scrollok(0) self.window.keypad(1) if NONBLOCKING: self.window.nodelay(1) self.window.timeout(NONBLOCKING_TIMEOUT) else: self.window.nodelay(0) self.window.timeout(-1) self.window.refresh()
def _initColors(): """ Initializes color mappings usable by curses. This can only be done after calling curses.initscr(). """ global COLOR_ATTR_INITIALIZED, COLOR_IS_SUPPORTED if not COLOR_ATTR_INITIALIZED: COLOR_ATTR_INITIALIZED = True COLOR_IS_SUPPORTED = False if not CONFIG["features.colorInterface"]: return try: COLOR_IS_SUPPORTED = curses.has_colors() except curses.error: return # initscr hasn't been called yet # initializes color mappings if color support is available if COLOR_IS_SUPPORTED: colorpair = 0 log.log(CONFIG["log.cursesColorSupport"], "Terminal color support detected and enabled") for colorName in COLOR_LIST: fgColor = COLOR_LIST[colorName] bgColor = -1 # allows for default (possibly transparent) background colorpair += 1 curses.init_pair(colorpair, fgColor, bgColor) COLOR_ATTR[colorName] = curses.color_pair(colorpair) else: log.log(CONFIG["log.cursesColorSupport"], "Terminal color support unavailable")
def _color_attr(): """ Initializes color mappings usable by curses. This can only be done after calling curses.initscr(). """ global COLOR_ATTR if COLOR_ATTR is None: if not CONFIG['features.colorInterface']: COLOR_ATTR = DEFAULT_COLOR_ATTR elif curses.has_colors(): color_attr = dict(DEFAULT_COLOR_ATTR) for color_pair, color_name in enumerate(COLOR_LIST): foreground_color = COLOR_LIST[color_name] background_color = -1 # allows for default (possibly transparent) background curses.init_pair(color_pair + 1, foreground_color, background_color) color_attr[color_name] = curses.color_pair(color_pair + 1) log.info('setup.color_support_available') COLOR_ATTR = color_attr else: log.info('setup.color_support_unavailable') COLOR_ATTR = DEFAULT_COLOR_ATTR return COLOR_ATTR
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() # new line curses.noecho() stdscr.timeout(0) x = 0 y = 0 while True: draw_map() stdscr.addch(y, x, ord("*")) y, x = auto_run(y, x) ch = stdscr.getch() if ch == ord("q") or ch == ord("Q"): return stdscr.erase() # erase and refresh should have a proper interval curses.napms(100) stdscr.refresh()
def initialize(self): # inialize curses env #self.stdscr = curses.initscr() if curses.has_colors(): curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) # turn off automatic echoing curses.noecho() # react keyboard immediatly, ie. cbreak mode curses.cbreak() self.stdscr.keypad(True) self.stdscr.clear() self.ikkuna() return True
def init(self): self.screen = curses.initscr() curses.noecho() curses.cbreak() self.screen.keypad(1) try: curses.curs_set(0) except: logging.warning("Cursor hiding is not supported") curses.halfdelay(1) # block for 0.1s if curses.has_colors(): self.colors = True curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) 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_BLUE, curses.COLOR_BLACK) else: self.colors = False logging.warning("Colors are not supported") logging.info("Console I/O initialized")
def __init__(self): self.stdscr = curses.initscr() self.WIDTH = curses.COLS self.HEIGHT = curses.LINES # dont write on screen and dont wait for enter curses.noecho() curses.cbreak() curses.curs_set(False) # no blinking curses.start_color() # colors # epic keys self.stdscr.keypad(True) self.stdscr = curses.newwin(self.HEIGHT-1,self.WIDTH,0,0) self.bottom = curses.newwin(1,self.WIDTH,self.HEIGHT-1,0) self.bar(default_items) curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) if curses.has_colors(): curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK) self.grapher = Grapher(self.stdscr,self.WIDTH,self.HEIGHT) self.painter = Painter(self.stdscr,self.WIDTH,self.HEIGHT) self.parser = Parser() self.command_hist = [] self.command_indx = -1
def point_placement(BP, BS, phys, bio, chem, math, screen): if curses.has_colors() == True: # spacing between points coloffset = 5 #index for column number colindex = 5 tmpstr = "BP: " + str(BP) + "/" + str(BS) screen.addstr(0, colindex, tmpstr) colindex = colindex + len(tmpstr) + coloffset tmpstr = "P: " + str(phys) screen.addstr(0, colindex, tmpstr, curses.color_pair(4)) colindex = colindex + len(tmpstr) + coloffset tmpstr = "B: " + str(bio) screen.addstr(0, colindex, tmpstr, curses.color_pair(2)) colindex = colindex + len(tmpstr) + coloffset tmpstr = "C: " + str(chem) screen.addstr(0, colindex, tmpstr, curses.color_pair(1)) colindex = colindex + len(tmpstr) + coloffset tmpstr = "M: " + str(math) screen.addstr(0, colindex, tmpstr) screen.refresh()
def __setColors(self): if curses.has_colors(): curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_GREEN) self.screen.bkgd(curses.color_pair(1))
def init_colors(): mylook = looks.get(Look.mylook, looks["default"]) cols = {} attrs = {} for m in dir(curses): if m.startswith("COLOR_"): cols[m[6:].lower()] = getattr(curses, m) elif m.startswith("A_"): attrs[m[2:].lower()] = getattr(curses, m) if curses.has_colors(): for i, (name, v) in enumerate(mylook.items()): fg, bg, attr = v myfg = cols.get(fg, -1) mybg = cols.get(bg, -1) myattr = 0 for a in attr.split("|"): myattr |= attrs.get(a.strip(), 0) curses.init_pair(i+1, myfg, mybg) colors[name] = curses.color_pair(i+1) | myattr else: for (name, v) in mylook.items(): fg, bg, attr = v myattr = 0 for a in attr.split("|"): myattr |= attrs.get(a.strip(), 0) colors[name] = myattr
def run(stdscr): curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i, i, -1) stdscr.attrset(curses.color_pair(1)) stdscr.addstr(15,2, str(curses.has_colors()), curses.color_pair(0)) stdscr.box() #w1 = curses.newwin(10,20, 0,0) #w1.attrset(curses.color_pair(7)) #w1.border(0, 0, 0, 0) ##w1.box() #w2 = curses.newwin(10,20, 3,10) #w2.attrset(curses.color_pair(7)) #w2.box() stdscr.refresh() lw = ListWindow([], "WINDOW TITLE", 80) lw.refresh() #w1.refresh() #w2.refresh() while 1: pass
def set_up_curses(self): # Instantiate standard screen object. self.stdscr = curses.initscr() # Properly initialize screen. curses.noecho() curses.cbreak() curses.curs_set(0) # Check for and begin color support. if curses.has_colors(): curses.start_color() # Optionally enable the F-1 etc. keys, which are multi-byte. self.stdscr.keypad(1) # Declare colors. curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i + 1, i, -1) # Create and configure window. curses.resizeterm(30, 80) self.window = curses.newwin(curses.LINES, curses.COLS) self.window.nodelay(1) # Create and configure main half-screen subwindows. half_screen = curses.COLS//2 self.attacks = curses.newwin(curses.LINES-3, half_screen, 1, 0) self.attacks.attrset(curses.color_pair(198)) self.attacks.addstr(1, 0, 'ATTACK STRINGS (KILL THESE)'. center(half_screen, ' ')) self.attacks.box() self.noncomb = curses.newwin( curses.LINES-3, half_screen, 1, half_screen) self.noncomb.attrset(curses.color_pair(47)) self.noncomb.addstr(1, 0, '''NON-COMBATANT STRINGS (DO NOT KILL)'''. center(half_screen, ' ')) self.noncomb.box()
def mybox(stdscr): stdscr.addstr(0,0,'KUNG FURY') stdscr.addstr(1,1,'KUNG FURY') stdscr.addstr( 1, 2, 'LOLO') stdscr.addstr(3, 4, 'AARFRFRF') stdscr.addstr(5, 6, 'huhu') stdscr.addstr(7, 7, "Current mode: Typing mode", curses.A_REVERSE) stdscr.addch(curses.ACS_ULCORNER) stdscr.addch(curses.ACS_URCORNER) stdscr.addch(curses.ACS_LLCORNER) stdscr.addch(curses.ACS_LRCORNER) stdscr.border() #stdscr.bkgd('.', curses.A_REVERSE) #stdscr.bkgdset('.', curses.A_UNDERLINE) #stdscr.addstr(10, 1, "Pretty text", curses.color_pair(1)) if curses.has_colors(): stdscr.addstr(5, 1, 'HAS COLOR') else: stdscr.addstr(5, 1, 'NO COLOR') if curses.can_change_color(): stdscr.addstr(6, 1, 'can_change_color = true') else: stdscr.addstr(6, 1, 'can_change_color = false') stdscr.addstr(10, 1, "Pretty text lots of space", curses.color_pair(1)) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) stdscr.addstr(11, 1, "RED ALERT!", curses.color_pair(1)) stdscr.addstr(12, 1, "RED ALERT!", curses.color_pair(0)) stdscr.refresh() stdscr.getkey()
def draw_form(self): if self.framed: if curses.has_colors() and not GlobalOptions.DISABLE_ALL_COLORS: self.curses_pad.attrset(0) self.curses_pad.bkgdset(" ", curses.A_NORMAL | self.theme_manager.findPair(self, self.color)) self.curses_pad.border() self.draw_title_and_help()
def __init__(self, x, y): """ Create new block with random color """ super(BlockFood, self).__init__(x, y) if curses.has_colors(): self.curses_attr |= curses.color_pair(random.randrange(1, 7))
def __init__(self, mainscr, stdscr, directory, encoding): self.encoding = encoding self.header_lns = HEADER_LNS self.mainscr = mainscr self.stdscr = stdscr self.color = curses.has_colors() if self.color: # set file type attributes (color and bold) curses.init_pair(1, curses.COLOR_BLUE, -1) self.attr_folder = curses.color_pair(1) | curses.A_BOLD curses.init_pair(2, 7, -1) self.attr_norm = curses.color_pair(2) # set wright / wrong attributes (color and bold) curses.init_pair(3, curses.COLOR_GREEN, -1) self.attr_wright = curses.color_pair(3) | curses.A_BOLD curses.init_pair(4, curses.COLOR_RED, -1) self.attr_wrong = curses.color_pair(4) | curses.A_BOLD self.kill = False self.ch = -1 self.visited = {} self.area = None self.container = FileSystem() self.directory = self.container.abspath(directory) self.checked = DirectoryTree(self.directory, self.container) self.chdir(self.directory)
def __init__(self): """ Initialize the UI by creating a window object that represents the entire screen of the user interface. The screen will be divided into smaller windows, each representing a particular section of the UI. Raises: curses.error: curs_set() returned ERR. The terminal does not support configuring the cursor state. """ # Window object: The entire screen of the UI. self.screen = curses.initscr() # Disable echo of keys to the screen and enable input without requiring # the carriage return (Enter). curses.noecho() curses.cbreak() # Bool: Denotes if color is enabled. self.color_enabled = False # Enable color mode, if the terminal supports colors. if curses.has_colors(): curses.start_color() curses.use_default_colors() self.color_enabled = True # Allow curses to interpret the escape sequences generated by some keys # and disable the display of the cursor. self.screen.keypad(True) curses.curs_set(False)
def mainprog(win): global disp assert curses.has_colors(), "Your terminal does not support colors." try: curses.curs_set(0) except: pass boxx, boxy = win.getmaxyx()[1] // 16, win.getmaxyx()[0] // 10 curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLUE) while True: t = time.strftime(f, time.localtime()) h1, h2, m1, m2 = [int(x) for x in t] disp = [[2, 1, 2, 2, 2, 1, 2, 2, 1, 2, 2, 2] for y in range(3)] tog(0, 1, h1, 3) tog(2, 5, h2, 4) tog(6, 8, m1, 5) tog(9, 12, m2, 3) for x in range(12): for y in range(3): for yy in range(boxy): win.addstr(y * (boxy + 1) + yy + boxy, x * (boxx + 1) + boxx, boxx * getsym(disp[y][x]), curses.color_pair(disp[y][x])) win.move(0, 0) win.refresh() time.sleep(inter)
def init(): curses.start_color() if curses.has_colors(): for i in range(8): for j in range(8): if (i * 8 + j) != 0: curses.init_pair(i * 8 + j, j, i)
def init_draw(): curscr = None if enable_curses: curscr = curses.initscr() curses.curs_set(0) if enable_curses: # and enable_colors: if curses.has_colors(): curses.start_color() curses.use_default_colors() else: enable_colors = False enable_color_players = False enable_color_walls = False pattern = classic if enable_curses: #and enable_colors: pair_number = 15 for color in ('red', 'yellow', 'blue', 'green', 'default'): if color == 'red': fg = curses.COLOR_RED elif color == 'yellow': fg = curses.COLOR_YELLOW elif color == 'blue': fg = curses.COLOR_BLUE elif color == 'green': fg = curses.COLOR_GREEN else: fg = -1 pair_number += 1 curses.init_pair(pair_number, fg, -1) return curscr
def Display(self, path): if self.pad != None: self.pad.erase() self.hilit = 1 # self.Paint(0,0,0) if os.access(path, os.R_OK | os.X_OK) and os.path.isdir(path): self.path = path self.dirlist = os.listdir(path) self.__SortAndMarkDirList() count = len(self.dirlist) rows = self.H colwidth = self.COLWIDTH if (count) * colwidth > self.__area(): rows -= 1 setupSB = 1 else: setupSB = 0 self.ROWS = rows cols = ((count / rows) * colwidth) self.pad = curses.newpad(rows+1,cols+((self.COLDISP+1) * (colwidth))) self.__initScrollBar( setupSB, (count / rows) ) if curses.has_colors(): self.pad.bkgdset(' ',curses.color_pair(1)) self.pad.erase() self.fillpad(1) self.Paint(None,None,None) self.SCREEN.Refresh() self.__first = 0
def mp_initialize(): global q, \ win_condition, \ map_fog_of_war, \ score_counter, \ score_top # Set global variables q = -1 win_condition = 0 map_fog_of_war = set() score_counter = 0 score_top = open('score', 'r').readlines() # Makes the cursor not blink curses.curs_set(False) # Speeds up vertical movement. curses.nonl() # Makes colors if curses.has_colors(): curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_WHITE) curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_WHITE) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_WHITE) curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(7, curses.COLOR_YELLOW, curses.COLOR_CYAN)
def __start_window(self): curses.echo() curses.cbreak() win_y, win_x = self.__main_win.getmaxyx() if curses.has_colors(): curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) self.__main_win.attrset(curses.color_pair(3)) ''' set welcoming ''' welcome_str = 'Welcome to the ScienWebbing...Please CONCENTRATE' self.__main_win.insstr(0, (win_x-len(welcome_str))/2, welcome_str) ''' set input field''' input_str = 'Input site address or time: ' self.__main_win.insstr(1, 0, input_str) ''' set annotations''' annotation = '(Input sites your want to block one each time, or the blocking minutes)' annotation1 = '(Address like: xxx.xx.com Time like: 30)' self.__main_win.insstr(2, 0, annotation) self.__main_win.insstr(3, 0, annotation1) self.__main_win.refresh() ''' set subwin for lst ''' self.__lst_win = self.__main_win.derwin(win_y-4, win_x/2, 4, 0) self.__set_list_win() ''' set subwin for time ''' self.__time_win = self.__main_win.derwin(win_y-4, win_x/2, 4, win_x/2) self.__set_time_win(self.__blocking_minutes, '') return self.__main_win.getstr(1, len(input_str)+1, 255), 1, len(input_str)+1,
def __init__(self): self._max_pairs = curses.COLOR_PAIRS - 1 self._defined_pairs = {} self._names = {} if curses.has_colors(): self.initialize_pairs() self.initialize_names()
def start(self): """ Initialize the screen and input mode. """ assert self._started == False self.s = curses.initscr() self.has_color = curses.has_colors() if self.has_color: curses.start_color() if curses.COLORS < 8: # not colourful enough self.has_color = False if self.has_color: try: curses.use_default_colors() self.has_default_colors=True except _curses.error: self.has_default_colors=False self._setup_colour_pairs() curses.noecho() curses.meta(1) curses.halfdelay(10) # use set_input_timeouts to adjust self.s.keypad(0) if not self._signal_keys_set: self._old_signal_keys = self.tty_signal_keys() super(Screen, self).start()
def set_up_curses(self): # Instantiate standard screen object. self.stdscr = curses.initscr() # Properly initialize screen. curses.noecho() curses.cbreak() curses.curs_set(0) # Check for and begin color support. if curses.has_colors(): curses.start_color() # Optionally enable the F-1 etc. keys, which are multi-byte. self.stdscr.keypad(1) # Declare colors. curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i + 1, i, -1) # Create and configure window. self.window = curses.newwin(curses.LINES, curses.COLS) self.window.chgat(curses.color_pair(198)) self.window.nodelay(1) # Create and configure main half-screen subwindows. half_screen = curses.COLS//2 self.attacks = curses.newwin(curses.LINES-3, half_screen, 1, 0) self.attacks.box() self.noncomb = curses.newwin( curses.LINES-3, half_screen, 1, half_screen) self.noncomb.chgat(-1, curses.color_pair(198)) self.noncomb.box()
def __init__(self, ySize, xSize, yStart, xStart, tArgs, audioClass): #self.ySize = ySize #self.xSize = xSize #self.yStart = yStart #self.xStart = xStart self.tArgs = tArgs self.infoPad = None self.settingPads = [] self.boxWidth = int(xSize / 3) self.title = TitleWindow(1, xSize, 0, 0) self.lock = threading.Lock() # Create windows and store them in the self.settingPads list. # Start range startWin = startRangeMenuItem(int(ySize/2), self.boxWidth, yStart, xStart, "beg", tArgs) startWin.setHoverMsg("Press enter to change the start range.") startWin.setToolTip("Setting start range... Press enter to apply.") startWin.setActionMsg("Start range changed!") startWin.setDisplayName("Start Value") startWin.updateValue(tArgs.start) # Progress bar progressWin = ProgressBar(int(ySize/2), self.boxWidth, yStart, xStart + self.boxWidth, audioClass, tArgs) progressWin.setHoverMsg("Press enter to change the progress bar settings") progressWin.setToolTip("V- toggle visibility, Left/Right Arrows- move back and forth, Space- pause/play") progressWin.setActionMsg("Done editing.") progressWin.setDisplayName("Progress Bar") # End range endWin = endRangeMenuItem(int(ySize/2), self.boxWidth, yStart, xStart + self.boxWidth * 2, "end", tArgs) endWin.setHoverMsg("Press enter to change the end range.") endWin.setToolTip("Setting end range... Press enter to apply.") endWin.setActionMsg("End range changed!") endWin.setDisplayName("End Value") endWin.updateValue(tArgs.end) # Step value stepWin = stepMenuItem(int(ySize/2), self.boxWidth, yStart + 1, xStart + self.boxWidth * 2, "step", tArgs) stepWin.setHoverMsg("Press enter to change the step amount.") stepWin.setToolTip("Setting step amount... Press enter to apply.") stepWin.setActionMsg("Step amount changed!") stepWin.setDisplayName("Step Value") stepWin.updateValue(tArgs.step) # This currently takes up the width of the screen. Change the value from xSize to resize it saveWin = saveButton(int(ySize/2), int(xSize*(2/3)-1), yStart+1, xStart, tArgs, progressWin) saveWin.setHoverMsg("Press enter to save a recording as a WAV file.") saveWin.setToolTip("Please enter filename, and press enter to save. Any existing file will be overwritten.") saveWin.setActionMsg("File saved in same directory!") saveWin.setDisplayName("Export Button") if curses.has_colors(): curses.init_pair(2, curses.COLOR_RED, -1) progressWin.win.bkgd(' ', curses.color_pair(2)) # Be sure to add your object to the settingPads list! # They will be selected by the arrow keys in the order of this list. self.settingPads.append(startWin) self.settingPads.append(progressWin) self.settingPads.append(endWin) self.settingPads.append(saveWin) self.settingPads.append(stepWin) self.focusedWindow = startWin self.focusedWindowIndex = 0 self.editing = False self.refreshAll()
def set_color(win, color): if curses.has_colors(): n = color + 1 curses.init_pair(n, color, my_bg) win.attroff(curses.A_COLOR) win.attron(curses.color_pair(n))
def unset_color(win): if curses.has_colors(): win.attrset(curses.color_pair(0))
def __init__(self, refresh_time = 1): # Global information to display self.__version = __version__ # Init windows positions self.term_w = 80 ; self.term_h = 24 self.host_x = 0 ; self.host_y = 0 self.system_x = 0 ; self.system_y = 1 self.cpu_x = 0 ; self.cpu_y = 3 self.load_x = 20; self.load_y = 3 self.mem_x = 41; self.mem_y = 3 self.network_x = 0 ; self.network_y = 9 self.diskio_x = 0 ; self.diskio_y = -1 self.fs_x = 0 ; self.fs_y = -1 self.process_x = 30; self.process_y = 9 self.help_x = 30; self.help_y = 12 self.now_x = 79; self.now_y = 3 self.caption_x = 0 ; self.caption_y = 3 # Init the curses screen self.screen = curses.initscr() if not self.screen: print _("Error: Can not init the curses library.\n") curses.start_color() curses.use_default_colors() curses.noecho() ; curses.cbreak() ; curses.curs_set(0) # Init colors self.hascolors = False if curses.has_colors(): self.hascolors = True # Init FG color BG color curses.init_pair(1, curses.COLOR_WHITE, -1) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_YELLOW) # Text colors/styles self.title_color = curses.A_BOLD|curses.A_UNDERLINE self.help_color = curses.A_BOLD self.no_color = curses.color_pair(1) self.default_color = curses.color_pair(3)|curses.A_BOLD self.if50pc_color = curses.color_pair(4)|curses.A_BOLD self.if70pc_color = curses.color_pair(5)|curses.A_BOLD self.if90pc_color = curses.color_pair(2)|curses.A_BOLD # By default all the stats are displayed self.network_tag = True self.diskio_tag = True self.fs_tag = True # Init main window self.term_window = self.screen.subwin(0, 0) # Init help panel term_help = self.screen.subwin(self.term_h-self.help_y-2, self.term_w-self.help_x, self.help_y, self.help_x) self.panel_help = curses.panel.new_panel(term_help) self.hideHelp() # Init refresh time self.__refresh_time = refresh_time # Catch key pressed with non blocking mode self.term_window.keypad(1) ; self.term_window.nodelay(1) ; self.pressedkey = -1
from __future__ import print_function import curses import time import sys errstr = '' numwidth = 5 fmt = '%%%dd' % numwidth stdscr = curses.initscr() curses.noecho() curses.cbreak() #if curses.can_change_color(): if curses.has_colors(): curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) colorpair = curses.color_pair(1) highlightpair = curses.color_pair(2) else: colorpair = curses.A_REVERSE highlightpair = curses.A_BOLD def cleanup(): curses.nocbreak() stdscr.keypad(0) curses.echo()
def main(argv = None): parser = argparse.ArgumentParser(description="A cross-platform script for creating and playing sound waves through mathematical expressions", prog="calcwave") parser.add_argument('expression', type = str, help = "The expression, in terms of x. When using the command line, it may help to surround it in single quotes. If --gui is specified, use 0 for this parimeter") parser.add_argument("-s", "--start", type = int, default = -100000, help = "The lower range of x to start from.") parser.add_argument("-e", "--end", type = int, default = 100000, help = "The upper range of x to end at.") parser.add_argument("-o", "--export", type = str, default = "", nargs = '?', help = "Export to specified file as wav. File extension is automatically added.") parser.add_argument("--channels", type = int, default = 1, help = "The number of audio channels to use") parser.add_argument("--rate", type = int, default = 44100, help = "The audio rate to use") parser.add_argument("--buffer", type = int, default = 1024, help = "The audio buffer frame size to use. This is the length of the list of floats, not the memory it will take.") parser.add_argument("--gui", default = False, action = "store_true", help = "Start with the GUI") if argv is None: argv = sys.argv # The class that is passed to other threads and holds # information about how to play sound and act tArgs = threadArgs() isGuiArgument = False isExportArgument = False isExpressionProvided = False args = None if len(sys.argv) > 1: args = parser.parse_args() #Parse arguments #Set variables tArgs.expression = args.expression tArgs.start = args.start tArgs.end = args.end tArgs.channels = args.channels tArgs.rate = args.rate tArgs.frameSize = args.buffer isExportArgument = args.export != "" isGuiArgument = args.gui isExpressionProvided = args.expression != "" # Initialize AudioPlayer audioClass = AudioPlayer(tArgs) window = None scr = None menu = None #The program may be started either in GUI mode or CLI mode. Test for GUI mode vvv if len(sys.argv) == 1 or isGuiArgument or not(isExportArgument or isExpressionProvided): #If no arguments are supplied - GUI if isExpressionProvided: tArgs.expression = args.expression sys.stderr.write("Starting GUI mode\n") tArgs.isGUI = True scr = curses.initscr() rows, cols = scr.getmaxyx() if curses.has_colors(): curses.start_color() curses.use_default_colors() # ySize, xSize, yStart, xStart menu = UIManager(2, cols, rows - 4, 0, tArgs, audioClass) #Start the GUI input thread window = WindowManager(tArgs, scr, menu) tArgs.expression = "0" # Default value else: tArgs.isGUI = False if len(sys.argv) >= 1 and isExportArgument: exportAudio(args.export, tArgs, None, None) else: # Keep in mind that menu will be None when it is not in GUI mode... audioClass.play() # When that exits tArgs.shutdown = True if window: window.thread.join()
def main(argv): """If this file is the main, create an instance of EstopNoGui and wait for user to terminate. This has little practical use, because calling the function this way does not give the user any way to trigger an estop from the terminal. """ parser = argparse.ArgumentParser() bosdyn.client.util.add_common_arguments(parser) parser.add_argument('-t', '--timeout', type=float, default=5, help='Timeout in seconds') options = parser.parse_args(argv) # Set up curses screen display to monitor for stop request stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) stdscr.nodelay(True) curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) # If terminal cannot handle colors, do not proceed if not curses.has_colors(): return # Create robot object sdk = bosdyn.client.create_standard_sdk('estop_nogui') robot = sdk.create_robot(options.hostname) robot.authenticate(options.username, options.password) # Create estop client for the robot estop_client = robot.ensure_client(EstopClient.default_service_name) # Create nogui estop estop_nogui = EstopNoGui(estop_client, options.timeout, "Estop NoGUI") # Create robot state client for the robot state_client = robot.ensure_client(RobotStateClient.default_service_name) def clean_exit(msg=''): """Shut down curses and exit the program.""" print('Exiting') #pylint: disable=unused-argument estop_nogui.estop_keep_alive.shutdown() # Clean up and close curses curses.nocbreak() stdscr.keypad(False) curses.echo() stdscr.nodelay(False) curses.endwin() print(msg) exit(0) def sigint_handler(sig, frame): """Exit the application on interrupt.""" clean_exit() # Curses eats Ctrl-C keyboard input, but keep a SIGINT handler around for # explicit kill signals outside of the program. signal.signal(signal.SIGINT, sigint_handler) # Clear screen stdscr.clear() # Display usage instructions in terminal stdscr.addstr('Estop w/o GUI running.\n') stdscr.addstr('\n') stdscr.addstr('[q] or [Ctrl-C]: Quit\n', curses.color_pair(2)) stdscr.addstr('[SPACE]: Trigger estop\n', curses.color_pair(2)) stdscr.addstr('[r]: Release estop\n', curses.color_pair(2)) stdscr.addstr('[s]: Settle then cut estop\n', curses.color_pair(2)) # Monitor estop until user exits while True: # Retrieve user input (non-blocking) c = stdscr.getch() try: if c == ord(' '): estop_nogui.stop() if c == ord('r'): estop_nogui.allow() if c == ord('q') or c == 3: clean_exit('Exit on user input') if c == ord('s'): estop_nogui.settle_then_cut() # If the user attempts to toggle estop without valid endpoint except bosdyn.client.estop.EndpointUnknownError: clean_exit("This estop endpoint no longer valid. Exiting...") # Check if robot is estopped by any estops estop_status = 'NOT_STOPPED\n' estop_status_color = curses.color_pair(1) state = state_client.get_robot_state() estop_states = state.estop_states for estop_state in estop_states: state_str = estop_state.State.Name(estop_state.state) if state_str == 'STATE_ESTOPPED': estop_status = 'STOPPED\n' estop_status_color = curses.color_pair(3) break elif state_str == 'STATE_UNKNOWN': estop_status = 'ERROR\n' estop_status_color = curses.color_pair(3) elif state_str == 'STATE_NOT_ESTOPPED': pass else: # Unknown estop status clean_exit() # Display current estop status if not estop_nogui.estop_keep_alive.status_queue.empty(): latest_status = estop_nogui.estop_keep_alive.status_queue.get()[1].strip() if latest_status != '': # If you lose this estop endpoint, report it to user stdscr.addstr(7, 0, latest_status, curses.color_pair(3)) stdscr.addstr(6, 0, estop_status, estop_status_color) # Slow down loop time.sleep(0.5)