def apply(self, chars, mainChar, displayChars): if not mainChar.room and mainChar.path: for item in mainChar.path: # highlight chars on the path if not chars[item[1]][item[0]] in (displayChars.pathMarker, "!!", "??"): # bad code: urwid specific code import urwid display = chars[item[1]][item[0]] if isinstance(display, int): display = displayChars.indexedMapping[chars[item[1]][ item[0]]] if isinstance(display, str): display = (urwid.AttrSpec("default", "black"), display) chars[item[1]][item[0]] = (urwid.AttrSpec( display[0].foreground, "#333"), display[1])
def render_text(text, lang="text", style_name=None, plain=False): """Render the provided text with the pygments renderer """ if style_name is None: style_name = config.STYLE["style"] lexer = get_lexer(lang) formatter, style_bg = get_formatter(style_name) start = time.time() code_tokens = lexer.get_tokens(text) config.LOG.debug(f"Took {time.time()-start}s to render {len(text)} bytes") markup = [] for x in formatter.formatgenerator(code_tokens): if style_bg: x[0].background = style_bg markup.append(x) if markup[-1][1] == "\n": markup = markup[:-1] if len(markup) == 0: markup = [(None, "")] elif markup[-1][1].endswith("\n"): markup[-1] = (markup[-1][0], markup[-1][1][:-1]) if plain: return markup else: return urwid.AttrMap(urwid.Text(markup), urwid.AttrSpec("default", style_bg))
def __init__(self, widget, color): body = urwid.LineBox(widget, lline=get_icon('block'), tlcorner=get_icon('block_top'), blcorner=get_icon('block_bottom'), tline='', trcorner='', rline='', bline='', brcorner='') super(Box, self).__init__(body, urwid.AttrSpec(color, 'h235'))
def __init__(self): super(SlackBot, self).__init__([ urwid.Text([ (urwid.AttrSpec(pair[1], pair[2]), pair[0]) for pair in row ], align='center') for row in self._matrix ])
def register_palette(self, style_class): """Converts pygmets style to urwid palatte""" default = 'default' palette = list(self.base_palette) mapping = self.rc['rgb_to_short'] for tok in style_class.styles.keys(): for t in tok.split()[::-1]: st = style_class.styles[t] if '#' in st: break if '#' not in st: st = '' st = st.split() st.sort() # '#' comes before '[A-Za-z0-9]' if len(st) == 0: c = default elif st[0].startswith('bg:'): c = default elif len(st[0]) == 7: c = 'h' + rgb_to_short(st[0][1:], mapping)[0] elif len(st[0]) == 4: c = 'h' + rgb_to_short( st[0][1] * 2 + st[0][2] * 2 + st[0][3] * 2, mapping)[0] else: c = default a = urwid.AttrSpec(c, default, colors=256) row = (tok, default, default, default, a.foreground, default) palette.append(row) self.loop.screen.register_palette(palette)
def read_config(): counter = 0 new_config = CONFIG # make a copy of the default config with open(CONFIG_PATH, 'r') as f: lines = [x.strip('\n') for x in f.readlines()] # strip any unempty lines for line in lines: counter += 1 if line.strip() and line.lstrip()[0] != '#': # skip lines with '#' at beginning split = line.split(':') # break the line into two parts item and attributes item = split[0].strip() if item in palette_items: # if this line is a palette line attribs = split[1].strip().split(",") try: # try creating an urwid attr spec a = urwid.AttrSpec(attribs[0].strip(), attribs[1].strip(), colors=256) if attribs[2] not in text_options: attribs[2] = '' new_config[item] = [item]+[a.foreground, a.background, attribs[2]] # add this to the new config except: print("error on line" + str(counter)) else: # this line isn't a palette lime if item in new_config: # if this item exists in config dict new_config[item] = split[1].strip() # redefine it in the dict return new_config
def set_at_time(self, hour, minute): now = datetime.now().time().replace(second=0, microsecond=0) self.header_text = [ self.header_text, ' ', (urwid.AttrSpec('h166', ''), hour + ':' + minute) ] if not self.reminder.month: if time <= now: self.header_text = [self.header_text, ' ', 'tomorrow'] self.reminder.in_days += 1 else: self.header_text = [self.header_text, ' ', 'today'] self.header_text = [self.header_text, '.'] self.reminder.hour = int(hour) self.reminder.minute = int(minute) self.reminder.build() self.header_text = [ self.header_text, '\n', '(', self.reminder.dt_string, ')' ] self.header.set_text([self.header_text, self.div]) conf_selector = ConfirmationSelector() urwid.connect_signal(conf_selector, 'select', self.signal_handler) self.holder.original_widget = conf_selector self.box_adapter.height = self.get_height()
def ansi_to_urwid(ansi_text): result = [] ansi_text = ansi_text.decode('utf-8') for instruction in ansi_text.split('\x1B['): try: attr, text = instruction.split('m', 1) except: attr = '0' text = instruction.split('m', 1) attr_list = [int(code) for code in attr.split(';')] attr_list.sort() foreground = -1 background = -1 for attr in attr_list: if attr <= 29: pass elif attr <= 37: foreground = attr - 30 elif attr <= 47: background = attr - 40 elif attr <= 94: foreground = foreground + 8 elif attr >= 100 and attr <= 104: background = background + 8 foreground = color_list[foreground] background = color_list[background] result.append((urwid.AttrSpec(foreground, background), text)) return result
def highlight_tags(self): text = self.text.split('\n') first_line = text[0] if len(first_line) != 0 and first_line[0] == '[' and first_line[-1] == ']': self.all_text.append((urwid.AttrSpec('#f00,bold', '', 256), 'tags: ' + first_line[1:-1] + '\n')) self.text = '\n'.join(text[1:])
def _assigned_to_input(self): members = [{ "user": "******", "full_name": "Unassigned" }] + list(data.active_memberships(self.project).values()) max_length = max([len(data.user_full_name(s)) for s in members]) selected_filters = self._filters.get("assigned_to", set()) self._assigned_to_group = [] for item in members: state = item["user"] in selected_filters color = utils.color_to_hex(data.color(item)) attr = urwid.AttrSpec("h{0}".format(color), "default") self._assigned_to_group.append( urwid.CheckBox((attr, data.user_full_name(item)), state, False, self._handle_filter_change, ("assigned_to", item["user"]))) colum_items = [(16, urwid.Padding(generic.ListText("Assigned To", align="right"), right=2))] colum_items.append( generic.Grid(self._assigned_to_group, 4 + max_length, 3, 0, "left")) return urwid.Columns(colum_items)
def draw(raw): def deserializeUrwid(inData): outData = [] for item in inData: if item[0] == "tuple": outData.append((urwid.AttrSpec(item[1][0],item[1][1]),deserializeUrwid(item[2]))) if item[0] == "list": outData.append(deserializeUrwid(item[1])) if item[0] == "str": outData.append(item[1]) return outData #header.set_text((urwid.AttrSpec("default","default"),deserializeUrwid(raw["head"]))) main.set_text((urwid.AttrSpec("default","default"),deserializeUrwid(raw["main"]))) footer.set_text((urwid.AttrSpec("default","default"),deserializeUrwid(raw["footer"])))
def getUrwirdCompatible(self): # the to be result out = [] # add newlines on top if self.shift[0] > 0: for x in range(0, self.shift[0]): out.append("\n") # add rendered content for line in self.chars: # add spaces left of the canvas if self.shift[1] > 0: for x in range(0, self.shift[1]): out.append((urwid.AttrSpec("default", "default"), " ")) # add this lines content for char in line: if isinstance(char, int): if self.displayChars.indexedMapping[char] == None: debugMessages.append( "failed render" + str(char) + " " + str(self.displayChars.indexedMapping[char - 10]) + " " + str(self.displayChars.indexedMapping[char + 10])) else: out.append(self.displayChars.indexedMapping[char]) else: out.append(char) # start new line out.append("\n") return out
def styled_text(text, new_styles, old_styles=None, supplement_style=False): """Return a styled text tuple that can be used within urwid.Text. .. note:: If an urwid.Text instance is passed in as the ``text`` parameter, alignment values will be lost and must be explicitly re-added by the caller. """ if isinstance(text, urwid.Text): new_spec = spec_from_style(new_styles) return flatten_text(text, new_spec) elif (isinstance(text, tuple) and isinstance(text[0], urwid.AttrSpec) and isinstance(text[1], urwid.Text)): text = text[1].text old_styles = text[0] new_fg, new_bg = get_fg_bg_styles(new_styles) old_fg, old_bg = get_fg_bg_styles(old_styles) def join(items): return ",".join(set(items)) spec = urwid.AttrSpec( join(new_fg + old_fg), join(new_bg + old_bg), ) return (spec, text)
def render(self, size, focus=False): spanre = self.SPAN_RE htmlparser = self.htmlparser # Calculate image size and any bounding box total_width, total_height = self.pack(size, focus) width, height = self.pack([s * self.scale for s in size], focus) width = int(width) height = int(height) top_pad = (total_height - height) // 2 bottom_pad = total_height - height - top_pad left_pad = (total_width - width) // 2 right_pad = total_width - width - left_pad padding_attr = urwid.AttrSpec(self.background, self.background) try: jp2a = subprocess.Popen([ 'jp2a', '--colors', '--fill', '--width=%s' % width, '--height=%s' % height, '--html-raw', '-' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError, e: if self._prime: if e.errno == 2: print("ERROR: jp2a is used but is not installed.") else: print("ERROR: unable to run jp2a: %s" % e) raw_input("Press ENTER to continue.") data = self._blank(width, height)
def getUrwirdCompatible(self): # the to be result out = [] # add newlines over the drawing area if self.shift[0] > 0: for x in range(0,self.shift[0]): out.append("\n") # add rendered content to result for line in self.chars: # add spaces to the left of the drawing area if self.shift[1] > 0: for x in range(0,self.shift[1]): out.append((urwid.AttrSpec("default","default")," ")) # add this lines content for char in line: # render the character via the abstraction layer if isinstance(char, int): if self.displayChars.indexedMapping[char] == None: debugMessages.append("failed rendering "+str(char)+" "+str(self.displayChars.indexedMapping[char-10])+" "+str(self.displayChars.indexedMapping[char+10])) else: out.append(self.displayChars.indexedMapping[char]) # render the character directly else: out.append(char) # start new line out.append("\n") return out
def translate_text_for_urwid(raw_text): """ Converts an ANSII escaped string into an urwid equivalent. First by finding all the matches for "\033[" or "\x1b[", reading the ANSII escape code(s) (semi-colon delimited), and converting these to the an urwid AttrSpec. >>> translate_text_for_urwid("\033[91mHello, world") [(AttrSpec('light red', 'default'), 'Hello, world')] >>> translate_text_for_urwid("\033[97;101mHello, world") [(AttrSpec('white', 'light red'), 'Hello, world')] >>> translate_text_for_urwid("\033[0mFin, reset everything") [(AttrSpec('default', 'default'), 'Fin, reset everything')] :param raw_text: :return: """ formated_text = [] if hasattr(raw_text, "decode"): raw_text = raw_text.decode("utf-8") # Reset the start of text (+ allow for text that isn't formatted) if not (raw_text.startswith("\033[") or raw_text.startswith("\x1b[")): raw_text = "\x1b[0m" + raw_text for (attr, text) in get_ansii_group_matches_for_text(raw_text): fgcolor, bgcolor = translate_color(attr) formated_text.append((urwid.AttrSpec(fgcolor, bgcolor), text)) return formated_text
def translate_color(raw_text): table = ['black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray', 'dark gray', 'light red', 'light green', 'yellow', 'light blue', 'light magenta', 'light cyan', 'white'] formated_text = [] raw_text = raw_text.decode("utf-8") for at in raw_text.split("\x1b["): try: attr, text = at.split("m",1) except: attr = '0' text = at.split("m",1) list_attr = [ int(i) for i in attr.split(';') ] list_attr.sort() fg = -1 bg = -1 for elem in list_attr: if elem <= 29: pass elif elem <= 37: fg = elem - 30 elif elem <= 47: bg = elem - 40 elif elem <= 94: fg = fg + 8 elif elem >= 100 and elem <= 104: bg = bg + 8 fgcolor = table[fg] bgcolor = table[bg] if fg < 0: fgcolor = '' if bg < 0: bgcolor = '' if list_attr == [0]: fgcolor = '' bgcolor = '' formated_text.append((urwid.AttrSpec(fgcolor, bgcolor), text)) return formated_text
def __init__(self, obj_type): self.response = '' self.text = urwid.Text(self.prompt_head + obj_type + self.prompt_tail, align='center') self.text._selectable = True self.map = urwid.AttrMap(self.text, urwid.AttrSpec('h231', 'h160')) self.fill = urwid.Filler(self.map) super().__init__(self.fill)
def __init__(self, xPosition=None, yPosition=None, name="goo flask"): super().__init__(" -", xPosition, yPosition, name=name) self.walkable = True self.uses = 100 self.displayByUses = ["ò ", "ò.", "ò,", "ò-", "ò~", "ò="] self.display = (urwid.AttrSpec("#3f3", "black"), self.displayByUses[self.uses // 20]) self.description = "a flask conatining goo"
def update(self): termcolor, alpha, textcolor = rgba_to_termcolor( self.channel.color_rgba) if self.channel.last_on is None: termcolor = "#ccc" colorspec = urwid.AttrSpec(textcolor, termcolor, 256) self.text.set_text([(colorspec, ' {:.0%} '.format(alpha)), (None, ' ' + str(self.channel))])
def apply(self, character): if self.uses > 0: self.uses -= 1 self.display = (urwid.AttrSpec("#3f3", "black"), self.displayByUses[self.uses // 20]) self.changed() character.satiation = 1000 character.changed()
def __init__(self): self._screen = urwid.raw_display.Screen(input=os.devnull, output=os.devnull) self._palette_escapes = {} for name, attrs in self.palette.items(): escape = self._convert_attr_spec(urwid.AttrSpec(*attrs)) self._palette_escapes[name] = escape self._palette_escapes[None] = self._palette_escapes['default']
def _finish_substring(end: int): if current_fg_color: to_join = [current_fg_color] + current_format else: to_join = current_format fg = ','.join(to_join) rv.append((urwid.AttrSpec(fg, current_bg_color), irc_string[current_text_start_idx:end]))
def update(self): termcolor, alpha, textcolor = rgba_to_termcolor(self.effect.color_rgba) if self.effect.clear: termcolor = "#ccc" colorspec = urwid.AttrSpec(textcolor, termcolor, 256) self.text.set_text([(colorspec, ' {:.0%} '.format(alpha)), (None, ' ' + str(self.effect) + str(self.effect.rate))])
def _attr_to_escape(self, a): if a in self._pal_escape: return self._pal_escape[a] elif isinstance(a, urwid.AttrSpec): return self._attrspec_to_escape(a) # undefined attributes use default/default # TODO: track and report these return self._attrspec_to_escape(urwid.AttrSpec('default', 'default'))
def __init__(self, id, name, color=None, is_app=False): self.id = id if not color: color = '333333' color = '#{}'.format(shorten_hex(color)) markup = [(urwid.AttrSpec(color, 'h235'), '{} '.format(name))] if is_app: markup.append(('app_badge', '[APP]')) super(User, self).__init__(markup)
def __init__(self): self.confirm_prompt = urwid.Text('Set reminder?', 'center') self.yes = 'yes' self.yes = urwid.Text(self.yes, 'center') self.yes._selectable = True self.yes = urwid.AttrMap(self.yes, attr_map=urwid.AttrSpec('', ''), focus_map=urwid.AttrSpec('h10', '')) self.no = 'no' self.no = urwid.Text(self.no, 'center') self.no._selectable = True self.no = urwid.AttrMap(self.no, attr_map=urwid.AttrSpec('', ''), focus_map=urwid.AttrSpec('h10', '')) self.columns = urwid.Columns([self.yes, self.no]) self.body = urwid.SimpleListWalker([self.confirm_prompt, self.columns]) self.list_box = urwid.ListBox(self.body) super().__init__(self.list_box)
def __init__(self): self.x = 0 self.y = 0 self.text_lines = [] self.attr_lines = [] self.background = urwid.AttrSpec('light gray', 'black') self.attr = self.background self.resetColor() self.moveTo(0, 0)
def colorize(text): """ Convert ansi escape codes to urwid display attributes """ # Convert console line to something this function can use. text = ansi_replace(safe_unicode(console_repr(text))) mappings_fg = { 30: 'black', 31: 'light red', 32: 'light green', 33: 'yellow', 34: 'light blue', 35: 'light magenta', 36: 'light cyan', 37: 'dark gray', 0: 'default' } mappings_bg = { 40: 'black', 41: 'dark red', 42: 'dark green', 43: 'brown', 44: 'dark blue', 45: 'dark magenta', 46: 'dark cyan', 47: 'light gray' } text_attributed = [] parts = str(text).split('\x1b') regex = re.compile(r"^\[([;\d]*)m(.*)$", re.UNICODE | re.DOTALL) for part in parts: r = regex.match(part) if r: if r.group(2) != '': foreground = 'default' background = 'default' for code in filter(None, r.group(1).split(';')): if (int(code) in mappings_fg): foreground = mappings_fg[int(code)] if (int(code) in mappings_bg): background = mappings_bg[int(code)] text_attributed.append( (urwid.AttrSpec(foreground, background), r.group(2))) else: if part != '': text_attributed.append(part) return text_attributed
def convert(payload): converted = [] colours = ['#f50', "#a60", "#f80", "#fa0", "#860"] counter = 0 for char in payload: counter += 1 if len(char): converted.append((urwid.AttrSpec(colours[counter * 7 % 5], 'default'), char)) return converted