Python urwid.SimpleFocusListWalker() Examples

The following are 30 code examples for showing how to use urwid.SimpleFocusListWalker(). 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: wikicurses   Author: ids1024   File: main.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        def selectButton(radio_button, new_state, parameter):
            if new_state:
                closeOverlay()
                self._select(parameter)

        super().__init__(urwid.SimpleFocusListWalker([]))
        buttons = []
        for i, item in enumerate(self._items()):
            if isinstance(item, urwid.Widget):
                self.body.append(item)
                continue
            elif isinstance(item, tuple):
                name, selected, parameter = item
            else:
                parameter = name = item
                selected = False
            self.body.append(urwid.RadioButton(buttons, name, selected,
                                               selectButton, parameter))
            if selected:
                self.set_focus(i) 
Example 2
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 6 votes vote down vote up
def quote_view_action(self, button, message):
        """
        Callback function to view a quote from the message object menu.
        """
        widget = OptionsMenu(
            ActionBox(urwid.SimpleFocusListWalker(self.make_message_body(message))),
            **self.frame_theme(">>%d" % message["post_id"])
        )

        self.loop.widget = urwid.Overlay(
            widget, self.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            width=("relative", 98),
            height=("relative", 60)
        ) 
Example 3
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 6 votes vote down vote up
def formatting_help(self, *_):
        """
        Pops a help window for formatting directives.
        """
        # we can "recycle" the server's formatting abilities to
        # use the same syntax for the help text itself
        message = network.fake_message(
            "\n\n".join(format_help), format="sequential")

        widget = OptionsMenu(
            urwid.ListBox(urwid.SimpleFocusListWalker(app.make_message_body(message, True))),
            **self.frame_theme("Formatting Help")
        )

        va = 5 if self.window_split else 50
        vh = 45 if self.window_split else 75
        app.loop.widget = urwid.Overlay(
            widget, app.loop.widget,
            align=("relative", 50),
            valign=("relative", va),
            width=self.prefs["max_text_width"],
            height=("relative", vh)
        ) 
Example 4
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 6 votes vote down vote up
def set_escape_key(self, button, args):
        mode = args[0]
        widget = OptionsMenu(
            urwid.ListBox(urwid.SimpleFocusListWalker([
                urwid.Text("Press Enter when done"),
                urwid.AttrMap(KeyPrompt(
                    self.prefs["edit_escapes"][mode],
                    self.save_escape_key,
                    [mode]
                ), "opt_prompt")])),
            **self.frame_theme("Set key for " + mode)
        )

        app.loop.widget = urwid.Overlay(
            urwid.AttrMap(widget, "30"),
            app.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            width=25, height=5
        ) 
Example 5
Project: stig   Author: rndusr   File: keymap_test.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_evaluated_key_does_not_replace_original_key(self):
        # Create a list of widgets that translate 'j' to 'down' in their
        # keypress() methods.
        lst_contents = [self.mk_widget(urwid.Text, str(i), context='item')
                        for i in range(1, 10)]
        self.keymap.bind('j', context='item', action=Key('down'))

        # Create ListBox with separate key context.  If the ListBox gets to
        # handle 'j', it just checks a mark we can look for.
        lst_widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(lst_contents), context='list')
        lst_got_j = FakeAction()
        self.keymap.bind('j', context='list', action=lst_got_j)

        # Make sure everything works regularly
        size = (3, 3)
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=0)
        lst_widget.keypress(size, 'down')
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=1)

        # Do the actual test: Pressing 'j' should pass 'j' to the focused item,
        # which evaluates it to 'down'.  But the list widget must get 'j'.
        lst_widget.keypress(size, 'j')
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=1)
        self.assertEqual(lst_got_j.callnum, 1) 
Example 6
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 7
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 8
Project: hangups   Author: tdryer   File: __main__.py    License: MIT License 6 votes vote down vote up
def __init__(self, coroutine_queue, conversation, on_cancel, on_save,
                 keybindings):
        self._coroutine_queue = coroutine_queue
        self._conversation = conversation
        edit = urwid.Edit(edit_text=get_conv_name(conversation))
        items = [
            urwid.Text('Rename conversation:'),
            edit,
            urwid.Button(
                'Save',
                on_press=lambda _: self._rename(edit.edit_text, on_save)
            ),
            urwid.Button('Cancel', on_press=lambda _: on_cancel()),
        ]
        list_walker = urwid.SimpleFocusListWalker(items)
        list_box = ListBox(keybindings, list_walker)
        super().__init__(list_box) 
