我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用urwid.ListBox()。
def main(): palette = [ ('body','black','dark cyan', 'standout'), ('foot','light gray', 'black'), ('key','light cyan', 'black', 'underline'), ('title', 'white', 'black',), ] footer_text = [ ('title', "Fibonacci Set Viewer"), " ", ('key', "UP"), ", ", ('key', "DOWN"), ", ", ('key', "PAGE UP"), " and ", ('key', "PAGE DOWN"), " move view ", ('key', "Q"), " exits", ] def exit_on_q(input): if input in ('q', 'Q'): raise urwid.ExitMainLoop() listbox = urwid.ListBox(FibonacciWalker()) footer = urwid.AttrMap(urwid.Text(footer_text), 'foot') view = urwid.Frame(urwid.AttrWrap(listbox, 'body'), footer=footer) loop = urwid.MainLoop(view, palette, unhandled_input=exit_on_q) loop.run()
def quit_prompt(self): """Pop-up window that appears when you try to quit.""" # Nothing fancy here. question = ur.Text(("bold", "Really quit?"), "center") yes_btn = ur.AttrMap(ur.Button( "Yes", self.button_press, "quit"), "red", None) no_btn = ur.AttrMap(ur.Button( "No", self.button_press, "back"), "green", None) prompt = ur.LineBox(ur.ListBox(ur.SimpleFocusListWalker( [question, self.div, self.div, no_btn, yes_btn]))) # The only interesting thing in this method is this Overlay widget. overlay = MyOverlay( prompt, self.loop.baseWidget, "center", 20, "middle", 8, 16, 8, parent=self) self.loop.Widget = overlay
def __init__(self, title, message, entry_prompt=None, entry_text='', buttons=[], ring=None): button_widgets = [] for button in buttons: button_widgets.append(('pack', button)) button_columns = urwid.Columns(button_widgets, dividechars=2) rows = [] rows.append(urwid.Text(message)) if entry_prompt: self.entry = MyEdit(entry_prompt, edit_text=entry_text, ring=ring) rows.append(self.entry) else: self.entry = None rows.append(urwid.Divider()) rows.append(button_columns) listbox = urwid.ListBox(rows) super(ButtonDialog, self).__init__(urwid.LineBox(listbox, title))
def __init__(self, app): super(BoardListView, self).__init__(urwid.Pile([])) self.log = logging.getLogger('boartty.view.board_list') self.searchInit() self.app = app self.active = True self.subscribed = False #True self.board_rows = {} self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([])) self.header = BoardListHeader() self.refresh() self._w.contents.append((app.header, ('pack', 1))) self._w.contents.append((urwid.Divider(),('pack', 1))) self._w.contents.append((urwid.AttrWrap(self.header, 'table-header'), ('pack', 1))) self._w.contents.append((self.listbox, ('weight', 1))) self._w.set_focus(3)
def __init__(self, app): super(ProjectListView, self).__init__(urwid.Pile([])) self.log = logging.getLogger('boartty.view.project_list') self.searchInit() self.app = app self.active = True self.subscribed = True self.project_rows = {} self.topic_rows = {} self.open_topics = set() self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([])) self.header = ProjectListHeader() self.refresh() self._w.contents.append((app.header, ('pack', 1))) self._w.contents.append((urwid.Divider(),('pack', 1))) self._w.contents.append((urwid.AttrWrap(self.header, 'table-header'), ('pack', 1))) self._w.contents.append((self.listbox, ('weight', 1))) self._w.set_focus(3)
def __init__(self, discord_client, chat_widget): self.discord = discord_client self.ui = self.discord.ui self.chat_widget = chat_widget self.list_walker = MessageListWalker(self) self.listbox = urwid.ListBox(self.list_walker) self.discord.add_event_handler('on_message', self._on_message) self.discord.add_event_handler('on_message_edit', self._on_message_edit) self.discord.add_event_handler('on_message_delete', self._on_message_delete) self.scroll_to_bottom() self.w_sidebar = Sidebar(chat_widget) self.w_columns = urwid.Columns([('weight', 1, self.listbox)]) self.sidebar_visible = False self.__super.__init__(self.w_columns)
def setUp(self): self.size = (80, 20) self.content = [ urwid.ListBox(urwid.SimpleFocusListWalker([ urwid.Edit('Field 1'), urwid.Edit('Field 2'), ])), urwid.ListBox(urwid.SimpleFocusListWalker([ SelectableText('Row 1'), urwid.Edit('', 'Edit field 2'), SelectableText('Row 3'), ])) ] self.editbox = self.content[1].body[1] self.editbox.edit_pos = 0 self.tabs = Tabs((urwid.Text('Edit fields'), self.content[0]), (urwid.Text('empty'),), (urwid.Text('Text rows'), self.content[1]))
def search_prompt(self): # XXX: remove if when thread search is supported if self.mode != "index": return popup = OptionsMenu( urwid.ListBox( urwid.SimpleFocusListWalker([ urwid.Text(("button", "Enter a query:")), urwid.AttrMap(StringPrompt(self.search_callback), "opt_prompt"), urwid.Text("Use a blank query to reset the {}.".format(self.mode)) ])), **frame_theme()) self.loop.widget = urwid.Overlay( popup, self.loop.widget, align=("relative", 50), valign=("relative", 25 if self.window_split else 50), width=("relative", 40), height=6)
def formatting_help(self, *_): """ Pops a help window for formatting directives. """ # we can "recycle" the server's formatting abilities to # use the same syntax for the help text itself message = network.fake_message( "\n\n".join(format_help), format="sequential") widget = OptionsMenu( urwid.ListBox(urwid.SimpleFocusListWalker(app.make_message_body(message, True))), title="Formatting Help", **frame_theme() ) va = 5 if self.window_split else 50 vh = 45 if self.window_split else 75 app.loop.widget = urwid.Overlay( widget, app.loop.widget, align=("relative", 50), valign=("relative", va), width=app.prefs["max_text_width"], height=("relative", vh) )
def set_escape_key(self, button, args): mode = args[0] widget = OptionsMenu( urwid.ListBox(urwid.SimpleFocusListWalker([ urwid.Text("Press Enter when done"), urwid.AttrMap(KeyPrompt( self.prefs["edit_escapes"][mode], self.save_escape_key, [mode] ), "opt_prompt")])), title="Set key for " + mode, **frame_theme() ) app.loop.widget = urwid.Overlay( urwid.AttrMap(widget, "30"), app.loop.widget, align=("relative", 50), valign=("relative", 50), width=25, height=5 )
def menu(title, SSID): body = [urwid.Text(title), urwid.Divider()] options = [] for c in SSID: button = urwid.Button("[ ] " + c) options.append(button) #if SSID_DICT[c] == True: # button.set_label(u"DH") urwid.connect_signal(button, 'click', item_chosen, c) body.append(urwid.AttrMap(button, None, focus_map='reversed')) swarmify_button = urwid.Button("Swarmify") options.append(swarmify_button) urwid.connect_signal(swarmify_button, 'click', swarm_chosen, c) body.append(urwid.AttrMap(swarmify_button, None, focus_map='reversed')) return urwid.ListBox(urwid.SimpleFocusListWalker(body))
def __init__(self, ui, query=None): self.ui = ui self.ui.set_header("Search: " + query) docs = self.ui.db.search(query) if len(docs) == 0: self.ui.set_status('No documents found.') items = [] for doc in docs: items.append(DocListItem(doc)) self.lenitems = len(items) self.listwalker = urwid.SimpleListWalker(items) self.listbox = urwid.ListBox(self.listwalker) w = self.listbox self.__super.__init__(w) self.update_prompt()
def menuAV(title, avail_stream_both): ###menu displaying formats with both audio and video ######### 2nd loop body = [urwid.Text(title), urwid.Divider()] for c in avail_stream_both: button = urwid.Button(str(c) + " ----->" + str(c.resolution) + "----->" + str((float(c.get_filesize())/1024)/1024)) urwid.connect_signal(button, 'click', chosen_URL, c) body.append(urwid.AttrMap(button, None, focus_map='reversed')) button = urwid.Button("Only Video/Audio Formats") urwid.connect_signal(button, 'click', menuVAOnly) body.append(urwid.AttrMap(button, None, focus_map='reversed')) button = urwid.Button("EXIT") urwid.connect_signal(button, 'click', exit_program) body.append(urwid.AttrMap(button, None, focus_map='reversed')) return urwid.ListBox(urwid.SimpleFocusListWalker(body)) ##########################################################################333
def menuVAOnlyMenu(title, avail_stream_VideoO,avail_stream_audioO): ###menu displaying formats with only audio or video ## must handle cases with audio and video alone ## for 3rd loop body = [urwid.Text(title), urwid.Divider()] for x in avail_stream_VideoO: button = urwid.Button(str(x).split('@',1)[0] + "---->" +x.resolution + "----->" + str((float(x.get_filesize())/1024)/1024)) urwid.connect_signal(button, 'click', chosen_URL, x) body.append(urwid.AttrMap(button, None, focus_map='reversed')) for x1 in avail_stream_audioO: button = urwid.Button(str(x1)) urwid.connect_signal(button, 'click', chosen_URL, x1) body.append(urwid.AttrMap(button, None, focus_map='reversed')) button = urwid.Button("EXIT") urwid.connect_signal(button, 'click', exit_program) body.append(urwid.AttrMap(button, None, focus_map='reversed')) return urwid.ListBox(urwid.SimpleFocusListWalker(body)) #################3333##################################################
def __init__(self, text, height, width, constr, items, has_default): j = [] if has_default: k, tail = 3, () else: k, tail = 2, ("no",) while items: j.append( items[:k] + tail ) items = items[k:] l = [] self.items = [] for tag, item, default in j: w = constr( tag, default=="on" ) self.items.append(w) w = urwid.Columns( [('fixed', 12, w), urwid.Text(item)], 2 ) w = urwid.AttrWrap(w, 'selectable','focus') l.append(w) lb = urwid.ListBox(l) lb = urwid.AttrWrap( lb, "selectable" ) DialogDisplay.__init__(self, text, height, width, lb ) self.frame.set_focus('body')
def cftest(self, desc, body, pos, offset_inset, coming_from, cursor, snap_rows, exp_offset_rows, exp_inset_fraction, exp_cur ): lbox = urwid.ListBox(body) lbox.change_focus( (4,5), pos, offset_inset, coming_from, cursor, snap_rows ) exp = exp_offset_rows, exp_inset_fraction act = lbox.offset_rows, lbox.inset_fraction cursor = None focus_widget, focus_pos = lbox.body.get_focus() if focus_widget.selectable(): if hasattr(focus_widget,'get_cursor_coords'): cursor=focus_widget.get_cursor_coords((4,)) assert act == exp, "%s got: %s expected: %s" %(desc, act, exp) assert cursor == exp_cur, "%s (cursor) got: %r expected: %r" %(desc,cursor,exp_cur)
def ktest(self, desc, key, body, focus, offset_inset, exp_focus, exp_offset_inset, exp_cur, lbox = None): if lbox is None: lbox = urwid.ListBox(body) lbox.body.set_focus( focus ) lbox.shift_focus((4,10), offset_inset ) ret_key = lbox.keypress((4,5),key) middle, top, bottom = lbox.calculate_visible((4,5),focus=1) offset_inset, focus_widget, focus_pos, _ign, cursor = middle if cursor is not None: x, y = cursor y += offset_inset cursor = x, y exp = exp_focus, exp_offset_inset act = focus_pos, offset_inset assert act == exp, "%s got: %r expected: %r" %(desc,act,exp) assert cursor == exp_cur, "%s (cursor) got: %r expected: %r" %(desc,cursor,exp_cur) return ret_key,lbox
def test_list_box(self): lb = urwid.ListBox(urwid.SimpleFocusListWalker([])) self.assertEqual(lb.focus, None) self.assertRaises(IndexError, lambda: getattr(lb, 'focus_position')) self.assertRaises(IndexError, lambda: setattr(lb, 'focus_position', None)) self.assertRaises(IndexError, lambda: setattr(lb, 'focus_position', 0)) t1 = urwid.Text(u'one') t2 = urwid.Text(u'two') lb = urwid.ListBox(urwid.SimpleListWalker([t1, t2])) self.assertEqual(lb.focus, t1) self.assertEqual(lb.focus_position, 0) lb.focus_position = 1 self.assertEqual(lb.focus, t2) self.assertEqual(lb.focus_position, 1) lb.focus_position = 0 self.assertRaises(IndexError, lambda: setattr(lb, 'focus_position', -1)) self.assertRaises(IndexError, lambda: setattr(lb, 'focus_position', 2))
def __init__(self, data, header): title = [ (4, urwid.AttrWrap(urwid.Text('#'), 'body', 'focus')), (2, urwid.AttrWrap(urwid.Text(''), 'body', 'focus')), (10, urwid.AttrWrap(urwid.Text('Tag'), 'body', 'focus')), urwid.AttrWrap(urwid.Text('Title'), 'body', 'focus'), (15, urwid.AttrWrap(urwid.Text('Acceptance'), 'body', 'focus')), (15, urwid.AttrWrap(urwid.Text('Difficulty'), 'body', 'focus')), ] title_column = urwid.Columns(title) self.marks = load_marks() items = make_itemwidgets(data, self.marks) self.listbox = urwid.ListBox(urwid.SimpleListWalker(items)) header_pile = urwid.Pile([header, title_column]) urwid.Frame.__init__(self, urwid.AttrWrap(self.listbox, 'body'), header=header_pile) self.last_sort = {'attr': 'id', 'reverse': True} self.last_search_text = None
def set_y_label(self, y_label): if len(y_label) == 0: return str_y_label = [str(i) for i in y_label] y_label_nums = str_y_label[1:] y_list_walker = [(1, urwid.ListBox([urwid.Text(str_y_label[0])]))] for num in y_label_nums: y_list_walker = [urwid.ListBox([urwid.Text(num)])] + y_list_walker y_list_walker = urwid.Pile(y_list_walker, focus_item=0) y_scale_len = len(max(str_y_label, key=len)) y_notation = [('fixed', y_scale_len, y_list_walker), ('weight', 1, self.bar_graph)] self.y_label.original_widget = urwid.Columns(y_notation, dividechars=1)
def __init__(self): self.walker = urwid.SimpleFocusListWalker(contents=self.log_messages) self.list_box = urwid.ListBox(self.walker) self.graph = urwid.BarGraph( attlist=['graph bg background', 'graph bg 1', 'graph bg 2'], satt={ (1, 0): 'graph bg 1 smooth', (2, 0): 'graph bg 2 smooth' } ) self.graph_widget = urwid.LineBox(self.graph, title=self.graph_title) self.default_widget = urwid.Columns([ urwid.LineBox( self.list_box, title="Logger" ), self.graph_widget ]) self.logger_widget = urwid.LineBox( self.list_box, title="Logger" )
def MOTD_screen(self): """MOTD display method - first screen shown.""" self.motd_flag = True self.header = self.make_header() mid = ur.Padding(ur.ListBox( ur.SimpleFocusListWalker([ self.div, ur.Text([("red", "Welcome to "), ("yellow", "sshchan!\n==========="), ("red", "========\n"), ("green", "SERVER: "), self.config.server_name, ("green", "\nMOTD:\n")], "center"), self.div])), "center", ("relative", 60), self.width, self.margin, self.margin) # TODO: add currently online users to the footer. self.footer = ur.AttrMap(ur.Text( " " + self.config.server_name + " " + self.config.version + " | Press H for help", align="center"), "reverse", None) try: with open(self.config.motd, 'r') as m: buf = m.read() except FileNotFoundError: buf = "---sshchan! woo!---" motd = ur.Text(buf, "center") mid.original_widget.body.append(motd) mid.original_widget.body.append(self.div) return ur.Frame(mid, self.header, self.footer, focus_part="body")
def show_help(self): """Create and return Frame object containing help docs.""" # Flags are gr8 against bugs. self.help_flag = True help_header = ur.Text(("green", "SSHCHAN HELP"), "center") pg1 = ur.Text( [("bold", "sshchan "), "is a textboard environment designed \ to run on remote SSH servers with multiple anonymous users simultaneously \ browsing and posting."], "center") pg2 = ur.Text(("bold", "Keybindings:")) pg3 = ur.Text([("green", "TAB"), ( None, " - switch focus between main body and top bar")]) pg4 = ur.Text( [("green", "H h"), (None, " - display this help dialog")]) pg5 = ur.Text( [("green", "B b"), (None, " - view available boards")]) pg6 = ur.Text( [("green", "ESC"), ( None, " - go back one screen (exits on MOTD screen)")]) back_btn = ur.AttrMap( ur.Button("Back", self.button_press, "back"), "red", "reverse") help_body = ur.Padding(ur.ListBox(ur.SimpleListWalker([ self.div, help_header, self.div, pg1, self.div, pg2, pg3, pg4, pg5, pg6, self.div, back_btn])), "center", self.width, 0, self.margin, self.margin) return ur.AttrMap(ur.Frame(help_body, self.header, self.footer, "body"), "bg")
def print_thread(self, button, thread): thr_no = self.board.thread_exists(int(thread)) thr_body = self.board.get_index()[thr_no] replies = ur.SimpleFocusListWalker([]) subject = ("reverse_red", thr_body[1]) if subject[1] == "": subject = (None, "") op = self.parse_post(thr_body[2]) op_info = ur.Text([("reverse_green", op["name"]), " " + op["stamp"] + " ", subject]) op_btn = CleanButton( "No. " + op["id"], self.reply_box, op["id"]) op_widget = ur.AttrMap(ur.Columns( [("pack", op_info), ("pack", op_btn)], 1), "reverse") replies.extend([op_widget, op["text"], self.parent.div]) if len(thr_body) > 3: for postno in range(3, len(thr_body)): reply = self.parse_post(thr_body[postno]) reply_info = ur.Text( [("green", reply["name"]), " " + reply["stamp"]]) reply_btn = CleanButton( "No. " + reply["id"], self.reply_box, reply["id"]) reply_widget = ur.Columns( [("pack", reply_info), ("pack", reply_btn)], 1) replies.extend([reply_widget, reply["text"], self.parent.div]) contents = ur.ListBox(replies) contents.set_focus(0) self.loop.Widget = ur.Frame( contents, self.parent.header, self.parent.footer, "body")
def __init__(self, test_id, text, escape_method): self.escape_method = escape_method lines = text.split('\n') list_items = [ urwid.AttrMap(urwid.Text(line), None, focus_map='reversed') for line in lines ] super(TestResultWindow, self).__init__( urwid.ListBox( urwid.SimpleFocusListWalker(list_items) ), title=test_id )
def test_listbox(self, test_list): list_items = [] for position, test_id in enumerate(test_list): test_line_attr = self.get_list_item(test_id, position) list_items.append(test_line_attr) return urwid.ListBox(urwid.SimpleFocusListWalker(list_items))
def __init__(self, pubpen): self.pubpen = pubpen self.keypress_map = IndexedMenuEnumerator() self._ship_moved_sub_id = None self.listwalker = urwid.SimpleFocusListWalker([]) box = urwid.ListBox(self.listwalker) outer_layout = LineBox(box, lline=None, blcorner='?', tlcorner='?', trcorner='\u252c', brcorner='\u2524') super().__init__(outer_layout) self.pubpen.subscribe('ship.destinations', self.handle_new_destinations) # pubpen event handlers
def __init__(self, pubpen): self.pubpen = pubpen self.save_button = urwid.Button('(S)ave') self.load_button = urwid.Button('(L)oad') self.quit_button = urwid.Button('(Q)uit') self.continue_button = urwid.Button('(ESC) Continue Game') self.buttons = urwid.SimpleFocusListWalker(( urwid.AttrMap(self.save_button, None, focus_map='reversed'), urwid.AttrMap(self.load_button, None, focus_map='reversed'), urwid.AttrMap(self.quit_button, None, focus_map='reversed'), urwid.AttrMap(self.continue_button, None, focus_map='reversed'), )) self.entrybox = urwid.ListBox(self.buttons) # Draw a box around the widget and constrain the widget's size linebox = urwid.LineBox(self.entrybox, tlcorner='\u2554', tline='\u2550', trcorner='\u2557', blcorner='\u255A', bline='\u2550', brcorner='\u255D', lline='\u2551', rline='\u2551') padding = urwid.Padding(linebox, align='center', width=len(self.continue_button.get_label()) + 6) filler = urwid.Filler(padding, valign='middle', height=len(self.buttons) + 2) outer_layout = LineBox(filler, lline=None, blcorner='?', tlcorner='?', trcorner='\u252c', brcorner='\u2524') super().__init__(outer_layout) urwid.connect_signal(self.save_button, 'click', self.save_game) urwid.connect_signal(self.load_button, 'click', self.load_game) urwid.connect_signal(self.quit_button, 'click', self.quit_client) urwid.connect_signal(self.continue_button, 'click', self.continue_game)
def __init__(self, pubpen): self.pubpen = pubpen self.loop = self.pubpen.loop self.message_list = urwid.SimpleFocusListWalker([]) list_box = urwid.ListBox(self.message_list) message_win = LineBox(list_box, tline=None, lline=None, bline=None, trcorner='?', brcorner='?') super().__init__(message_win) self.pubpen.subscribe('user.login_failure', partial(self.add_message, severity=MsgType.error)) self.pubpen.subscribe('user.order_failure', partial(self.add_message, severity=MsgType.error)) self.pubpen.subscribe('ship.movement_failure', partial(self.add_message, severity=MsgType.error)) self.pubpen.subscribe('market.event', self.handle_market_event) self.pubpen.subscribe('ui.urwid.message', self.add_message)
def __init__(self, app, query, query_desc=None, project_key=None, active=False, sort_by=None, reverse=None): super(StoryListView, self).__init__(urwid.Pile([])) self.log = logging.getLogger('boartty.view.story_list') self.searchInit() self.app = app self.query = query self.query_desc = query_desc or query self.active = active self.story_rows = {} self.enabled_columns = set() for colinfo in COLUMNS: if (colinfo.name in self.required_columns or colinfo.name not in self.optional_columns): self.enabled_columns.add(colinfo.name) self.disabled_columns = set() self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([])) self.project_key = project_key if 'Project' not in self.required_columns and project_key is not None: self.enabled_columns.discard('Project') self.disabled_columns.add('Project') #storyboard: creator if 'Owner' not in self.required_columns and 'owner:' in query: # This could be or'd with something else, but probably # not. self.enabled_columns.discard('Owner') self.disabled_columns.add('Owner') self.sort_by = sort_by or app.config.story_list_options['sort-by'] if reverse is not None: self.reverse = reverse else: self.reverse = app.config.story_list_options['reverse'] self.header = StoryListHeader(self.enabled_columns) self.refresh() self._w.contents.append((app.header, ('pack', 1))) self._w.contents.append((urwid.Divider(), ('pack', 1))) self._w.contents.append((urwid.AttrWrap(self.header, 'table-header'), ('pack', 1))) self._w.contents.append((self.listbox, ('weight', 1))) self._w.set_focus(3)
def __init__(self, content): """ :param content: text string to be displayed """ lines = [UnicodeText(line) for line in content] body = urwid.SimpleFocusListWalker(lines) urwid.ListBox.__init__(self, body)
def __init__(self, chat_widget): self.chat_widget = chat_widget self.list_walker = urwid.SimpleListWalker([]) self.w_listbox = urwid.ListBox(self.list_walker) self.update_list() self.__super.__init__(urwid.Padding(self.w_listbox, left=2)) keymaps.GLOBAL.add_command("redraw", self.update_list) def updlst(*args, **kwargs): self.update_list() self.chat_widget.discord.add_event_handler("on_member_join", updlst) self.chat_widget.discord.add_event_handler("on_member_remove", updlst) self.chat_widget.discord.add_event_handler("on_member_update", updlst)
def mk_test_subjects(self, *listbox_items): listbox = urwid.ListBox( urwid.SimpleListWalker(list(listbox_items)) ) return listbox
def test_hardcoded_keys_keep_working(self): list_contents = [urwid.Text(str(i)) for i in range(1, 10)] widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(list_contents), context='list') size = (3, 3) self.assert_lines(widget, size, exp_lines=('1 ', '2 ', '3 ')) widget.keypress(size, 'down') self.assert_lines(widget, size, exp_lines=('2 ', '3 ', '4 ')) widget.keypress(size, 'page down') self.assert_lines(widget, size, exp_lines=('5 ', '6 ', '7 ')) widget.keypress(size, 'up') self.assert_lines(widget, size, exp_lines=('4 ', '5 ', '6 ')) widget.keypress(size, 'page up') self.assert_lines(widget, size, exp_lines=('1 ', '2 ', '3 '))
def test_non_hardcoded_keys_are_evaluated(self): list_contents = [urwid.Text(str(i)) for i in range(1, 10)] widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(list_contents), context='list') action = FakeAction() self.keymap.bind('a', context='list', action=action) size = (3, 3) self.assert_lines(widget, size, exp_lines=('1 ', '2 ', '3 ')) widget.keypress(size, 'a') self.assert_lines(widget, size, exp_lines=('1 ', '2 ', '3 ')) self.assertEqual(action.callnum, 1) self.assertEqual(action.args, (widget,))
def test_evaluated_keys_are_offered_to_parent_again(self): list_contents = [urwid.Text(str(i)) for i in range(1, 10)] action = FakeAction() widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(list_contents), context='list', callback=action) self.keymap.bind('j', context='list', action=Key('down')) size = (3, 3) self.assert_lines(widget, size, exp_lines=('1 ', '2 ', '3 ')) widget.keypress(size, 'j') self.assertEqual(action.callnum, 0) self.assert_lines(widget, size, exp_lines=('2 ', '3 ', '4 '))
def test_key_translation_to_builtin_key(self): class SelectableText(urwid.Text): def selectable(self): return True def keypress(self, size, key): return key list_contents = [SelectableText(str(i)) for i in range(1, 10)] listw = self.km.wrap(urwid.ListBox, context='list')(urwid.SimpleFocusListWalker(list_contents)) self.km.bind(key='j', action=Key('down')) self.assertEqual(listw.focus_position, 0) listw.keypress((3, 3), 'j') self.assertEqual(listw.focus_position, 1)
def setUpModule(): # Monkey-patch stuff in the urwid module in-place if 'stig.tui.urwidpatches' not in sys.modules: import stig.tui.urwidpatches else: import stig.tui.urwidpatches importlib.reload(stig.tui.urwidpatches) import urwid assert hasattr(urwid.ListBox, 'get_scrollpos') assert ' ' not in urwid.command_map._command
def tearDownModule(self): # Remove monkey patches import urwid urwid.command_map.restore_defaults() importlib.reload(urwid) assert not hasattr(urwid.ListBox, 'get_scrollpos') assert ' ' in urwid.command_map._command
def __init__(self, srvapi, keymap, columns=None, sort=None, title=None): self._srvapi = srvapi self._keymap = keymap if self.focusable_items: self._ListItemClass = keymap.wrap(self.ListItemClass, context=self.keymap_context) else: self._ListItemClass = self.ListItemClass self._items = () self._marked = set() self._columns = columns or [] self._sort = sort self._sort_orig = sort self._title_name = title self.title_updater = None self._table = Table(**self.tuicolumns) self._table.columns = self._columns if self.focusable_items: walker = urwid.SimpleFocusListWalker([]) else: walker = urwid.SimpleListWalker([]) self._listbox = keymap.wrap(urwid.ListBox, context=self.keymap_context + 'list')(walker) listbox_sb = urwid.AttrMap( ScrollBar(urwid.AttrMap(self._listbox, self.palette_name)), 'scrollbar' ) pile = urwid.Pile([ ('pack', urwid.AttrMap(self._table.headers, self.palette_name + '.header')), listbox_sb ]) super().__init__(pile)
def __init__(self, movies): footer=urwid.AttrWrap(urwid.Text('Press q to exit, use up and down arrow to navigate, press Enter to select'), 'footer') items = self.make_items(movies) self.listbox = urwid.ListBox(urwid.SimpleListWalker(items)) top = urwid.Overlay(self.listbox, urwid.SolidFill(' '), align='center', width=('relative', 60), valign='middle', height=('relative', 60), min_width=20, min_height=9) urwid.Frame.__init__(self, urwid.AttrWrap(top, 'body'), footer=footer)
def __init__(self, model, got_focus, max_size=None): urwid.ListBox.__init__(self,model) self._got_focus=got_focus self.max_size=max_size self._lock=threading.Lock()
def __init__(self, message): listbox = urwid.ListBox(urwid.SimpleListWalker([ urwid.Text(line) for line in message.split("\n") ])) footer = urwid.Pile([ urwid.Divider(), urwid.Text("<close>") ]) self.box = urwid.LineBox(urwid.Frame(listbox, footer=footer)) super(PopUpDialog, self).__init__(urwid.AttrMap(self.box, 'popup'))
def quote_view_menu(self, button, post_ids): """ Receives a list of quote ids and makes a frilly menu to pick one to view. It retrieves messages objects from the thread and attaches them to a callback to `quote_view_action` """ buttons = [] for pid in post_ids: try: message = self.thread["messages"][pid] if len(post_ids) == 1: return self.quote_view_action(button, message) author = self.usermap[message["author"]] label = [ ("button", ">>%d " % pid), "(", (str(author["color"]), author["user_name"]), ")" ] buttons.append(cute_button(label, self.quote_view_action, message)) except IndexError: continue # users can submit >>29384234 garbage references widget = OptionsMenu( urwid.ListBox(urwid.SimpleFocusListWalker(buttons)), title="View a Quote", **frame_theme() ) self.loop.widget = urwid.Overlay( widget, self.loop.widget, align=("relative", 50), valign=("relative", 50), height=len(buttons) + 3, width=30 )
def deletion_dialog(self, button, message): """ Prompts the user to confirm deletion of an item. This can delete either a thread or a post. """ op = message["post_id"] == 0 buttons = [ urwid.Text(("bold", "Delete this %s?" % ("whole thread" if op else "post"))), urwid.Divider(), cute_button(("10" , ">> Yes"), lambda _: [ network.message_delete(message["thread_id"], message["post_id"]), self.remove_overlays(), self.index() if op else self.refresh() ]), cute_button(("30", "<< No"), self.remove_overlays) ] # TODO: create a central routine for creating popups. this is getting really ridiculous popup = OptionsMenu( urwid.ListBox(urwid.SimpleFocusListWalker(buttons)), **frame_theme()) self.loop.widget = urwid.Overlay( popup, self.loop.widget, align=("relative", 50), valign=("relative", 50), width=30, height=6)
def back(self, terminate=False): if app.mode == "index" and terminate: frilly_exit() elif self.overlay_p(): self.loop.widget = self.loop.widget[0] elif self.window_split: # display a confirmation dialog before killing off an in-progress post buttons = [ urwid.Text(("bold", "Discard current post?")), urwid.Divider(), cute_button(("10" , ">> Yes"), lambda _: [ self.remove_overlays(), self.index() ]), cute_button(("30", "<< No"), self.remove_overlays) ] # TODO: create a central routine for creating popups. this is getting really ridiculous popup = OptionsMenu( urwid.ListBox(urwid.SimpleFocusListWalker(buttons)), **frame_theme()) self.loop.widget = urwid.Overlay( popup, self.loop.widget, align=("relative", 50), valign=("relative", 25), width=30, height=6) else: mark() self.index()
def general_help(self): """ Show a general help dialog. In all honestly, its not very useful and will only help people who have never really used terminal software before =) """ widget = OptionsMenu( urwid.ListBox( urwid.SimpleFocusListWalker([ urwid_rainbows( "This is BBJ, a client/server textboard made for tilde.town!", True), urwid.Text(("dim", "...by ~desvox")), urwid.Divider("-"), urwid.Button("Post Formatting Help", self.formatting_help), urwid.Divider("-"), urwid.Text(general_help) ])), title="?????", **frame_theme() ) app.loop.widget = urwid.Overlay( widget, app.loop.widget, align=("relative", 50), valign=("relative", 50), width=30, height=("relative", 60) )
def __init__(self, model, got_focus, max_size=None): urwid.ListBox.__init__(self, model) self._got_focus = got_focus self.max_size = max_size self._lock = threading.Lock()
def __init__(self): self.log = urwid.SimpleFocusListWalker([]) self.top = urwid.ListBox(self.log) self.inventory = set() self.update_place(map_top)