Python urwid.Text() Examples

The following are 30 code examples of urwid.Text(). 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 also want to check out all available functions/classes of the module urwid , or try the search function .
Example #1
Source File: boxes.py    From zulip-terminal with Apache License 2.0 6 votes vote down vote up
def main_view(self) -> Any:
        search_text = ("Search ["
                       + ", ".join(keys_for_command("SEARCH_MESSAGES"))
                       + "]: ")
        self.text_box = ReadlineEdit(search_text + " ")
        # Add some text so that when packing,
        # urwid doesn't hide the widget.
        self.conversation_focus = urwid.Text(" ")
        self.search_bar = urwid.Columns([
            ('pack', self.conversation_focus),
            ('pack', urwid.Text("  ")),
            self.text_box,
        ])
        self.msg_narrow = urwid.Text("DONT HIDE")
        self.recipient_bar = urwid.LineBox(
            self.msg_narrow, title="Current message recipients",
            tline='─', lline='', trcorner='─', tlcorner='─',
            blcorner='─', rline='', bline='─', brcorner='─')
        return [self.search_bar, self.recipient_bar] 
Example #2
Source File: view_help.py    From sncli with MIT License 6 votes vote down vote up
def create_color_help_lines(self):
        lines = [ urwid.AttrMap(urwid.Text(''),
                                'help_header',
                                'help_focus') ]
        lines.append(urwid.AttrMap(urwid.Text(' Colors'),
                                   'help_header',
                                   'help_focus'))
        fmap = {}
        for c in self.config.colors:
            fmap[re.search('^(.*)(_fg|_bg)$', c).group(1)] = 'help_focus'
        for c in self.config.colors:
            lines.append(
                urwid.AttrMap(urwid.AttrMap(
                    urwid.Text(
                    [
                     ('help_descr',  ('{:>' + str(self.descr_width) + '} ').format(self.config.get_color_descr(c))),
                     ('help_config', ('{:>' + str(self.config_width) + '} ').format('clr_' + c)),
                     (re.search('^(.*)(_fg|_bg)$', c).group(1), "'" + self.config.get_color(c) + "'")
                    ]
                    ),
                    attr_map = None,
                    focus_map = fmap
                ), 'default', 'help_focus'))
        return lines 
Example #3
Source File: main.py    From bbj with MIT License 6 votes vote down vote up
def search_prompt(self):
        if self.mode == "index":
            callback = self.search_index_callback
        elif self.mode == "thread":
            callback = self.search_thread_callback
        else:
            return

        popup = OptionsMenu(
            urwid.ListBox(
                urwid.SimpleFocusListWalker([
                    urwid.Text(("button", "Enter a query:")),
                    urwid.AttrMap(StringPrompt(callback), "opt_prompt"),
                    urwid.Text("Use a blank query to reset the {}.".format(self.mode))
                ])),
            **self.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) 
Example #4
Source File: views.py    From zulip-terminal with Apache License 2.0 6 votes vote down vote up
def make_table_with_categories(contents: PopUpViewTableContent,
                                   column_widths: List[int],
                                   dividechars: int=2) -> List[Any]:
        """
        Returns a list of widgets to render a table with different categories.
        """
        widgets = []  # type: List[Any]
        for category, content in contents:
            if category:
                if len(widgets) > 0:  # Separate categories with newline.
                    widgets.append(urwid.Text(''))
                widgets.append(urwid.Text(('popup_category', category)))
            for index, row in enumerate(content):
                label, data = row
                strip = urwid.Columns([
                        urwid.Text(label),
                        (column_widths[1], urwid.Text(data))
                    ], dividechars=dividechars)
                widgets.append(urwid.AttrWrap(
                    strip, None if index % 2 else 'popup_contrast')
                )
        return widgets 
Example #5
Source File: view_help.py    From sncli with MIT License 6 votes vote down vote up
def get_status_bar(self):
        cur   = -1
        total = 0
        if len(self.body.positions()) > 0:
            cur   = self.focus_position
            total = len(self.body.positions())

        status_title = \
            urwid.AttrMap(urwid.Text('Help',
                                     wrap='clip'),
                          'status_bar')
        status_index = \
            ('pack', urwid.AttrMap(urwid.Text(' ' +
                                              str(cur + 1) +
                                              '/' +
                                              str(total)),
                                   'status_bar'))
        return \
            urwid.AttrMap(urwid.Columns([ status_title, status_index ]),
                          'status_bar') 