Example 9
Project: sncli   Author: insanum   File: view_help.py    License: 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 10
Project: sncli   Author: insanum   File: view_log.py    License: MIT License 5 votes vote down vote up
def __init__(self, config):
        self.config = config
        super(ViewLog, self).__init__(urwid.SimpleFocusListWalker([])) 
Example 11
Project: sncli   Author: insanum   File: view_log.py    License: MIT License 5 votes vote down vote up
def update_log(self):
        lines = []
        f = open(self.config.logfile)
        for line in f:
            lines.append(
                urwid.AttrMap(urwid.Text(line.rstrip()),
                                'note_content',
                                'note_content_focus'))
        f.close()
        if self.config.get_config('log_reversed') == 'yes':
            lines.reverse()
        self.body[:] = urwid.SimpleFocusListWalker(lines)
        self.focus_position = 0 
Example 12
Project: sncli   Author: insanum   File: view_note.py    License: MIT License 5 votes vote down vote up
def __init__(self, config, args):
        self.config = config
        self.ndb = args['ndb']
        self.key = args['key']
        self.log = args['log']
        self.search_string = ''
        self.search_mode = 'gstyle'
        self.search_direction = ''
        self.note = self.ndb.get_note(self.key) if self.key else None
        self.old_note = None
        self.tabstop = int(self.config.get_config('tabstop'))
        self.clipboard = Clipboard()
        super(ViewNote, self).__init__(
                  urwid.SimpleFocusListWalker(self.get_note_content_as_list())) 
Example 13
Project: sncli   Author: insanum   File: view_note.py    License: MIT License 5 votes vote down vote up
def update_note_view(self, key=None, version=None):
        if key: # setting a new note
            self.key      = key
            self.note     = self.ndb.get_note(self.key)
            self.old_note = None

        if self.key and version:
            # verify version is within range
            if int(version) <= 0 or int(version) >= self.note['version'] + 1:
                self.log('Version v{0} is unavailable (key={1})'.
                         format(version, self.key))
                return

        if (not version and self.old_note) or \
           (self.key and version and version == self.note['version']):
            self.log('Displaying latest version v{0} of note (key={1})'.
                     format(self.note['version'], self.key))
            self.old_note = None
        elif self.key and version:
            # get a previous version of the note
            self.log('Fetching version v{0} of note (key={1})'.
                     format(version, self.key))
            version_note = self.ndb.get_note_version(self.key, version)
            if not version_note:
                self.log('Failed to get version v{0} of note (key={1})'.
                         format(version, self.key))
                # don't do anything, keep current note/version
            else:
                self.old_note = version_note

        self.body[:] = \
            urwid.SimpleFocusListWalker(self.get_note_content_as_list())
        if not self.search_string:
            self.focus_position = 0 
Example 14
Project: sncli   Author: insanum   File: view_titles.py    License: MIT License 5 votes vote down vote up
def __init__(self, config, args):
        self.config = config
        self.ndb = args['ndb']
        self.search_string = args['search_string']
        self.log = args['log']
        self.note_list, self.match_regex, self.all_notes_cnt = \
            self.ndb.filter_notes(self.search_string, sort_mode=self.config.get_config('sort_mode'))
        super(ViewTitles, self).__init__(
                  urwid.SimpleFocusListWalker(self.get_note_titles())) 
Example 15
Project: sncli   Author: insanum   File: view_titles.py    License: MIT License 5 votes vote down vote up
def update_note_list(self, search_string, search_mode='gstyle', sort_mode='date'):
        self.search_string = search_string
        self.note_list, self.match_regex, self.all_notes_cnt = \
            self.ndb.filter_notes(self.search_string, search_mode, sort_mode=sort_mode)
        self.body[:] = \
            urwid.SimpleFocusListWalker(self.get_note_titles())
        if len(self.note_list) == 0:
            self.log('No notes found!')
        else:
            self.focus_position = 0 
