class ZTVApp(with_metaclass(urwid.MetaSuper, urwid.MainLoop)): """Provide CLI app event loop functionality.""" palette = [ ('body', 'black', 'light gray', 'standout'), ('reverse', 'light gray', 'black'), ('column_header', 'dark blue', 'black', ('bold', 'underline')), ('column', 'light gray', 'black'), ('header', 'white', 'dark red', 'bold'), ('important_header', 'white', 'dark red', 'bold'), ('important', 'dark blue', 'light gray', ('standout', 'underline')), ('editfc', 'white', 'dark blue', 'bold'), ('editbx', 'light gray', 'dark blue'), ('editcp', 'black', 'light gray', 'standout'), ('footer', 'dark gray', 'light gray', ('bold', 'standout')), ('buttn', 'black', 'dark cyan'), ('buttnf', 'white', 'dark blue', 'bold'), ] def __init__(self, client=None, config=None): """ Initialize ZTVApp instance. Args: ---- client (:obj:`zenpy.Zenpy`): The Zendesk API client """ self.config = config or configargparse.Namespace() self.screen = urwid.raw_display.Screen() self.frame = AppFrame( client=client, title=u"Zendesk Ticket Viewer", loop=self, ) self.frame.add_page('WELCOME', WelcomePage) self.frame.add_page('TICKET_LIST', TicketListPage) self.frame.add_page('TICKET_VIEW', TicketViewPage) self.frame.add_page('ERROR', ErrorPage) self.frame.set_page('WELCOME') if getattr(self.config, 'unpickle_tickets'): # no creds required when unpickle_tickets so bypass log in self.frame.pages['WELCOME']._action_login() del self.frame.pages['WELCOME'] self.__super.__init__( widget=self.frame, palette=self.palette, screen=self.screen, )
class PositiveNegativeBarGraph(with_metaclass(urwid.BarGraphMeta, urwid.Widget)): _sizing = frozenset([BOX]) maxcol = None ignore_focus = True def __init__(self, attlist, hatt=None): """ Create a bar graph with the passed display characteristics. see set_segment_attributes for a description of the parameters. """ self.set_segment_attributes(attlist, hatt) self.set_data([], 1, 0) self.set_bar_width(None) def set_segment_attributes(self, attlist, hatt=None): """ :param attlist: list containing display attribute or (display attribute, character) tuple for background, first segment, and optionally following segments. ie. len(attlist) == num segments+1 character defaults to ' ' if not specified. :param hatt: list containing attributes for horizontal lines. First element is for lines on background, second is for lines on first segment, third is for lines on second segment etc. eg: set_segment_attributes( ['no', ('unsure',"?"), 'yes'] ) will use the attribute 'no' for the background (the area from the top of the graph to the top of the bar), question marks with the attribute 'unsure' will be used for the topmost segment of the bar, and the attribute 'yes' will be used for the bottom segment of the bar. """ self.attr = [] self.char = [] if len(attlist) < 2: raise PositiveNegativeGraphError( "attlist must include at least background and seg1: %r" % (attlist, )) assert len(attlist) >= 2, 'must at least specify bg and fg!' for a in attlist: if type(a) != tuple: self.attr.append(a) self.char.append(' ') else: attr, ch = a self.attr.append(attr) self.char.append(ch) self.hatt = [] if hatt is None: hatt = [self.attr[0]] elif type(hatt) != list: hatt = [hatt] self.hatt = hatt def set_data(self, bardata, top, bottom): """ Store bar data, bargraph top and horizontal line positions. bardata -- a list of bar values. top -- maximum value for segments within bardata bar values are [ segment1, segment2, ... ] lists where top is the maximal value corresponding to the top of the bar graph and segment1, segment2, ... are the values for the top of each segment of this bar. Simple bar graphs will only have one segment in each bar value. Eg: if top is 100 and there is a bar value of [ 80, 30 ] then the top of this bar will be at 80% of full height of the graph and it will have a second segment that starts at 30%. """ self.data = bardata, top, bottom # pylint: disable=no-member self._invalidate() def _get_data(self, size): """ Return (bardata, top, bottom) This function is called by render to retrieve the data for the graph. It may be overloaded to create a dynamic bar graph. This implementation will truncate the bardata list returned if not all bars will fit within maxcol. """ (maxcol, maxrow) = size bardata, top, bottom = self.data widths = self.calculate_bar_widths((maxcol, maxrow), bardata) if len(bardata) > len(widths): return bardata[:len(widths)], top, bottom return bardata, top, bottom def set_bar_width(self, width): """ Set a preferred bar width for calculate_bar_widths to use. width -- width of bar or None for automatic width adjustment """ assert width is None or width > 0 self.bar_width = width # pylint: disable=no-member self._invalidate() def calculate_bar_widths(self, size, bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, _) = size if self.bar_width is not None: return [self.bar_width] * min(len(bardata), maxcol // self.bar_width) if len(bardata) >= maxcol: return [1] * maxcol widths = [] grow = maxcol remain = len(bardata) for _ in bardata: w = int(float(grow) / remain + 0.5) widths.append(w) grow -= w remain -= 1 return widths def selectable(self): """ Return False. """ return False def calculate_display(self, size): """ Calculate display data. """ (maxcol, maxrow) = size # pylint: disable=no-member bardata, top, bottom = self.get_data((maxcol, maxrow)) widths = self.calculate_bar_widths((maxcol, maxrow), bardata) # initialize matrix halfwayScaled = maxrow // 2 # use overscore if the item is above 0 or underscore if below 0, dash if on 0 disp = [[ '\u203E' if i < halfwayScaled else '-' if i == halfwayScaled else '_' for j in range(maxcol) ] for i in range(maxrow)] def split(word): return [char for char in word] # first column should be used for scale and if (len(bardata) > 0): formatString = '{:0.3f}' if type( bardata[0][0]) is float else '{:4d}' for i in range(maxrow): value = self.calculate_scale(maxrow, top, i) stringVal = '' if (value >= 0): stringVal = ' ' + formatString.format(value)[1:] else: stringVal = '-' + formatString.format(value)[2:] characters = split(stringVal) for cIndex, c in enumerate(characters): disp[i][cIndex] = c # add bar entries to matrix bar_positions = self.get_bar_positions(bardata, top, bottom, widths, maxrow) disp = self.update_matrix_with_bar_positions(bar_positions, disp) return disp def calculate_scale(self, maxrow, top, row): halfwayScaled = maxrow // 2 unit = top / halfwayScaled unitsAway = (halfwayScaled - row) return unitsAway * unit def update_matrix_with_bar_positions(self, bar_positions, disp): for i in range(len(disp)): for j in range(len(disp[i])): if (self.location_is_a_bar(bar_positions, i, j)): disp[i][j] = 'X' return disp def location_is_a_bar(self, bar_positions, row, col): res = False if (bar_positions[row] is not None): for _, colStart, _ in bar_positions[row]: if colStart == col: res = True return res def render(self, size, focus=False): """ Render BarGraph. """ (maxcol, maxrow) = size self.maxcol = maxcol disp = self.calculate_display((maxcol, maxrow)) combinelist = [] for row in disp: l = [] for _, currLoc in enumerate(row, start=0): if currLoc == 'X': # bar a = self.attr[1] t = self.char[0] elif currLoc == ' ': a = None t = currLoc else: a = None t = currLoc # this would likely be printing the scale on the left hand side l.append((a, t)) c = Text(l).render((maxcol, )) assert c.rows() == 1, "Invalid characters in BarGraph!" combinelist += [(c, None, False)] canv = CanvasCombine(combinelist) return canv def scale_bar_values(self, bar, top, bottom, maxrow): """ Return a list of bar values aliased to integer values of maxrow. maxrow is the maximum colums used in the terminal """ results = [] for v in bar: if (v >= 0): start = maxrow // 2 # you want to start positive bar values at the middle of the widget end = start - int(((float(v) * (maxrow // 2)) / top) + 0.5) results.append((start, end)) else: # you want to start the negative bar values at the last row in the widget start = maxrow // 2 + 1 end = start + int(((float(v) * (maxrow // 2)) / bottom) + 0.5) results.append((start, end)) return results def get_bar_positions(self, bardata, top, bottom, bar_widths, maxrow): """ Calculate a rendering of the bar graph described by data, bar_widths and height. bardata -- bar information with same structure as BarGraph.data top -- maximal value for bardata segments bar_widths -- list of integer column widths for each bar maxrow -- rows for display of bargraph Returns a structure as follows: [ ( y_count, [ ( bar_type, width), ... ] ), ... ] The outer tuples represent a set of identical rows. y_count is the number of rows in this set, the list contains the data to be displayed in the row repeated through the set. The inner tuple describes a run of width characters of bar_type. bar_type is an integer starting from 0 for the background, 1 for the 1st segment, 2 for the 2nd segment etc.. This function should complete in approximately O(n+m) time, where n is the number of bars displayed and m is the number of rows. """ assert len(bardata) == len(bar_widths) # build intermediate data structure rows = [None] * maxrow def add_segment(seg_num, col, rowStart, rowEnd, width, rows=rows): # iterate between rowStart and rowEnd filling the rows # check and see if this is a positive bar. if it is you have # to use a negative step to count down because row 0 is at the top step = 1 if (rowEnd < rowStart): step = -1 for rowIndex in range(rowStart, rowEnd + step, step): if rows[rowIndex] is None: rows[rowIndex] = [] rows[rowIndex].append((seg_num, col, col + width)) col = 6 # has to be 6 to account for the scale column being in column 0 barnum = 0 for bar in bardata: width = bar_widths[barnum] if width < 1: continue # loop through in reverse order segments = self.scale_bar_values(bar, top, bottom, maxrow) for k in range(len(bar) - 1, -1, -1): # each segment has a start and end in the form of a tuple sStart, sEnd = segments[k] if sEnd >= maxrow: sEnd = maxrow - 1 if sEnd < 0: sEnd = 0 add_segment(k + 1, col, sStart, sEnd, width) col += width barnum += 1 return rows
class BarGraph(with_metaclass(BarGraphMeta, Widget)): _sizing = frozenset([BOX]) ignore_focus = True eighths = u' ▁▂▃▄▅▆▇' hlines = u'_⎺⎻─⎼⎽' def __init__(self, attlist, hatt=None, satt=None): """ Create a bar graph with the passed display characteristics. see set_segment_attributes for a description of the parameters. """ self.set_segment_attributes(attlist, hatt, satt) self.set_data([], 1, None) self.set_bar_width(None) def set_segment_attributes(self, attlist, hatt=None, satt=None): """ :param attlist: list containing display attribute or (display attribute, character) tuple for background, first segment, and optionally following segments. ie. len(attlist) == num segments+1 character defaults to ' ' if not specified. :param hatt: list containing attributes for horizontal lines. First element is for lines on background, second is for lines on first segment, third is for lines on second segment etc. :param satt: dictionary containing attributes for smoothed transitions of bars in UTF-8 display mode. The values are in the form: (fg,bg) : attr fg and bg are integers where 0 is the graph background, 1 is the first segment, 2 is the second, ... fg > bg in all values. attr is an attribute with a foreground corresponding to fg and a background corresponding to bg. If satt is not None and the bar graph is being displayed in a terminal using the UTF-8 encoding then the character cell that is shared between the segments specified will be smoothed with using the UTF-8 vertical eighth characters. eg: set_segment_attributes( ['no', ('unsure',"?"), 'yes'] ) will use the attribute 'no' for the background (the area from the top of the graph to the top of the bar), question marks with the attribute 'unsure' will be used for the topmost segment of the bar, and the attribute 'yes' will be used for the bottom segment of the bar. """ self.attr = [] self.char = [] if len(attlist) < 2: raise BarGraphError("attlist must include at least background and seg1: %r" % (attlist,)) assert len(attlist) >= 2, 'must at least specify bg and fg!' for a in attlist: if type(a) != tuple: self.attr.append(a) self.char.append(' ') else: attr, ch = a self.attr.append(attr) self.char.append(ch) self.hatt = [] if hatt is None: hatt = [self.attr[0]] elif type(hatt) != list: hatt = [hatt] self.hatt = hatt if satt is None: satt = {} for i in satt.items(): try: (fg, bg), attr = i except ValueError: raise BarGraphError("satt not in (fg,bg:attr) form: %r" % (i,)) if type(fg) != int or fg >= len(attlist): raise BarGraphError("fg not valid integer: %r" % (fg,)) if type(bg) != int or bg >= len(attlist): raise BarGraphError("bg not valid integer: %r" % (fg,)) if fg <= bg: raise BarGraphError("fg (%s) not > bg (%s)" % (fg, bg)) self.satt = satt def set_data(self, bardata, top, hlines=None): """ Store bar data, bargraph top and horizontal line positions. bardata -- a list of bar values. top -- maximum value for segments within bardata hlines -- None or a bar value marking horizontal line positions bar values are [ segment1, segment2, ... ] lists where top is the maximal value corresponding to the top of the bar graph and segment1, segment2, ... are the values for the top of each segment of this bar. Simple bar graphs will only have one segment in each bar value. Eg: if top is 100 and there is a bar value of [ 80, 30 ] then the top of this bar will be at 80% of full height of the graph and it will have a second segment that starts at 30%. """ if hlines is not None: hlines = hlines[:] # shallow copy hlines.sort() hlines.reverse() self.data = bardata, top, hlines self._invalidate() def _get_data(self, size): """ Return (bardata, top, hlines) This function is called by render to retrieve the data for the graph. It may be overloaded to create a dynamic bar graph. This implementation will truncate the bardata list returned if not all bars will fit within maxcol. """ (maxcol, maxrow) = size bardata, top, hlines = self.data widths = self.calculate_bar_widths((maxcol, maxrow), bardata) if len(bardata) > len(widths): return bardata[:len(widths)], top, hlines return bardata, top, hlines def set_bar_width(self, width): """ Set a preferred bar width for calculate_bar_widths to use. width -- width of bar or None for automatic width adjustment """ assert width is None or width > 0 self.bar_width = width self._invalidate() def calculate_bar_widths(self, size, bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, maxrow) = size if self.bar_width is not None: return [self.bar_width] * min( len(bardata), maxcol // self.bar_width) if len(bardata) >= maxcol: return [1] * maxcol widths = [] grow = maxcol remain = len(bardata) for row in bardata: w = int(float(grow) / remain + 0.5) widths.append(w) grow -= w remain -= 1 return widths def selectable(self): """ Return False. """ return False def use_smoothed(self): return self.satt and get_encoding_mode() == "utf8" def calculate_display(self, size): """ Calculate display data. """ (maxcol, maxrow) = size bardata, top, hlines = self.get_data((maxcol, maxrow)) widths = self.calculate_bar_widths((maxcol, maxrow), bardata) if self.use_smoothed(): disp = calculate_bargraph_display(bardata, top, widths, maxrow * 8) disp = self.smooth_display(disp) else: disp = calculate_bargraph_display(bardata, top, widths, maxrow) if hlines: disp = self.hlines_display(disp, top, hlines, maxrow) return disp def hlines_display(self, disp, top, hlines, maxrow): """ Add hlines to display structure represented as bar_type tuple values: (bg, 0-5) bg is the segment that has the hline on it 0-5 is the hline graphic to use where 0 is a regular underscore and 1-5 are the UTF-8 horizontal scan line characters. """ if self.use_smoothed(): shiftr = 0 r = [(0.2, 1), (0.4, 2), (0.6, 3), (0.8, 4), (1.0, 5), ] else: shiftr = 0.5 r = [(1.0, 0), ] # reverse the hlines to match screen ordering rhl = [] for h in hlines: rh = float(top - h) * maxrow / top - shiftr if rh < 0: continue rhl.append(rh) # build a list of rows that will have hlines hrows = [] last_i = -1 for rh in rhl: i = int(rh) if i == last_i: continue f = rh - i for spl, chnum in r: if f < spl: hrows.append((i, chnum)) break last_i = i # fill hlines into disp data def fill_row(row, chnum): rout = [] for bar_type, width in row: if (type(bar_type) == int and len(self.hatt) > bar_type): rout.append(((bar_type, chnum), width)) continue rout.append((bar_type, width)) return rout o = [] k = 0 rnum = 0 for y_count, row in disp: if k >= len(hrows): o.append((y_count, row)) continue end_block = rnum + y_count while k < len(hrows) and hrows[k][0] < end_block: i, chnum = hrows[k] if i - rnum > 0: o.append((i - rnum, row)) o.append((1, fill_row(row, chnum))) rnum = i + 1 k += 1 if rnum < end_block: o.append((end_block - rnum, row)) rnum = end_block #assert 0, o return o def smooth_display(self, disp): """ smooth (col, row*8) display into (col, row) display using UTF vertical eighth characters represented as bar_type tuple values: ( fg, bg, 1-7 ) where fg is the lower segment, bg is the upper segment and 1-7 is the vertical eighth character to use. """ o = [] r = 0 # row remainder def seg_combine(a, b): (bt1, w1), (bt2, w2) = a, b if (bt1, w1) == (bt2, w2): return (bt1, w1), None, None wmin = min(w1, w2) l1 = l2 = None if w1 > w2: l1 = (bt1, w1 - w2) elif w2 > w1: l2 = (bt2, w2 - w1) if type(bt1) == tuple: return (bt1, wmin), l1, l2 if (bt2, bt1) not in self.satt: if r < 4: return (bt2, wmin), l1, l2 return (bt1, wmin), l1, l2 return ((bt2, bt1, 8 - r), wmin), l1, l2 def row_combine_last(count, row): o_count, o_row = o[-1] row = row[:] # shallow copy, so we don't destroy orig. o_row = o_row[:] l = [] while row: (bt, w), l1, l2 = seg_combine( o_row.pop(0), row.pop(0)) if l and l[-1][0] == bt: l[-1] = (bt, l[-1][1] + w) else: l.append((bt, w)) if l1: o_row = [l1] + o_row if l2: row = [l2] + row assert not o_row o[-1] = (o_count + count, l) # regroup into actual rows (8 disp rows == 1 actual row) for y_count, row in disp: if r: count = min(8 - r, y_count) row_combine_last(count, row) y_count -= count r += count r = r % 8 if not y_count: continue assert r == 0 # copy whole blocks if y_count > 7: o.append((y_count // 8 * 8, row)) y_count = y_count % 8 if not y_count: continue o.append((y_count, row)) r = y_count return [(y // 8, row) for (y, row) in o] def render(self, size, focus=False): """ Render BarGraph. """ (maxcol, maxrow) = size disp = self.calculate_display((maxcol, maxrow)) combinelist = [] for y_count, row in disp: l = [] for bar_type, width in row: if type(bar_type) == tuple: if len(bar_type) == 3: # vertical eighths fg, bg, k = bar_type a = self.satt[(fg, bg)] t = self.eighths[k] * width else: # horizontal lines bg, k = bar_type a = self.hatt[bg] t = self.hlines[k] * width else: a = self.attr[bar_type] t = self.char[bar_type] * width l.append((a, t)) c = Text(l).render((maxcol,)) assert c.rows() == 1, "Invalid characters in BarGraph!" combinelist += [(c, None, False)] * y_count canv = CanvasCombine(combinelist) return canv
class BaseScreen(with_metaclass(signals.MetaSignals, object)): """ Base class for Screen classes (raw_display.Screen, .. etc) """ signals = [UPDATE_PALETTE_ENTRY, INPUT_DESCRIPTORS_CHANGED] def __init__(self): super(BaseScreen, self).__init__() self._palette = {} self._started = False started = property(lambda self: self._started) def start(self, *args, **kwargs): """Set up the screen. If the screen has already been started, does nothing. May be used as a context manager, in which case :meth:`stop` will automatically be called at the end of the block: with screen.start(): ... You shouldn't override this method in a subclass; instead, override :meth:`_start`. """ if not self._started: self._start(*args, **kwargs) self._started = True return StoppingContext(self) def _start(self): pass def stop(self): if self._started: self._stop() self._started = False def _stop(self): pass def run_wrapper(self, fn, *args, **kwargs): """Start the screen, call a function, then stop the screen. Extra arguments are passed to `start`. Deprecated in favor of calling `start` as a context manager. """ with self.start(*args, **kwargs): return fn() def register_palette(self, palette): """Register a set of palette entries. palette -- a list of (name, like_other_name) or (name, foreground, background, mono, foreground_high, background_high) tuples The (name, like_other_name) format will copy the settings from the palette entry like_other_name, which must appear before this tuple in the list. The mono and foreground/background_high values are optional ie. the second tuple format may have 3, 4 or 6 values. See register_palette_entry() for a description of the tuple values. """ for item in palette: if len(item) in (3, 4, 6): self.register_palette_entry(*item) continue if len(item) != 2: raise ScreenError("Invalid register_palette entry: %s" % repr(item)) name, like_name = item if like_name not in self._palette: raise ScreenError("palette entry '%s' doesn't exist" % like_name) self._palette[name] = self._palette[like_name] def register_palette_entry(self, name, foreground, background, mono=None, foreground_high=None, background_high=None): """Register a single palette entry. name -- new entry/attribute name foreground -- a string containing a comma-separated foreground color and settings Color values: 'default' (use the terminal's default foreground), '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' Settings: 'bold', 'underline', 'blink', 'standout', 'strikethrough' Some terminals use 'bold' for bright colors. Most terminals ignore the 'blink' setting. If the color is not given then 'default' will be assumed. background -- a string containing the background color Background color values: 'default' (use the terminal's default background), 'black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray' mono -- a comma-separated string containing monochrome terminal settings (see "Settings" above.) None = no terminal settings (same as 'default') foreground_high -- a string containing a comma-separated foreground color and settings, standard foreground colors (see "Color values" above) or high-colors may be used High-color example values: '#009' (0% red, 0% green, 60% red, like HTML colors) '#fcc' (100% red, 80% green, 80% blue) 'g40' (40% gray, decimal), 'g#cc' (80% gray, hex), '#000', 'g0', 'g#00' (black), '#fff', 'g100', 'g#ff' (white) 'h8' (color number 8), 'h255' (color number 255) None = use foreground parameter value background_high -- a string containing the background color, standard background colors (see "Background colors" above) or high-colors (see "High-color example values" above) may be used None = use background parameter value """ basic = AttrSpec(foreground, background, 16) if type(mono) == tuple: # old style of specifying mono attributes was to put them # in a tuple. convert to comma-separated string mono = ",".join(mono) if mono is None: mono = DEFAULT mono = AttrSpec(mono, DEFAULT, 1) if foreground_high is None: foreground_high = foreground if background_high is None: background_high = background high_88 = AttrSpec(foreground_high, background_high, 88) high_256 = AttrSpec(foreground_high, background_high, 256) # 'hX' where X > 15 are different in 88/256 color, use # basic colors for 88-color mode if high colors are specified # in this way (also avoids crash when X > 87) def large_h(desc): if not desc.startswith('h'): return False if ',' in desc: desc = desc.split(',', 1)[0] num = int(desc[1:], 10) return num > 15 if large_h(foreground_high) or large_h(background_high): high_88 = basic else: high_88 = AttrSpec(foreground_high, background_high, 88) signals.emit_signal(self, UPDATE_PALETTE_ENTRY, name, basic, mono, high_88, high_256) self._palette[name] = (basic, mono, high_88, high_256)
class AppElementMixin(with_metaclass(urwid.MetaSuper)): """ Functionality common to app elements. - Run `refresh_widgets` whenever `render` or `keypress` is called. - Handle events. """ # A mapping of keys to actions (override this). key_actions = {} def refresh_widgets(self, size): pass def _mix_render(self, size, focus=False): """Wrap super `render` to refresh widgets.""" PKG_LOGGER.debug('{} rendering, size={} focus={}'.format( self.__class__.__name__, size, focus)) self.refresh_widgets(size) def _mix_keypress(self, size, key): """Wrap super `keypress` to refresh widgets.""" PKG_LOGGER.debug('{} keypress, size={} key={}'.format( self.__class__.__name__, size, repr(key))) # TODO: replace logic with urwid.command_map ? if key in self.key_actions: getattr(self, '_action_{}'.format(self.key_actions[key]))(size, key) self.refresh_widgets(size) def _action_exit(self, *_): raise urwid.ExitMainLoop() def _get_markup(self, ticket_dict, key, formatter=None): formatter = formatter or id unformatted = ticket_dict.get(key, '') try: return formatter(unformatted) except UnicodeEncodeError: if not isinstance(unformatted, six.text_type): unformatted = six.text_type(unformatted) unformatted = (unformatted).encode('ascii', errors='ignore') return formatter(unformatted) def modal_fatal_error(self, message=None, exc=None): """Cause a fatal error to be displayed and the program to exit.""" message = "Error: {}".format(message) if message else "Fatal Error" # This could be called from a parent frame or a page. parent_frame = getattr(self, 'parent_frame', self) if message: PKG_LOGGER.critical(message) parent_frame.pages['ERROR'].page_title = message details = [] if exc: PKG_LOGGER.critical(exc) details.insert(0, str(exc)) details.append("press ctrl-c to exit") parent_frame.pages['ERROR'].error_details = "\n\n".join(details) parent_frame.set_page('ERROR')