def run(self): palette = [ ("header", "white", "dark red"), ("footer", "light red", "black"), ] self._net_selector = NetworkInterfaceSelector(self._main_frame, self._memory_seconds, self._features_lag) self._ip_selector = IPSelector(self._main_frame, self._sampling_seconds, self._memory_seconds, self._net_selector) self._aggregate_stats = AggregateStatsViewer(self._main_frame, self._sampling_seconds, self._ip_selector, self._iot_classifier_dt) self._ip_stats_viewer = IPStatsViewer( self._main_frame, self._sampling_seconds, self._net_selector, self._ip_selector, self._iot_classifier_dt, self._aggregate_stats) header_text = urwid.Text( ("header", "IoT Classifier v0.1 - Press \"q\" to Exit"), align="center") head = urwid.AttrMap(header_text, "header") tree_depth = "Unbounded" if (self._max_tree_depth is not None): tree_depth = self._max_tree_depth self._footer_text = urwid.Text( "Sampling seconds: %d, Memory seconds: %d, Features lag: %d, Max tree depth: %s" % (self._sampling_seconds, self._memory_seconds, self._features_lag, tree_depth), align="left") foot = urwid.AttrMap(self._footer_text, "footer") interfaces_box = urwid.LineBox(self._net_selector.get_list_box(), title="Interfaces") aggregate_stats_box = urwid.LineBox( self._aggregate_stats.get_list_box(), title="Aggregate Statistics") ip_addresses_box = urwid.LineBox(self._ip_selector.get_list_box(), title="Tracking IP Addresses") ip_statistics_box = urwid.LineBox(self._ip_stats_viewer.get_list_box(), title="IP Statistics") left_column = urwid.Pile([("fixed", 7, interfaces_box), ip_addresses_box]) right_column = urwid.Pile([("fixed", 7, aggregate_stats_box), ip_statistics_box]) main_cols = urwid.Columns([left_column, right_column]) self._main_frame.contents["body"] = (main_cols, None) self._main_frame.contents["header"] = (head, None) self._main_frame.contents["footer"] = (foot, None) self._loop = urwid.MainLoop(self._main_frame, palette, unhandled_input=self._show_or_exit) self._net_selector.attach_to_loop(self._loop) self._ip_selector.attach_to_loop(self._loop) self._ip_stats_viewer.attach_to_loop(self._loop) self._aggregate_stats.attach_to_loop(self._loop) self._loop.run()
def help_dialog(body): """ Help dialog. """ textT = urwid.Text(('header', _('wicd-curses help')), 'right') textSH = urwid.Text([ 'This is ', ('blue', 'wicd-curses-' + CURSES_REV), ' using wicd ', unicode(daemon.Hello()), '\n' ]) textH = urwid.Text([ _('For more detailed help, consult the wicd-curses(8) man page.') + "\n", ('bold', '->'), ' and ', ('bold', '<-'), " are the right and left arrows respectively.\n" ]) text1 = urwid.Text([ ('bold', ' H h ?'), ": " + _('Display this help dialog') + "\n", ('bold', 'enter C'), ": " + _('Connect to selected network') + "\n", ('bold', ' D'), ": " + _('Disconnect from all networks') + "\n", ('bold', ' ESC'), ": " + _('Stop a connection in progress') + "\n", ('bold', ' F5 R'), ": " + _('Refresh network list') + "\n", ('bold', ' P'), ": " + _('Preferences dialog') + "\n", ]) text2 = urwid.Text([ ('bold', ' I'), ": " + _('Scan for hidden networks') + "\n", ('bold', ' S'), ": " + _('Select scripts') + "\n", ('bold', ' O'), ": " + _('Set up Ad-hoc network') + "\n", ('bold', ' X'), ": " + _('Remove settings for saved networks') + "\n", ('bold', ' ->'), ": " + _('Configure selected network') + "\n", ('bold', ' A'), ": " + _("Display 'about' dialog") + "\n", ('bold', ' F8 q Q'), ": " + _('Quit wicd-curses') + "\n", ]) textF = urwid.Text(_('Press any key to return.')) #textJ = urwid.Text(('important', 'Nobody expects the Spanish Inquisition!')) blank = urwid.Text('') cols = urwid.Columns([text1, text2]) pile = urwid.Pile([textH, cols]) fill = urwid.Filler(pile) frame = urwid.Frame(fill, header=urwid.Pile([textT, textSH]), footer=textF) dim = ui.get_cols_rows() while True: ui.draw_screen(dim, frame.render(dim, True)) keys = ui.get_input() # Don't stop because someone let go of the mouse on the frame mouse_release = False for k in keys: if urwid.VERSION < (1, 0, 0): check_mouse_event = urwid.is_mouse_event else: check_mouse_event = urwid.util.is_mouse_event if check_mouse_event(k) and k[0] == "mouse release": mouse_release = True break if mouse_release: continue if 'window resize' in keys: dim = ui.get_cols_rows() elif keys: break
def __init__(self, event_loop, palette, interpreter, config): import urwid_geventloop from bpython import repl #super(MyURWIDRepl, self).__init__(urwid_geventloop.GeventLoop(), palette, interpreter, config) repl.Repl.__init__(self, interpreter, config) self._redraw_handle = None self._redraw_pending = False self._redraw_time = 0 self.listbox = bpython.BPythonListBox(urwid.SimpleListWalker([])) self.tooltip = urwid.ListBox(urwid.SimpleListWalker([])) self.tooltip.grid = None self.overlay = bpython.Tooltip(self.listbox, self.tooltip) self.stdout_hist = '' self.frame = urwid.Frame(self.overlay) if urwid.get_encoding_mode() == 'narrow': input_filter = decoding_input_filter else: input_filter = None # This constructs a raw_display.Screen, which nabs sys.stdin/out. self.main_loop = urwid.MainLoop( self.frame, palette, event_loop=urwid_geventloop.GeventLoop(), unhandled_input=self.handle_input, input_filter=input_filter, handle_mouse=False, screen=MyScreen()) # String is straight from bpython.cli self.statusbar = bpython.Statusbar( config, bpython._(" <%s> Rewind <%s> Save <%s> Pastebin " " <%s> Pager <%s> Show Source ") % (config.undo_key, config.save_key, config.pastebin_key, config.last_output_key, config.show_source_key), self.main_loop) self.frame.set_footer(self.statusbar.widget) self.interact = bpython.URWIDInteraction(self.config, self.statusbar, self.frame) self.edits = [] self.edit = None self.current_output = None self._completion_update_suppressed = False # Bulletproof: this is a value extract_exit_value accepts. self.exit_value = () bpython.load_urwid_command_map(config) logging.root.handlers = [ MyLogHandler(self), logging.StreamHandler(file('/tmp/upnpy_browser.log', 'w')) ] logging.root.setLevel(logging.INFO) logging.getLogger('http.access').setLevel(logging.ERROR) self.devices = urwid.ListBox( urwid.SimpleListWalker([urwid.Text('Devices:')])) self.logs = urwid.ListBox(urwid.SimpleListWalker([])) self.frame.set_footer(urwid.BoxAdapter(self.logs, 15)) self.main_frame = urwid.Columns([ self.frame, ('fixed', 35, self.devices), ]) self.main_loop.widget = self.main_frame self.handler = MyDiscoverHandler(u, self) u.add_handler(self.handler)
def raw_format_flow(f): f = dict(f) pile = [] req = [] if f["extended"]: req.append( fcol(human.format_timestamp(f["req_timestamp"]), "highlight")) else: req.append(fcol(">>" if f["focus"] else " ", "focus")) if f["marked"]: req.append(fcol(SYMBOL_MARK, "mark")) if f["req_is_replay"]: req.append(fcol(SYMBOL_REPLAY, "replay")) req.append(fcol(f["req_method"], "method")) preamble = sum(i[1] for i in req) + len(req) - 1 if f["intercepted"] and not f["acked"]: uc = "intercept" elif "resp_code" in f or "err_msg" in f: uc = "text" else: uc = "title" url = f["req_url"] if f["max_url_len"] and len(url) > f["max_url_len"]: url = url[:f["max_url_len"]] + "…" if f["req_http_version"] not in ("HTTP/1.0", "HTTP/1.1"): url += " " + f["req_http_version"] req.append(urwid.Text([(uc, url)])) pile.append(urwid.Columns(req, dividechars=1)) resp = [] resp.append(("fixed", preamble, urwid.Text(""))) if "resp_code" in f: codes = { 2: "code_200", 3: "code_300", 4: "code_400", 5: "code_500", } ccol = codes.get(f["resp_code"] // 100, "code_other") resp.append(fcol(SYMBOL_RETURN, ccol)) if f["resp_is_replay"]: resp.append(fcol(SYMBOL_REPLAY, "replay")) resp.append(fcol(f["resp_code"], ccol)) if f["extended"]: resp.append(fcol(f["resp_reason"], ccol)) if f["intercepted"] and f["resp_code"] and not f["acked"]: rc = "intercept" else: rc = "text" if f["resp_ctype"]: resp.append(fcol(f["resp_ctype"], rc)) resp.append(fcol(f["resp_clen"], rc)) resp.append(fcol(f["roundtrip"], rc)) elif f["err_msg"]: resp.append(fcol(SYMBOL_RETURN, "error")) resp.append(urwid.Text([("error", f["err_msg"])])) pile.append(urwid.Columns(resp, dividechars=1)) return urwid.Pile(pile)
def tmp_generator(): for x in piles: yield urwid.Columns([x], dividechars=1, min_width=K.width)
def apply(self, ui): logging.debug('HELP') if self.commandname == 'bindings': text_att = settings.get_theming_attribute('help', 'text') title_att = settings.get_theming_attribute('help', 'title') section_att = settings.get_theming_attribute('help', 'section') # get mappings if ui.mode in settings._bindings: modemaps = dict(settings._bindings[ui.mode].items()) else: modemaps = {} is_scalar = lambda (k, v): k in settings._bindings.scalars globalmaps = dict(filter(is_scalar, settings._bindings.items())) # build table maxkeylength = len( max((modemaps).keys() + globalmaps.keys(), key=len)) keycolumnwidth = maxkeylength + 2 linewidgets = [] # mode specific maps if modemaps: linewidgets.append( urwid.Text( (section_att, '\n%s-mode specific maps' % ui.mode))) for (k, v) in modemaps.items(): line = urwid.Columns([('fixed', keycolumnwidth, urwid.Text((text_att, k))), urwid.Text((text_att, v))]) linewidgets.append(line) # global maps linewidgets.append(urwid.Text((section_att, '\nglobal maps'))) for (k, v) in globalmaps.items(): if k not in modemaps: line = urwid.Columns([('fixed', keycolumnwidth, urwid.Text((text_att, k))), urwid.Text((text_att, v))]) linewidgets.append(line) body = urwid.ListBox(linewidgets) ckey = 'cancel' titletext = 'Bindings Help (%s cancels)' % ckey box = widgets.DialogBox(body, titletext, bodyattr=text_att, titleattr=title_att) # put promptwidget as overlay on main widget overlay = urwid.Overlay(box, ui.mainframe, 'center', ('relative', 70), 'middle', ('relative', 70)) ui.show_as_root_until_keypress(overlay, 'cancel') else: logging.debug('HELP %s' % self.commandname) parser = commands.lookup_parser(self.commandname, ui.mode) if parser: ui.notify(parser.format_help(), block=True) else: ui.notify('command not known: %s' % self.commandname, priority='error')
def __init__(self, items, callback=None, args=None): cols = urwid.Columns(items) # pylint: disable-msg=E1101 self.__super.__init__(cols) self.callback = callback self.args = args
def __init__(self): self.prefix_text = urwid.Text(u' \N{WATCH} ') self.breadcrumbs = urwid.Columns([], dividechars=3) self.display_widget = urwid.Columns([('pack', self.prefix_text), self.breadcrumbs]) super(BreadCrumbBar, self).__init__(self.display_widget)
import urwid from dictionary import Dictionary class ChatListBox(urwid.Filler): pass text = urwid.Text('12345', align='right') linebox = urwid.LineBox(text, title='1234', title_align='left') listbox = urwid.ListBox(urwid.SimpleListWalker([linebox, linebox, linebox])) detaillinebox = urwid.LineBox(urwid.Text(''), title='jajaj', title_align='left') detaillistbox = urwid.ListBox( urwid.SimpleListWalker([detaillinebox, detaillinebox])) columns = urwid.Columns([(20, listbox), detaillistbox]) urwid.MainLoop(columns).run()
def get_status_text(focus_index, num_tab, title): tab_text = "Tab: " + str(focus_index + 1) + "/" + str(num_tab) return urwid.Columns([urwid.Text(title, align='left'), urwid.Text(tab_text, align='right')])
def __init__(self, scale, question_tonic_pitch, main_loop=None, keyboard_index=None, *args, **kwargs): self.main_loop = main_loop self.scale = scale self.key_index = {} self.highlighted_keys = list() tonic_pitch = scale[0] tonic_str = scale[0].note key_scale = [pitch for pitch in scale] chromatic_keys = list() diatonic_keys = list() is_key_chromatic = is_chromatic(key=tonic_str) # start (left) padding first_pad = diatonic_keys if is_key_chromatic else chromatic_keys if tonic_str == "E" or tonic_str == "B": first_pad.append(Pad(weight=1.5)) else: first_pad.append(Pad(weight=0.5)) first_chromatic = [ pitch for pitch in key_scale if len(pitch.note) == 2 ][0] for index, pitch in enumerate(key_scale): pitch_str = str(pitch) note_str = pitch.note _idx = abs(int(question_tonic_pitch) - int(pitch)) letter = keyboard_index[_idx] #letter = keyboard_index[index] bottom_text = letter middle_text = INTERVALS[keyboard_index.index(letter)][1] if is_chromatic(pitch.note): if KEY_PADS[note_str] == 1 and (pitch is not first_chromatic): chromatic_keys.append(Pad(weight=1)) chromatic_keys.append( KeyboardButton(pitch=pitch, middle=middle_text, bottom=bottom_text)) else: diatonic_keys.append( KeyboardButton(pitch=pitch, middle=middle_text, bottom=bottom_text)) # end (right) padding: if is_key_chromatic: weight = 0.5 diatonic_keys.append(Pad(weight=weight)) else: if KEY_PADS[first_chromatic.note]: if tonic_str == "E" or tonic_str == "B": weight = 0.5 else: weight = (KEY_PADS[first_chromatic.note] / 2) + 1 chromatic_keys.append(Pad(weight=weight)) if not KEY_PADS[first_chromatic.note]: weight = 0.5 chromatic_keys.append(Pad(weight=weight)) self.key_index = { item.pitch_str: item for item in chromatic_keys + diatonic_keys if type(item).__name__ == 'KeyboardButton' } chromatic = urwid.Columns(widget_list=chromatic_keys, dividechars=1) diatonic = urwid.Columns(widget_list=diatonic_keys, dividechars=1) keyboard = urwid.Pile([chromatic, diatonic]) box = urwid.LineBox(keyboard) super(Keyboard, self).__init__(body=box, min_height=10, *args, **kwargs)
br_txt1 = 'Bottom Right 1' tl_txtbox1 = urwid.Text(tl_txt1) tr_txtbox1 = urwid.Text(tr_txt1) bl_txtbox1 = urwid.Text(bl_txt1) br_txtbox1 = urwid.Text(br_txt1) tl_txtmap1 = urwid.AttrMap(tl_txtbox1, 'tl_txt_pal') tr_txtmap1 = urwid.AttrMap(tr_txtbox1, 'tr_txt_pal') bl_txtmap1 = urwid.AttrMap(bl_txtbox1, 'bl_txt_pal') br_txtmap1 = urwid.AttrMap(br_txtbox1, 'br_txt_pal') right_pile1 = urwid.Pile([tl_txtmap1, bl_txtmap1]) left_pile1 = urwid.Pile([tr_txtmap1, br_txtmap1]) column1 = urwid.Columns([right_pile1, left_pile1]) padding1 = urwid.Padding(column1, left=10, right=3) tl_txt2 = 'Top Left 2' tr_txt2 = 'Top Right 2' bl_txt2 = 'Bottom Left 2' br_txt2 = 'Bottom Right 2' tl_txtbox2 = urwid.Text(tl_txt2) tr_txtbox2 = urwid.Text(tr_txt2) bl_txtbox2 = urwid.Text(bl_txt2) br_txtbox2 = urwid.Text(br_txt2) tl_txtmap2 = urwid.AttrMap(tl_txtbox2, 'tl_txt_pal') tr_txtmap2 = urwid.AttrMap(tr_txtbox2, 'tr_txt_pal')
def main(self): #Disable kernel print messages. They make our UI ugly noout = open('/dev/null', 'w') subprocess.call(["sysctl", "-w", "kernel.printk=4 1 1 7"], stdout=noout, stderr=noout) text_header = (u"Fuel %s setup " u"Use Up/Down/Left/Right to navigate. F8 exits." % self.version) text_footer = (u"Status messages go here.") #Top and bottom lines of frame self.header = urwid.AttrWrap(urwid.Text(text_header), 'header') self.footer = urwid.AttrWrap(urwid.Text(text_footer), 'footer') #Prepare submodules loader = Loader(self) moduledir = "%s/modules" % (os.path.dirname(__file__)) self.children, self.choices = loader.load_modules(module_dir=moduledir) if len(self.children) == 0: import sys sys.exit(1) #Build list of choices excluding visible self.visiblechoices = [] for child, choice in zip(self.children, self.choices): if child.visible: self.visiblechoices.append(choice) self.menuitems = self.menu(u'Menu', self.visiblechoices) menufill = urwid.Filler(self.menuitems, 'top', 40) self.menubox = urwid.BoxAdapter(menufill, 40) self.child = self.children[0] self.childpage = self.child.screenUI() self.childfill = urwid.Filler(self.childpage, 'top', 22) self.childbox = urwid.BoxAdapter(self.childfill, 22) self.cols = urwid.Columns( [ ('fixed', 20, urwid.Pile([ urwid.AttrMap(self.menubox, 'bright'), urwid.Divider(" ")])), ('weight', 3, urwid.Pile([ urwid.Divider(" "), self.childbox, urwid.Divider(" ")])) ], 1) self.listwalker = urwid.SimpleListWalker([self.cols]) #self.listwalker = urwid.TreeWalker([self.cols]) self.listbox = urwid.ListBox(self.listwalker) #listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) self.frame = urwid.Frame(urwid.AttrWrap(self.listbox, 'body'), header=self.header, footer=self.footer) palette = \ [ ('body', 'black', 'light gray', 'standout'), ('reverse', 'light gray', 'black'), ('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'), ('bright', 'dark gray', 'light gray', ('bold', 'standout')), ('buttn', 'black', 'dark cyan'), ('buttnf', 'white', 'dark blue', 'bold'), ('light gray', 'white', 'light gray', 'bold'), ('red', 'dark red', 'light gray', 'bold'), ('black', 'black', 'black', 'bold'), ] # use appropriate Screen class if urwid.web_display.is_web_request(): self.screen = urwid.web_display.Screen() else: self.screen = urwid.raw_display.Screen() def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() if key == 'shift tab': self.child.walker.tab_prev() if key == 'tab': self.child.walker.tab_next() self.mainloop = urwid.MainLoop(self.frame, palette, self.screen, unhandled_input=unhandled) #Initialize each module completely before any events are handled for child in reversed(self.children): self.setChildScreen(name=child.name) #Prepare DNS for resolution dnsobj = self.children[int(self.choices.index("DNS & Hostname"))] dnsobj.setEtcResolv() signal.signal(signal.SIGUSR1, self.handle_sigusr1) self.mainloop.run()
def edit(self, event, always_save=False, external_edit=False): """create an EventEditor and display it :param event: event to edit :type event: khal.event.Event :param always_save: even save the event if it hasn't changed :type always_save: bool """ if event.readonly: self.pane.window.alert( ('alert', 'Calendar `{}` is read-only.'.format(event.calendar))) return if isinstance(event.start_local, dt.datetime): original_start = event.start_local.date() else: original_start = event.start_local if isinstance(event.end_local, dt.datetime): original_end = event.end_local.date() else: original_end = event.end_local def update_colors(new_start, new_end, everything=False): """reset colors in the calendar widget and dates in DayWalker between min(new_start, original_start) :type new_start: datetime.date :type new_end: datetime.date :param everything: set to True if event is a recurring one, than everything gets reseted """ # TODO cleverer support for recurring events, where more than start and # end dates are affected (complicated) if isinstance(new_start, dt.datetime): new_start = new_start.date() if isinstance(new_end, dt.datetime): new_end = new_end.date() start = min(original_start, new_start) end = max(original_end, new_end) self.pane.eventscolumn.base_widget.update(start, end, everything) # set original focus date self.pane.calendar.original_widget.set_focus_date(new_start) self.pane.eventscolumn.original_widget.set_focus_date(new_start) if self.editor: self.pane.window.backtrack() assert not self.editor if external_edit: self.pane.window.loop.screen.stop() text = click.edit(event.raw) self.pane.window.loop.screen.start() if text is None: return # KeyErrors can occurr here when we destroy DTSTART, # otherwise, even broken .ics files seem to be no problem new_event = Event.fromString( text, locale=self._conf['locale'], href=event.href, calendar=event.calendar, etag=event.etag, ) self.pane.collection.update(new_event) update_colors(new_event.start_local, new_event.end_local, (event.recurring or new_event.recurring)) else: self.editor = True editor = EventEditor(self.pane, event, update_colors, always_save=always_save) ContainerWidget = linebox[self.pane._conf['view']['frame']] new_pane = urwid.Columns( [('weight', 2, ContainerWidget(editor)), ('weight', 1, ContainerWidget(self.dlistbox))], dividechars=0, focus_column=0) new_pane.title = editor.title def teardown(data): self.editor = False self.pane.window.open(new_pane, callback=teardown)
def onClick_set_parameters_from_main(self, button): # Title and divider title_set_params = urwid.Text( "Set parameters and directories\nYour base directory is {}".format( self.base_dir), align="center") div = urwid.Divider() # Ask and answer ask_flen = urwid.Text('Focal length of the camera in mm:\n', align="left") answer_flen = self.editors.get_editor("flen") ask_ori_video_shape = urwid.Text( 'Original video shape (height,width) in pixel:\n', align="left") answer_ori_video_shape = self.editors.get_editor("ori_video_shape") ask_sensor_size = urwid.Text('Sensor size (height,width) in mm:\n', align="left") answer_sensor_size = self.editors.get_editor("sensor_size") ask_GPU = urwid.Text('GPU number:\n', align="left") answer_GPU = self.editors.get_editor("GPU") ask_batch = urwid.Text('Batch size:\n', align="left") answer_batch = self.editors.get_editor("batch_size") ask_fitting_dir = urwid.Text( 'Directory of videos for model fitting:\n', align="left") answer_fitting_dir = self.editors.get_editor("fitting_dir") ask_eyeballmodel_dir = urwid.Text( 'Directory of fitted 3D eyeball models:\n', align="left") answer_eyeballmodel_dir = self.editors.get_editor("eyeballmodel_dir") ask_inference_dir = urwid.Text( 'Directory of videos for gaze inference:\n', align="left") answer_inference_dir = self.editors.get_editor("inference_dir") ask_results_dir = urwid.Text('Directory of output results:\n', align="left") answer_results_dir = self.editors.get_editor("results_dir") # Buttons for save/back save_button = Button_centered("Save workspace parameters") urwid.connect_signal(save_button, 'click', self.onClick_save_params) load_button = Button_centered("Load workspace parameters") urwid.connect_signal(load_button, 'click', self.onClick_load_params) back_button = Button_centered("Back") urwid.connect_signal(back_button, 'click', self.onClick_back_from_params) # Constructing piles and columns col_flen = urwid.Columns([ask_flen, answer_flen]) col_ori_video_shape = urwid.Columns( [ask_ori_video_shape, answer_ori_video_shape]) col_sensor_size = urwid.Columns([ask_sensor_size, answer_sensor_size]) col_GPU = urwid.Columns([ask_GPU, answer_GPU]) col_batch = urwid.Columns([ask_batch, answer_batch]) col_fitting_dir = urwid.Columns([ask_fitting_dir, answer_fitting_dir]) col_eyeballmodel_dir = urwid.Columns( [ask_eyeballmodel_dir, answer_eyeballmodel_dir]) col_inference_dir = urwid.Columns( [ask_inference_dir, answer_inference_dir]) col_results_dir = urwid.Columns([ask_results_dir, answer_results_dir]) all_piles = urwid.Pile([ col_flen, col_ori_video_shape, col_sensor_size, col_GPU, col_batch, col_fitting_dir, col_eyeballmodel_dir, col_inference_dir, col_results_dir ]) whole_fill = urwid.Filler( urwid.Pile([ title_set_params, div, all_piles, urwid.AttrMap(save_button, None, 'reversed'), urwid.AttrMap(load_button, None, 'reversed'), urwid.AttrMap(back_button, None, 'reversed') ])) # Set the interface self.main_widget.original_widget = whole_fill
def _resources(self): self.view_widgets.append(RowWidget([SelectableText("")])) self.view_widgets.append( RowWidget([ SelectableText("Resource Usage", maps=get_map("main_list_white")) ])) cpu_g = ContainerInfoGraph("graph_lines_cpu_tips", "graph_lines_cpu") mem_g = ContainerInfoGraph("graph_lines_mem_tips", "graph_lines_mem") blk_r_g = ContainerInfoGraph("graph_lines_blkio_r_tips", "graph_lines_blkio_r") blk_w_g = ContainerInfoGraph("graph_lines_blkio_w_tips", "graph_lines_blkio_w") net_r_g = ContainerInfoGraph("graph_lines_net_r_tips", "graph_lines_net_r") net_w_g = ContainerInfoGraph("graph_lines_net_w_tips", "graph_lines_net_w") cpu_label = ColorText("CPU ", "graph_lines_cpu_legend") cpu_value = ColorText("0.0 %", "graph_lines_cpu_legend") mem_label = ColorText("Memory ", "graph_lines_mem_legend") mem_value = ColorText("0.0 %", "graph_lines_mem_legend") blk_r_label = ColorText("I/O Read ", "graph_lines_blkio_r_legend") blk_r_value = ColorText("0 B", "graph_lines_blkio_r_legend") blk_w_label = ColorText("I/O Write ", "graph_lines_blkio_w_legend") blk_w_value = ColorText("0 B", "graph_lines_blkio_w_legend") net_r_label = ColorText("Net Rx ", "graph_lines_net_r_legend") net_r_value = ColorText("0 B", "graph_lines_net_r_legend") net_w_label = ColorText("Net Tx ", "graph_lines_net_w_legend") net_w_value = ColorText("0 B", "graph_lines_net_w_legend") self.view_widgets.append( urwid.Columns([ BoxAdapter(cpu_g, 12), BoxAdapter(mem_g, 12), ("weight", 0.5, BoxAdapter(blk_r_g, 12)), ("weight", 0.5, BoxAdapter(blk_w_g, 12)), ("weight", 0.5, BoxAdapter(net_r_g, 12)), ("weight", 0.5, BoxAdapter(net_w_g, 12)), BoxAdapter( UnselectableListBox( urwid.SimpleFocusListWalker([ UnselectableRowWidget([(12, cpu_label), cpu_value]), UnselectableRowWidget([(12, mem_label), mem_value]), UnselectableRowWidget([(12, blk_r_label), blk_r_value]), UnselectableRowWidget([(12, blk_w_label), blk_w_value]), UnselectableRowWidget([(12, net_r_label), net_r_value]), UnselectableRowWidget([(12, net_w_label), net_w_value]), ])), 12), ])) self.view_widgets.append(RowWidget([SelectableText("")])) @log_traceback def realtime_updates(): g = self.docker_container.stats().response while True: try: update = next(g) except Exception as ex: if "Timeout" in ex.__class__.__name__: logger.info("timeout when reading stats: %r", ex) g = self.docker_container.stats().response continue logger.error("error while getting stats: %r", ex) self.ui.notify_message("Error while getting stats: %s" % ex, level="error") break if self.stop.is_set(): break logger.debug(update) cpu_percent = update["cpu_percent"] cpu_value.text = "%.2f %%" % cpu_percent cpu_g.rotate_value(int(cpu_percent), max_val=100) mem_percent = update["mem_percent"] mem_current = humanize_bytes(update["mem_current"]) mem_value.text = "%.2f %% (%s)" % (mem_percent, mem_current) mem_g.rotate_value(int(mem_percent), max_val=100) blk_read = update["blk_read"] blk_write = update["blk_write"] blk_r_value.text = humanize_bytes(blk_read) blk_w_value.text = humanize_bytes(blk_write) r_max_val = blk_r_g.rotate_value(blk_read, adaptive_max=True) w_max_val = blk_w_g.rotate_value(blk_write, adaptive_max=True) blk_r_g.set_max(max((r_max_val, w_max_val))) blk_w_g.set_max(max((r_max_val, w_max_val))) net_read = update["net_rx"] net_write = update["net_tx"] net_r_value.text = humanize_bytes(net_read) net_w_value.text = humanize_bytes(net_write) r_max_val = net_r_g.rotate_value(net_read, adaptive_max=True) w_max_val = net_w_g.rotate_value(net_write, adaptive_max=True) net_r_g.set_max(max((r_max_val, w_max_val))) net_w_g.set_max(max((r_max_val, w_max_val))) self.thread = threading.Thread(target=realtime_updates, daemon=True) self.thread.start()
def raw_format_table(f): f = dict(f) pile = [] req = [] cursor = [' ', 'focus'] if f.get('resp_is_replay', False): cursor[0] = SYMBOL_REPLAY cursor[1] = 'replay' if f['marked']: if cursor[0] == ' ': cursor[0] = SYMBOL_MARK cursor[1] = 'mark' if f['focus']: cursor[0] = '>' req.append(fcol(*cursor)) if f["two_line"]: req.append( TruncatedText(f["req_url"], colorize_url(f["req_url"]), 'left')) pile.append(urwid.Columns(req, dividechars=1)) req = [] req.append(fcol(' ', 'text')) if f["intercepted"] and not f["acked"]: uc = "intercept" elif "resp_code" in f or f["err_msg"] is not None: uc = "highlight" else: uc = "title" if f["extended"]: s = human.format_timestamp(f["req_timestamp"]) else: s = datetime.datetime.fromtimestamp( time.mktime(time.localtime( f["req_timestamp"]))).strftime("%H:%M:%S") req.append(fcol(s, uc)) methods = { 'GET': 'method_get', 'POST': 'method_post', 'DELETE': 'method_delete', 'HEAD': 'method_head', 'PUT': 'method_put' } uc = methods.get(f["req_method"], "method_other") if f['extended']: req.append(fcol(f["req_method"], uc)) if f["req_promise"]: req.append(fcol('PUSH_PROMISE', 'method_http2_push')) else: if f["req_promise"]: uc = 'method_http2_push' req.append(("fixed", 4, truncated_plain(f["req_method"], uc))) if f["two_line"]: req.append(fcol(f["req_http_version"], 'text')) else: schemes = { 'http': 'scheme_http', 'https': 'scheme_https', } req.append( fcol(fixlen(f["req_scheme"].upper(), 5), schemes.get(f["req_scheme"], "scheme_other"))) req.append(('weight', 0.25, TruncatedText(f["req_host"], colorize_host(f["req_host"]), 'right'))) req.append(('weight', 1.0, TruncatedText(f["req_path"], colorize_req(f["req_path"]), 'left'))) ret = (' ' * len(SYMBOL_RETURN), 'text') status = ('', 'text') content = ('', 'text') size = ('', 'text') duration = ('', 'text') if "resp_code" in f: codes = { 2: "code_200", 3: "code_300", 4: "code_400", 5: "code_500", } ccol = codes.get(f["resp_code"] // 100, "code_other") ret = (SYMBOL_RETURN, ccol) status = (str(f["resp_code"]), ccol) if f["resp_len"] < 0: if f["intercepted"] and f["resp_code"] and not f["acked"]: rc = "intercept" else: rc = "content_none" if f["resp_len"] == -1: contentdesc = "[content missing]" else: contentdesc = "[no content]" content = (contentdesc, rc) else: if f["resp_ctype"]: ctype = f["resp_ctype"].split(";")[0] if ctype.endswith('/javascript'): rc = 'content_script' elif ctype.startswith('text/'): rc = 'content_text' elif (ctype.startswith('image/') or ctype.startswith('video/') or ctype.startswith('font/') or "/x-font-" in ctype): rc = 'content_media' elif ctype.endswith('/json') or ctype.endswith('/xml'): rc = 'content_data' elif ctype.startswith('application/'): rc = 'content_raw' else: rc = 'content_other' content = (ctype, rc) rc = 'gradient_%02d' % int( 99 - 100 * min(math.log2(1 + f["resp_len"]) / 20, 0.99)) size_str = human.pretty_size(f["resp_len"]) if not f['extended']: # shorten to 5 chars max if len(size_str) > 5: size_str = size_str[0:4].rstrip('.') + size_str[-1:] size = (size_str, rc) if f['duration'] is not None: rc = 'gradient_%02d' % int( 99 - 100 * min(math.log2(1 + 1000 * f['duration']) / 12, 0.99)) duration = (human.pretty_duration(f['duration']), rc) elif f["err_msg"]: status = ('Err', 'error') content = f["err_msg"], 'error' if f["two_line"]: req.append(fcol(*ret)) req.append(fcol(fixlen(status[0], 3), status[1])) req.append(('weight', 0.15, truncated_plain(content[0], content[1], 'right'))) if f['extended']: req.append(fcol(*size)) else: req.append(fcol(fixlen_r(size[0], 5), size[1])) req.append(fcol(fixlen_r(duration[0], 5), duration[1])) pile.append(urwid.Columns(req, dividechars=1, min_width=15)) return urwid.Pile(pile)
def prompt(self, prefix, text=u'', completer=None, tab=0, history=None): """ prompt for text input. This returns a :class:`asyncio.Future`, which will have a string value :param prefix: text to print before the input field :type prefix: str :param text: initial content of the input field :type text: str :param completer: completion object to use :type completer: :meth:`alot.completion.Completer` :param tab: number of tabs to press initially (to select completion results) :type tab: int :param history: history to be used for up/down keys :type history: list of str :rtype: asyncio.Future """ history = history or [] fut = asyncio.get_event_loop().create_future() oldroot = self.mainloop.widget def select_or_cancel(text): """Restore the main screen and invoce the callback (delayed return) with the given text.""" self.mainloop.widget = oldroot self._passall = False fut.set_result(text) def cerror(e): logging.error(e) self.notify('completion error: %s' % str(e), priority='error') self.update() prefix = prefix + settings.get('prompt_suffix') # set up widgets leftpart = urwid.Text(prefix, align='left') editpart = CompleteEdit(completer, on_exit=select_or_cancel, edit_text=text, history=history, on_error=cerror) for _ in range(tab): # hit some tabs editpart.keypress((0, ), 'tab') # build promptwidget both = urwid.Columns([ ('fixed', len(prefix), leftpart), ('weight', 1, editpart), ]) att = settings.get_theming_attribute('global', 'prompt') both = urwid.AttrMap(both, att) # put promptwidget as overlay on main widget overlay = urwid.Overlay(both, oldroot, ('fixed left', 0), ('fixed right', 0), ('fixed bottom', 1), None) self.mainloop.widget = overlay self._passall = True return fut
self.draw() return urwid.Pile.render(self, size, focus) def next_blob(): pass header = urwid.AttrWrap(urwid.Text("The header!", align="center"), "header") footer = urwid.AttrWrap(urwid.Text("The footer"), "footer") items = [] for i in range(100): items.append(ItemWidget(i, "Item {0}".format(i))) browser_header = urwid.AttrMap(urwid.Text("selected:"), "head") browser_listbox = urwid.ListBox(urwid.SimpleListWalker(items)) browser_view = urwid.Frame(urwid.AttrWrap(browser_listbox, "body"), header=browser_header) blobs = BlobWidget() footer = urwid.Columns([urwid.Text("Info\nSecond kube"), blobs]) main_frame = urwid.AttrWrap(urwid.Frame(browser_view, focus_part="body"), "default") main_frame.set_header(header) main_frame.set_footer(footer) loop = urwid.MainLoop(main_frame, UI.palette, unhandled_input=handle_input) loop.run()
def choice(self, message, choices=None, select=None, cancel=None, msg_position='above', choices_to_return=None): """ prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choices :type choices: dict: keymap->choice (both str) :param choices_to_return: dict of possible choices to return for the choices of the choices of paramter :type choices: dict: keymap->choice key is str and value is any obj) :param select: choice to return if enter/return is hit. Ignored if set to `None`. :type select: str :param cancel: choice to return if escape is hit. Ignored if set to `None`. :type cancel: str :param msg_position: determines if `message` is above or left of the prompt. Must be `above` or `left`. :type msg_position: str :rtype: asyncio.Future """ choices = choices or {'y': 'yes', 'n': 'no'} assert select is None or select in choices.values() assert cancel is None or cancel in choices.values() assert msg_position in ['left', 'above'] fut = asyncio.get_event_loop().create_future( ) # Create a returned future oldroot = self.mainloop.widget def select_or_cancel(text): """Restore the main screen and invoce the callback (delayed return) with the given text.""" self.mainloop.widget = oldroot self._passall = False fut.set_result(text) # set up widgets msgpart = urwid.Text(message) choicespart = ChoiceWidget(choices, choices_to_return=choices_to_return, callback=select_or_cancel, select=select, cancel=cancel) # build widget if msg_position == 'left': both = urwid.Columns([ ('fixed', len(message), msgpart), ('weight', 1, choicespart), ], dividechars=1) else: # above both = urwid.Pile([msgpart, choicespart]) att = settings.get_theming_attribute('global', 'prompt') both = urwid.AttrMap(both, att, att) # put promptwidget as overlay on main widget overlay = urwid.Overlay(both, oldroot, ('fixed left', 0), ('fixed right', 0), ('fixed bottom', 1), None) self.mainloop.widget = overlay self._passall = True return fut
class DisplayTest(urwid.WidgetWrap): """ Display test result """ currently_displayed = 0 top_columns = urwid.Columns([]) test_result = urwid.Pile([]) def __init__(self, result): self.result = result self.total = len(result) self.update_view('next_callback') walker = urwid.SimpleListWalker([ urwid.Padding(self.top_columns, left=3, right=3), self.test_result ]) adapter = urwid.BoxAdapter(urwid.ListBox(walker), height=14) urwid.WidgetWrap.__init__(self, adapter) @staticmethod def test_display(test, options): """ Compose the element that will display the test Returns: [urwid.Widget]: """ empty_line = (DIV, options('weight', 1)) title = (urwid.Text( ('text bold', test['title'][0].upper() + test['title'][1:])), options('weight', 1)) caption = (urwid.Text(('text', test['caption'])), options('weight', 1)) severity = (urwid.Text([('input', 'Severity: '), ('text', ['HIGH', 'Medium', 'Low'][test['severity']])]), options('weight', 1)) result = (urwid.Text([ ('input', 'Result: '), (['failed', 'passed', 'warning', 'info'][test['result']], ['✘ FAILED', '✔ PASSED', '! WARNING', '* OMITTED'][test['result']]) ]), options('weight', 1)) if isinstance(test['message'], list): message_string = test['message'][0] + \ test['extra_data'] + test['message'][1] else: message_string = test['message'] message = (urwid.Text(('text', message_string)), options('weight', 1)) return [ empty_line, title, empty_line, severity, caption, result, message ] def get_top_text(self): """ Returns: tuple(str,str): PALETTE , Test n/total """ return 'header red', 'Test ' + \ str(self.currently_displayed) + '/' + str(self.total) def get_top_row(self, current, options): def get_button(sign, text): return urwid.AttrMap( TextButton(sign, on_press=(lambda _: self.update_view(text))), 'button') next_btn = get_button('>', 'next_callback') prev_btn = get_button('<', 'prev') top_row = [] if current > 1: top_row.append((prev_btn, options('weight', 0))) top_row.append((urwid.Padding(urwid.Text(self.get_top_text()), left=25), options('weight', 1))) if current < len(self.result): top_row.append((next_btn, options('weight', 0.2))) return top_row def update_currently_displayed(self, btn): self.currently_displayed += 1 if btn is 'next_callback' else -1 def set_focus_position(self, current, btn): focus = 0 # moving to the left if current <= 1: focus = 1 # first element elif btn is 'next_callback' and current < self.total: focus = 2 # moving to the right self.top_columns.focus_position = focus def update_view(self, btn): self.update_currently_displayed(btn) self.top_columns.contents = self.get_top_row(self.currently_displayed, self.top_columns.options) self.set_focus_position(self.currently_displayed, btn) self.test_result.contents = self.test_display( self.result[self.currently_displayed - 1], self.test_result.options)
def build_line(msg, prio): cols = urwid.Columns([urwid.Text(msg)]) att = settings.get_theming_attribute('global', 'notify_' + prio) return urwid.AttrMap(cols, att)
def render_text(text, K): # XXX: make this code lazy-reader reader-proxy aware txts = [make_text(t, K.width) for t in text.split('\n')] K.txts = txts piles = [] p = Pile([]) for t in txts[:]: #if 'What emerges' in t.text: pu.db p.contents.append((t, p.options())) t_size = t.rows((K.width, )) #if piles and h(piles[-1]) > height: pu.db while h(p, K) > K.height: # Add a new pile, and send the trimmings in there piles.append(p) d = h(t, K) - (h(p, K) - K.height) #if d <= 0: pu.db # start the next column p_new = Pile([]) t_extra = trim(t, d, K.width) # TODO: include diff status in here, and line numbers p_new.contents.append((t_extra, p.options())) p = p_new t = t_extra #if piles and h(piles[-1]) > height: # # ACK! # break if h(p, K) == K.height: piles.append(p) # start the next column p = Pile([]) # all done, don't forget the last pile which we haven't added to the list yet piles.append(p) palette = [('black', 'light gray', 'black'), ('heading', 'black', 'light gray'), ('important', 'black', 'light cyan'), ('line', 'black', 'light gray'), ('options', 'dark gray', 'black'), ('focus heading', 'white', 'dark red'), ('focus line', 'black', 'dark red'), ('diff old', 'dark red', 'black'), ('diff new', 'dark green', 'black'), ('focus options', 'black', 'light gray'), ('pg normal', 'white', 'black', 'standout'), ('pg complete', 'white', 'dark magenta'), ('selected', 'white', 'dark blue')] #piles = urwid.ListBox(urwid.SimpleFocusListWalker(piles)) #cols = piles #fill = cols dc = int(K.max_width / K.width) # number of displayed columns while len(piles) < int(dc): piles.append(Pile([])) cols = urwid.Columns(piles[:dc], dividechars=1, min_width=K.width) K.cols = cols col_widths = cols.column_widths(K.screen.get_cols_rows()) K.displayed_columns = len(col_widths) def tmp_generator(): for x in piles: yield urwid.Columns([x], dividechars=1, min_width=K.width) K.reader = LazyReader(tmp_generator()) # XXX: I need to subclass columns, and make it so the keypress function # "rolls" the piles under the hood, and re-renders all the widgets. # # self.contents.append(self.contents.pop(0)) # #cols.box_columns.extend(cols.widget_list) #grid = urwid.GridFlow(txts, cell_width=20, h_sep=4, v_sep=0, align='left') fill = urwid.Filler(cols, 'top', top=K.top_margin) K.total_cols = len(piles) # XXX: this is not the full story, it ignores the borders between columns c_columns = [sum(col_widths[:i + 1]) for i in range(K.displayed_columns)] border = (K.max_width - c_columns[-1]) / K.displayed_columns def xpos_to_col(pos): for i, c in enumerate(c_columns): if pos < (c + i * border): return i K.xpos_to_col = xpos_to_col pbar = ProgressBar('pg normal', 'pg complete', K.displayed_columns, K.total_cols) K.pbar = pbar p = urwid.ListBox(urwid.SimpleListWalker([pbar])) all = Pile([ fill, (1, p), ]) cmd_line_text = urwid.Edit(K.fname) K.cmd_line_text = cmd_line_text #cmd_line_prompt = urwid.Text('hi there') #cmd_line_combined = urwid.Filler([cmd_line_prompt, cmd_line_text]) #all = urwid.Frame(body=all, footer=cmd_line_combined) K.all = urwid.Frame(body=all, footer=cmd_line_text) K.loop = urwid.MainLoop(K.all, palette, K.screen, unhandled_input=show_or_exit) K.loop.exit = urwid.Text(" Help? ") #IPython.embed() if K.args.diff: set_cmd("set ft=diff".split(), K) elif have_pygments: set_cmd(("set ft=" + lexer.name.split()[0].lower()).split(), K) if K.args.quick: K.loop.set_alarm_in(1, lambda x, y: quit()) pbh = progress_bar_handler(p) K.pbh = pbh next(pbh) try: K.loop.run() except KeyboardInterrupt: pass
avg_t, urwid.Text("max"), max_t, urwid.Text("spot"), spot_t, ]) from_date = urwid.Text("") mid_date = urwid.Text("", align="center") to_date = urwid.Text("", align="right") cols = urwid.Columns( [ (4, gscale), urwid.Frame(graph, footer=urwid.Columns([from_date, mid_date, to_date])), (10, stats), ], dividechars=1, ) def fmtdate(d): return d.strftime("%H:%M") def ceil(val, mult=1): return math.ceil(val / mult) * mult def floor(val, mult=1):
def __init__(self, conf, event, collection=None): self.conf = conf self.collection = collection self.event = event divider = urwid.Divider(' ') lines = [] lines.append( urwid.Columns([ urwid.Text(event.vevent['SUMMARY']), urwid.Text('Calendar: ' + event.calendar) ], dividechars=2)) lines.append(divider) # show organizer try: organizer = to_unicode(event.vevent['ORGANIZER'], 'utf-8').split(':') lines.append( urwid.Text('Organizer: ' + organizer[len(organizer) - 1])) except KeyError: pass # description and location for key, desc in [('LOCATION', 'Location'), ('DESCRIPTION', 'Description')]: try: lines.append( urwid.Text(desc + ': ' + to_unicode(event.vevent[key], 'utf-8'))) except KeyError: pass if lines[-1] != divider: lines.append(divider) # start and end time/date if event.allday: startstr = event.start.strftime(self.conf['locale']['dateformat']) end = event.end - timedelta(days=1) endstr = end.strftime(self.conf['locale']['dateformat']) else: startstr = event.start.strftime('{} {}'.format( self.conf['locale']['dateformat'], self.conf['locale']['timeformat'])) if event.start.date == event.end.date: endstr = event.end.strftime(self.conf['locale']['timeformat']) else: endstr = event.end.strftime('{} {}'.format( self.conf['locale']['dateformat'], self.conf['locale']['timeformat'])) if startstr == endstr: lines.append(urwid.Text('On: ' + startstr)) else: lines.append(urwid.Text('From: ' + startstr)) lines.append(urwid.Text('To: ' + endstr)) pile = CPile(lines) urwid.WidgetWrap.__init__(self, urwid.Filler(pile, valign='top'))
def __init__(self,fName): CaseBuilderTUI.__init__(self) self.desc=CaseBuilderFile(fName) # print "Read case description",self.desc.name() items=[] items.append( urwid.AttrWrap( urwid.Text("Builder Template: " + self.desc.name()+"\n"+self.desc.description() ),'banner')) items.append( urwid.AttrWrap( urwid.Divider("-"),'banner')) items.append( urwid.AttrWrap( urwid.Text("Data Template: " + self.desc.templatePath() ),'banner')) items.append( urwid.AttrWrap( urwid.Divider("="),'banner')) self.caseField=urwid.Edit(('banner',"Name of the generated case ")) items.append(urwid.AttrWrap(self.caseField,'editbox')) items.append( urwid.AttrWrap( urwid.Divider("="),'banner')) args=self.desc.arguments() mLen=apply(max,map(len,args)) aDesc=self.desc.argumentDescriptions() aDef=self.desc.argumentDefaults() self.argfields=[] groups=[None]+self.desc.argumentGroups() gDesc=self.desc.argumentGroupDescription() for g in groups: if g!=None: items.append(urwid.AttrWrap(urwid.Text("\n"+g+" - "+gDesc[g]),"group")) for a in self.desc.groupArguments(g): items.append(urwid.Text(aDesc[a])) fld=urwid.Edit(('banner',a+" "*(mLen+1-len(a))),edit_text=aDef[a]) self.argfields.append(fld) items.append(urwid.AttrWrap(fld,'editbox')) items.append( urwid.AttrWrap( urwid.Divider("="),'banner')) self.forceCheck=urwid.CheckBox("ForceOverwrite") items.append( urwid.Columns( [ urwid.AttrWrap(self.forceCheck,'bgbutton') ] )) items.append( urwid.Padding( urwid.AttrWrap(urwid.Button("Generate Case",self.doGenerate),'bgbutton','button'), align='center',width=20)) self.items = urwid.SimpleListWalker(items) self.listbox = urwid.ListBox(self.items) self.statusText = urwid.Text("Dummy") footer = urwid.AttrWrap( self.statusText, 'header' ) self.setStatus("") top = urwid.Frame(self.listbox, footer=footer) self.top=urwid.AttrWrap(top,'bg') self.done=False
def __init__(self): self.conn_status = False self.tcount = 0 # Counter for connection twirl indicator self.size = ui.get_cols_rows() # Happy screen saying that you can't do anything because we're scanning # for networks. :-) self.screen_locker = urwid.Filler( urwid.Text( ('important', _('Scanning networks... stand by...')), align='center' ) ) self.no_wlan = urwid.Filler( urwid.Text( ('important', _('No wireless networks found.')), align='center' ) ) self.TITLE = _('Wicd Curses Interface') self.WIRED_IDX = 1 self.WLESS_IDX = 3 header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'), 'header') self.wiredH = urwid.Filler(urwid.Text(_('Wired Networks'))) self.list_header = urwid.AttrWrap( urwid.Text(gen_list_header()), 'listbar' ) self.wlessH = NSelListBox([ urwid.Text(_('Wireless Networks')), self.list_header ]) # Init this earlier to make update_status happy self.update_tag = None # FIXME: This should be two variables self.focusloc = [1, 0] # These are empty to make sure that things go my way. wiredL, wlessL = [], [] self.frame = None self.diag = None self.wiredCB = urwid.Filler(WiredComboBox(wiredL)) self.wlessLB = urwid.ListBox(wlessL) self.update_netlist(force_check=True, firstrun=True) # Keymappings proposed by nanotube in #wicd keys = [ ('H', _('Help'), None), ('right', _('Config'), None), #(' ', ' ', None), ('K', _('RfKill'), None), ('C', _('Connect'), None), ('D', _('Disconn'), None), ('R', _('Refresh'), None), ('P', _('Prefs'), None), ('I', _('Hidden'), None), ('A', _('About'), None), ('Q', _('Quit'), loop.quit) ] self.primaryCols = OptCols(keys, self.handle_keys) self.status_label = urwid.AttrWrap(urwid.Text(''), 'important') self.footer2 = urwid.Columns([self.status_label]) self.footerList = urwid.Pile([self.primaryCols, self.footer2]) self.frame = urwid.Frame(self.thePile, header=header, footer=self.footerList) self.wiredCB.get_body().build_combobox(self.frame, ui, 3) # Init the other columns used in the program self.init_other_optcols() self.frame.set_body(self.thePile) # Booleans gallore! self.prev_state = False self.connecting = False self.screen_locked = False self.do_diag_lock = False # Whether the screen is locked beneath a dialog self.diag_type = 'none' # The type of dialog that is up self.scanning = False self.pref = None self.update_status()
header = apply_markup(urwid.Text(header_text), 'header') footer = apply_markup(urwid.Text(footer_text), 'footer') status_widget = apply_markup(urwid.Text(''), 'status_line') command_output = apply_markup(urwid.Text(''), 'command_output') onclick = lambda widget: (handle_click( status_widget=status_widget.original_widget, command_output_widget=command_output.original_widget, clicked_widget=widget)) displayed_widgets = [] if args.header_text or not Config.HIDE_HEADER: displayed_widgets.append(header) for button_row in BUTTON_ROWS: columns = urwid.Columns([]) for index, text in enumerate(button_row): label = find_command(text) number_of_wide_chars = len([ char for char in list(label) if unicodedata.east_asian_width(char) == 'W' ]) col_width = (len(label) + 2 + number_of_wide_chars) if Config.HORIZONTAL_PADDING == 'auto': col_opts = columns.options('weight', 1) else: if not Config.HORIZONTAL_PADDING: Config.HORIZONTAL_PADDING = [0, 0] if isinstance(Config.HORIZONTAL_PADDING, int): Config.HORIZONTAL_PADDING = [ Config.HORIZONTAL_PADDING, Config.HORIZONTAL_PADDING
def main(): text_header = (u"Welcome to the urwid tour! " u"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits.") text_intro = [('important', u"Text"), u" widgets are the most common in " u"any urwid program. This Text widget was created " u"without setting the wrap or align mode, so it " u"defaults to left alignment with wrapping on space " u"characters. ", ('important', u"Change the window width"), u" to see how the widgets on this page react. " u"This Text widget is wrapped with a ", ('important', u"Padding"), u" widget to keep it indented on the left and right."] text_right = (u"This Text widget is right aligned. Wrapped " u"words stay to the right as well. ") text_center = u"This one is center aligned." text_clip = (u"Text widgets may be clipped instead of wrapped.\n" u"Extra text is discarded instead of wrapped to the next line. " u"65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n" u"Newlines embedded in the string are still respected.") text_right_clip = (u"This is a right aligned and clipped Text widget.\n" u"<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 " u"Text will be cut off at the left of this widget.") text_center_clip = (u"Center aligned and clipped widgets will have " u"text cut off both sides.") text_ellipsis = (u"Text can be clippped using the ellipsis character (…)\n" u"Extra text is discarded and a … mark is shown." u"50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n" ) text_any = (u"The 'any' wrap mode will wrap on any character. This " u"mode will not collapse space characters at the end of the " u"line but it still honors embedded newline characters.\n" u"Like this one.") text_padding = (u"Padding widgets have many options. This " u"is a standard Text widget wrapped with a Padding widget " u"with the alignment set to relative 20% and with its width " u"fixed at 40.") text_divider = [u"The ", ('important', u"Divider"), u" widget repeats the same character across the whole line. " u"It can also add blank lines above and below."] text_edit = [u"The ", ('important', u"Edit"), u" widget is a simple text editing widget. It supports cursor " u"movement and tries to maintain the current column when focus " u"moves to another edit widget. It wraps and aligns the same " u"way as Text widgets." ] text_edit_cap1 = ('editcp', u"This is a caption. Edit here: ") text_edit_text1 = u"editable stuff" text_edit_cap2 = ('editcp', u"This one supports newlines: ") text_edit_text2 = (u"line one starts them all\n" u"== line 2 == with some more text to edit.. words.. whee..\n" u"LINE III, the line to end lines one and two, unless you " u"change something.") text_edit_cap3 = ('editcp', u"This one is clipped, try " u"editing past the edge: ") text_edit_text3 = u"add some text here -> -> -> ...." text_edit_alignments = u"Different Alignments:" text_edit_left = u"left aligned (default)" text_edit_center = u"center aligned" text_edit_right = u"right aligned" text_intedit = ('editcp', [('important', u"IntEdit"), u" allows only numbers: "]) text_edit_padding = ('editcp', u"Edit widget within a Padding widget ") text_columns1 = [('important', u"Columns"), u" are used to share horizontal screen space. " u"This one splits the space into two parts with " u"three characters between each column. The " u"contents of each column is a single widget."] text_columns2 = [u"When you need to put more than one " u"widget into a column you can use a ",('important', u"Pile"), u" to combine two or more widgets."] text_col_columns = u"Columns may be placed inside other columns." text_col_21 = u"Col 2.1" text_col_22 = u"Col 2.2" text_col_23 = u"Col 2.3" text_column_widths = (u"Columns may also have uneven relative " u"weights or fixed widths. Use a minimum width so that " u"columns don't become too small.") text_weight = u"Weight %d" text_fixed_9 = u"<Fixed 9>" # should be 9 columns wide text_fixed_14 = u"<--Fixed 14-->" # should be 14 columns wide text_edit_col_cap1 = ('editcp', u"Edit widget within Columns") text_edit_col_text1 = u"here's\nsome\ninfo" text_edit_col_cap2 = ('editcp', u"and within Pile ") text_edit_col_text2 = u"more" text_edit_col_cap3 = ('editcp', u"another ") text_edit_col_text3 = u"still more" text_gridflow = [u"A ",('important', u"GridFlow"), u" widget " u"may be used to display a list of flow widgets with equal " u"widths. Widgets that don't fit on the first line will " u"flow to the next. This is useful for small widgets that " u"you want to keep together such as ", ('important', u"Button"), u", ",('important', u"CheckBox"), u" and ", ('important', u"RadioButton"), u" widgets." ] text_button_list = [u"Yes", u"No", u"Perhaps", u"Certainly", u"Partially", u"Tuesdays Only", u"Help"] text_cb_list = [u"Wax", u"Wash", u"Buff", u"Clear Coat", u"Dry", u"Racing Stripe"] text_rb_list = [u"Morning", u"Afternoon", u"Evening", u"Weekend"] text_listbox = [u"All these widgets have been displayed " u"with the help of a ", ('important', u"ListBox"), u" widget. " u"ListBox widgets handle scrolling and changing focus. A ", ('important', u"Frame"), u" widget is used to keep the " u"instructions at the top of the screen."] def button_press(button): frame.footer = urwid.AttrWrap(urwid.Text( [u"Pressed: ", button.get_label()]), 'header') radio_button_group = [] blank = urwid.Divider() listbox_content = [ blank, urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20), blank, urwid.Text(text_right, align='right'), blank, urwid.Text(text_center, align='center'), blank, urwid.Text(text_clip, wrap='clip'), blank, urwid.Text(text_right_clip, align='right', wrap='clip'), blank, urwid.Text(text_center_clip, align='center', wrap='clip'), blank, urwid.Text(text_ellipsis, wrap='ellipsis'), blank, urwid.Text(text_any, wrap='any'), blank, urwid.Padding(urwid.Text(text_padding), ('relative', 20), 40), blank, urwid.AttrWrap(urwid.Divider("=", 1), 'bright'), urwid.Padding(urwid.Text(text_divider), left=2, right=2, min_width=20), urwid.AttrWrap(urwid.Divider("-", 0, 1), 'bright'), blank, urwid.Padding(urwid.Text(text_edit), left=2, right=2, min_width=20), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap1, text_edit_text1), 'editbx', 'editfc'), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap2, text_edit_text2, multiline=True ), 'editbx', 'editfc'), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap3, text_edit_text3, wrap='clip' ), 'editbx', 'editfc'), blank, urwid.Text(text_edit_alignments), urwid.AttrWrap(urwid.Edit("", text_edit_left, align='left'), 'editbx', 'editfc' ), urwid.AttrWrap(urwid.Edit("", text_edit_center, align='center'), 'editbx', 'editfc' ), urwid.AttrWrap(urwid.Edit("", text_edit_right, align='right'), 'editbx', 'editfc' ), blank, urwid.AttrWrap(urwid.IntEdit(text_intedit, 123), 'editbx', 'editfc' ), blank, urwid.Padding(urwid.AttrWrap(urwid.Edit(text_edit_padding, ""), 'editbx','editfc' ), left=10, width=50), blank, blank, urwid.AttrWrap(urwid.Columns([ urwid.Divider("."), urwid.Divider(","), urwid.Divider("."), ]), 'bright'), blank, urwid.Columns([ urwid.Padding(urwid.Text(text_columns1), left=2, right=0, min_width=20), urwid.Pile([ urwid.Divider("~"), urwid.Text(text_columns2), urwid.Divider("_")]) ], 3), blank, blank, urwid.Columns([ urwid.Text(text_col_columns), urwid.Columns([ urwid.Text(text_col_21), urwid.Text(text_col_22), urwid.Text(text_col_23), ], 1), ], 2), blank, urwid.Padding(urwid.Text(text_column_widths), left=2, right=2, min_width=20), blank, urwid.Columns( [ urwid.AttrWrap(urwid.Text(text_weight % 1),'reverse'), ('weight', 2, urwid.Text(text_weight % 2)), ('weight', 3, urwid.AttrWrap(urwid.Text( text_weight % 3), 'reverse')), ('weight', 4, urwid.Text(text_weight % 4)), ('weight', 5, urwid.AttrWrap(urwid.Text( text_weight % 5), 'reverse')), ('weight', 6, urwid.Text(text_weight % 6)), ], 0, min_width=8), blank, urwid.Columns([ ('weight', 2, urwid.AttrWrap(urwid.Text( text_weight % 2), 'reverse')), ('fixed', 9, urwid.Text(text_fixed_9)), ('weight', 3, urwid.AttrWrap(urwid.Text( text_weight % 2), 'reverse')), ('fixed', 14, urwid.Text(text_fixed_14)), ], 0, min_width=8), blank, urwid.Columns([ urwid.AttrWrap(urwid.Edit(text_edit_col_cap1, text_edit_col_text1, multiline=True), 'editbx','editfc'), urwid.Pile([ urwid.AttrWrap(urwid.Edit( text_edit_col_cap2, text_edit_col_text2), 'editbx','editfc'), blank, urwid.AttrWrap(urwid.Edit( text_edit_col_cap3, text_edit_col_text3), 'editbx','editfc'), ]), ], 1), blank, urwid.AttrWrap(urwid.Columns([ urwid.Divider("'"), urwid.Divider('"'), urwid.Divider("~"), urwid.Divider('"'), urwid.Divider("'"), ]), 'bright'), blank, blank, urwid.Padding(urwid.Text(text_gridflow), left=2, right=2, min_width=20), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.Button(txt, button_press), 'buttn','buttnf') for txt in text_button_list], 13, 3, 1, 'left'), left=4, right=3, min_width=13), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.CheckBox(txt),'buttn','buttnf') for txt in text_cb_list], 10, 3, 1, 'left') , left=4, right=3, min_width=10), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.RadioButton(radio_button_group, txt), 'buttn','buttnf') for txt in text_rb_list], 13, 3, 1, 'left') , left=4, right=3, min_width=13), blank, blank, urwid.Padding(urwid.Text(text_listbox), left=2, right=2, min_width=20), blank, blank, ] header = urwid.AttrWrap(urwid.Text(text_header), 'header') listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header) palette = [ ('body','black','light gray', 'standout'), ('reverse','light gray','black'), ('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'), ('bright','dark gray','light gray', ('bold','standout')), ('buttn','black','dark cyan'), ('buttnf','white','dark blue','bold'), ] # use appropriate Screen class if urwid.web_display.is_web_request(): screen = urwid.web_display.Screen() else: screen = urwid.raw_display.Screen() def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
def __init__(self, screen, on_ok, on_cancel, text_file=True, backwards=False, use_regex=False, use_hex=False): self.screen = screen self.on_ok = on_ok self.on_cancel = on_cancel label = urwid.Text('Enter search string:', layout=TildeLayout) self.edit = urwid.Edit(wrap='clip') w = urwid.AttrMap(self.edit, 'input', 'input') w = urwid.SimpleFocusListWalker([ label, w, ]) w = urwid.ListBox(w) w = urwid.LineBox(urwid.Padding(w, left=1, right=1), 'Search', title_attr='dialog_title', bline='') top = urwid.Padding(w, left=1, right=1) bgroup = [] self.btn_normal = urwid.RadioButton(bgroup, 'Normal') attr_btn_normal = urwid.AttrMap(self.btn_normal, 'dialog', 'dialog_focus') self.btn_regex = urwid.RadioButton(bgroup, 'Regular expression') attr_btn_regex = urwid.AttrMap(self.btn_regex, 'dialog', 'dialog_focus') self.btn_hex = urwid.CheckBox('Hexadecimal') attr_btn_hex = urwid.AttrMap(self.btn_hex, 'dialog', 'dialog_focus') self.btn_wildcard = urwid.RadioButton(bgroup, 'Wildcard search') attr_btn_wildcard = urwid.AttrMap(self.btn_wildcard, 'dialog', 'dialog_focus') if text_file and use_regex: self.btn_regex.set_state(True) else: self.btn_normal.set_state(True) self.btn_hex.set_state(use_hex) if text_file: w = urwid.SimpleFocusListWalker([ attr_btn_normal, attr_btn_regex, attr_btn_wildcard, ]) height_middle = 4 else: w = urwid.SimpleFocusListWalker([ attr_btn_hex, ]) height_middle = 2 left = urwid.BoxAdapter(urwid.ListBox(w), 5) self.btn_case = urwid.CheckBox('Case sensitive') attr_btn_case = urwid.AttrMap(self.btn_case, 'dialog', 'dialog_focus') self.btn_backwards = urwid.CheckBox('Backwards') attr_btn_backwards = urwid.AttrMap(self.btn_backwards, 'dialog', 'dialog_focus') self.btn_words = urwid.CheckBox('Whole words') attr_btn_words = urwid.AttrMap(self.btn_words, 'dialog', 'dialog_focus') self.btn_backwards.set_state(backwards) if text_file: w = urwid.SimpleFocusListWalker([ attr_btn_case, attr_btn_backwards, attr_btn_words, ]) else: w = urwid.SimpleFocusListWalker([ attr_btn_backwards, ]) right = urwid.BoxAdapter(urwid.ListBox(w), 5) w = urwid.Columns([urwid.Filler(left), urwid.Filler(right)]) self.divider = urwid.LineBox(urwid.Padding(w, left=1, right=1), tlcorner='├', trcorner='┤', bline='') middle = urwid.Padding(self.divider, left=1, right=1) self.btn_ok = urwid.Button('OK', self.on_click_ok) attr_btn_ok = urwid.AttrMap(self.btn_ok, 'dialog', 'dialog_focus') self.btn_cancel = urwid.Button('Cancel', on_cancel) attr_btn_cancel = urwid.AttrMap(self.btn_cancel, 'dialog', 'dialog_focus') w = urwid.Columns([ urwid.Divider(' '), (6, attr_btn_ok), (1, urwid.Text(' ')), (10, attr_btn_cancel), urwid.Divider(' ') ]) w = urwid.LineBox(urwid.Filler(w), tlcorner='├', trcorner='┤') bottom = urwid.Padding(w, left=1, right=1) self.pile = urwid.Pile([ (1, urwid.Filler(urwid.Text(' '))), (3, top), (height_middle, middle), (3, bottom), (1, urwid.Filler(urwid.Text(' '))), ]) w = urwid.AttrMap(self.pile, 'dialog') super().__init__(w)