Example #6
Source File: boxes.py    From zulip-terminal with Apache License 2.0 6 votes vote down vote up
def stream_header(self) -> Any:
        stream_topic_separator = '▶'
        color = self.model.stream_dict[self.stream_id]['color']
        bar_color = 's' + color
        stream_title_markup = ('bar', [
            (bar_color, '{} {} '.format(self.stream_name,
                                        stream_topic_separator)),
            ('title', ' {}'.format(self.topic_name))
        ])
        stream_title = urwid.Text(stream_title_markup)
        header = urwid.Columns([
            ('pack', stream_title),
            (1, urwid.Text((color, ' '))),
            urwid.AttrWrap(urwid.Divider('━'), color),
        ])
        header.markup = stream_title_markup
        return header 
Example #7
Source File: command.py    From screeps_console with MIT License 6 votes vote down vote up
def list(self, comp):
        command_list = ''
        aliases = list(comp.aliases)
        builtin_list = [method for method in dir(self) if callable(getattr(self, method))]
        commands = builtin_list

        for alias in aliases:
            alias_real = comp.aliases[alias]
            if alias_real not in builtin_list:
                commands.append(alias)

        commands.sort()
        commands.reverse()
        for builtin_command in commands:
            if builtin_command != 'turtle' and not builtin_command.startswith('__'):
                command_list = builtin_command + '  ' + command_list

        comp.listwalker.append(urwid.Text(('logged_response', command_list)))
        return 
Example #8
Source File: test_ui_tools.py    From zulip-terminal with Apache License 2.0 6 votes vote down vote up
def test_main_view_generates_stream_header(self, mocker, message,
                                               to_vary_in_last_message):
        self.model.stream_dict = {
            5: {
                'color': '#bd6',
            },
        }
        last_message = dict(message, **to_vary_in_last_message)
        msg_box = MessageBox(message, self.model, last_message)
        view_components = msg_box.main_view()
        assert len(view_components) == 3

        assert isinstance(view_components[0], Columns)

        assert isinstance(view_components[0][0], Text)
        assert isinstance(view_components[0][1], Text)
        assert isinstance(view_components[0][2], Divider) 
Example #9
Source File: command.py    From screeps_console with MIT License 6 votes vote down vote up
def console(self, comp):
        helpmessage = 'Control console output. `console quiet` to suppress console output and `console reset` to turn it back on.'
        userInput = comp.edit
        user_text = userInput.get_edit_text()
        user_command_split = user_text.split(' ')

        if len(user_command_split) < 2:
            comp.listwalker.append(urwid.Text(('logged_response', helpmessage)))
            return False

        command = user_command_split[1]

        if command == 'quiet':
            comp.consolemonitor.quiet = True
            comp.listwalker.append(urwid.Text(('logged_response', 'Limiting display to user interactions only.')))
        elif command == 'reset' or command == 'verbose':
            comp.consolemonitor.quiet = False
            comp.listwalker.append(urwid.Text(('logged_response', 'Displaying all console output.')))
        else:
            comp.listwalker.append(urwid.Text(('logged_response', helpmessage))) 
Example #10
Source File: shutdown.py    From conjure-up with MIT License 6 votes vote down vote up
def __init__(self, exit_code):
        self.exit_code = exit_code
        self.message = Text('Do you want to quit?', align='center')
        super().__init__(LineBox(Pile([
            Padding.line_break(""),
            self.message,
            Padding.line_break(""),
            Columns([
                Text(""),
                SubmitButton('Yes', lambda _: self.confirm()),
                Text(""),
                SubmitButton('No', lambda _: self.cancel()),
                Text(""),
            ]),
            Padding.line_break(""),
        ])))
        if events.Error.is_set():
            self.confirm() 
Example #11
Source File: step.py    From conjure-up with MIT License 6 votes vote down vote up
def __init__(self, app, step_model):
        """
        Arguments:
        step_model: step model
        step_model_widget: step model widget
        cb: callback
        """
        self.app = app
        self.model = step_model

        self.title = Text(('info_minor', step_model.title))
        self.description = Text(('body', step_model.description))
        self.result = Text(step_model.result)
        self.sudo_label = Text(('body', ''))
        self.icon = Text(("pending_icon", "\N{BALLOT BOX}"))
        self.sudo_input = None
        self.complete = asyncio.Event()
        self.requires_input = False
        form_fields = (self._build_form_header() +
                       self._build_sudo_field() +
                       self._build_form_fields())
        super().__init__(form_fields)
        if self.sudo_input or self.fields:
            self.show_button()
            self.focus_position = 4 