Example 16
Project: sncli   Author: insanum   File: view_titles.py    License: MIT License 5 votes vote down vote up
def sort_note_list(self, sort_mode):
        self.ndb.filtered_notes_sort(self.note_list, sort_mode)
        self.body[:] = \
            urwid.SimpleFocusListWalker(self.get_note_titles()) 
Example 17
Project: wikicurses   Author: ids1024   File: main.py    License: MIT License 5 votes vote down vote up
def __init__(self, page):
        super().__init__(urwid.SimpleFocusListWalker([]))
        self._content = page.content.copy()
        self._render() 
Example 18
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, streams_btn_list: List[Any], view: Any) -> None:
        self.view = view
        self.log = urwid.SimpleFocusListWalker(streams_btn_list)
        self.streams_btn_list = streams_btn_list
        self.focus_index_before_search = 0
        list_box = urwid.ListBox(self.log)
        self.stream_search_box = PanelSearchBox(self,
                                                'SEARCH_STREAMS',
                                                self.update_streams)
        super().__init__(list_box, header=urwid.LineBox(
            self.stream_search_box, tlcorner='─', tline='', lline='',
            trcorner='─', blcorner='─', rline='',
            bline='─', brcorner='─'
        ))
        self.search_lock = threading.Lock() 
Example 19
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, topics_btn_list: List[Any], view: Any,
                 stream_button: Any) -> None:
        self.view = view
        self.log = urwid.SimpleFocusListWalker(topics_btn_list)
        self.topics_btn_list = topics_btn_list
        self.stream_button = stream_button
        self.focus_index_before_search = 0
        self.list_box = urwid.ListBox(self.log)
        self.topic_search_box = PanelSearchBox(self,
                                               'SEARCH_TOPICS',
                                               self.update_topics)
        self.header_list = urwid.Pile([self.stream_button,
                                       urwid.Divider('─'),
                                       self.topic_search_box])
        super().__init__(self.list_box, header=urwid.LineBox(
            self.header_list, tlcorner='─', tline='', lline='',
            trcorner='─', blcorner='─', rline='',
            bline='─', brcorner='─'
        ))
        self.search_lock = threading.Lock() 
Example 20
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, users_btn_list: List[Any]) -> None:
        self.log = urwid.SimpleFocusListWalker(users_btn_list)
        super().__init__(self.log) 
Example 21
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def menu_view(self) -> Any:
        count = self.model.unread_counts.get('all_msg', 0)
        self.view.home_button = HomeButton(self.controller,
                                           count=count,
                                           width=self.width)

        count = self.model.unread_counts.get('all_pms', 0)
        self.view.pm_button = PMButton(self.controller,
                                       count=count,
                                       width=self.width)

        self.view.mentioned_button = MentionedButton(
            self.controller,
            width=self.width,
            count=self.model.unread_counts['all_mentions'])

        # Starred messages are by definition read already
        self.view.starred_button = StarredButton(self.controller,
                                                 width=self.width)

        menu_btn_list = [
            self.view.home_button,
            self.view.pm_button,
            self.view.mentioned_button,
            self.view.starred_button,
        ]
        w = urwid.ListBox(urwid.SimpleFocusListWalker(menu_btn_list))
        return w 
Example 22
Project: zulip-terminal   Author: zulip   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, controller: Any, widgets: List[Any],
                 command: str, requested_width: int, title: str) -> None:
        self.controller = controller
        self.command = command
        self.title = title
        self.log = urwid.SimpleFocusListWalker(widgets)

        max_cols, max_rows = controller.maximum_popup_dimensions()

        self.width = min(max_cols, requested_width)

        height = self.calculate_popup_height(widgets, self.width)
        self.height = min(max_rows, height)

        super().__init__(self.log) 
Example 23
Project: topydo   Author: bram85   File: CompletionBoxWidget.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.items = urwid.SimpleFocusListWalker([])
        self.min_width = 0

        super().__init__(self.items) 
