Python urwid.Columns() Examples

The following are 30 code examples of urwid.Columns(). 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: scroll_test.py    From stig with GNU General Public License v3.0 6 votes vote down vote up
def test_shards_bug(self):
        scrl = Scrollable(
            urwid.Pile([urwid.Columns([urwid.Text("text")] * 3)] * 3)
        )
        sb = ScrollBar(scrl, thumb_char='#', trough_char='|', width=3)
        area = urwid.Overlay(urwid.SolidFill("O"), sb, "center", 4, "middle", 5)

        self.check(area, (10, 5), cursor_pos=(), text=(
            'tetOOOO###',
            'xttOOOO###',
            'tetOOOO###',
            'xttOOOO###',
            'tetOOOO|||',
        ))

    # https://github.com/urwid/urwid/issues/226#issuecomment-437176837 
Example #2
Source File: gazua.py    From ec2-gazua with MIT License 6 votes vote down vote up
def _init_views(self):
        aws_names = list(self.manager.aws_names)
        self.aws_view = AWSView(aws_names)

        aws_name = self.aws_view.get_selected_name()
        group_names = list(self.manager.instances[aws_name].keys())
        self.group_view = GroupView(group_names)

        group_name = self.group_view.get_selected_name()
        init_instances = self.manager.instances[aws_name][group_name]
        self.instance_view = InstanceView(init_instances)

        urwid.connect_signal(self.aws_view.get_walker(), "modified",
                             self.on_aws_changed)
        urwid.connect_signal(self.group_view.get_walker(), "modified",
                             self.on_group_changed)

        self.view = Columns([
            (15, self.aws_view.get_widget()),
            (25, self.group_view.get_widget()),
            self.instance_view.get_widget()
        ]) 
Example #3
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 #4
Source File: step.py    From conjure-up with MIT License 6 votes vote down vote up
def _build_sudo_field(self):
        if not utils.is_linux() or not self.model.needs_sudo:
            return []

        rows = []
        if not self.app.sudo_pass:
            self.sudo_input = PasswordEditor()
        self.clear_sudo_error()
        columns = [
            ('weight', 0.5, Padding.left(self.sudo_label, left=5)),
        ]
        if self.sudo_input:
            columns.append((
                'weight', 1,
                Filler(Color.string_input(self.sudo_input,
                                          focus_map='string_input focus'),
                       valign='bottom')))
        rows.extend([
            Padding.line_break(""),
            Columns(columns, dividechars=3, box_columns=[1]),
        ])
        return rows 
Example #5
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 #6
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 #7
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 #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: ui.py    From sen with MIT License 6 votes vote down vote up
def run(self):
        """
        prompt for text input.
        """
        # set up widgets
        leftpart = urwid.Text(self.arguments.prompt_text, align='left')
        editpart = urwid.Edit(multiline=True, edit_text=self.arguments.initial_text)

        # build promptwidget
        edit = urwid.Columns([
            ('fixed', len(self.arguments.prompt_text), leftpart),
            ('weight', 1, editpart),
        ])
        self.ui.prompt_bar = urwid.AttrMap(edit, "main_list_dg")

        self.ui.reload_footer()
        self.ui.set_focus("footer")

        urwid.connect_signal(editpart, "change", run_command_callback,
                             user_args=[self.ui, self.docker_object]) 
Example #10
Source File: widgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def build(self):
        wlist = []
        addnew = urwid.Button("Add")
        urwid.connect_signal(addnew, 'click', self._add_new_option)
        addnew = urwid.AttrWrap(addnew, 'selectable', 'butfocus')
        wlist.append(addnew)
        for attrib in getattr(self.row, self.metadata.colname): # list-like attribute
            entry = ListEntry(urwid.Columns(
                    [(30, urwid.Text(str(attrib.type))),
                     urwid.Text(unicode(attrib.value).encode("utf-8"))]))
            entry.attrname = attrib.type.name
            urwid.connect_signal(entry, 'activate', self._edit_option)
            urwid.connect_signal(entry, 'delete', self._delete)
            wlist.append(entry)
        listbox = urwid.ListBox(urwid.SimpleFocusListWalker(wlist))
        return urwid.BoxAdapter(urwid.LineBox(listbox), max(7, len(wlist)+2)) 
