def set_palette(self, new_palette, new_palette1): """Build the game palette.""" if self.can_change_palette: for i in range(len(new_palette)): r, g, b = new_palette[i] curses.init_color(self.default_colors[i], (r*1000)//255, (g*1000)//255, (b*1000)//255)
def _destroy(self): iter = 1 for i, h, j in self.origmodes: # print iter, i, h, j curses.init_color(iter, i, h, j) iter += 1 self.initPairs() ## demethodise!
def d_team(team): screen.nodelay(0) screen.clear() selection = -1 option = 0 while selection < 0: screen.border() tName = 'Team: '+team.Name screen.addstr(1, (dims[1] - len(tName))/2, tName, curses.A_BOLD) graphics = [0]*team.Nmems graphics[option] = curses.A_BLINK for i in xrange(1, team.Nmems + 1): pk = team.get_Member(i) Name = pk.Name if len(Name) > 13: d_Name = Name[0:10]+'...' else: d_Name = Name screen.addstr(3*i+2, 1, d_Name, curses.A_BOLD | graphics[i - 1]) screen.addstr(3*i+2, 17, 'Lv. '+str(int(pk.Level)).rjust(3, ' ')) max_HP = pk.Stats['HP'] cur_HP = pk.CurHP s_hp = 'HP: '+str(int(cur_HP)).rjust(3,' ')+'/'+str(int(max_HP)).ljust(3,' ') x = np.ceil(cur_HP * 20. / max_HP) screen.addstr(3*i+2, 27, s_hp) screen.addstr(3*i+2, 39, '['+('X'*x).ljust(20, ' ')+']') Item = str(pk.Item) sts = str(pk.Status) if sts == 'None': sts = '---' if len(Item) > 0: hasItem = 1 else: hasItem = 0 screen.addstr(3*i+2, 64, 'Item: ['+('X'*hasItem).ljust(1,' ')+']') d_status = {'---':0, 'PSN':1, 'BRN':2, 'FZN':3, 'SLP':4, 'PAR':5} curses.init_color(15, 500, 500, 500) curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(4, curses.COLOR_WHITE, 8) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_YELLOW) screen.addstr(3*i+2, 76, sts, curses.color_pair(d_status[sts])) screen.refresh() action = screen.getch() if action == curses.KEY_UP: option = (option - 1)%team.Nmems elif action == curses.KEY_DOWN: option = (option + 1)%team.Nmems elif action == ord('\n'): selection = option elif action == ord('q'): selection = action if selection == ord('q'): return else: pk = team.get_Member(selection + 1) d_poke(pk) d_team(team) screen.clear()
def initColors (self): curses.start_color() if self.conf.params_transparency: curses.use_default_colors() bgcolor = -1 else: bgcolor = 0 # Setup colors # TODO, check the term capability before if curses.can_change_color(): for i in range(len(self.conf.color_set)): if not self.conf.color_set[i]: continue else: rgb = self.conf.color_set[i] curses.init_color(i, rgb[0], rgb[1], rgb[2]) curses.init_pair(0, curses.COLOR_BLACK, bgcolor) # 1 black curses.init_pair(1, curses.COLOR_RED, bgcolor) # 2 red curses.init_pair(2, curses.COLOR_GREEN, bgcolor) # 3 green curses.init_pair(3, curses.COLOR_YELLOW, bgcolor) # 4 yellow curses.init_pair(4, curses.COLOR_BLUE, bgcolor) # 5 blue curses.init_pair(5, curses.COLOR_MAGENTA, bgcolor) # 6 magenta curses.init_pair(6, curses.COLOR_CYAN, bgcolor) # 7 cyan curses.init_pair(7, curses.COLOR_WHITE, bgcolor) # 8 white
def __setup(self, stdscr): self.stdscr = stdscr curses.use_default_colors() curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) #Initialize colors for c in range(1, len(self.config['Colors'])): (c1,c2) = self.config['Colors']['ColorPair' + str(c)].split(',') curses.init_pair(c, int(c1), int(c2)) #Hide cursor curses.curs_set(0) #Setup class members self.global_keys = { '1' : self.activate_window, '2' : self.activate_window, '3' : self.activate_window, '4' : self.activate_window, 'q' : self.quit_sequence } #Initialize windows self.construct_windows() self.activeWindow = 1 self.__loop()
def init_color(self,t): """ Attempts to allocate a custom color. If the color you try to allocate has already been allocated once, it will return the old color If the value passed is not a 3-tuple, this function will return the input parameter. """ try: return self.allocated[t] except KeyError: pass try: if len(t) == 3: if self.colorcounter > curses.COLORS: return 1 if not curses.can_change_color(): return 1 curses.init_color(self.colorcounter,t[0],t[1],t[2]) c = self.colorcounter self.allocated[t] = c self.colorcounter += 1 return c else: return t except (KeyError, IndexError, TypeError) as e: return t
def __init__(self, fileName): """ """ self.logger = logging.getLogger('FrontEnd') self.cursor = Cursor.Cursor(fileName) self.stdscr = curses.initscr() curses.def_shell_mode() self.fileName = './tmp/'+fileName curses.noecho() screenHeight, screenWidth = self.stdscr.getmaxyx() self.statusWin = curses.newwin( 1,screenWidth, screenHeight-1,0) self.leftBorder = curses.newwin( screenHeight-0,4, 0,0) self.contentWin = curses.newwin( screenHeight, screenWidth-3, 0,4) self.height, self.width = self.contentWin.getmaxyx() bY,bX = self.contentWin.getbegyx() self.cursorWindow = CursorWindow.CursorWindow(0,0,self.width-1,self.height-1, 0) self.stdscr.clear() self.stdscr.keypad(True) if curses.can_change_color(): # init_color(n, r, g, b) # n=0 is background curses.start_color() curses.init_color(0, 255, 255, 255) self.fh = open(self.fileName, 'rb') self.RedrawBuffer() self.stdscr.move(0,4)
def reset_colors(old_colors): """ Terminal colours are fubar unless we reset them! """ for key, (r, g, b) in old_colors.items(): logging.info('{}, {}'.format(key, (r, g, b))) curses.init_color(key, r, g, b)
def main(win): curses.start_color() curses.use_default_colors() curses.init_color(curses.COLOR_GREEN, 797, 0, 0) curses.init_pair(1,curses.COLOR_GREEN,curses.COLOR_BLACK) win.addstr(str(curses.can_change_color()), curses.color_pair(1)) win.refresh()
def init_graphics(): global stdscr, win, height, width, color_pairs stdscr = curses.initscr() curses.noecho() stdscr.keypad(True) curses.curs_set(0) curses.start_color() begin_x = 0 begin_y = 0 height = curses.LINES width = curses.COLS win = curses.newwin(height + 1, width + 1, begin_y, begin_x) cls = parse.read_colors() colors = [(i[0], i[1][1:]) for i in sorted(list(cls.items()), key=lambda x: x[1][0])] color_number = len(colors) log(colors) cls = {} for i in range(color_number): curses.init_color(16 + i, *colors[i][1]) cls[colors[i][0]] = 16 + i log(cls) color_pairs = {} for i in range(color_number): for j in range(color_number): curses.init_pair(16 + i * 16 + j, cls[colors[i][0]], cls[colors[j][0]]) color_pairs[colors[i][0] + "+" + colors[j][0]] = curses.color_pair(16 + i * 16 + j)
def initColors (self): '''Setup all colors stuff, rgb as well.''' curses.start_color() if self.conf.params['transparency']: curses.use_default_colors() bgcolor = -1 else: bgcolor = False # Setup colors rgb if curses.can_change_color(): for i in range(len(self.conf.color_set)): if not self.conf.color_set[i]: continue else: rgb = self.conf.color_set[i] curses.init_color(i, rgb[0], rgb[1], rgb[2]) curses.init_pair(0, curses.COLOR_BLACK, bgcolor) # 0 black curses.init_pair(1, curses.COLOR_RED, bgcolor) # 1 red curses.init_pair(2, curses.COLOR_GREEN, bgcolor) # 2 green curses.init_pair(3, curses.COLOR_YELLOW, bgcolor) # 3 yellow curses.init_pair(4, curses.COLOR_BLUE, bgcolor) # 4 blue curses.init_pair(5, curses.COLOR_MAGENTA, bgcolor) # 5 magenta curses.init_pair(6, curses.COLOR_CYAN, bgcolor) # 6 cyan curses.init_pair(7, curses.COLOR_WHITE, bgcolor) # 7 white
def init_colors(): """ Modify and then initialize color pairs to match an actual Rubiks cube. """ colors = { 20: 'C41E3A', # red 21: '0051BA', # green 22: '009E60', # blue 23: 'FFD500', # yellow 24: 'FF5800', # orange } old_colors = {} for key, value in colors.items(): old_colors[key] = curses.color_content(key) logging.info('Old color: {} - {}'.format(key, old_colors)) r = int(value[0:2], 16) / 255 * 1000 g = int(value[2:4], 16) / 255 * 1000 b = int(value[4:6], 16) / 255 * 1000 curses.init_color(key, int(r), int(g), int(b)) logging.info('New color: {} - {}'.format(key, curses.color_content(key))) curses.init_pair(1, 20, -1) # red curses.init_pair(2, 21, -1) # green curses.init_pair(3, 22, -1) # blue curses.init_pair(4, curses.COLOR_WHITE, -1) # white curses.init_pair(5, 23, -1) # yellow curses.init_pair(6, 24, -1) # orange return old_colors
def _define_color(self, i_color: int, r: int, g: int, b: int): key = (r, g, b) old_rgb = curses.color_content(i_color) self.colors[key] = (i_color, old_rgb) r = int(1000 * r / 255) g = int(1000 * g / 255) b = int(1000 * b / 255) curses.init_color(i_color, r, g, b)
def init_rgb_colors(self): if curses.can_change_color(): for i in range(len(self.conf.color_set)): if not self.conf.color_set[i]: continue else: rgb = self.conf.color_set[i] curses.init_color(i, rgb[0], rgb[1], rgb[2])
def edit(self, state, name, fg, bg, *args): ''' Adds given item to the theme Parameters: state (str): Theme state name (str): Identifier keyed to curses attribute fg (3-tuple<float>): Foreground color as normalized rgb values bg (3-tuple<float>): Background color as normalized rgb values *args: Formatting attributes in {'BLINK', 'BOLD', 'REVERSE', 'UNDERLINE'} (Optional) Preconditions: Curses library shall be intialized. ''' # Return early if given state is invalid. if state not in self._data: return # Process color input. color_attr = 0; if curses.has_colors() and curses.can_change_color(): # Translate give colors to curses color items. colors = self._colors fg = tuple(math.floor(i * 1000) for i in fg) bg = tuple(math.floor(i * 1000) for i in bg) for rgb in fg, bg: if rgb not in colors: color_idx = len(colors) + 16 # 16-color terminal palette curses.init_color(color_idx, *rgb) colors[rgb] = color_idx # Associate foreground and background as a curses color pair object. color_pairs = self._color_pairs pair = (fg, bg) if pair not in color_pairs: color_pair_idx = len(color_pairs) + 8 # 16-color terminal palette curses.init_pair(color_pair_idx, colors[fg], colors[bg]) color_pairs[pair] = color_pair_idx # Get color attribute. color_attr = curses.color_pair(color_pairs[pair]) # Combine formatting attributes into a single curses attribute. format_attr = 0 if 'BLINK' in args: format_attr |= curses.A_BLINK if 'BOLD' in args: format_attr |= curses.A_BOLD if 'REVERSE' in args: format_attr |= curses.A_REVERSE if 'UNDERLINE' in args: format_attr |= curses.A_UNDERLINE # Insert combined color and formatting attributes into this theme. self._data[state][name] = color_attr | format_attr
def set_curses_colors(): s = 1000 / 255 for r, g, b in itertools.product(range(8), range(8), range(4)): index = r + 8 * (g + 8 * b) # Color 0 is black and can't be changed. # Pair 0 is white on black and can't be changed. if index: r, g, b = r << 5, g << 5, b << 6 _curses.init_color(index, int(r * s), int(g * s), int(b * s)) _curses.init_pair(index, index, 0)
def _makecolor(self, colnum, rgb): """Initializes a color and color pair in curses, as well as storing the relevant data in self._tokentocolorpair. Assumes rgb is an (r,g,b) tuple, where r,g,b are in the range 0-255""" r,g,b = rgb r = r*1000/255 g = g*1000/255 b = b*1000/255 curses.init_color(colnum, r,g,b)
def findcolor(self, rgb): if self.nextcolor >= curses.COLORS: self.log.debug('no colors left') return -1 color = self.nextcolor self.nextcolor += 1 self.log.debug('initializing %d as %s', color, repr(rgb)) curses.init_color(color, *[int(i * (1000 / 255)) for i in rgb]) return color
def init_colors(): curses.start_color() global USE_GRADIENT USE_GRADIENT = curses.can_change_color() # use xterm-256 if this is false if USE_GRADIENT: curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) for i in range(NUMBER_OF_COLOR + 1): green_value = (1000 - COLOR_STEP * NUMBER_OF_COLOR) + COLOR_STEP * i curses.init_color(START_COLOR_NUM + i, 0, green_value, 0) curses.init_pair(START_COLOR_NUM + i, START_COLOR_NUM + i, curses.COLOR_BLACK) else: curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
def __init__(self, color_map, pair_map): self.__stdscr = curses.initscr() self.__stdscr.keypad(1) curses.noecho() curses.cbreak() curses.curs_set(0) curses.start_color() for number, (r, b, g) in color_map.items(): curses.init_color(number, r, b, g) for number, (fg, bg) in pair_map.items(): curses.init_pair(number, fg, bg)
def init(): pair = 0 for r, g, b in product(range(0b111 + 1), range(0b111 + 1), range(0b11 + 1)): if pair + 8 >= 255: break pair += 1 curses.init_color(pair + 8, int(r / float(0b111) * 1000), int(g / float(0b111) * 1000), int(b / float(0b11) * 1000)) curses.init_pair(pair, pair + 8, 0) _colors[(r, g, b)] = pair return
def init(stdscr): curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.nodelay(1) curses.curs_set(0) curses.start_color() curses.use_default_colors() if curses.COLORS == 256: for i in range(0,curses.COLORS): r = (i >> 5) & 7 g = (i >> 2) & 7 b = (i) & 3 curses.init_color(i, r*142, g*142, int(b*333.334)) curses.init_color(curses.COLORS-1, 0,0,0) for i in range(0, curses.COLORS): curses.init_pair(i, 0, i) else: for i in range(0,curses.COLORS): r = (i >> 2) & 1 g = (i >> 1) & 1 b = (i) & 1 curses.init_color(i, r*1000, g*1000, b*1000) curses.init_color(curses.COLORS-1, 1000,1000,1000) for i in range(0, curses.COLORS): curses.init_pair(i, 0, i)
def init_colors(self): div = (self.kDEPTH - 1) / 1000.0 pair = 1 try: for r in xrange(self.kDEPTH): for g in xrange(self.kDEPTH): for b in xrange(self.kDEPTH): curses.init_color(pair, int(r / div), int(g / div), int(b / div)) if self.ascii_on: curses.init_pair(pair, pair, 0) else: curses.init_pair(pair, 0, pair) pair = pair + 1 except: # will fail for terminal that don't support 256 colors pass
def start_colors(): curses.start_color() curses.init_pair(10, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(20, curses.COLOR_RED, curses.COLOR_BLACK) if curses.can_change_color(): curses.init_color(COLOR_ORANGE, 600, 400, 250) curses.init_pair(30, COLOR_ORANGE, curses.COLOR_BLACK) curses.init_color(COLOR_GREY, 400, 400, 400) curses.init_pair(40, COLOR_GREY, curses.COLOR_BLACK) else: # Use default curses colors curses.init_pair(30, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(40, curses.COLOR_BLUE, curses.COLOR_BLACK)
def __init__(self): self.Running = True self.stdscr = curses.initscr() curses.noecho() curses.start_color() self.origmodes = [] if True: # curses.can_change_color():## Debug _ True: for i in range(1, 6): self.origmodes.append(curses.color_content(i)) curses.init_color(1, 0, 150, 0) curses.init_color(2, 0, 350, 0) curses.init_color(3, 0, 500, 0) curses.init_color(4, 0, 680, 0) curses.init_color(5, 0, 999, 0) self.initPairs() self.height, self.width = self.stdscr.getmaxyx() self.stdscr.refresh()
def setup_screen(self, input_file): """ Sets up the curses terminal with the appropriate colour scheme. """ curses.init_color(curses.COLOR_MAGENTA, 999, 0, 600) 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_BLUE, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(7, curses.COLOR_MAGENTA, curses.COLOR_BLACK) self.stdscr.addstr(0, 100, "REGISTER FILE", curses.A_BOLD) self.stdscr.addstr(0, 10, "MACHINE INFORMATION", curses.A_BOLD) self.stdscr.addstr(2, 10, "Program: " + str(input_file), curses.color_pair(4)) self.stdscr.addstr(4, 35, "Cycles per second: " + str(1 / instruction_time)[:5], curses.color_pair(3)) self.stdscr.addstr(12, 10, "PIPELINE INFORMATION", curses.A_BOLD) self.stdscr.addstr(51, 0, "Press `SPACE' to automate execution or any other key to single step.")
def init_win(self): """ initializes the window and sets up all of the defaults """ curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_BLACK) 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_WHITE, curses.COLOR_BLACK) self.green = curses.color_pair(1) self.red = curses.color_pair(2) self.cyan = curses.color_pair(3) self.white = curses.color_pair(4) self.black = curses.color_pair(5) if curses.can_change_color(): self.color_min = 8 self.color_max = 256 red = 0 green = 100 blue = 20 for c in range(self.color_min, self.color_max): curses.init_color(c, red, green, blue) red += 23 green += 33 blue += 53 red = red % 1000 green = green % 1000 blue = blue % 1000 for cidx in range(self.color_min, self.color_max): curses.init_pair(cidx, cidx, curses.COLOR_BLACK) else: self.color_min = 0 self.color_max = 8 if self.win: self.max_y, self.max_x = self.win.getmaxyx() self.char_map = [[None] * self.max_y for i in range(self.max_x)] self.max_y = self.max_y * 2 self.max_x = self.max_x * 2 else: self.max_y, self.max_x = (0, 0) self.char_map = None
def main(stdscr): curses.curs_set(0) curses.mousemask(1) curses.init_color(curses.COLOR_BLACK, 150, 150, 150) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_BLACK) current_row = 0 print_menu(stdscr, current_row) while 1: try: _, mouse_x, mouse_y, _, _ = curses.getmouse() except Exception as e: pass h, w = stdscr.getmaxyx() key = stdscr.getch() stdscr.clear() try: if (mouse_y == h // 2 - (len(MENU) // 2) + 2) and mouse_x == (w // 2 - 4): home(stdscr) except: pass if key == curses.KEY_UP and current_row > 0: current_row -= 1 elif key == curses.KEY_DOWN and current_row < len(MENU) - 1: current_row += 1 elif key == curses.KEY_ENTER or key in [10, 13]: if current_row == len(MENU) - 1: break elif current_row == 0: home(stdscr) elif current_row == 1: play(stdscr) elif current_row == 2: show_doc(stdscr) elif key == 27 or key == ord('q'): break print_menu(stdscr, current_row) stdscr.refresh()
def load(self): with open(sys.argv[1]) as choice: font, start, end, rate, bg, fg = ast.literal_eval(choice.readline()) self.script = map(lambda x: list(x.rstrip()), choice.readlines()) self.seq = map(chr, range(start, end + 1)) self.h = len(self.script) self.w = len(max(self.script)) self.area = curses.newpad(self.h + 1, self.w + 1) self.area.timeout(rate) curses.init_color(1, bg[0], bg[1], bg[2]) curses.init_color(2, fg[0], fg[1], fg[2]) curses.init_pair(2, 1, 2) os.system('setfont ' + font + '.psf')
def c_main(stdscr: 'curses._CursesWindow') -> int: if curses.has_colors(): curses.use_default_colors() curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE) curses.init_pair(2, 84, 232) if curses.can_change_color(): # curses.init_color(color_num, r, g, b) # 0x1e, 0x77, 0xd3 curses.init_color( 255, 0x1e * 1000 // 0xff, 0x77 * 1000 // 0xff, 0xd3 * 1000 // 0xff, ) curses.init_pair(3, 255, -1) stdscr.insstr(5, 0, f'COLORS: {curses.COLORS}') stdscr.insstr(6, 0, f'COLOR_PAIRS: {curses.COLOR_PAIRS}') name = '' name_done = False while True: stdscr.addstr(0, 0, 'what is your name? ', curses.color_pair(1)) stdscr.clrtoeol() stdscr.addstr(' ') stdscr.addstr(name) if name_done: stdscr.addstr(1, 0, f'OHAI {name}!', curses.color_pair(3)) char = stdscr.get_wch() if name_done: return 0 elif isinstance(char, str) and char.isprintable(): name += char elif char == curses.KEY_BACKSPACE or char == '\x7f': # char == '\x97' name = name[:-1] elif char == '\n': name_done = True else: raise AssertionError(char)
def demo(screen): # save the colors and restore it later save_colors = [curses.color_content(i) for i in range(curses.COLORS)] curses.curs_set(0) curses.start_color() # use 250 to not interfere with tests later curses.init_color(250, 1000, 0, 0) curses.init_pair(250, 250, curses.COLOR_BLACK) curses.init_color(251, 0, 1000, 0) curses.init_pair(251, 251, curses.COLOR_BLACK) screen.addstr(0, 20, 'Test colors for r,g,b = {0, 200}\n', curses.color_pair(250) | curses.A_BOLD | curses.A_UNDERLINE) i = 0 for r in (0, 200): for g in (0, 200): for b in (0, 200): i += 1 curses.init_color(i, r, g, b) curses.init_pair(i, i, curses.COLOR_BLACK) screen.addstr('{},{},{} '.format(r, g, b), curses.color_pair(i)) screen.addstr(3, 20, 'Test colors for r,g,b = {0..1000}\n', curses.color_pair(251) | curses.A_BOLD | curses.A_UNDERLINE) j=0 for r in range(0, 1001, 200): for g in range(0, 1001, 200): for b in range(0, 1001, 200): i += 1 j += 1 curses.init_color(i, r, g, b) curses.init_pair(i, curses.COLOR_BLACK, i) # screen.addstr('{},{},{} '.format(r, g, b), curses.color_pair(i)) # s = "test{0} {1} {2} {3}".format(i,r,g,b) # print(s) screen.addstr(j, 0, "ad", curses.color_pair(i)) #screen.addstr("test{0}: {1} {2} {3} ".format(i,r,g,b), curses.color_pair(i)) screen.getch() # restore colors for i in range(curses.COLORS): curses.init_color(i, *save_colors[i])
def _set_colors(self) -> None: """Set the colors for curses.""" # curses colors may have already been initialized # with another instance of curses window if self._ui_config.colors_initialized is True: return self._curs_set(0) # in the case of a TERM with limited capabilities # disable color and get out fast try: curses.use_default_colors() except curses.error: self._logger.error("Errors setting up terminal, no color support") self._term_osc4_support = False self._ui_config.colors_initialized = True return self._logger.debug("curses.COLORS: %s", curses.COLORS) self._logger.debug("curses.can_change_color: %s", curses.can_change_color()) self._term_osc4_support = curses.can_change_color() if self._ui_config.osc4 is False: self._term_osc4_support = False self._logger.debug("term_osc4_support: %s", self._term_osc4_support) if self._term_osc4_support: with open(self._ui_config.terminal_colors_path, encoding="utf-8") as fh: colors = json.load(fh) for color_name, color_hex in colors.items(): idx = COLOR_MAP[color_name] color = hex_to_rgb_curses(color_hex) curses.init_color(idx, *color) self._logger.debug("Custom colors set") else: self._logger.debug("Using terminal defaults") for i in range(0, curses.COLORS): curses.init_pair(i, i, -1) self._ui_config.colors_initialized = True
def _run(self, stdscr: Any) -> None: if self.animate: if curses.can_change_color(): curses.init_color(0, 0, 0, 0) # Set background (coloru 0) to rgb black stdscr.clear() curses.curs_set(0) # Hide the cursor while True: self.m.run() if self.m.halted: break elif len(self.m.output_vals) == 0: # Paused for input if self.paddle_position < self.ball_position: self.m.input_vals.append(1) elif self.paddle_position > self.ball_position: self.m.input_vals.append(-1) else: self.m.input_vals.append(0) elif len(self.m.output_vals) == 3: # Output full x, y, tile_id = self.m.output_vals self.m.output_vals = [] if (x, y) == (-1, 0): self.score = tile_id else: if self.animate: stdscr.addstr(y, x, tile(tile_id)) if tile_id == 4: self.ball_position = x if self.animate: stdscr.refresh() curses.napms(50) # stdscr.getkey() elif tile_id == 3: self.paddle_position = x else: # Wait for more output pass if self.animate: stdscr.refresh() stdscr.getkey()
def express_genome(organism, sync=0): color_tuples = organism.colors if not options.noblink: for i in range(evolight.__length__): blink_state[i] = False ## first, set the colors to be expressed, respecting the blinkstate for i in range(0, len(color_tuples)): (R, G, B) = color_tuples[i] colornum = i + __color_offset__ curses.init_color(colornum, R, G, B) ## these are kept by curses. use = colornum if not blink_state[i] and not options.noblink: use = -1 curses.init_pair(colornum, use, use) ## this is the key bit if not options.noblink: ## perform the blink expression blink_transitions = [val/2 for val in organism.blinks] ## the number of ticks between transitions blink_ticks = [0 for val in organism.blinks] ## the number of ticks in the current state for tick in range(__ticks__ * 2): for light in range(0, len(color_tuples)): colornum = light + __color_offset__ blink_ticks[light] += 1 main_window.clear(line=10) if blink_ticks[light] == blink_transitions[light]: blink_ticks[light] = 0 # reset the counter if blink_state[light]: blink_state[light] = False # light off curses.init_pair(colornum, -1, -1) else: blink_state[light] = True # light on curses.init_pair(colornum, colornum, colornum) busy = 0 for i in range(__busy_loop_time__): busy += 1
def changeColorsUI(editorObj, backgroundKey): raise NotImplementedError """ backgroundKey is the key for the background color currently being used in the editor Opens up a curses interface for the user to pick the colors for each type of token as defined in syntaxHighlighting.py by displaying all the possible colors and telling the user what the user is picking it for. The user then gets a sample display of some file with the syntax applied, and is prompted with a yes/no to save the syntax with some specified filename and load it. """ editorObj.editorscr.clear() editorObj.lineLinkedList = LineLinkedList(['A']) editorObj.topLine = editorObj.currentLine = editorObj.lineLinkedList.start editorUtil.insertLine(editorObj, editorObj.currentLine) editorObj.drawLines(editorObj.editorscr, editorObj.topLine) # don't have to save anything for later since the only time where # we call this, we are in options from before so we'll retrieve everything # on the way out of this function ref = 50 for i in range(0, 1000, 200): for j in range(0, 1000, 200): for k in range(0, 1000, 200): curses.init_color(ref, i, j, k) curses.init_pair(ref, ref, backgroundKey) #editorObj.editorscr.addstr('A', curses.color_pair(ref)) editorObj.currentLine.value = ( editorObj.currentLine.value[:-1] + 'A' + '\n') editorObj.currentLine.colors.append(ref) ref += 1 editorObj.drawLines(editorObj.editorscr, editorObj.topLine) # getcmd for the name editorObj.editorscr.getch() return 'default.json'
def main(): stdscr = curses.initscr() # MANDATORY! curses.start_color() # MANDATORY! curses.use_default_colors() # optional. stdscr.addstr("can_change_color(): " + str(curses.can_change_color()) + '\n') stdscr.addstr("COLOR_PAIRS: " + str(curses.COLOR_PAIRS) + '\n\n') #################################### stdscr.addstr("color 67 before:\n") curses.init_pair(20, 67, 0) stdscr.addstr(str(curses.color_content(67)) + '\n', curses.color_pair(20)) stdscr.addstr("color 67 after:\n") curses.init_color(67, 0, 255, 0) curses.init_pair(21, 67, 0) stdscr.addstr(str(curses.color_content(67)) + '\n\n', curses.color_pair(21)) #################################### stdscr.addstr("color 101 before:\n") curses.init_pair(22, 101, 0) stdscr.addstr(str(curses.color_content(101)) + '\n', curses.color_pair(22)) stdscr.addstr("color 101 after:\n") curses.init_color(101, 128, 128, 128) curses.init_pair(23, 101, 0) stdscr.addstr(str(curses.color_content(101)) + '\n\n', curses.color_pair(23)) #################################### stdscr.addstr("pair 40 before:\n") stdscr.addstr(str(curses.pair_content(40)) + '\n', curses.color_pair(40)) stdscr.addstr("pair 40 after:\n") curses.init_pair(40, 101, 67) stdscr.addstr(str(curses.pair_content(40)) + '\n\n', curses.color_pair(40)) stdscr.getch() curses.endwin() # optional, but recommended.
def initialize_gradient(start_hex="#0000cc", finish_hex='#FFFFFF', n=20, init_idx=100, bg_color=COLOR_BLACK): gradient = rgb_funcs.linear_gradient(start_hex, finish_hex, n) gradient = (999. / 255. * arr(gradient)).astype(int) color_indicies = [] for i, rgb in enumerate(gradient): r, g, b = rgb color_idx = init_idx + i color_indicies.append(color_idx) curses.init_color(color_idx, r, g, b) curses.init_pair(color_idx, color_idx, bg_color) return color_indicies
def load(self): with open(sys.argv[1]) as choice: font, start, end, rate, bg, fg = ast.literal_eval( choice.readline()) self.script = map(lambda x: list(x.rstrip()), choice.readlines()) self.seq = map(chr, range(start, end + 1)) self.h = len(self.script) self.w = len(max(self.script)) self.area = curses.newpad(self.h + 1, self.w + 1) self.area.timeout(rate) curses.init_color(1, bg[0], bg[1], bg[2]) curses.init_color(2, fg[0], fg[1], fg[2]) curses.init_pair(2, 1, 2) os.system('setfont ' + font + '.psf')
def init_rgb255(colour, r, g, b): """ Wrapper around curses.init_color taking values in range 0-255 instead of 0-999 Args: colour (int): number of colour to assign r (int): red componenta (0-255) g (int): green componenta (0-255) b (int): blue component (0-255) """ if r < 0 or r > 255: raise ValueError elif g < 0 or g > 255: raise ValueError elif b < 0 or b > 255: raise ValueError adj = 999 / 255. curses.init_color(colour, int(r * adj), int(g * adj), int(b * adj))
def init(main_screen): """Main function""" # Colors init # curses.init_color(8, 700, 500, 0) curses.init_color(9, 999, 800, 0) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, 8, curses.COLOR_BLACK) curses.init_pair(4, 9, curses.COLOR_BLACK) curses.curs_set(0) main_scr = curses.newwin(20, 40, 9, 0) # The main self.main_screen command_scr = curses.newwin(3, 60, 5, 0) # The command self.main_screen keys_scr = curses.newwin(20, 40, 9, 40) # self.main_screen that display connection between key and ingredient constant_scr = curses.newwin(4, 60, 0, 0) # self.main_screen that display money, day, etc... main_scr.keypad(True) return (main_scr, command_scr, keys_scr, constant_scr)
def stream_progress(self, pipeline_name): if self.logger.check_pipeline_exists(pipeline_name) == False: exit(1) scr = curses.initscr() scr.scrollok(True) scr.keypad(1) curses.halfdelay(5) curses.start_color() curses.noecho() # Colors curses.init_color(10, 100, 100, 100) curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_MAGENTA, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Update self.update_screen(scr, pipeline_name)
def colors() -> None: """Initializes the color pairs for the curses TUI.""" # Start colors in curses curses.start_color() # parse user color configuration color_cfg = config.tui.colors colors: Dict[str, Dict[str, str]] = {col: {} for col in TUI.COLOR_NAMES} for attr, col in color_cfg.items(): if attr in TUI.COLOR_VALUES: if not curses.can_change_color(): # cannot change curses default colors LOGGER.warning( "Curses cannot change the default colors. Skipping color setup." ) continue # update curses-internal color with HEX-color rgb_color = tuple( int(col.strip("#")[i:i + 2], 16) for i in (0, 2, 4)) # curses colors range from 0 to 1000 curses_color = tuple(col * 1000 // 255 for col in rgb_color) curses.init_color(TUI.COLOR_VALUES[attr], *curses_color) else: if attr[:-3] not in TUI.COLOR_NAMES: LOGGER.warning( "Detected unknown TUI color name specification: %s", attr[:-3]) continue colors[attr[:-3]][attr[-2:]] = col # initialize color pairs for TUI elements for idx, attr in enumerate(TUI.COLOR_NAMES): foreground = colors[attr].get("fg", "white") background = colors[attr].get("bg", "black") LOGGER.debug("Initiliazing color pair %d for %s", idx + 1, attr) curses.init_pair(idx + 1, TUI.COLOR_VALUES[foreground], TUI.COLOR_VALUES[background]) LOGGER.debug("Adding ANSI color code for %s", attr) TUI.ANSI_MAP[config.get_ansi_color( attr)] = TUI.COLOR_NAMES.index(attr) + 1
def main(window): curses.init_color(curses.COLOR_RED, 1000, 1000, 0) curses.init_pair(1, curses.COLOR_RED, 0) curses.curs_set(0) while True: window.clear() clock = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] cur_time = str(datetime.now().strftime('%H:%M:%S')) for x, row in enumerate(clock): for y, element in enumerate(row): if cur_time[x] == '0': clock[x] = [0, 0, 0, 0] if cur_time[x] == '1': clock[x] = [0, 0, 0, 1] if cur_time[x] == '2': clock[x] = [0, 0, 1, 0] if cur_time[x] == '3': clock[x] = [0, 0, 1, 1] if cur_time[x] == '4': clock[x] = [0, 1, 0, 0] if cur_time[x] == '5': clock[x] = [0, 1, 0, 1] if cur_time[x] == '6': clock[x] = [0, 1, 1, 0] if cur_time[x] == '7': clock[x] = [0, 1, 1, 1] if cur_time[x] == '8': clock[x] = [1, 0, 0, 0] if cur_time[x] == '9': clock[x] = [1, 0, 0, 1] clock = rotated_ccw(clock) draw_clock(clock, cur_time, window) window.refresh() time.sleep(0.05)
def main(window, speed): if curses.can_change_color(): curses.init_color(curses.COLOR_BLACK, 0, 0, 0) curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) curses.init_color(curses.COLOR_YELLOW, 1000, 1000, 0) curses.init_pair(1, curses.COLOR_YELLOW, 0) try: curses.curs_set(0) except Exception: pass # Can't hide cursor in 2019 huh? snowflakes = {} while True: height, width = max_dimensions(window) if len(snowflakes.keys()) >= 0.95 * (height * width): snowflakes.clear() snowflakes = update_snowflakes(snowflakes, window) snowflake = snowflake_char(window) snowflakes[(snowflake[0], snowflake[1])] = snowflake[2] window.clear() draw_moon(window) redisplay(snowflakes, window) window.refresh() try: time.sleep((0.2) / (speed / 100)) except ZeroDivisionError: time.sleep(0.2)
def __init__(self): curses.use_default_colors() curses.init_color(12, 350, 350, 350) curses.init_color(13, 1000, 600, 750) curses.init_color(14, 500, 300, 375) # number colors curses.init_pair(1, curses.COLOR_BLUE, -1) curses.init_pair(2, curses.COLOR_GREEN, -1) curses.init_pair(3, curses.COLOR_RED, -1) curses.init_pair(4, curses.COLOR_CYAN, -1) curses.init_pair(5, curses.COLOR_MAGENTA, -1) curses.init_pair(6, 13, -1) # other curses.init_pair(7, curses.COLOR_WHITE, -1) curses.init_pair(8, curses.COLOR_WHITE, -1) # error colors curses.init_pair(9, curses.COLOR_BLACK, curses.COLOR_RED) curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(11, curses.COLOR_BLACK, curses.COLOR_RED) # not relevant fields curses.init_pair(12, 12, -1) curses.init_pair(14, 14, -1)
def main(stdscr): stdscr.clear() curses.init_color(curses.COLOR_GREEN, 0, 1000, 0) curses.init_color(curses.COLOR_RED, 1000, 0, 0) curses.init_color(curses.COLOR_YELLOW, 1000, 1000, 0) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_BLACK) color_data = { 'JAN': [], 'FEB': [], 'MAR': [], 'APR': [], 'MAY': [], 'JUN': [], 'JUL': [], 'AUG': [], 'SEP': [], 'OCT': [], 'NOV': [], 'DEC': [] } color_data = read_data(color_data) if len(sys.argv) is 2: write_data(sys.argv[1]) print_data(stdscr, color_data) stdscr.refresh() stdscr.getkey()
def get_composite_color( self, foreground_color, background_color=DEFAULT_BACKGROUND_COLOR): """ The curse attribute representing this composite color Arguments: foreground_color {tuple} -- A foreground color corresponding to a tuple (r, g, b) that represents the value of the components R, G, and B that range between 0 and 255 background_color {tuple} -- A background color corresponding to a tuple (r, g, b) that represents the value of the components R, G, and B that range between 0 and 255. Returns: The `curse` attribute representing this composite color. """ # Convert RGB colors of the characters to `curses` color curses_color = self.__convert_rgb_to_1000(foreground_color) # Define and register the colors of the characters color_number = COLOR_NUMBER_DICT[foreground_color] curses.init_color(color_number, curses_color[0], curses_color[1], curses_color[2]) # Re-define background color if it is not a default color curses.init_color( 0, background_color[0], background_color[1], background_color[2]) # Definde color pair for each of character (start with 1) curses.init_pair( COLOR_NUMBER_DICT[foreground_color] - 7, color_number, curses.COLOR_BLACK) try: # Complete register the colors # Return the attribute value for displaying characters curses.color_pair(color_number) except curses.error: pass # Return attribute representing the composite color. return (COLOR_NUMBER_DICT[foreground_color]-7) * 256
def main(window, speed): if curses.can_change_color(): curses.init_color(curses.COLOR_BLACK, 0, 0, 0) curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) curses.init_color(curses.COLOR_YELLOW, 1000, 1000, 0) try: curses.curs_set(0) except Exception: pass # Can't hide cursor in 2019 huh? cells = {} for i in range( 10000 ): # initial population # @todo: make it a portion of height * width cell = random_cell(window) cells[cell[0]] = cell[1] while True: height, width = max_dimensions(window) if len(cells.keys()) >= 0.95 * (height * width): cells.clear() cells = update_cells(cells, window) window.clear() redisplay(cells, window) window.refresh() try: time.sleep((0.2) / (speed / 100)) except ZeroDivisionError: time.sleep(0.2)
def _set_colors(self) -> None: """Set the colors for curses""" curses.use_default_colors() self._logger.debug("curses.COLORS: %s", curses.COLORS) self._logger.debug("curses.can_change_color: %s", curses.can_change_color()) self._logger.debug("self._osc4: %s", self._osc4) if curses.COLORS > 16: if self._osc4 is False: self._custom_colors_enabled = False else: self._custom_colors_enabled = curses.can_change_color() else: self._custom_colors_enabled = False self._logger.debug("_custom_colors_enabled: %s", self._custom_colors_enabled) if self._custom_colors_enabled: with open(os.path.join(self._theme_dir, DEFAULT_COLORS)) as data_file: colors = json.load(data_file) for color_name, color_hex in colors.items(): idx = COLOR_MAP[color_name] color = hex_to_rgb_curses(color_hex) curses.init_color(idx, *color) self._logger.debug("Custom colors set") else: self._logger.debug("Using terminal defaults") if self._custom_colors_enabled: # set to 16, since 17+ are used on demand for RGBs self._number_colors = 16 else: # Stick to the define terminal colors, RGB will be mapped to these self._number_colors = curses.COLORS for i in range(0, self._number_colors): curses.init_pair(i, i, -1)
def main(window, speed): if curses.can_change_color(): curses.init_color(curses.COLOR_BLACK, 0, 0, 0) curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) curses.init_color(curses.COLOR_YELLOW, 1000, 1000, 0) curses.init_pair(1, curses.COLOR_YELLOW, 0) try: curses.curs_set(0) except Exception: pass # Can't hide cursor in 2019 huh? window.border() twice_flakes = {} #twiceflakes is an empty dict right? while True: height, width = max_dimensions(window) if len(twice_flakes.keys()) >= 0.95 * ( height * width ): #What does this part do? Wait isn't this part clearing everything print(twice_flakes.key()) twice_flakes.clear( ) #Nope it still doesn't work. It still clears the screen twice_flakes = update_twiceflakes( twice_flakes, window) #Maybe it's something to do with clearing the screen twiceflake = twiceflake_char(window) print(twiceflake) twice_flakes[(twiceflake[0], twiceflake[1])] = twiceflake[ 2] #What does this part of the code do? Why is twiceflake member str name assigned? window.clear() draw_moon(window) redisplay(twice_flakes, window) window.refresh() try: time.sleep((0.2) / (speed / 100)) except ZeroDivisionError: time.sleep(0.2)
def winmain(stdscr, args): ''' ''' (height, width) = stdscr.getmaxyx() logger.debug("height,width") logger.debug((height, width)) if height < ANSWER_ROW + 1: return -1, "screen height too small" if width < KEY_N_COL * KEY_WIDTH * 2 + KBD_CENTER_WIDTH: return -1, "screen width too small" curses.curs_set(0) curses.start_color() curses.init_color(1, int(0x84 / 0xff * 1000), int(0xff / 0xff * 1000), int(0xff / 0xff * 1000)) curses.init_pair(1, 1, curses.COLOR_BLACK) curses.init_color(2, int(0xcc / 0xff * 1000), int(0xff / 0xff * 1000), int(0x90 / 0xff * 1000)) curses.init_pair(2, 2, curses.COLOR_BLACK) curses.init_color(3, int(0xff / 0xff * 1000), int(0x3d / 0xff * 1000), int(0x00 / 0xff * 1000)) curses.init_pair(3, 3, curses.COLOR_WHITE) stdscr.refresh() return Trainer(stdscr, args).run()
def __init__(self): self._screen = curses.initscr() curses.start_color() curses.use_default_colors() if not curses.has_colors() or curses.COLORS < 8: print('Can\'t display colors. Terminating...') sys.exit() curses.noecho() self._screen.refresh() self._screen.scrollok(True) self.BUILD_STATUS_POS = (0, 10) self.OUTPUT_POS = (2, 0) # curses.init_color(8, 128, 128, 128) curses.init_color(8, 119, 136, 153) curses.init_pair(1, curses.COLOR_RED, -1) curses.init_pair(2, curses.COLOR_GREEN, -1) curses.init_pair(3, curses.COLOR_WHITE, -1) curses.init_pair(4, curses.COLOR_CYAN, -1) curses.init_pair(5, 8, -1) self.ERROR_ATTR = curses.color_pair(1) self.OK_ATTR = curses.color_pair(2) self.TESTSUITE_ATTR = curses.color_pair(3) self.TEST_ATTR = curses.color_pair(4) self.TEST_FAIL_ATTR = curses.color_pair(5) self.IMPORTANT_ATTR = curses.color_pair(3) | curses.A_BOLD self.BUILD_ERROR_ATTR = curses.color_pair(3) self.BASIC_TEXT = curses.color_pair(5) self.KEY_ENTER = curses.KEY_ENTER self._key_to_handler = {} self._key_to_description = {} self._alive = True self._input_thread = Thread(target=self._process_input) self._input_thread.start()
def _define_default_colors(self): curses.init_pair(1, curses.COLOR_CYAN, 0) curses.init_pair(2, curses.COLOR_RED, 0) if curses.COLORS > 8: if curses.COLORS > 16: # Win10 - 768 curses.init_color(20, 0, 0, 850) curses.init_pair(3, 20, -1) else: # Win7 - 16 curses.init_pair(3, curses.COLOR_BLUE + 8, -1) curses.init_pair(4, curses.COLOR_RED + 8, -1) curses.init_pair(5, curses.COLOR_GREEN + 8, -1) curses.init_pair(6, curses.COLOR_YELLOW + 8, -1) curses.init_pair(7, curses.COLOR_BLACK + 8, -1) curses.init_pair(8, curses.COLOR_CYAN + 8, -1) else: curses.init_pair(3, curses.COLOR_BLUE, -1) curses.init_pair(4, curses.COLOR_RED, -1) curses.init_pair(5, curses.COLOR_GREEN, -1) curses.init_pair(6, curses.COLOR_YELLOW, -1) curses.init_pair(7, curses.COLOR_GREEN, -1) curses.init_pair(8, curses.COLOR_CYAN, -1)
def colors(): """Initialize the color pairs for the curses TUI.""" # Start colors in curses curses.start_color() # parse user color configuration color_cfg = CONFIG.config['COLORS'] colors = {col: {} for col in TUI.COLOR_NAMES} for attr, col in color_cfg.items(): if attr in TUI.COLOR_VALUES.keys(): if not curses.can_change_color(): # cannot change curses default colors LOGGER.warning( 'Curses cannot change the default colors. Skipping color setup.' ) continue # update curses-internal color with HEX-color rgb_color = tuple( int(col.strip('#')[i:i + 2], 16) for i in (0, 2, 4)) # curses colors range from 0 to 1000 curses_color = tuple(col * 1000 // 255 for col in rgb_color) curses.init_color(TUI.COLOR_VALUES[attr], *curses_color) else: if attr[:-3] not in TUI.COLOR_NAMES: LOGGER.warning( 'Detected unknown TUI color name specification: %s', attr[:-3]) continue colors[attr[:-3]][attr[-2:]] = col # initialize color pairs for TUI elements for idx, attr in enumerate(TUI.COLOR_NAMES): foreground = colors[attr].get('fg', 'white') background = colors[attr].get('bg', 'black') LOGGER.debug('Initiliazing color pair %d for %s', idx + 1, attr) curses.init_pair(idx + 1, TUI.COLOR_VALUES[foreground], TUI.COLOR_VALUES[background]) LOGGER.debug('Adding ANSI color code for %s', attr) TUI.ANSI_MAP[CONFIG.get_ansi_color( attr)] = TUI.COLOR_NAMES.index(attr) + 1
def process(self, data): for datum in data: if self.stdscr.getch() != -1: break self.pad.clear() if 'time=' in datum: ping = int(datum.partition('time=')[2].partition('ms')[0]) half = self.limit/2 green,red = 1000,1000-int(1000*abs(min(ping, self.limit) - half)/half) if ping > self.limit/2: green,red = red,green curses.init_color(1, red, green, 0) # color #1, up to 1000 of each channel fill = self.char * int(self.width * min(ping, self.limit) / self.limit) + '\n' self.pad.addstr((fill * self.height).strip(), curses.color_pair(1)) self.pad.refresh(0,0, 0,0, self.height-1,self.width-1) elif 'timed out' in datum: curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) self.pad.refresh(0,0, 0,0, self.height-1,self.width-1) for _ in range(3): curses.flash() curses.napms(50) curses.init_pair(1, 1, 1)
def __init__(self, cursesScreen): self.clicks = 0 self.debugMouseEvent = (0, 0, 0, 0, 0) self.exiting = False self.cursesScreen = cursesScreen self.ch = 0 curses.mousemask(-1) curses.mouseinterval(0) # Enable mouse tracking in xterm. sys.stdout.write('\033[?1002;h\n') #sys.stdout.write('\033[?1005;h\n') curses.meta(1) # Access ^c before shell does. curses.raw() # Enable Bracketed Paste Mode. sys.stdout.write('\033[?2004;h\n') #curses.start_color() curses.use_default_colors() if 0: assert (curses.COLORS == 256) assert (curses.can_change_color() == 1) assert (curses.has_colors() == 1) app.log.detail("color_content:") for i in range(0, curses.COLORS): app.log.detail("color", i, ": ", curses.color_content(i)) for i in range(16, curses.COLORS): curses.init_color(i, 500, 500, i * 787 % 1000) app.log.detail("color_content, after:") for i in range(0, curses.COLORS): app.log.detail("color", i, ": ", curses.color_content(i)) if 1: #rows, cols = self.cursesScreen.getmaxyx() cursesWindow = self.cursesScreen cursesWindow.leaveok(1) # Don't update cursor position. cursesWindow.scrollok(0) cursesWindow.timeout(10) cursesWindow.keypad(1) app.window.mainCursesWindow = cursesWindow self.zOrder = []
def _init_colors(self): """Initialize colors""" curses.use_default_colors() if curses.can_change_color( ) and not self._config.prefer_terminal_colors: curses.init_color(curses.COLOR_RED, 1000, 300, 300) curses.init_color(curses.COLOR_GREEN, 500, 1000, 300) curses.init_color(curses.COLOR_BLUE, 300, 700, 1000) curses.init_color(curses.COLOR_YELLOW, 1000, 750, 0) curses.init_pair(2, curses.COLOR_RED, -1) curses.init_pair(3, curses.COLOR_GREEN, -1) curses.init_pair(4, curses.COLOR_BLUE, -1) curses.init_pair(5, curses.COLOR_YELLOW, -1)
def _color_lines_for_term(self, lines: List) -> CursesLines: """Give a list of dicts from tokenized lines transform them into lines for curses add colors as needed, maintain a mapping of rgb colors to curses colors in self._rgb_to_curses_color_idx :params lines: the lines to transform :type lines: list of lists of dicts Lines[LinePart[{"color": rgb, "chars": text, "column": n},...]] :return: the lines ready for curses :type: CursesLines """ if self._custom_colors_enabled: unique_colors = list( set(chars["color"] for line in lines for chars in line if chars["color"]) ) # start custom colors at 16 for color in unique_colors: scale = 1000 / 255 red, green, blue = color if color not in self._rgb_to_curses_color_idx: if not self._rgb_to_curses_color_idx: curses_colors_idx = 16 else: curses_colors_idx = max(self._rgb_to_curses_color_idx.values()) + 1 self._rgb_to_curses_color_idx[color] = curses_colors_idx curses.init_color( curses_colors_idx, int(red * scale), int(green * scale), int(blue * scale) ) self._logger.debug( "Added color: %s:%s", curses_colors_idx, curses.color_content(curses_colors_idx), ) curses.init_pair(curses_colors_idx, curses_colors_idx, -1) colored_lines = self._colored_lines(lines) return colored_lines
def seatmap(win): (MY, MX) = win.getmaxyx() #putting screen size in a corner win.border(0) win.addstr(0,0, str(win.getmaxyx())) win.addstr(MY-1, MX/2-4, "Colormode: %s" % curses.has_colors() ) #Tells if we can use colors or not :) win.refresh() logoheight, logolen = len(LOGO.split('\n'))+2 , max( [len(x)+1 for x in LOGO.split('\n')] ) #Width of the logo (logowin, logopan) = make_panel(logoheight, logolen, MY/2-20/2, MX/2-logolen/2, LOGO) curses.panel.update_panels() logopan.top() logowin.refresh() if curses.can_change_color(): curses.init_color(COLOR_RED, 0, 300, 200) while 1: time.sleep(1) (PY,PX) = logowin.getmaxyx() (MY, MX) = win.getmaxyx() win.addstr(0, MX/2, str(logowin.getmaxyx()) ) Y,X = random.randrange(PADDING, MY-PY-PADDING), random.randrange(PADDING, MX+1-PX-PADDING) logopan.move(Y,X) curses.init_pair(1,random.randrange(0, 8), 0 ) logowin.addstr(2, 2, LOGO, curses.color_pair(1)) curses.panel.update_panels() logowin.refresh() win.refresh()
def main(stdscr): curses.start_color() curses.init_color(7, 1000, 627, 0) curses.init_color(8, 1000, 1000, 1000) for i, j in enumerate([6, 3, 5, 2, 1, 4, 7, 8], 1): curses.init_pair(i, j, curses.COLOR_BLACK) curses.curs_set(0) curses.noecho() stdscr.nodelay(1) game = Tetris(20, 10) game.start() stdscr.clear() while game.continues: c = stdscr.getch() if c == ord("q"): game.continues = False elif c == curses.KEY_LEFT: game.left() elif c == curses.KEY_RIGHT: game.right() elif c == curses.KEY_UP: game.rotate() elif c == curses.KEY_DOWN: game.down() for i, line in enumerate(game.curses_str().splitlines()): for j, c in enumerate(line): if c == "0": stdscr.addstr(i, j, " ") elif c.isdigit(): stdscr.addstr(i, j, "█" if sys.version_info >= (3,) else "X", curses.color_pair(int(c))) else: stdscr.addstr(i, j, c, curses.color_pair(8)) stdscr.addstr(22, 0, "Lines: {}".format(game.lines), curses.color_pair(8)) stdscr.addstr(23, 0, "Level: {}".format(game.level), curses.color_pair(8)) stdscr.addstr(24, 0, "Score: {}".format(game.score), curses.color_pair(8)) stdscr.refresh() return game