Example 24
Project: topydo   Author: bram85   File: TodoListWidget.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, p_view, p_title, p_keymap):
        self._view = None

        self.keymap = p_keymap
        # store a state for multi-key shortcuts (e.g. 'gg')
        self.keystate = None
        # store offset length for postpone command (e.g. '3' for 'p3w')
        self._pp_offset = None

        self._title_widget = urwid.Text(p_title, align='center')

        self.todolist = urwid.SimpleFocusListWalker([])
        self.listbox = urwid.ListBox(self.todolist)
        self.view = p_view

        pile = urwid.Pile([
            (1, urwid.Filler(self._title_widget)),
            (1, urwid.Filler(urwid.Divider('\u2500'))),
            ('weight', 1, self.listbox),
        ])

        pile.focus_position = 2

        super().__init__(pile)

        urwid.register_signal(TodoListWidget, ['execute_command_silent',
                                               'execute_command',
                                               'refresh',
                                               'add_pending_action',
                                               'remove_pending_action',
                                               'repeat_cmd',
                                               'column_action',
                                               'show_keystate',
                                               'toggle_mark',
                                               ]) 
Example 25
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        self.prefs = bbjrc("load")
        self.client_pinned_threads = load_client_pins()
        self.usermap = {}
        self.match_data = {
            "query": "",
            "matches": [],
            "position": 0,
        }

        try:
            self.theme = themes[self.prefs["frame_theme"]].copy()
            if isinstance(self.prefs["custom_divider_char"], str):
                self.theme["divider"] = self.prefs["custom_divider_char"]
        except KeyError:
            exit("Selected theme does not exist. Please check "
                 "the `frame_theme` value in ~/.bbjrc")

        self.mode = None
        self.thread = None
        self.window_split = False
        self.last_index_pos = None
        self.last_alarm = None

        if self.prefs["use_custom_frame_title"]:
            self.frame_title = self.prefs["frame_title"]
        else:
            self.frame_title = network.instance_info["instance_name"]

        self.walker = urwid.SimpleFocusListWalker([])
        self.box = ActionBox(self.walker)
        self.body = urwid.AttrMap(
            urwid.LineBox(self.box, **self.frame_theme(self.frame_title)),
            "default"
        )
        self.loop = urwid.MainLoop(
            urwid.Frame(self.body),
            palette=colormap,
            handle_mouse=self.prefs["mouse_integration"]) 
Example 26
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 5 votes vote down vote up
def quote_view_menu(self, button, post_ids):
        """
        Receives a list of quote ids and makes a frilly menu to pick one to view.
        It retrieves messages objects from the thread and attaches them to a
        callback to `quote_view_action`
        """
        buttons = []
        for pid in post_ids:
            try:
                message = self.thread["messages"][pid]
                if len(post_ids) == 1:
                    return self.quote_view_action(button, message)
                author = self.usermap[message["author"]]
                label = [
                    ("button", ">>%d " % pid),
                    "(",
                    (str(author["color"]),
                     author["user_name"]),
                    ")"
                ]
                buttons.append(cute_button(label, self.quote_view_action, message))
            except IndexError:
                continue # users can submit >>29384234 garbage references

        widget = OptionsMenu(
            urwid.ListBox(urwid.SimpleFocusListWalker(buttons)),
            **self.frame_theme("View a Quote")
        )

        self.loop.widget = urwid.Overlay(
            widget, self.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            height=len(buttons) + 3,
            width=30
        ) 
Example 27
Project: bbj   Author: bbj-dev   File: main.py    License: 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
Project: bbj   Author: bbj-dev   File: main.py    License: 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 29
Project: bbj   Author: bbj-dev   File: main.py    License: 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 30
Project: bbj   Author: bbj-dev   File: main.py    License: MIT License 5 votes vote down vote up
def general_help(self):
        """
        Show a general help dialog. In all honestly, its not
        very useful and will only help people who have never
        really used terminal software before =)
        """
        widget = OptionsMenu(
            urwid.ListBox(
                urwid.SimpleFocusListWalker([
                    urwid_rainbows(
                        "This is BBJ, a client/server textboard made for tildes!",
                        True),
                    urwid.Text(("dim", "...by ~desvox")),
                    urwid.Divider(self.theme["divider"]),
                    urwid.Button("Post Formatting Help", self.formatting_help),
                    urwid.Divider(self.theme["divider"]),
                    urwid.Text(general_help)
                ])),
            **self.frame_theme("?????")
        )

        app.loop.widget = urwid.Overlay(
            widget, app.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            width=30,
            height=("relative", 60)
        )