Example #11
Source File: runner.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def build(self):
        environments = db.get_environment_names()
        reports = [None] + db.get_report_names()

        self._envsel = widgets.ListScrollSelector(environments)
        self._repsel = widgets.ListScrollSelector(reports)
        self._tclist = urwid.SimpleListWalker([])
        butcols = urwid.Columns([
                ("pack", urwid.Text("environment:")),
                AM(self._envsel, "selectable", "butfocus"),
                ("pack", urwid.Text("report:")),
                AM(self._repsel, "selectable", "butfocus"),
            ], dividechars=2)
        header = urwid.Pile([
        AM(urwid.Text("Select environment, report, and set options. Use Tab to switch to environment selector. Selected:"), "subhead"),
                urwid.BoxAdapter(urwid.ListBox(self._tclist), 2),
                butcols,
        ])
        body = self._build_test_selector(False)
        return urwid.Frame(body, header=header, focus_part="body") 
Example #12
Source File: treewidgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def _construct_spacer(self, pos, acc):
        """
        build a spacer that occupies the horizontally indented space between
        pos's parent and the root node. It will return a list of tuples to be
        fed into a Columns widget.
        """
        parent = self._walker.parent_position(pos)
        if parent is not None:
            grandparent = self._walker.parent_position(parent)
            if self._indent > 0 and grandparent is not None:
                parent_sib = self._walker.next_sibling_position(parent)
                draw_vbar = parent_sib is not None and self._arrow_vbar_char is not None
                space_width = self._indent - 1 * (
                    draw_vbar) - self._childbar_offset
                if space_width > 0:
                    void = AttrMap(urwid.SolidFill(' '), self._arrow_att)
                    acc.insert(0, ((space_width, void)))
                if draw_vbar:
                    barw = urwid.SolidFill(self._arrow_vbar_char)
                    bar = AttrMap(
                        barw, self._arrow_vbar_att or self._arrow_att)
                    acc.insert(0, ((1, bar)))
            return self._construct_spacer(parent, acc)
        else:
            return acc 
Example #13
Source File: treewidgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def _construct_line(self, pos):
        """
        builds a list element for given position in the tree.
        It consists of the original widget taken from the TreeWalker and some
        decoration columns depending on the existence of parent and sibling
        positions. The result is a urwid.Culumns widget.
        """
        line = None
        if pos is not None:
            original_widget = self._walker[pos]
            cols = self._construct_spacer(pos, [])

            # Construct arrow leading from parent here,
            # if we have a parent and indentation is turned on
            if self._indent > 0:
                indent = self._construct_first_indent(pos)
                if indent is not None:
                    cols = cols + indent

            # add the original widget for this line
            cols.append(original_widget)
            # construct a Columns, defining all spacer as Box widgets
            line = urwid.Columns(cols, box_columns=range(len(cols))[:-1])
        return line 
Example #14
Source File: widgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def build(self):
        wlist = []
        addnew = urwid.Button("Add")
        urwid.connect_signal(addnew, 'click', self._add_new_attribute)
        addnew = urwid.AttrWrap(addnew, 'selectable', 'butfocus')
        wlist.append(addnew)
        for attrib in getattr(self.row, self.metadata.colname): # list-like attribute
            entry = ListEntry(urwid.Columns(
                    [(30, urwid.Text(str(attrib.type))),
                     urwid.Text(unicode(attrib.value).encode("utf-8"))]))
            entry.attrname = attrib.type.name
            urwid.connect_signal(entry, 'activate', self._edit_attribute)
            urwid.connect_signal(entry, 'delete', self._delete)
            wlist.append(entry)
        listbox = urwid.ListBox(urwid.SimpleFocusListWalker(wlist))
        return urwid.BoxAdapter(urwid.LineBox(listbox), max(7, len(wlist)+2))

    # edit attrib 
Example #15
Source File: gazua.py    From ec2-gazua with MIT License 6 votes vote down vote up
def _create_widget(self, instance):
        widgets = [
            (25, SSHCheckBox(
                instance.name[:21],
                instance.is_connectable,
                self._run_tmux,
                self.not_checkable_callback,
                on_state_change=self.instance_check_changed,
                user_data=instance)),
            (15, ClippedText(instance.private_ip or '-')),
            (15, ClippedText(instance.public_ip or '-')),
            (15, ClippedText(instance.type[:15])),
            (3, ClippedText('O' if instance.is_running else 'X')),
            ClippedText(instance.key_name or '-'),
        ]

        columns_widget = Columns(widgets, dividechars=1)
        return AttrMap(columns_widget, None, 'instance_focus') 
Example #16
Source File: group.py    From stig with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *widgets, cls=urwid.Columns, **kwargs):
        """Create new Group widget

        Widgets can be added by providing mappings as positional arguments.
        Each mapping is then provided to the `add` method as keyword
        arguments.

        cls: `Columns` or `Pile` (or derivatives of either)

        All other keyword arguments are forwarded to `cls` on instantiation.
        """
        self._main = cls([], **kwargs)
        self._items_list = []
        self._items_dict = {}
        # Add initial widgets
        for widget in widgets:
            self.add(**widget)
        super().__init__(self._main) 
