Python urwid.Padding() Examples

The following are 30 code examples for showing how to use urwid.Padding(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module urwid , or try the search function .

Example 1
Project: vpngate-with-proxy   Author: Dragon2fly   File: ui_elements.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, key=None, value=('', '')):
        self.trigger = key
        self.yn = value[0]
        self.yn_but = MyButton([('attention', 'Use proxy: '), self.yn], self.on_change)
        self.input_addr = urwid.Edit(('attention', u' \N{BULLET} Address  : '), edit_text=value[1], wrap='clip')
        self.input_port = urwid.IntEdit(('attention', u' \N{BULLET} Port     : '), default=value[2])
        self.input_port.set_wrap_mode('clip')
        exit_but = urwid.Padding(urwid.Button('OKay'.center(8), self.item_callback), 'center', 12)

        widgets = [self.yn_but] \
                  + [urwid.AttrMap(wid, None, 'popbgs') for wid in (self.input_addr, self.input_port, exit_but)]

        self.pile = urwid.Pile(widgets)
        fill = urwid.LineBox(urwid.Filler(self.pile))
        self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))

        self.chosen = value 
Example 2
Project: topydo   Author: bram85   File: Main.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _show_completion_box(self):
        contents = self.cli_wrapper.contents
        if len(contents) == 1:
            completion_box = self.commandline.completion_box
            opts = ('given', completion_box.height)

            max_width = self.cli_wrapper.width
            pos = self.commandline.get_cursor_coords((max_width,))[0]
            l_margin = pos - completion_box.margin
            r_margin = max_width - pos - completion_box.min_width + completion_box.margin

            padding = urwid.Padding(completion_box,
                                    min_width=completion_box.min_width,
                                    left=l_margin,
                                    right=r_margin)

            contents.insert(0, (padding, opts))
            completion_box.focus.set_attr_map({None: PaletteItem.MARKED})
            self.cli_wrapper.focus_position = 1 
Example 3
Project: pycopia   Author: kdart   File: widgets.py    License: Apache License 2.0 6 votes vote down vote up
def build(self):
        self._showeq = urwid.Text("")
        eqi = self._create_equipment_input()
        maxlen = 0
        uutcb = urwid.CheckBox("DUT/UUT", state=False)
        urwid.connect_signal(uutcb, 'change', self._uut_select)
        blist = [AM(uutcb, "important")]
        for role in self._roles:
            label = str(role)
            maxlen = max(len(label), maxlen)
            but = urwid.CheckBox(str(role), state=False)
            urwid.connect_signal(but, 'change', self._multi_select, role)
            blist.append(but)
        roleboxes = urwid.Padding(urwid.GridFlow(blist, maxlen+4, 1, 0, "left"))
        # buttons
        ok, cancel = self.get_form_buttons()
        buts = urwid.Columns([(10, ok), (10, cancel)], dividechars=1, focus_column=0)
        return urwid.ListBox(urwid.SimpleListWalker([eqi, AM(self._showeq, "flagged"), roleboxes, buts])) 
Example 4
Project: pycopia   Author: kdart   File: widgets.py    License: Apache License 2.0 6 votes vote down vote up
def build(self):
        showeq = urwid.Text(self._testequipment.equipment.name)
        maxlen = 0
        uutcb = urwid.CheckBox("DUT/UUT", state=self._testequipment.UUT)
        urwid.connect_signal(uutcb, 'change', self._uut_select)
        blist = [AM(uutcb, "important")]
        for role in self._roles:
            label = str(role)
            maxlen = max(len(label), maxlen)
            state = role in self._testequipment.roles
            but = urwid.CheckBox(str(role), state=state)
            urwid.connect_signal(but, 'change', self._multi_select, role)
            blist.append(but)
        roleboxes = urwid.Padding(urwid.GridFlow(blist, maxlen+4, 1, 0, "left"))
    #    # buttons
        ok, cancel = self.get_form_buttons()
        buts = urwid.Columns([(10, ok), (10, cancel)], dividechars=1, focus_column=0)
        div = urwid.Divider()
        return urwid.ListBox(urwid.SimpleListWalker([AM(showeq, "flagged"), div, roleboxes, div, buts])) 