Example #12
Source File: applicationconfigure.py    From conjure-up with MIT License 6 votes vote down vote up
def do_toggle_show_all_config(self):
        if not self.showing_all:
            new_ows = await self.get_non_whitelisted_option_widgets()
            header = Text("Advanced Configuration Options")
            opts = self.widget.options()
            self.widget.contents.append((header, opts))
            for ow in new_ows:
                self.widget.contents.append((ow, opts))
            self.toggle_show_all_button.set_label(
                "Hide Advanced Configuration")
            self.showing_all = True
        else:
            i = self.toggle_show_all_button_index
            self.widget.contents = self.widget.contents[:i + 1]
            self.toggle_show_all_button.set_label(
                "Show Advanced Configuration")
            self.showing_all = False 
Example #13
Source File: destroy_confirm.py    From conjure-up with MIT License 6 votes vote down vote up
def _build_footer(self):
        no = menu_btn(on_press=self.cancel,
                      label="\n  NO\n")
        yes = menu_btn(on_press=self.submit,
                       label="\n  YES\n")
        self.buttons = Columns([
            ('fixed', 2, Text("")),
            ('fixed', 11, Color.menu_button(
                no,
                focus_map='button_primary focus')),
            Text(""),
            ('fixed', 11, Color.menu_button(
                yes,
                focus_map='button_primary focus')),
            ('fixed', 2, Text(""))
        ])

        self.footer = Pile([
            Padding.line_break(""),
            self.buttons
        ])
        return Color.frame_footer(self.footer) 
Example #14
Source File: destroy_confirm.py    From conjure-up with MIT License 6 votes vote down vote up
def _build_widget(self):
        applications = self.app.juju.client.applications
        total_items = [Instruction("Deployment Information:"), HR()]
        tbl = Pile([
            Columns([('fixed', 15, Text("Name")),
                     Text(self.model['name'])]),
            Columns([('fixed', 15, Text("Cloud")),
                     Text(self.model['cloud'])]),
            Columns([('fixed', 15, Text("Status")),
                     Text(self.model['status']['current'])]),
            Columns([('fixed', 15, Text("Online")),
                     Text(self._sanitize_date(
                         self.model['status']['since']))]),
            Columns([('fixed', 15, Text("Applications")),
                     Text(", ".join(applications.keys()))]),
            Columns([('fixed', 15, Text("Machines")),
                     Text(str(self._total_machines(self.model)))])

        ])
        total_items.append(tbl)
        total_items.append(HR())
        return Padding.center_80(Filler(Pile(total_items), valign='top')) 
Example #15
Source File: lxdsetup.py    From conjure-up with MIT License 6 votes vote down vote up
def build_widget(self):
        return [
            Columns([
                ('fixed', 16, Text('network bridge', align="right")),
                Color.string_input(
                    self.lxd_config['network'],
                    focus_map='string_input focus')
            ], dividechars=1),
            HR(),
            Columns([
                ('fixed', 16, Text('storage pool', align="right")),
                Color.string_input(
                    self.lxd_config['storage-pool'],
                    focus_map='string_input focus')
            ], dividechars=1),
        ] 
Example #16
Source File: addons.py    From conjure-up with MIT License 6 votes vote down vote up
def build_widget(self):
        self.choices.append(HR())
        for addon in sorted(app.addons.values(), key=attrgetter('name')):
            self.choices.append_option(label=addon.friendly_name,
                                       value=addon.name,
                                       state=addon.name in app.selected_addons)
            self.choices.append(Padding.line_break(""))
            self.choices.append(
                Columns([
                    ('fixed', 3, Text('')),
                    Text(addon.description)
                ], dividechars=5)
            )
            self.choices.append(HR())
        if app.addons:
            self.choices.focus_position = 1
        return self.choices 
Example #17
Source File: cloud.py    From conjure-up with MIT License 6 votes vote down vote up
def __init__(self, app, public_clouds, custom_clouds,
                 compatible_cloud_types, cb=None, back=None):
        self.app = app
        self.cb = cb
        self.back = back
        self.public_clouds = public_clouds
        self.custom_clouds = custom_clouds
        self.compatible_cloud_types = compatible_cloud_types
        self.config = self.app.config
        self.buttons_pile_selected = False
        self.message = Text('')
        self._items_localhost_idx = None
        self.show_back_button = back is not None

        super().__init__()
        self.update_message() 
