Пример #1
0
class TestSuiteWidget(urwid.TreeWidget):

    unexpanded_icon = urwid.SelectableIcon("▹", 0)
    expanded_icon = urwid.SelectableIcon("▿", 0)

    def __init__(self, *args, **kwargs):
        self.selected_w = urwid.Text("[ ]")
        super().__init__(*args, **kwargs)
        # insert an extra AttrWrap for our own use
        self._w = urwid.AttrWrap(self._w, None)
        self._w.attr = "body"
        self._w.focus_attr = "focus"
        self.update_w()

        self.expanded = True
        self.update_expanded_icon()

    def load_inner_widget(self):
        main_w = urwid.Text(self.get_display_text())
        return urwid.Columns([("fixed", 3, self.selected_w), main_w], dividechars=1)

    def get_display_text(self):
        return self.get_node().get_key()

    def selectable(self):
        return True

    def keypress(self, size, key):
        """allow subclasses to intercept keystrokes"""
        key = self.__super.keypress(size, key)
        if key:
            key = self.unhandled_keys(size, key)
        return key

    def unhandled_keys(self, size, key):
        """
        Override this method to intercept keystrokes in subclasses.
        Default behavior: Toggle flagged on space, ignore other keys.
        """
        if key == " ":
            self.get_node().toggle_flag()
        else:
            return key

    def update_w(self):
        """Update the attributes of self.widget based on self.flagged.
        """
        node = self.get_node()
        if node.flagged:
            if node.all_flagged:
                icon = "x"
            elif node.any_flagged:
                icon = "~"
            else:
                raise ValueError()
            self.selected_w.set_text("[%s]" % icon)
        else:
            self.selected_w.set_text("[ ]")
Пример #2
0
    def __init__(self, scrobble):
        self.content = self.scrobble = scrobble

        info = scrobble.scrobble_info
        text = '{} - {}'.format(info.artist, info.title)

        super(SelectableScrobble, self).__init__(urwid.SelectableIcon(text))
Пример #3
0
 def get_mark(self):
     """Gets an expanded, collapsed, or leaf icon."""
     if self.is_leaf:
         char = self.icon_chars[2]
     else:
         char = self.icon_chars[int(self.expanded)]
     return urwid.SelectableIcon(('mark', char), 0)
Пример #4
0
    def widget(self, count: int) -> Any:
        if count < 0:
            count_text = 'M'  # Muted
        elif count == 0:
            count_text = ''
        else:
            count_text = str(count)

        # Note that we don't modify self._caption
        max_caption_length = (self.width_for_text_and_count - len(count_text))
        if len(self._caption) > max_caption_length:
            caption = (self._caption[:max_caption_length - 1] +
                       '\N{HORIZONTAL ELLIPSIS}')
        else:
            caption = self._caption
        num_extra_spaces = (self.width_for_text_and_count - len(count_text) -
                            len(caption))

        # NOTE: Generated text does not include space at end
        return urwid.AttrMap(
            urwid.SelectableIcon([
                ' ', self.prefix_character, self.post_prefix_spacing,
                '{}{}'.format(caption, num_extra_spaces * ' '), ' ',
                ('idle', count_text)
            ], self.width_for_text_and_count + 5),  # cursor location
            self.text_color,
            'selected')
Пример #5
0
def stream_list_submenu(title, data, m_id):
    s_links = []
    viewer_order = sorted(data['stream_links'],
                          key=itemgetter('viewers'),
                          reverse=True)
    # viewer_order = data['stream_links']
    for new_s in viewer_order:
        link_txt = '[{}] {} - {} [Viewers: {}]'.format(new_s['provider'],
                                                       new_s['channel'],
                                                       new_s['title'],
                                                       new_s['viewers'])
        add_link = urwid.Button(link_txt)
        add_link._w = urwid.AttrMap(urwid.SelectableIcon(['', link_txt], 0),
                                    None, 'reversed')
        urwid.connect_signal(add_link,
                             'click',
                             open_link,
                             user_arg=new_s['link'])
        s_links.append(add_link)
    s_links.append(urwid.Text(''))  # links separator
    s_links.append(menu_button('Return to match', m_id=m_id, callback=go_back))
    body = urwid.ListBox(urwid.SimpleFocusListWalker(s_links))
    top.open_box(body,
                 title='dotaticker - Live Streams for {} vs {}'.format(
                     data['r_tag'], data['d_tag']))