Example 5
Project: pycopia   Author: kdart   File: widgets.py    License: Apache License 2.0 6 votes vote down vote up
def build(self):
        # buttons
        done = urwid.Button("Done")
        urwid.connect_signal(done, 'click', self._done_multiselect)
        done = urwid.AttrWrap(done, 'selectable', 'butfocus')
        add = urwid.Button("Add New")
        urwid.connect_signal(add, 'click', self._add_new)
        add = urwid.AttrWrap(add, 'selectable', 'butfocus')
        cancel = urwid.Button("Cancel")
        urwid.connect_signal(cancel, 'click', self._cancel)
        cancel = urwid.AttrWrap(cancel, 'selectable', 'butfocus')
        # footer and header
        footer = urwid.GridFlow([done, add, cancel], 15, 3, 1, 'center')
        header = urwid.Padding(urwid.Text(
            ("popup", "Select multiple items. Tab to button box to select buttons. Arrow keys move selection.")))
        listbox = self._build_list()
        return urwid.Frame(listbox, header=header, footer=footer, focus_part="body") 
Example 6
Project: pycopia   Author: kdart   File: widgets.py    License: Apache License 2.0 6 votes vote down vote up
def build(self):
        # buttons
        done = urwid.Button("Done")
        urwid.connect_signal(done, 'click', self._done_multiselect)
        done = urwid.AttrWrap(done, 'selectable', 'butfocus')
        add = urwid.Button("Add New")
        urwid.connect_signal(add, 'click', self._add_new)
        add = urwid.AttrWrap(add, 'selectable', 'butfocus')
        cancel = urwid.Button("Cancel")
        urwid.connect_signal(cancel, 'click', self._cancel)
        cancel = urwid.AttrWrap(cancel, 'selectable', 'butfocus')
        # footer and header
        header = urwid.GridFlow([done, add, cancel], 15, 3, 1, 'center')
        footer = urwid.Padding(urwid.Text(
            ("popup", "Tab to button box to select buttons. Arrow keys transfer selection.")))
        body = self._build_body()
        return urwid.Frame(body, header=header, footer=footer, focus_part="body") 
Example 7
Project: statcode   Author: shobrook   File: statcode.py    License: MIT License 6 votes vote down vote up
def generate_content(status_code):
    try:
        code_descriptions, num, status_code = get_yaml_dictionary(status_code)
        content = code_descriptions[status_code]
        pile = urwid.Pile([
            urwid.Text("STATCODE: The Manual for HTTP Status Codes and Headers\n", align="center"),
            urwid.Text(("title", "STATUS MESSAGE" if num else "HEADER INFO")),
            urwid.Padding(
                urwid.Text(''.join([str(status_code), ": " if num else ", Example= ", content["message"], '\n'])),
                left=5),
            urwid.Text(("title", "CATEGORY")),
            urwid.Padding(urwid.Text(''.join([content["category"], '\n'])), left=5),
            urwid.Text(("title", "DESCRIPTION")),
            urwid.Padding(urwid.Text(''.join([content["description"], '\n'])), left=5),
            urwid.Text(("title", "COPYRIGHT")),
            urwid.Padding(urwid.Text(''.join([__load_file_data(num), '\n'])), left=5),
        ])
        padding = urwid.Padding(Scrollable(pile), left=1, right=1)

        return padding
    except KeyError:  # None is used to print "not recognized", so KeyError. Other errors have nothing to do with it
        return None 
Example 8
Project: binch   Author: tunz   File: view.py    License: MIT License 6 votes vote down vote up
def __init__(self, filename):
        self.header = urwid.Text(" BINCH: %s" % (filename))

        self.disasmblr = Disassembler(filename)

        items = self.setup_list(True)
        self.disasmlist = DisassembleList(items)
        start_index = self.find_index(self.disasmblr.entry)
        if start_index != -1:
            self.disasmlist.set_focus(start_index)

        self.history = list()

        self.body = urwid.Padding(self.disasmlist, 'center', 105)
        self.body = urwid.Filler(self.body, ('fixed top',1), ('fixed bottom',1))

        self.footer = StatusBar("HotKeys -> g: Go to a address | s: Save | d: Remove | enter: Modify | q: Quit", self)
        self.view = DisassembleWindow(self,
                urwid.AttrWrap(self.body, 'body'),
                urwid.AttrWrap(self.header, 'head'),
                self.footer)

        signals.call_delay.connect(self.sig_call_delay) 