Example #18
Source File: jaas.py    From conjure-up with MIT License 6 votes vote down vote up
def build_widget(self):
        rows = []

        def add_row(label, field):
            rows.extend([
                Columns([('fixed', 23, Text(label)),
                         Color.string_input(field,
                                            focus_map='string_input focus')]),
                Padding.line_break(""),
            ])

        add_row('Email:', self.email),
        add_row('Password:', self.password),
        add_row('Two-Factor Auth (2FA):', self.twofa),
        if self.error:
            rows.append(Color.error_major(Text(" {}".format(self.error))))
        return rows 
Example #19
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
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)),
                **self.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() 
Example #20
Source File: step.py    From conjure-up with MIT License 5 votes vote down vote up
def build_widget(self):
        self.icon = Text(("pending_icon", "\N{BALLOT BOX}"))
        self.result = Text("")
        self.row = Columns([
            ('fixed', 3, self.icon),
            ('weight', 0.1, Text(('body', self.step.title))),
            ('weight', 0.4, self.result),
        ], dividechars=1) 
Example #21
Source File: view_help.py    From sncli with MIT License 5 votes vote down vote up
def __init__(self, config):
        self.config = config

        self.descr_width  = 26
        self.config_width = 29

        lines = []
        lines.extend(self.create_kb_help_lines('Keybinds Common', 'common'))
        lines.extend(self.create_kb_help_lines('Keybinds Note List', 'titles'))
        lines.extend(self.create_kb_help_lines('Keybinds Note Content', 'notes'))
        lines.extend(self.create_config_help_lines())
        lines.extend(self.create_color_help_lines())
        lines.append(urwid.Text(('help_header', '')))

        super(ViewHelp, self).__init__(urwid.SimpleFocusListWalker(lines)) 
Example #22
Source File: bundle_readme_view.py    From conjure-up with MIT License 5 votes vote down vote up
def build_widgets(self):
        readme_files = glob(os.path.join(self.spell_dir, 'README.*'))
        if len(readme_files) == 0:
            self.readme_w = Text("No README found for bundle.")
        else:
            readme_file = readme_files[0]
            if len(readme_files) != 1:
                utils.warning("Unexpected: {} files matching README.*"
                              "- using {}".format(len(readme_files),
                                                  readme_file))
            with open(readme_file) as rf:
                rlines = [Text(l) for l in rf.readlines()]
                self.readme_w = BoxAdapter(ListBox(rlines),
                                           self.initial_height)

        ws = [Text("About {}:".format(self.spell_name)),
              Padding.right_50(Color.button_primary(
                  PlainButton("Continue",
                              self.do_continue),
                  focus_map='button_primary focus')),
              Padding.center(HR()),
              Padding.center(self.readme_w, left=2),
              Padding.center(HR()),
              Padding.center(Text("Use arrow keys to scroll text "
                                  "and TAB to select the button."))]

        self.pile = Pile(ws)
        return Padding.center_90(Filler(self.pile, valign="top")) 
Example #23
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
def goto_post_prompt(self, init):
        if self.mode != "thread":
            return

        count = self.thread["reply_count"]
        live_display = urwid.Text("")
        edit = JumpPrompt(count, lambda x: self.goto_post(x))
        items = [
            urwid.Text(("button", "   Jump to post")),
            urwid.AttrMap(edit, "opt_prompt"),
            urwid.Text(("bold", ("(max %d)" % count).center(18, " "))),
            live_display
        ]

        urwid.connect_signal(edit, "change", self.jump_peek, live_display)
        if init.isdigit():
            edit.keypress((self.loop.screen_size[0],), init)

        popup = OptionsMenu(
            urwid.ListBox(urwid.SimpleFocusListWalker(items)),
            **self.frame_theme())

        self.loop.widget = urwid.Overlay(
            popup, self.loop.widget,
            align=("relative", 50),
            valign=("relative", 25 if self.window_split else 50),
            width=20, height=6) 
Example #24
Source File: spellpicker.py    From conjure-up with MIT License 5 votes vote down vote up
def build_widget(self):
        widget = MenuSelectButtonList()
        prev_cat = None
        for category, spell in self.spells:
            if category == "_unassigned_spells":
                category = "other"
            if category != prev_cat:
                if prev_cat:
                    widget.append(Text(""))
                widget.append(Color.label(Text(category)))
                prev_cat = category
            widget.append_option(spell['name'], spell)
        widget.focus_position = 1
        return widget 