Example #17
Source File: spotify-restore.py    From spotify-playlists-2-deezer with MIT License 6 votes vote down vote up
def playlistitems(title):
	global listitems
	bt_sv = urwid.Button("Save")
	urwid.connect_signal(bt_sv, 'click', showmenu)
	bt_ca = urwid.Button("Cancel")
	urwid.connect_signal(bt_ca, 'click', showmenu)
	bt_sa = urwid.Button("Select all")
	urwid.connect_signal(bt_sa, 'click', select_all)
	bt_da = urwid.Button("Deselect all")
	urwid.connect_signal(bt_da, 'click', deselect_all)
	footer = urwid.Columns([bt_sv, bt_sa, bt_da, bt_ca], 1)
	items = []
	for item in playlist_names:
		items.append(urwid.CheckBox(item['name'], is_selected(item['id']), on_state_change=checkbox_callback, user_data=item['id']))
	start.original_widget = TabFrame(urwid.ListBox(urwid.SimpleListWalker(items)), header=urwid.Text("Select Playlists"), footer=footer, focus_part='body')

# main menu button handler 
Example #18
Source File: help_menu.py    From s-tui with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, return_fn):

        self.return_fn = return_fn

        self.help_message = HELP_MESSAGE

        self.time_out_ctrl = urwid.Text(self.help_message)

        cancel_button = urwid.Button(('Exit'), on_press=self.on_cancel)
        cancel_button._label.align = 'center'

        if_buttons = urwid.Columns([cancel_button])

        title = urwid.Text(('bold text', u"  Help Menu  \n"), 'center')

        self.titles = [title,
                       self.time_out_ctrl,
                       if_buttons]

        self.main_window = urwid.LineBox(ViListBox(self.titles)) 
Example #19
Source File: summary_text_list.py    From s-tui with GNU General Public License v2.0 6 votes vote down vote up
def get_text_item_list(self):

        summery_text_list = []
        for key, val in self.source.get_summary().items():
            label_w = urwid.Text(str(key[0:self.MAX_LABEL_L]))
            value_w = urwid.Text(str(val), align='right')
            # This can be accessed by the update method
            self.summary_text_items[key] = value_w
            col_w = urwid.Columns([('weight', 1.5, label_w), value_w])
            try:
                _ = self.visible_summaries[key]
            except KeyError:
                # If an unkonwn key appers, add it to list
                self.visible_summaries[key] = True
            if self.visible_summaries[key]:
                summery_text_list.append(col_w)

        return summery_text_list 
Example #20
Source File: about_menu.py    From s-tui with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, return_fn):

        self.return_fn = return_fn

        self.about_message = ABOUT_MESSAGE

        self.time_out_ctrl = urwid.Text(self.about_message)

        cancel_button = urwid.Button('Exit', on_press=self.on_cancel)
        cancel_button._label.align = 'center'

        if_buttons = urwid.Columns([cancel_button])

        title = urwid.Text(('bold text', u"  About Menu  \n"), 'center')

        self.titles = [title,
                       self.time_out_ctrl,
                       if_buttons]

        self.main_window = urwid.LineBox(ViListBox(self.titles)) 
Example #21
Source File: components.py    From sclack with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, text='', date=None, char='─'):
        text_size = len(text if isinstance(text, str) else text[1]) + 2
        self.text_widget = ('fixed', text_size, urwid.Text(('new_messages_text', text), align='center'))
        body = [
            urwid.Divider(char)
        ]
        if date is None:
            body.append(self.text_widget)
            body.append(('fixed', 1, urwid.Divider(char)))
        else:
            date_size = len(date if isinstance(date, str) else date[1]) + 2
            date_widget = ('fixed', date_size, urwid.Text(date, align='center'))
            body.append(date_widget)
            body.append(urwid.Divider(char))
            body.append(self.text_widget)
            body.append(('fixed', 1, urwid.Divider(char)))
        super(NewMessagesDivider, self).__init__(urwid.Columns(body), 'new_messages_line') 