Пример #6
0
 def __init__(self,
              caption: Any,
              email: str = '',
              controller: Any = None,
              view: Any = None,
              user: str = False,
              stream: bool = False,
              color: str = None) -> None:
     self.caption = caption  # str
     if stream:  # caption = [stream_name, stream_id, color]
         self.caption = caption[0]
         self.stream_id = caption[1]
         color = caption[2]
         color = color[:2] + color[3] + color[5]
         view.palette['default'].append((color, '', '', '', color, 'black'))
     self.email = email
     super(MenuButton, self).__init__("")
     self._w = urwid.AttrMap(
         urwid.SelectableIcon([u'  # ', self.caption], 0), color,
         'selected')
     if stream:
         urwid.connect_signal(self, 'click', controller.narrow_to_stream)
         urwid.connect_signal(self, 'click', view.write_box.stream_box_view)
     if user:
         urwid.connect_signal(self, 'click', controller.narrow_to_user)
         urwid.connect_signal(self, 'click',
                              view.write_box.private_box_view)
     if self.caption == u'All messages':
         urwid.connect_signal(self, 'click', controller.show_all_messages)
     if self.caption == u'Private messages':
         urwid.connect_signal(self, 'click', controller.show_all_pm)
Пример #7
0
 def __init__(self, name, main):
     self.main = main
     super(FolderListItem, self).__init__(name)
     urwid.connect_signal(self, 'click', self.open_folder)
     self._w = urwid.AttrMap(urwid.SelectableIcon(name, 1),
                             None,
                             focus_map='reversed')
Пример #8
0
 def __init__(self, controller: Any = None) -> None:
     self.caption = 'Private messages'
     super(PMButton, self).__init__("")
     self._w = urwid.AttrMap(
         urwid.SelectableIcon([u'  \u260F  ', self.caption], 0), None,
         'selected')
     urwid.connect_signal(self, 'click', controller.show_all_pm)
Пример #9
0
 def set_selected_mode(self, mode: EditPropagateMode) -> None:
     self.mode = mode
     self._w = urwid.AttrMap(
         urwid.SelectableIcon(EDIT_MODE_CAPTIONS[self.mode], self.width),
         None,
         "selected",
     )
Пример #10
0
 def widget(self, count: int) -> Any:
     return urwid.AttrMap(urwid.SelectableIcon(
         [(self.color, u' # '), self.caption,
          ('idle', '' if count <= 0 else ' ' + str(count))],
         len(self.caption) + 2),
         None,
         'selected')
Пример #11
0
 def widget(self, count: int) -> Any:
     return urwid.AttrMap(urwid.SelectableIcon(
         [u' \N{BULLET} ', self.caption,
          ('idle', '' if count <= 0 else ' ' + str(count))],
         len(self.caption) + 4),
         None,
         'selected')
Пример #12
0
 def __init__(self, caption, callback, user_arg=None):
     """Initialize a button."""
     super(ActionButton, self).__init__("")
     self.caption = caption
     urwid.connect_signal(self, 'click', callback, user_arg)
     self._w = urwid.AttrMap(urwid.SelectableIcon([u'> ', self.caption], 0),
                             'button', 'button_reversed')
Пример #13
0
 def __init__(self, caption, callback):
     """Initialize a button."""
     super(PasswordButton, self).__init__("")
     self.caption = caption[:-len('.gpg')]
     urwid.connect_signal(self, 'click', callback, self.caption)
     self._w = urwid.AttrMap(urwid.SelectableIcon([u'├ ', self.caption], 0),
                             'button', 'button_reversed')
Пример #14
0
 def __init__(self, value, icon):
     self._value = value
     self._icon = icon
     self.text = urwid.SelectableIcon('    {} {}'.format(self._icon, self._value))
     self.text.set_layout('left', 'clip', None)
     self.content = urwid.AttrWrap(self.text, 'default', 'selected')
     super(AbstractListItem, self).__init__([self.content])
Пример #15
0
 def __init__(self):
     self._left = urwid.SelectableIcon('', cursor_position=1000)
     self._left.set_layout('left', 'clip', None)
     self._right = urwid.Text('x')
     self._content = urwid.Columns(
         [self._left, ('pack', self._right), ('pack', urwid.Text(' '))])
     self._wrap = urwid.AttrWrap(self._content, 'line1')