Example #25
Source File: applicationconfigure.py    From conjure-up with MIT License 5 votes vote down vote up
def _build_widget(self):
        ws = []
        if not self.application.is_subordinate:
            ws.append(OptionWidget("Units", "int",
                                   "How many units to deploy.",
                                   self.application.num_units,
                                   current_value=self.num_units_copy,
                                   value_changed_callback=self.handle_scale))

        constraints_ow = OptionWidget(
            "Constraints", "string",
            "Set constraints on the application, ie. cores=4 mem=4G.",
            self.application.constraints,
            current_value=self.constraints_copy,
            value_changed_callback=self.handle_constraints)
        ws.append(constraints_ow)
        ws.append(self.constraints_error_label)

        ws += await self.get_whitelisted_option_widgets()
        self.toggle_show_all_button_index = len(ws) + 1
        self.toggle_show_all_button = SecondaryButton(
            "Show Advanced Configuration",
            lambda sender: app.loop.create_task(
                self.do_toggle_show_all_config()))
        if await self.get_non_whitelisted_option_widgets():
            ws += [HR(),
                   Columns([('weight', 1, Text(" ")),
                            (36, self.toggle_show_all_button)])]
        for widget in ws:
            self.widget.contents.append((widget,
                                         self.widget.options())) 
Example #26
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
def make_thread_body(self, thread, pinned=False):
        """
        Returns the pile widget that comprises a thread in the index.
        """
        button = cute_button(">>", self.thread_load, thread["thread_id"])
        if pinned == "server":
            title = urwid.AttrWrap(urwid.Text("[STICKY] " + thread["title"]), "20")
        elif pinned == "client":
            title = urwid.AttrWrap(urwid.Text("[*] " + thread["title"]), "50")
        else:
            title = urwid.Text(thread["title"])
        user = self.usermap[thread["author"]]
        dateline = [
            ("default", "by "),
            (str(user["color"]), "~%s " % user["user_name"]),
            ("dim", "@ %s" % self.timestring(thread["created"]))
        ]

        infoline = "%d replies; active %s" % (
            thread["reply_count"],
            self.timestring(thread["last_mod"], "delta"))

        last_author = self.usermap[thread["last_author"]]
        pile = [
            urwid.Columns([(3, urwid.AttrMap(button, "button", "hover")), title]),
            urwid.Text(dateline),
            urwid.Text(("dim", infoline)),
            urwid.Text([
                ("dim", "last post by "),
                (str(last_author["color"]), "~" + last_author["user_name"])
            ]),
            urwid.AttrMap(urwid.Divider(self.theme["divider"]), "dim")
        ]

        if self.prefs["index_spacing"]:
            pile.insert(4, urwid.Divider())

        pile = urwid.Pile(pile)
        pile.thread = thread
        return pile 
Example #27
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
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)),
            **self.frame_theme())

        self.loop.widget = urwid.Overlay(
            popup, self.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            width=30, height=6) 
Example #28
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
def set_footer(self, string):
        """
        Sets the footer to display `string`, applying bar formatting.
        Other than setting the color, `string` is shown verbatim.
        """
        widget = urwid.AttrMap(urwid.Text(string), "bar")
        self.loop.widget.footer = widget
        # TODO: make this set the title line when the window is split
        # if self.window_split:
        #     self.loop.widget.footer[0].set_text(widget)
        # else: 
Example #29
Source File: main.py    From bbj with MIT License 5 votes vote down vote up
def set_header(self, text, *format_specs):
        """
        Update the header line with the logged in user, a seperator,
        then concat text with format_specs applied to it. Applies
        bar formatting to it.
        """
        header = ("{}@bbj | " + text).format(
            (network.user_name or "anonymous"),
            *format_specs
        )
        self.loop.widget.header = urwid.AttrMap(urwid.Text(header), "bar") 
Example #30
Source File: applicationconfigure.py    From conjure-up with MIT License 5 votes vote down vote up
def __init__(self, application, close_cb):
        self.title = "Configure {}".format(application.name)
        self.application = application
        self.prev_screen = close_cb
        self.options_copy = self.application.options.copy()
        self.num_units_copy = self.application.num_units
        self.constraints_copy = self.application.constraints
        self.constraints_error_label = Text(('body', ''))
        self.showing_all = False
        super().__init__()