我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用urwid.Padding()。
def __init__(self, config, board): """Initialize the most needed components.""" self.config = config self.board = board self.header = None self.footer = None # Some sugar. self.div = ur.Divider() # Used in list_boards(). self.boards_count = 0 self.loop = Loop(None, self.unhandled) # Calculate min_width and left/right margins for Padding widgets. self.width = self.loop.dimensions[0] // 2 self.margin = int((self.loop.dimensions[0] - self.width) * 0.60) # Flag for checking if board list is currently being displayed. self.list_visible = False # This flag needs to be here to fix a bug where Enter doesn't work # after hitting 'h' twice. self.help_flag = False # Another flag, this one is for board list display - it should only # be printed in the main menu/MOTD screen, nowhere else. self.motd_flag = False
def init_main_screen(self): self.w_filter_edit = urwid.Edit('Filter ') aw_filter_edit = urwid.AttrMap(self.w_filter_edit, 'edit', 'edit_focus') self.w_status_line = urwid.AttrMap(StatusLine(self.store.get_test_stats), 'statusline', '') urwid.connect_signal(self.w_filter_edit, 'change', self.on_filter_change) self.init_test_listbox() self.w_main = urwid.Padding( urwid.Pile([ ('pack', urwid.Text(u'Python Urwid Test Runner', align='center')), ('pack', urwid.Divider()), ('pack', aw_filter_edit), ('pack', urwid.Divider()), self.w_test_listbox, ('pack', urwid.Divider()), ('pack', self.w_status_line), ]), left=2, right=2 )
def __init__(self, chat_widget): self.chat_widget = chat_widget self.message = FakeMessage(datetime.datetime.min) self._selectable = False txt = urwid.Text( " \n" " \n" " \n" " \n" "< moo > \n" " ----- \n" " \ ^__^ \n" " \ (oo)\_______ \n" " (__)\ )\/\ \n" " ||----w | \n" " || || \n" " \n" " \n" "Congratulations! You have reached the top, Thats awesome! Unless " "the channel is empty, in which case, meh... big deal.\n\n", align=urwid.CENTER) w = urwid.Padding(txt, left=5, right=5) self.__super.__init__(w)
def __init__(self, prompt_text=u"Input:", default_text=u""): close_button = urwid.Button("OK") prompt = urwid.Text(prompt_text) edit_field = CustomEdit(caption=u'', edit_text=default_text, multiline=False, align='left', wrap='space', allow_tab=False, edit_pos=None, layout=None, mask=None) prompt_wrap = urwid.AttrMap(prompt, 'header') close_button_wrap = urwid.AttrMap(close_button, 'buttn', 'buttnf') edit_field_wrap = urwid.AttrMap(edit_field, 'editcp') urwid.connect_signal(close_button, 'click', edit_field.on_finish) urwid.connect_signal(edit_field, 'done', self.on_close) pile = urwid.Pile([prompt_wrap, edit_field_wrap, urwid.Padding(close_button_wrap, 'center', 6)]) fill = urwid.Filler(urwid.Padding(pile, 'center', left=1, right=1)) self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))
def test_reduced_padding_cursor(self): # FIXME: This is at least consistent now, but I don't like it. # pack() on an Edit should leave room for the cursor # fixing this gets deep into things like Edit._shift_view_to_cursor # though, so this might not get fixed for a while p = urwid.Padding(urwid.Edit(u'',u''), width='pack', left=4) self.assertEqual(p.render((10,), True).cursor, None) self.assertEqual(p.get_cursor_coords((10,)), None) self.assertEqual(p.render((4,), True).cursor, None) self.assertEqual(p.get_cursor_coords((4,)), None) p = urwid.Padding(urwid.Edit(u'',u''), width=('relative', 100), left=4) self.assertEqual(p.render((10,), True).cursor, (4, 0)) self.assertEqual(p.get_cursor_coords((10,)), (4, 0)) self.assertEqual(p.render((4,), True).cursor, None) self.assertEqual(p.get_cursor_coords((4,)), None)
def make_failed_view(self): blank = urwid.Divider() status_header = urwid.AttrWrap(urwid.Text('Run Code Status: '), 'body') status = urwid.AttrWrap(urwid.Text('Wrong Answer'), 'hometag') columns = urwid.Columns([(17, status_header), (20, status)]) result_header = urwid.Text('--- Run Code Result: ---', align='center') passed_header = urwid.Text('Passed test cases:') s = self.result['compare_result'] passed = urwid.Text('%d/%d' % (s.count('1'), len(s))) your_input_header = urwid.Text('Your input:') your_input = urwid.Text(self.result['input']) your_answer_header = urwid.Text('Your answer:') your_answer = urwid.Text(self.result['code_output']) expected_answer_header = urwid.Text('Expected answer:') expected_answer = urwid.Text(self.result['expected_output']) list_items = [ result_header, blank, columns, blank, passed_header, passed, blank, your_input_header, your_input, blank, your_answer_header, your_answer, blank, expected_answer_header, expected_answer ] self._append_stdout_if_non_empty(list_items) return urwid.Padding(urwid.ListBox(urwid.SimpleListWalker(list_items)), left=2, right=2)
def make_compile_error_view(self): blank = urwid.Divider() status_header = urwid.AttrWrap(urwid.Text('Run Code Status: '), 'body') status = urwid.AttrWrap(urwid.Text('Compile Error'), 'hometag') columns = urwid.Columns([(17, status_header), (20, status)]) column_wrap = urwid.WidgetWrap(columns) result_header = urwid.Text('--- Run Code Result: ---', align='center') your_input_header = urwid.Text('Your input:') your_input = urwid.Text('') your_answer_header = urwid.Text('Your answer:') your_answer = urwid.Text(self.result['compile_error']) expected_answer_header = urwid.Text('Expected answer:') expected_answer = urwid.Text('Unkown Error') list_items = [ result_header, blank, column_wrap, blank, your_input_header, your_input, blank, your_answer_header, your_answer, blank, expected_answer_header, expected_answer ] self._append_stdout_if_non_empty(list_items) return urwid.Padding(urwid.ListBox(urwid.SimpleListWalker(list_items)), left=2, right=2)
def make_runtime_error_view(self): blank = urwid.Divider() status_header = urwid.AttrWrap(urwid.Text('Run Code Status: '), 'body') status = urwid.AttrWrap(urwid.Text('Runtime Error'), 'hometag') columns = urwid.Columns([(17, status_header), (20, status)]) column_wrap = urwid.WidgetWrap(columns) result_header = urwid.Text('--- Run Code Result: ---', align='center') error_header = urwid.Text('Runtime Error Message:') error_message = urwid.Text(self.result['runtime_error']) your_input_header = urwid.Text('Last input:') your_input = urwid.Text(self.result['last_testcase']) list_items = [ result_header, blank, column_wrap, blank, error_header, error_message, blank, your_input_header, your_input, ] self._append_stdout_if_non_empty(list_items) return urwid.Padding(urwid.ListBox(urwid.SimpleListWalker(list_items)), left=2, right=2)
def pad(widget, left=2, right=2): return urwid.Padding(widget, left=left, right=right)
def __init__(self, text, vertical_padding=True): content = [urwid.Padding(self.get_content(text), left=3, right=3)] if vertical_padding: content = [DIV] + content + [DIV] lbox = urwid.LineBox(urwid.Pile(content)) self.__super.__init__(urwid.AttrMap(urwid.Pile( [lbox]), 'image button', 'image button focus'))
def __init__(self, pic, text): content = self.get_content(text) lbox = urwid.LineBox(urwid.Pile([DIV, urwid.Padding( urwid.Columns([(8, pic), content], 4), left=3, right=3), DIV])) self.__super.__init__(urwid.AttrMap(urwid.Pile( [lbox]), 'image button', 'image button focus'))
def __init__(self, label="", label_width=15, next_callback=False): self.label, self.next_callback = label, next_callback self.edit = urwid.Padding(urwid.Edit(), left=1, right=1) label = urwid.LineBox( urwid.Text(label), tlcorner=' ', tline=' ', lline=' ', trcorner=' ', blcorner=' ', rline=' ', brcorner=' ', bline=' ') lbox = urwid.AttrMap( urwid.LineBox( self.edit, tlcorner=' ', tline=' ', lline=' ', trcorner=' ', blcorner=' ', rline=' ', brcorner=' '), 'input', 'input focus') cols = urwid.Columns([(label_width, label), lbox]) urwid.WidgetWrap.__init__(self, cols)
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)
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 __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 username_label = urwid.Text('Username: ', align='right') password_label = urwid.Text('Password: ', align='right') self.username = urwid.Edit() self.password = urwid.Edit() login_button = urwid.Button('Login') decorated_login_button = urwid.AttrMap(login_button, None, focus_map='reversed') quit_button = urwid.Button('Quit') decorated_quit_button = urwid.AttrMap(quit_button, None, focus_map='reversed') buttons = urwid.Columns(( (len('Login') + 4, decorated_login_button), (len('Quit') + 4, decorated_quit_button), ), focus_column=1) labels = urwid.Pile([username_label, password_label]) self.fields = urwid.Pile([self.username, self.password, buttons], focus_item=0) entry_box = urwid.Columns([labels, self.fields]) self.status_message = urwid.Text(' ', align='center') entry_with_status = urwid.Pile([entry_box, self.status_message]) padded_entry_with_status = urwid.Padding(entry_with_status, align='center') self.display = urwid.Filler(padded_entry_with_status, valign='middle') decorate = urwid.LineBox(self.display) super().__init__(decorate) self.focusable_widgets = (w for w in itertools.cycle(( ((self.fields, 1),), ((self.fields, 2), (buttons, 0)), ((self.fields, 2), (buttons, 1)), ((self.fields, 0),) ))) urwid.connect_signal(login_button, 'click', self.attempt_login) urwid.connect_signal(quit_button, 'click', self.quit) self.pubpen.subscribe('user.login_success', self.handle_login_success) self.pubpen.subscribe('user.login_failure', self.handle_login_failure)
def generate_display_widget(self, size): p = super(MyGridFlow, self).generate_display_widget(size) for item in p.contents: if isinstance(item[0], urwid.Padding): c = item[0].original_widget if isinstance(c, urwid.Columns): if c.focus_position == 0 and not c.contents[0][0].selectable(): for i, w in enumerate(c.contents): if w[0].selectable(): c.focus_position = i break return p
def get_widget(self): txt = urwid.Text(self.content, align=self.align) if self.padding[0] > 0 or self.padding[1] > 0: txt = urwid.Padding( txt, left=self.padding[0], right=self.padding[1]) return urwid.AttrMap(txt, self.attr_map)
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 update_list(self): async def callback(): servers = set() memberset = set() for ch in self.chat_widget.channels: servers.add(ch.server) for serv in servers: for member in serv.members: memberset.add(member) items = [] on = [] idle = [] off = [] for member in memberset: if member.status == discord.Status.online: on.append(member) if member.status == discord.Status.offline: off.append(member) if member.status == discord.Status.idle: idle.append(member) members = on + idle + off for member in members: items.append( urwid.AttrMap( urwid.Padding( urwid.Text(member.display_name), left=1, right=1), self._get_user_attr(member), self._get_user_attr(member))) self.list_walker[:] = items self.chat_widget.discord.async(callback())
def _greedy_spacer(): return urwid.Padding(urwid.Text(''))
def make_message_body(self, message, no_action=False): """ Returns the widgets that comprise a message in a thread, including the text body, author info and the action button """ info = "@ " + self.timestring(message["created"]) if message["edited"]: info += " [edited]" if no_action: callback = ignore name = urwid_rainbows("~SYSTEM", True) color = "0" else: callback = self.on_post name = urwid.Text("~{}".format(self.usermap[message["author"]]["user_name"])) color = str(self.usermap[message["author"]]["color"]) post = str(message["post_id"]) head = urwid.Columns([ (2 + len(post), urwid.AttrMap( cute_button(">" + post, callback, message), "button", "hover")), (len(name._text) + 1, urwid.AttrMap(name, color)), urwid.AttrMap(urwid.Text(info), "dim") ]) head.message = message return [ head, urwid.Divider(), urwid.Padding( MessageBody(message), width=self.prefs["max_text_width"]), urwid.Divider(), urwid.AttrMap(urwid.Divider("-"), "dim") ]
def __init__(self, mod: Mod, *callbacks: Iterable[ModItemCallback]): """Wrap mod in the set of display widgets. Keyword arguments: mod: The :class:`Mod` to be wrapped. callbacks: The functions to be called when this object is selected. """ btn_prefix = ' ? ' # Construct button (the selectable part) btn = urwid.Button('') btn._w = urwid.AttrMap( urwid.SelectableIcon([btn_prefix, mod.name], 2), 'title', 'title_focus', ) for callback in callbacks: urwid.connect_signal(btn, 'click', callback, user_args=[mod]) # Construct the mod summary text = urwid.Padding( urwid.AttrMap(urwid.Text(mod.summary), 'description'), left=len(btn_prefix)*2, ) pile = btn, text super().__init__(pile)
def __init__(self, node_name, topics): self.node_name = node_name self.child_widgets = [ urwid.Padding(TopicCheckBox(topic, self), align='left', left=2) for topic in topics] super(NodeCheckBox, self).__init__( node_name, state=False, has_mixed=True, on_state_change=None) for chkbox in self.get_child_chkboxes(): urwid.connect_signal(chkbox, 'change', self.child_changed)
def create(cls, node_name, topics): return urwid.Padding(NodeCheckBox(node_name, topics), align='left', left=0)
def padding_values(self, size, focus): maxcol = size[0] width, ignore = self.original_widget.pack(size, focus=focus) if maxcol > width: self.align = "left" else: self.align = "right" return urwid.Padding.padding_values(self, size, focus)
def main_window(self): self.graph = self.bar_graph() self.graph_wrap = urwid.WidgetWrap( self.graph ) vline = urwid.AttrWrap( urwid.SolidFill(u'\u2502'), 'line') c = self.graph_controls() w = urwid.Columns([('weight',2,self.graph_wrap), ('fixed',1,vline), c], dividechars=1, focus_column=2) w = urwid.Padding(w,('fixed left',1),('fixed right',0)) w = urwid.AttrWrap(w,'body') w = urwid.LineBox(w) w = urwid.AttrWrap(w,'line') w = self.main_shadow(w) return w
def __init__(self, text, height, width, body=None): width = int(width) if width <= 0: width = ('relative', 80) height = int(height) if height <= 0: height = ('relative', 80) self.body = body if body is None: # fill space with nothing body = urwid.Filler(urwid.Divider(),'top') self.frame = urwid.Frame( body, focus_part='footer') if text is not None: self.frame.header = urwid.Pile( [urwid.Text(text), urwid.Divider()] ) w = self.frame # pad area around listbox w = urwid.Padding(w, ('fixed left',2), ('fixed right',2)) w = urwid.Filler(w, ('fixed top',1), ('fixed bottom',1)) w = urwid.AttrWrap(w, 'body') # "shadow" effect w = urwid.Columns( [w,('fixed', 2, urwid.AttrWrap( urwid.Filler(urwid.Text(('border',' ')), "top") ,'shadow'))]) w = urwid.Frame( w, footer = urwid.AttrWrap(urwid.Text(('border',' ')),'shadow')) # outermost border area w = urwid.Padding(w, 'center', width ) w = urwid.Filler(w, 'middle', height ) w = urwid.AttrWrap( w, 'border' ) self.view = w
def petest(self, desc, align, width): self.assertRaises(urwid.PaddingError, lambda: urwid.Padding(None, align, width))
def mctest(self, desc, left, right, size, cx, innercx): class Inner: def __init__(self, desc, innercx): self.desc = desc self.innercx = innercx def move_cursor_to_coords(self,size,cx,cy): assert cx==self.innercx, desc i = Inner(desc,innercx) p = urwid.Padding(i, ('fixed left',left), ('fixed right',right)) p.move_cursor_to_coords(size, cx, 0)
def get_indented_widget(self): widget = self.get_inner_widget() if not self.is_leaf: widget = urwid.Columns([('fixed', 1, [self.unexpanded_icon, self.expanded_icon][self.expanded]), widget], dividechars=1) indent_cols = self.get_indent_cols() return urwid.Padding(widget, width=('relative', 100), left=indent_cols)
def _setup_ui(self): email = input('???? (Email??): ') password = getpass.getpass('????: ') api = DoubanFMApi() api.login(email, password) songs = api.get_redheart_songs() # ?? self.title = urwid.Text('') self._update_title() divider = urwid.Divider() header = urwid.Padding(urwid.Pile([divider, self.title, divider]), left=4, right=4) # ???? index = 0 for song in songs: self.btns.append(SongButton(song, self._on_item_pressed, index)) index += 1 self.song_listbox = SongListBox(self.btns) # ?? self.main = urwid.Padding( urwid.Frame(self.song_listbox, header=header, footer=divider), left=4, right=4) # ?????? urwid.register_signal( SongListBox, ['exit', 'stop', 'next_song', 'change_mode']) urwid.connect_signal(self.song_listbox, 'exit', self._on_exit) urwid.connect_signal(self.song_listbox, 'stop', self.stop_song) urwid.connect_signal(self.song_listbox, 'next_song', self.next_song) urwid.connect_signal(self.song_listbox, 'change_mode', self.change_mode) self.loop = urwid.MainLoop(self.main, palette=self.palette) self.loop.screen.set_terminal_properties(colors=256)
def make_header(self): if self.leetcode.is_login: columns = [ ('fixed', 15, urwid.Padding(urwid.AttrWrap( urwid.Text('%s' % config.username), 'head', ''))), urwid.AttrWrap(urwid.Text('You have solved %d / %d problems. ' % (len(self.leetcode.solved), len(self.leetcode.quizzes))), 'head', ''), ] return urwid.Columns(columns) else: text = urwid.AttrWrap(urwid.Text('Not login'), 'head') return text
def make_success_view(self): blank = urwid.Divider() status_header = urwid.AttrWrap(urwid.Text('Run Code Status: '), 'body') status = urwid.AttrWrap(urwid.Text('Accepted'), 'accepted') columns = urwid.Columns([(20, status_header), (20, status)]) runtime = urwid.Text('Run time: %s' % self.result['status_runtime']) result_header = urwid.Text('--- Run Code Result: ---', align='center') list_items = [ result_header, blank, columns, blank, runtime ] self._append_stdout_if_non_empty(list_items) return urwid.Padding(urwid.ListBox(urwid.SimpleListWalker(list_items)), left=2, right=2)
def __init__(self, delegate): """ init """ self.delegate = delegate # Create the components of the frame: # * The title and the clock in the header titleBar = TitleBar(("titleBar", "ChatMaster 3000"), align="center") clock = urwid.AttrMap(Clock(self.delegate, align="right"), "titleBar") # The actual title bar. The title has a relative width, while clock has a set width of 5 columns wide. self.titleBar = ColumnView([('weight', 1, titleBar), (5, clock)]) self.chatLog = ChatWindow() self.chatBox = ChatBox("> ", self) # Create the channel list and set its label self.channelList = ChannelList() self.channelList.body.insert(0, urwid.Text(("channelList-text-bold", "Channels:"))) # Wrap them with a display attribute. This will enable color application. header = self.titleBar.wrapWithAttribute("titleBar") footer = self.chatBox.wrapWithAttribute("footer") chatLog = self.chatLog.wrapWithAttribute("body") channelList = self.channelList.wrapWithAttribute("channelList") # Create a border between the channel list and the chat log channelListWithPadding = urwid.Padding(channelList, align="left", width=("relative", 95)) channelListWithPadding = urwid.AttrMap(channelListWithPadding, "border") # Put them both in a columns widget self.columnView = ColumnView([(15, channelListWithPadding), ('weight', 1, chatLog)]) # Call the super class and let it handle the heavy lifting. super(ChatFrame, self).__init__(self.columnView, header=header, footer=footer, focus_part='footer')
def unhandled(self, key): """Input not handled by any other widgets. @key - string representing key that was pressed. Most key presses inside sshchan should be handled by this function. Buttons don't need handling here, they respond to Enter, Space or mouse clicks. """ # Refresh screen dimensions in case terminal is resized. self.loop.dimensions = self.loop.screen.get_cols_rows() # Calculate width and margins of Padding based on terminal size. self.width = self.loop.dimensions[0] // 2 self.margin = int((self.loop.dimensions[0] - self.width) * 0.60) if key in ("Q", "q"): self.quit_prompt() elif key == "tab": # Switch focus from body to top bar and vice versa. if self.loop.baseWidget.focus_position == "header": self.loop.baseWidget.focus_position = "body" else: self.loop.baseWidget.focus_position = "header" elif key in ("H", "h"): # Disable MOTD flag. self.motd_flag = False if not self.help_flag: self.loop.Widget = self.show_help() elif key in ("B", "b"): if not self.list_visible and self.motd_flag: # If board list isn't currently being displayed, let's show it. self.list_visible = True self.loop.frameBody.extend(self.list_boards()) elif self.list_visible and self.motd_flag: # Board list was being displayed, get rid of it. for i in range(self.boards_count): self.loop.frameBody.pop() self.list_visible = False elif key == "esc": # If not on the main screen, ESC goes back, otherwise try to quit. if not self.motd_flag: self.button_press(None, "back") else: self.quit_prompt() # Urwid expects the handler function to return True after it's done. return True
def show_board(self): index = self.board.get_index() new_btn = ur.AttrMap( ur.Button("New thread", self.reply_box, -1), "green", "b_green") thread_list = ur.SimpleFocusListWalker( [ur.Padding(new_btn, "center", ("relative", 40)), self.parent.div]) for thread in index: # Check subject, because empty subject with set color attribute # produces wrong output. subject = ("reverse_red", thread[1]) if subject[1] == "": subject = (None, "") op = self.parse_post(thread[2]) post_info = ur.Text([("reverse_green", op["name"]), " " + op["stamp"] + " ", subject, " No. " + op["id"]]) reply_btn = ur.AttrMap(CleanButton( "Reply", self.print_thread, op["id"]), None, "reverse") replies = [] if len(thread) > 3: for i in range(3, 6): try: reply = self.parse_post(thread[i]) replies_info = ur.Text( [("green", reply["name"]), " " + reply["stamp"]]) no_btn = CleanButton( "No. " + reply["id"], self.print_thread, reply["id"]) replies_header = ur.Padding(ur.Columns( [("pack", replies_info), ("pack", no_btn)], 1), left=1) reply_text = ur.Padding(reply["text"], left=1) replies.extend( [replies_header, reply_text, self.parent.div]) except IndexError: break header = ur.AttrMap(ur.Columns( [("pack", post_info), ("pack", reply_btn)], 1), "reverse") thread_buf = [header, op["text"], self.parent.div] thread_buf.extend(replies) thread_list.extend(thread_buf) body = ur.ListBox(thread_list) if len(thread_list) > 0: body.set_focus(0) self.loop.Widget = ur.Frame( body, self.parent.header, self.parent.footer, "body")
def select_project(project_list, path_callback): max_width = len(max(project_list, key=len)) f = ProjectSelector(project_list, 'normal', 'highlighted', 'selected') def refresh_list(key=''): if key: if key in ('delete', 'backspace'): f.remove_key() else: if key in 'abcdefghijklmnopqrstuvwxyz- .0123456789': f.add_key(key) s = f.render() txt.set_text(s) def exit_on_q(key): if key.__class__ is not str: return if key in ('Q',): raise urwid.ExitMainLoop() if key == 'up': f.up() if key == 'down': f.down() if key == 'enter': path_callback(f.select()) raise urwid.ExitMainLoop() key = key.lower() refresh_list(key) palette = [ ('normal', 'light gray', ''), ('selected', 'yellow, bold', ''), ('highlighted', 'black, bold', 'yellow'), ('quit button', 'light red, bold', ''), ('enter button', 'light green, bold', '') ] txt = urwid.Text('', align='left') fill = urwid.Filler(txt) pad = urwid.Padding(fill, align='center', width=max_width+4) box = urwid.LineBox(pad, title="Projects") footer = urwid.Text(['Start typing to search. Use arrow keys to navigate. Press (', ('enter button', 'Enter'), ') to select project. ', 'Press (', ('quit button', 'Q'), ') to exit.']) frame = urwid.Frame(body=box, footer=footer) loop = urwid.MainLoop(frame, palette, unhandled_input=exit_on_q) refresh_list() loop.run()
def __init__(self, app, story_view, task): super(TaskRow, self).__init__(urwid.Pile([])) self.app = app self.story_view = story_view self.task_key = task.key self._note = u'' self.taskid = mywid.TextButton(self._note) urwid.connect_signal(self.taskid, 'click', lambda b:self.editNote(b)) self.project = ProjectButton(self.app) urwid.connect_signal(self.project, 'changed', lambda b:self.updateProject(b)) self.status = StatusButton(self.app) urwid.connect_signal(self.status, 'changed', lambda b:self.updateStatus(b)) self._title = u'' self.title = mywid.TextButton(self._title) urwid.connect_signal(self.title, 'click', lambda b:self.editTitle(b)) self.assignee = AssigneeButton(self.app) urwid.connect_signal(self.assignee, 'changed', lambda b:self.updateAssignee(b)) self.description = urwid.Text(u'') self.columns = urwid.Columns([], dividechars=1) for (widget, attr, packing) in [ (self.taskid, 'task-id', ('given', 4, False)), (self.project, 'task-project', ('weight', 1, False)), (self.title, 'task-title', ('weight', 2, False)), (self.status, 'task-status', ('weight', 1, False)), (self.assignee, 'task-assignee', ('weight', 1, False)), ]: w = urwid.AttrMap(urwid.Padding(widget, width='pack'), attr, focus_map={'focused': 'focused-'+attr}) self.columns.contents.append((w, packing)) self.pile = urwid.Pile([self.columns]) self.note = urwid.Text(u'') self.note_visible = False self.note_columns = urwid.Columns([], dividechars=1) self.note_columns.contents.append((urwid.Text(u''), ('given', 1, False))) self.note_columns.contents.append((self.note, ('weight', 1, False))) self._w = urwid.AttrMap(self.pile, None)#, focus_map=self.task_focus_map) self.refresh(task)
def __init__(self, app, story_key): super(StoryView, self).__init__(urwid.Pile([])) self.log = logging.getLogger('boartty.view.story') self.searchInit() self.app = app self.story_key = story_key self.task_rows = {} self.event_rows = {} self.hide_events = True self.marked_seen = False self.title_label = urwid.Text(u'', wrap='clip') self.creator_label = mywid.TextButton(u'', on_press=self.searchCreator) self.tags_label = urwid.Text(u'', wrap='clip') self.created_label = urwid.Text(u'', wrap='clip') self.updated_label = urwid.Text(u'', wrap='clip') self.status_label = urwid.Text(u'', wrap='clip') self.permalink_label = mywid.TextButton(u'', on_press=self.openPermalink) story_info = [] story_info_map={'story-data': 'focused-story-data'} for l, v in [("Title", self.title_label), ("Creator", urwid.Padding(urwid.AttrMap(self.creator_label, None, focus_map=story_info_map), width='pack')), ("Tags", urwid.Padding(urwid.AttrMap(self.tags_label, None, focus_map=story_info_map), width='pack')), ("Created", self.created_label), ("Updated", self.updated_label), ("Status", self.status_label), ("Permalink", urwid.Padding(urwid.AttrMap(self.permalink_label, None, focus_map=story_info_map), width='pack')), ]: row = urwid.Columns([(12, urwid.Text(('story-header', l), wrap='clip')), v]) story_info.append(row) story_info = urwid.Pile(story_info) self.description = DescriptionBox(app, u'') self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([])) self._w.contents.append((self.app.header, ('pack', 1))) self._w.contents.append((urwid.Divider(), ('pack', 1))) self._w.contents.append((self.listbox, ('weight', 1))) self._w.set_focus(2) self.listbox.body.append(story_info) self.listbox.body.append(urwid.Divider()) self.listbox_tasks_start = len(self.listbox.body) self.listbox.body.append(urwid.Divider()) self.listbox.body.append(self.description) self.listbox.body.append(urwid.Divider()) self.refresh() self.listbox.set_focus(3)