Пример #16
0
 def __init__(self, caption, callback=None, user_data=None):
     super(SimpleButton, self).__init__("")
     if callback:
         urwid.connect_signal(self, 'click', callback, user_data)
     label = urwid.SelectableIcon(caption, 0)
     label.set_align_mode('center')
     self._w = urwid.AttrMap(label, None, 'simple_button')
Пример #17
0
    def _create_entry(self, position, story_id, story):

        data = {"story_id": story_id}

        w1 = urwid.Text(("entry main", "%2s. " % position))

        markup = [("entry main", story["title"])]
        # BBB: walrus operator
        url = story.get("url")
        if url:
            data["url"] = url
            markup.append(("entry url", " (%s)" % url2domain(url)))
        # NB: cursor_position is set to a big number to make it disappear
        w21 = urwid.SelectableIcon(markup, cursor_position=float("inf"))

        if story["type"] == "job":
            text = "%s" % timeago.format(story["time"])
        else:
            text = "%s %s by %s %s" % (
                story["score"],
                pluralize("point", story["score"]),
                story["by"],
                timeago.format(story["time"]),
            )
        # BBB: walrus operator
        comments = story.get("descendants")
        if comments is not None:
            text += " | %s %s" % (comments, pluralize("comment", comments))
        w22 = urwid.Text(text)

        w2 = urwid.Pile([w21, w22])

        w = urwid.Columns([("pack", w1), w2])

        return Entry(w, data)
Пример #18
0
    def update_widget(self, count_text: Tuple[Optional[str], str],
                      text_color: Optional[str]) -> Any:
        # Note that we don't modify self._caption
        max_caption_length = self.width_for_text_and_count - len(count_text[1])
        if len(self._caption) > max_caption_length:
            caption = (self._caption[:max_caption_length - 1] +
                       "\N{HORIZONTAL ELLIPSIS}")
        else:
            caption = self._caption
        num_extra_spaces = (self.width_for_text_and_count -
                            len(count_text[1]) - len(caption))

        # NOTE: Generated text does not include space at end
        # NOTE: Some are styles, so are not included in f-string
        self._w = urwid.AttrMap(
            urwid.SelectableIcon(
                [
                    " ",
                    self.prefix_character,
                    f"{self.post_prefix_spacing}{caption}{num_extra_spaces * ' '} ",
                    count_text,
                ],
                self.width_for_text_and_count + 5,  # cursor location
            ),
            text_color,
            "selected",
        )
Пример #19
0
 def update_expanded_icon(self):
     if self.get_node().get_key() == "..":
         self._w.base_widget.widget_list[0] = urwid.AttrMap(
             urwid.SelectableIcon(" ", 0), "browser dirmark",
             "browser dirmark_focus")
     else:
         super().update_expanded_icon()
Пример #20
0
    def __init__(self, label, signal, user_data='', uri='', id=-1):
        self.id = id
        self.uri = uri
        super(ffIdButton, self).__init__(label, signal)
        #change display widget from default thing

        self._w = urwid.AttrMap(urwid.SelectableIcon(label, 2), None, 'body')
Пример #21
0
 def __init__(self, email, main):
     self.main = main
     super(MessageListItem, self).__init__("")
     urwid.connect_signal(self, 'click', self.open_message)
     self._w = urwid.AttrMap(urwid.SelectableIcon(email, 1),
                             None,
                             focus_map='reversed')
Пример #22
0
 def __init__(self, caption):
     self.caption = caption
     cursor_position = len(caption) + 1
     super(SelectGroupButton, self).__init__("")
     self._w = urwid.AttrMap(
         urwid.SelectableIcon(['', caption], cursor_position), None,
         'selected')