Example #22
Source File: widgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def get_items(self):
        q = self.session.query(self.modelclass).order_by(self._orderby)
        if self._filter:
            filt = []
            for name, value in self._filter.items():
                filt.append(getattr(self.modelclass, name).like("%{}%".format(value)))
            q = q.filter(*filt)
        items = []
        for row in q:
            disprow = []
            pk = getattr(row, str(self._pkname))
            disprow.append( ('fixed', 6, urwid.Text(str(pk))) )
            for colname in self._colnames:
                md = self.metadata[colname]
                fmt, width = self._FORMATS.get(md.coltype, ("{!s:10.10}", 10))
                disprow.append( ('fixed', width, urwid.Text(fmt.format(getattr(row, colname)))) )
            le = ListEntry(urwid.Columns(disprow, dividechars=1))
            urwid.connect_signal(le, 'activate', self._edit, pk)
            urwid.connect_signal(le, 'delete', self._delete, pk)
            items.append(le)
        return urwid.SimpleListWalker(items) 
Example #23
Source File: widgets.py    From pycopia with 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 #24
Source File: widgets.py    From pycopia with 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 #25
Source File: widgets.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def _create_relation_input(self):
        choices = dict(models.get_choices(self.session, self.modelclass, self.metadata.colname, None))
        addnew = urwid.Button("Add New")
        urwid.connect_signal(addnew, 'click', self._add_new_related)
        # Cancel
        canc = urwid.Button("Cancel")
        urwid.connect_signal(canc, 'click', self._cancel)
        butcol = urwid.Columns([AM(addnew, "buttn", "buttnf"), AM(canc, "buttn", "buttnf")])
        wlist = [butcol]
        if self.metadata.nullable:
            entry = ListEntry(urwid.Text("None (remove)"))
            urwid.connect_signal(entry, 'activate', self._single_select)
            wlist.append(entry)
        for pk, cname in choices.items():
            entry = ListEntry(urwid.Text(cname))
            urwid.connect_signal(entry, 'activate', self._single_select, pk)
            wlist.append(entry)
        listbox = urwid.ListBox(urwid.SimpleListWalker(wlist))
        return urwid.BoxAdapter(urwid.LineBox(listbox), 9) 
Example #26
Source File: widgets.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def build(self):
        self._pkname = models.get_primary_key_name(self.modelclass)
        self._orderby = self._pkname
        self._filter = {}
        self._colnames = models.get_rowdisplay(self.modelclass)
        # col headings
        colforms = [('fixed', 6, urwid.Text(("colhead", "filt:")))]
        colnames = [('fixed', 6, urwid.Text(("colhead", self._pkname))) ]
        clsname = self.modelclass.__name__
        for colname in self._colnames:
            md = self.metadata[colname]
            fmt, width = self._FORMATS.get(md.coltype, ("{!s:10.10}", 10))
            colnames.append( ('fixed', width, urwid.Text(("colhead", md.colname))) )
            if md.coltype in ("TEXT", "VARCHAR"):
                fb = SimpleEdit() # TODO use FilterInput to select sort order, once it works
                fb.colname = md.colname
                urwid.connect_signal(fb, "change", self._set_filter)
                colforms.append(('fixed', width, AM(fb, "selectable", "butfocus")))
            else:
                colforms.append(('fixed', width, urwid.Divider()))

        cb = urwid.Button("Create new {}".format(clsname.lower()))
        urwid.connect_signal(cb, 'click', self._create_cb)
        header = urwid.Pile( [
                urwid.Columns([AM(urwid.Text(clsname), "subhead"), AM(cb, "selectable", "butfocus") ], focus_column=1), 
                urwid.Columns(colforms, dividechars=1),
                urwid.Columns(colnames, dividechars=1),
                ])
        listbox = urwid.ListBox(self.get_items())
        return urwid.Frame(urwid.AttrMap(listbox, 'body'), header=header, focus_part="body") 
Example #27
Source File: app.py    From sclack with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        self._loading = False
        self.config = config
        self.quick_switcher = None
        self.set_snooze_widget = None
        self.workspaces = list(config['workspaces'].items())
        self.store = Store(self.workspaces, self.config)
        Store.instance = self.store
        urwid.set_encoding('UTF-8')
        sidebar = LoadingSideBar()
        chatbox = LoadingChatBox('Everything is terrible!')
        palette = themes.get(config['theme'], themes['default'])

        custom_loop = SclackEventLoop(loop=loop)
        custom_loop.set_exception_handler(self._exception_handler)

        if len(self.workspaces) <= 1:
            self.workspaces_line = None
        else:
            self.workspaces_line = Workspaces(self.workspaces)

        self.columns = urwid.Columns([
            ('fixed', config['sidebar']['width'], urwid.AttrWrap(sidebar, 'sidebar')),
            urwid.AttrWrap(chatbox, 'chatbox')
        ])
        self._body = urwid.Frame(self.columns, header=self.workspaces_line)

        self.urwid_loop = urwid.MainLoop(
            self._body,
            palette=palette,
            event_loop=custom_loop,
            unhandled_input=self.unhandled_input
        )
        self.configure_screen(self.urwid_loop.screen)
        self.last_keypress = (0, None) 