Example 9
Project: yTermPlayer   Author: TimeTraveller-San   File: ui.py    License: GNU General Public License v3.0 6 votes vote down vote up
def start_screen(self):
        #Ovrlay top screen at start
        txt1_1=urwid.Button("New playlist [Enter URL]")
        urwid.connect_signal(txt1_1, 'click', self.input_screen)
        txt1 = urwid.AttrMap(txt1_1,None,focus_map='reversed')
        txt2_2=urwid.Button("Load saved playlist")
        urwid.connect_signal(txt2_2, 'click', self.load_list_screen)
        txt2 = urwid.AttrMap(txt2_2,None,focus_map='reversed')
        start_list=urwid.SimpleFocusListWalker([txt1,txt2])
        box=urwid.ListBox(start_list)
        selection=urwid.LineBox(
                                box, title='', title_align='center',
                                tlcorner='┌', tline='─', lline='│',
                                trcorner='┐', blcorner='└', rline='│',
                                bline='─', brcorner='┘'
                                )
        selection_with_padding=urwid.Padding(selection,left=2,right=2)
        return selection_with_padding 
Example 10
Project: yTermPlayer   Author: TimeTraveller-San   File: ui.py    License: GNU General Public License v3.0 6 votes vote down vote up
def load_list_screen(self,button):
        #overlay second screen after start case2
        txt=urwid.Text("Choose from the following:- ")
        _list=self.player_object.get_saved_lists()
        saved_list=[]
        for every_list in _list:
            b=urwid.Button(str(every_list).rstrip(),user_data=None)
            urwid.connect_signal(b, 'click', self.list_load)
            saved_list.append(urwid.AttrMap(b,None,focus_map='reversed'))
        box=urwid.ListBox(urwid.SimpleFocusListWalker(saved_list))
        list_box=urwid.LineBox(
                                box, title='', title_align='center',
                                tlcorner='┌', tline='─', lline='│',
                                trcorner='┐', blcorner='└', rline='│',
                                bline='─', brcorner='┘'
                                )
        list_box_padding=urwid.Padding(list_box,right=0,left=0)
        self.top.original_widget=list_box_padding 
Example 11
Project: terminal-leetcode   Author: chishui   File: result.py    License: MIT License 6 votes vote down vote up
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) 
Example 12
Project: terminal-leetcode   Author: chishui   File: result.py    License: MIT License 6 votes vote down vote up
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) 
Example 13
Project: terminal-leetcode   Author: chishui   File: result.py    License: MIT License 6 votes vote down vote up
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) 
Example 14
Project: terminal-leetcode   Author: chishui   File: result.py    License: MIT License 6 votes vote down vote up
def make_unified_error_view(self, error_title):
        blank = urwid.Divider()
        status_header = urwid.AttrWrap(urwid.Text('Run Code Status: '), 'body')
        status = urwid.AttrWrap(urwid.Text(error_title), 'hometag')
        columns = urwid.Columns([(17, status_header), (30, status)])
        column_wrap = urwid.WidgetWrap(columns)
        if 'last_testcase' in self.result:
            result_header = urwid.Text('--- Run Code Result: ---', align='center')
            your_input_header = urwid.Text('Last executed input:')
            your_input = urwid.Text(self.result['last_testcase'])
            list_items = [
                result_header,
                blank, column_wrap,
                blank, your_input_header, your_input,
            ]
        else:
            list_items = [
                result_header,
                blank, column_wrap,
            ]
        self._append_stdout_if_non_empty(list_items)
        return urwid.Padding(urwid.ListBox(urwid.SimpleListWalker(list_items)), left=2, right=2) 
Example 15
Project: ceph-ansible-copilot   Author: pcuzner   File: networking.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def render_page(self):

        return urwid.AttrMap(
                 urwid.Filler(
                   urwid.Pile([
                     urwid.Padding(
                       urwid.Text(self.text),
                       left=2, right=2),
                     urwid.Divider(),
                     urwid.Columns([
                         urwid.Pile([
                             urwid.Text("Public Network", align="center"),
                             urwid.Padding(self.public_buttons,left=4)
                         ]),
                         urwid.Pile([
                             urwid.Text("Cluster Network", align="center"),
                             urwid.Padding(self.cluster_buttons, left=4)
                         ])
                     ]),
                     urwid.Divider(),
                     self.next_btn
                   ]),
                   valign='top', top=1),
                 'active_step') 
Example 16
def render_page(self):

        host_widgets = urwid.Padding(self.host_panels,
                                    left=2, right=2)

        return urwid.AttrMap(
                 urwid.Filler(
                   urwid.Pile([
                               urwid.Padding(urwid.Text(self.text),
                                             left=2, right=2),
                               urwid.Divider(),
                               host_widgets,
                               urwid.Divider(),
                               self.next_btn]),
                   valign='top',top=1),
                 'active_step') 