Пример #23
0
    def __init__(self, track):
        self.track = track
        self.rating = self.RATING_ICONS[track.rating]
        self.explicit = self.EXPLICIT_ICONS[track.explicit_rating]
        self.index = 0
        self.state = SongListItem.STATE_IDLE
        self.line1_left = urwid.SelectableIcon('', cursor_position=1000)
        self.line1_left.set_layout('left', 'clip', None)
        self.line1_right = urwid.Text('x')
        self.line1 = urwid.Columns([
            self.line1_left,
            ('pack', self.line1_right),
            ('pack', urwid.Text(' '))
        ])
        self.line2 = urwid.Text('', wrap='clip')

        self.line1_wrap = urwid.AttrWrap(self.line1, 'line1')
        self.line2_wrap = urwid.AttrWrap(self.line2, 'line2')

        self.content = urwid.Pile([
            self.line1_wrap,
            self.line2_wrap,
            urwid.Text('')
        ])

        self.is_focused = False

        super(SongListItem, self).__init__([
            self.content
        ])
        self.update_text()
Пример #24
0
 def widget(self, count: int) -> Any:
     if count <= 0:
         count = ''  # type: ignore
     return urwid.AttrMap(
         urwid.SelectableIcon(
             [u'  \N{BULLET}  ', self.caption, ('idle', ' ' + str(count))],
             len(self.caption) + 5), self.color, 'selected')
Пример #25
0
 def __init__(self, caption, callback, selected):
     super(SelectionButton, self).__init__("")
     self.selection = selected
     urwid.connect_signal(self, 'click', callback)
     self._w = urwid.AttrMap(urwid.SelectableIcon(caption, 1),
                             None,
                             focus_map='reversed')
Пример #26
0
 def widget(self, count: int) -> Any:
     if count <= 0:
         count = ''  # type: ignore
     return urwid.AttrMap(
         urwid.SelectableIcon([(self.color, u'  # '), self.caption,
                               ('idle', ' ' + str(count))],
                              len(self.caption) + 4), None, 'selected')
Пример #27
0
 def __init__(self, number, name):
     separator = ('inactive', format(get_icon('divider')))
     self.number = number
     self.text = ' {}: {} '.format(number, name)
     self.body = urwid.SelectableIcon([self.text, separator])
     self.last_time_clicked = None
     super(Workspace, self).__init__(self.body, 'inactive', None)
Пример #28
0
        def __init__(self, mod: Mod, *callbacks: Iterable[ModItemCallback]):
            """Wrap mod in the set of display widgets.

            Keyword arguments:
                mod: The :class:`Mod` to be wrapped.
                callbacks: The functions to be called when this object
                    is selected.
            """

            btn_prefix = '  ◈ '

            # Construct button (the selectable part)
            btn = urwid.Button('')
            btn._w = urwid.AttrMap(
                urwid.SelectableIcon([btn_prefix, mod.name], 2),
                'title', 'title_focus',
            )
            for callback in callbacks:
                urwid.connect_signal(btn, 'click', callback, user_args=[mod])

            # Construct the mod summary
            text = urwid.Padding(
                urwid.AttrMap(urwid.Text(mod.summary), 'description'),
                left=len(btn_prefix)*2,
            )

            pile = btn, text
            super().__init__(pile)
Пример #29
0
 def __init__(self, timestamp, text, datetimefmt, user=None,
              show_date=False):
     # Save the timestamp as an attribute for sorting.
     self.timestamp = timestamp
     text = [
         ('msg_date', self._get_date_str(timestamp, datetimefmt,
                                         show_date=show_date) + ' '),
         ('msg_text_self' if user is not None and user.is_self
          else 'msg_text', text)
     ]
     if user is not None:
         text.insert(1, ('msg_self' if user.is_self else 'msg_sender',
                         user.first_name + ': '))
     self._widget = urwid.SelectableIcon(text, cursor_position=0)
     super().__init__(urwid.AttrMap(
         self._widget, '', {
             # If the widget is focused, map every other display attribute
             # to 'msg_selected' so the entire message is highlighted.
             None: 'msg_selected',
             'msg_date': 'msg_selected',
             'msg_text_self': 'msg_selected',
             'msg_text': 'msg_selected',
             'msg_self': 'msg_selected',
             'msg_sender': 'msg_selected',
         }
     ))
Пример #30
0
 def __init__(self, text, func):
     super(CommandButton, self).__init__('')
     urwid.connect_signal(self, 'click', self.callback)
     self.text = text
     self.func = func
     self.textwidget = urwid.AttrWrap(urwid.SelectableIcon(' {}'.format(self.text), cursor_position=0), None)
     self._w = urwid.AttrMap(self.textwidget, None, self.focus_map)