Example #28
Source File: complex_bar_graph.py    From s-tui with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,
                 title,
                 sub_title_list,
                 y_label,
                 bar_graph_vector,
                 visible_graph_list):
        for bar_graph in bar_graph_vector:
            if not isinstance(bar_graph, ScalableBarGraph):
                raise Exception(
                    'graph vector items must be ScalableBarGraph')
        if not self.check_label(y_label):
            raise Exception(
                'Y label must be a valid label')

        self.visible_graph_list = visible_graph_list
        self.bar_graph_vector = []
        self.set_graph(bar_graph_vector)

        self.y_label_and_graphs = urwid.WidgetPlaceholder(urwid.Columns([]))
        self.y_label = []
        self.set_y_label(y_label)

        list_w = urwid.ListBox(urwid.SimpleFocusListWalker([]))
        self.title = urwid.WidgetPlaceholder(list_w)
        self.sub_title_list = sub_title_list
        self.set_title(title)

        super(LabeledBarGraphVector, self).__init__(urwid.Pile([]))
        self.set_visible_graphs(visible_graph_list) 
Example #29
Source File: complex_bar_graph.py    From s-tui with GNU General Public License v2.0 5 votes vote down vote up
def set_visible_graphs(self, visible_graph_list=None):
        """Show a column of the graph selected for display"""
        if visible_graph_list is None:
            visible_graph_list = self.visible_graph_list

        vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line')

        graph_vector_column_list = []
        for state, graph, sub_title in zip(visible_graph_list,
                                           self.bar_graph_vector,
                                           self.sub_title_list):
            if state:
                text_w = urwid.Text(sub_title, align='center')
                sub_title_widget = urwid.ListBox([text_w])
                graph_a = [('fixed', 1, sub_title_widget),
                           ('weight', 1, graph)]
                graph_and_title = urwid.Pile(graph_a)
                graph_vector_column_list.append(('weight', 1, graph_and_title))
                graph_vector_column_list.append(('fixed', 1, vline))

        # if all sub graph are disabled
        if not graph_vector_column_list:
            self.visible_graph_list = visible_graph_list
            self.original_widget = urwid.Pile([])
            return

        # remove the last vertical line separator
        graph_vector_column_list.pop()

        y_label_a = ('weight', 1, urwid.Columns(graph_vector_column_list))
        y_label_and_graphs = [self.y_label,
                              y_label_a]
        column_w = urwid.Columns(y_label_and_graphs, dividechars=1)
        y_label_and_graphs_widget = urwid.WidgetPlaceholder(column_w)

        init_widget = urwid.Pile([('fixed', 1, self.title),
                                  ('weight', 1, y_label_and_graphs_widget)])

        self.visible_graph_list = visible_graph_list
        self.original_widget = init_widget 
Example #30
Source File: ui.py    From zulip-terminal with Apache License 2.0 5 votes vote down vote up
def main_window(self) -> Any:
        self.left_panel = self.left_column_view()
        self.center_panel = self.message_view()
        self.right_panel = self.right_column_view()
        if self.controller.autohide:
            body = [
                (View.LEFT_WIDTH, self.left_panel),
                ('weight', 10, self.center_panel),
                (0, self.right_panel),
            ]
        else:
            body = [
                (View.LEFT_WIDTH, self.left_panel),
                ('weight', 10, self.center_panel),
                (View.RIGHT_WIDTH, self.right_panel),
            ]
        self.body = urwid.Columns(body, focus_column=0)
        # NOTE: set_focus_changed_callback is actually called before the
        # focus is set, so the message is not read yet, it will be read when
        # the focus is changed again either vertically or horizontally.
        self.body._contents.set_focus_changed_callback(
            self.model.msg_list.read_message)
        div_char = '═'

        title_text = " {full_name} ({email}) - {server_name} ({url}) ".format(
                     full_name=self.model.user_full_name,
                     email=self.model.user_email,
                     server_name=self.model.server_name,
                     url=self.model.server_url)

        title_bar = urwid.Columns([
            urwid.Divider(div_char=div_char),
            (len(title_text), urwid.Text([title_text])),
            urwid.Divider(div_char=div_char),
        ])

        w = urwid.Frame(self.body, title_bar, focus_part='body',
                        footer=self.footer_view())
        return w