Example 17
Project: Discurses   Author: topisani   File: message_list.py    License: MIT License 6 votes vote down vote up
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) 
Example 18
Project: Discurses   Author: topisani   File: message_list.py    License: MIT License 6 votes vote down vote up
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"
            "Oops! This channel is Forbidden. You don't have access. Sorry!\n",
            align=urwid.CENTER)
        w = urwid.Padding(txt, left=5, right=5)
        self.__super.__init__(w) 
Example 19
Project: anyMesh-Python   Author: AnyMesh   File: test_decoration.py    License: MIT License 6 votes vote down vote up
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) 
Example 20
Project: toot   Author: ihabunek   File: app.py    License: GNU General Public License v3.0 6 votes vote down vote up
def build_intro(self):
        font = urwid.font.Thin6x6Font()

        # NB: Padding with width="clip" will convert the fixed BigText widget
        # to a flow widget so it can be used in a Pile.

        big_text = "Toot {}".format(__version__)
        big_text = urwid.BigText(("intro_bigtext", big_text), font)
        big_text = urwid.Padding(big_text, align="center", width="clip")

        intro = urwid.Pile([
            big_text,
            urwid.Divider(),
            urwid.Text([
                "Maintained by ",
                ("intro_smalltext", "@ihabunek"),
                " and contributors"
            ], align="center"),
            urwid.Divider(),
            urwid.Text(("intro_smalltext", "Loading toots..."), align="center"),
        ])

        return urwid.Filler(intro) 
Example 21
Project: vpngate-with-proxy   Author: Dragon2fly   File: ui_elements.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, key=None, value=''):
        self.trigger = key
        info = urwid.Text("'ESC' to clear, leave blank or 'all' for all country and port", 'center')
        self.country = urwid.Edit(('attention', u' \N{BULLET} Country: '), edit_text=value[0], wrap='clip')
        self.port = urwid.Edit(('attention', u' \N{BULLET} Port   : '), edit_text=value[1], wrap='clip')
        self.score = urwid.Edit(('attention', u' \N{BULLET} Score >: '), edit_text=value[2], wrap='clip')
        exit_but = urwid.Padding(urwid.Button('OKay'.center(8), self.item_callback), 'center', 12)
        filter_ = [urwid.AttrMap(wid, None, 'popbgs') for wid in (self.country, self.port, self.score, exit_but)]

        self.pile = urwid.Pile([info]+filter_)
        fill = urwid.LineBox(urwid.Filler(self.pile))
        self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))

        self.chosen = value 
Example 22
Project: vpngate-with-proxy   Author: Dragon2fly   File: ui_elements.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, key=None, value=('', '')):
        self.trigger = key
        self.yn = value[0]
        self.yn_but = MyButton([('attention', 'Fix it: '), self.yn], self.on_change)
        self.input_dns = urwid.Edit(('attention', u' \N{BULLET} DNS   : '), edit_text=value[1], wrap='clip')
        exit_but = urwid.Padding(urwid.Button('OKay'.center(8), self.item_callback), 'center', 12)

        widgets = [self.yn_but] + [urwid.AttrMap(wid, None, 'popbgs') for wid in (self.input_dns, exit_but)]

        self.pile = urwid.Pile(widgets)
        fill = urwid.LineBox(urwid.Filler(self.pile))
        self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))

        self.chosen = value 
Example 23
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, controller: Any,
                 notice_text: str,
                 width: int,
                 title: str) -> None:
        widgets = [
            urwid.Divider(),
            urwid.Padding(urwid.Text(notice_text), left=1, right=1),
            urwid.Divider(),
        ]
        super().__init__(controller, widgets, 'GO_BACK', width, title) 
Example 24
Project: zulip-terminal   Author: zulip   File: boxes.py    License: Apache License 2.0 5 votes vote down vote up
def reactions_view(self, reactions: List[Dict[str, Any]]) -> Any:
        if not reactions:
            return ''
        try:
            reaction_stats = defaultdict(set)
            for reaction in reactions:
                user_id = int(reaction['user'].get('id', -1))
                if user_id == -1:
                    user_id = int(reaction['user']['user_id'])
                reaction_stats[reaction['emoji_name']].add(user_id)

            sorted_stats = sorted(
                (reaction, count)
                for reaction, count in reaction_stats.items()
            )

            my_user_id = self.model.user_id
            reaction_texts = [
                ('reaction_mine' if my_user_id in ids else 'reaction',
                 ':{}: {}'.format(reaction, len(ids)))
                for reaction, ids in sorted_stats
            ]

            spaced_reaction_texts = [
                entry
                for pair in zip(reaction_texts,
                                ' ' * len(reaction_texts))
                for entry in pair
            ]
            return urwid.Padding(
                urwid.Text(spaced_reaction_texts),
                align='left', width=('relative', 90), left=25, min_width=50)
        except Exception:
            return '' 
Example 25
Project: zulip-terminal   Author: zulip   File: boxes.py    License: Apache License 2.0 5 votes vote down vote up
def indent_quoted_content(self, soup: Any, padding_char: str) -> None:
        """
        We indent quoted text by padding them.
        The extent of indentation depends on their level of quoting.
        For example:
        [Before Padding]               [After Padding]

        <blockquote>                    <blockquote>
        <blockquote>                    <blockquote>
        <p>Foo</p>                      <p>▒ ▒ </p><p>Foo</p>
        </blockquote>       --->        </blockquote>
        <p>Boo</p>                      <p>▒ </p><p>Boo</p>
        </blockquote>                   </blockquote>
        """
        pad_count = 1
        blockquote_list = soup.find_all('blockquote')
        self.bq_len = len(blockquote_list)
        for tag in blockquote_list:
            child_list = tag.findChildren(recursive=False)
            actual_padding = (padding_char + ' ') * pad_count
            if len(child_list) == 1:
                pad_count = 0
                child_iterator = child_list
            else:
                child_iterator = child_list[1:]
            for child in child_iterator:
                new_tag = soup.new_tag('p')
                new_tag.string = actual_padding
                # If the quoted message is multi-line message
                # we deconstruct it and pad it at break-points (<br/>)
                if child.findAll('br'):
                    for br in child.findAll('br'):
                        next_s = br.nextSibling
                        text = str(next_s).strip()
                        if text:
                            insert_tag = soup.new_tag('p')
                            insert_tag.string = '\n' + actual_padding + text
                            next_s.replace_with(insert_tag)
                child.insert_before(new_tag)
            pad_count += 1 
Example 26
Project: zulip-terminal   Author: zulip   File: test_ui_tools.py    License: Apache License 2.0 5 votes vote down vote up
def test_main_view_content_header_without_header(self, mocker, message,
                                                     expected_header,
                                                     current_year,
                                                     starred_msg,
                                                     to_vary_in_last_message):
        date = mocker.patch('zulipterminal.ui_tools.boxes.date')
        date.today.return_value = datetime.date(current_year, 1, 1)
        date.side_effect = lambda *args, **kw: datetime.date(*args, **kw)

        stars = {msg: ({'flags': ['starred']} if msg == starred_msg else {})
                 for msg in ('this', 'last')}
        this_msg = dict(message, **stars['this'])
        all_to_vary = dict(to_vary_in_last_message, **stars['last'])
        last_msg = dict(message, **all_to_vary)
        msg_box = MessageBox(this_msg, self.model, last_msg)
        expected_header[1] = msg_box._time_for_message(message)
        if current_year > 2018:
            expected_header[1] = '2018 - ' + expected_header[1]
        expected_header[2] = '*' if starred_msg == 'this' else ' '

        view_components = msg_box.main_view()

        assert len(view_components) == 2
        assert isinstance(view_components[0], Columns)
        assert ([w.text for w in view_components[0].widget_list]
                == expected_header)
        assert isinstance(view_components[1], Padding) 
Example 27
Project: zulip-terminal   Author: zulip   File: test_ui_tools.py    License: Apache License 2.0 5 votes vote down vote up
def test_main_view_compact_output(self, mocker, message_fixture,
                                      to_vary_in_each_message):
        message_fixture.update({'id': 4})
        varied_message = dict(message_fixture, **to_vary_in_each_message)
        msg_box = MessageBox(varied_message, self.model, varied_message)
        view_components = msg_box.main_view()
        assert len(view_components) == 1
        assert isinstance(view_components[0], Padding) 
Example 28
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 5 votes vote down vote up
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. Unlike the thread objects
        used in the index, this is not a pile widget, because using a pile
        causes line-by-line text scrolling to be unusable.
        """
        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(self.theme["divider"]), "dim")
        ] 
Example 29
Project: profiling   Author: what-studio   File: viewer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_indented_widget(self):
        icon = self.get_mark()
        widget = self.get_inner_widget()
        node = self.get_node()
        widget = urwid.Columns([('fixed', 1, icon), widget], 1)
        indent = (node.get_depth() - 1)
        widget = urwid.Padding(widget, left=indent)
        return widget 
Example 30
Project: profiling   Author: what-studio   File: viewer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self.table = StatisticsTable(self)
        self.widget = urwid.Padding(self.table, right=1)