summaryrefslogtreecommitdiff
path: root/alot/buffers/thread.py
blob: eafd84b499fde01661de53fdc852177cf102a892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Copyright (C) 2011-2018  Patrick Totzke <patricktotzke@gmail.com>
# Copyright © 2018 Dylan Baker
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import asyncio
import urwid
import logging

from .buffer import Buffer
from ..settings.const import settings
from ..widgets.thread import MessageWidget, ThreadNode
from .. import commands
from ..db.errors import NonexistantObjectError


class ThreadBuffer(Buffer):
    """displays a thread as a tree of messages."""

    modename = 'thread'

    # list of the widgets containing the message body
    # indexed by its depth-first position in the thread tree
    _msg_widgets    = None
    # widget showing the thread tree
    _msgtree_widget = None

    # WidgetPlaceholder that wraps currently displayed message
    _cur_msg_holder = None
    # WidgetPlaceholder that wraps current divider
    _divider_holder = None

    # divider widgets placed between the thread tree and the message
    _divider_up   = None
    _divider_down = None

    def __init__(self, ui, thread):
        """
        :param ui: main UI
        :type ui: :class:`~alot.ui.UI`
        :param thread: thread to display
        :type thread: :class:`~alot.db.Thread`
        """
        self.thread        = thread
        self._indent_width = settings.get('thread_indent_replies')

        # create the widgets composing the buffer
        self._msgtree_widget = urwid.ListBox(urwid.SimpleFocusListWalker([]))
        self._divider_up     = urwid.Divider('↑')
        self._divider_down   = urwid.Divider('↓')
        self._divider_holder = urwid.WidgetPlaceholder(self._divider_up)
        self._cur_msg_holder = urwid.WidgetPlaceholder(urwid.SolidFill())

        self.body = urwid.Pile([
            # 0 is a dummy value and is overridden later rebuild()
            ('weight',  0, self._msgtree_widget),
            ('pack',       self._divider_holder),
            # fixed weight for the message body
            # TODO: should it depend on the message body length (or perhaps something else)?
            ('weight', 50, self._cur_msg_holder),
            ])

        urwid.connect_signal(self._msgtree_widget.body, "modified", self._update_cur_msg)

        self.rebuild()

        super().__init__(ui, self.body)

    def __str__(self):
        return '[thread] %s (%d message%s)' % (self.thread.subject,
                                               self.thread.total_messages,
                                               's' * (self.thread.total_messages > 1))

    def _update_cur_msg(self):
        pos = self._msgtree_widget.body.focus
        if pos is not None and pos < len(self._msg_widgets):
            logging.debug('displaying message %s ', pos)
            self._cur_msg_holder.original_widget = self._msg_widgets[pos]

    def translated_tags_str(self, intersection=False):
        tags = self.thread.get_tags(intersection=intersection)
        trans = [settings.get_tagstring_representation(tag)['translated']
                 for tag in tags]
        return ' '.join(trans)

    def get_info(self):
        info = {}
        info['subject']           = self.thread.subject
        info['authors'] = self.thread.get_authors_string()
        info['tid']               = self.thread.id
        info['message_count'] = self.thread.total_messages
        info['thread_tags'] = self.translated_tags_str()
        info['intersection_tags'] = self.translated_tags_str(intersection=True)
        return info

    def rebuild(self):
        self._msg_widgets = []
        self._msgtree_widget.body.clear()
        self._cur_msg_holder.original_widget = urwid.SolidFill()

        try:
            self.thread.refresh()
        except NonexistantObjectError:
            return

        list_walker = self._msgtree_widget.body
        for pos, msg in enumerate(self.thread.message_list):
            msg_wgt = MessageWidget(msg)
            wgt     = ThreadNode(msg, self.thread, pos, self._indent_width)

            self._msg_widgets.append(msg_wgt)
            list_walker.append(wgt)

        # the weight given to the thread-tree widget is equal to the number of
        # messages in it, up to the limit of 50 (when it is equal to the message
        # body widget)
        tree_weight = min(len(self._msg_widgets), 50)
        self.body.contents[0] = (self._msgtree_widget, ('weight', tree_weight))

        if len(self._msg_widgets) > 0:
            self._cur_msg_holder.original_widget = self._msg_widgets[0]

    def get_selected_message_position(self):
        """Return position of focussed message in the thread tree."""
        return self._msgtree_widget.focus_position

    def get_selected_message_widget(self):
        """Return currently focused :class:`MessageWidget`."""
        pos = self.get_selected_message_position()
        return self._msg_widgets[pos]

    def get_selected_message(self):
        """Return focussed :class:`~alot.db.message.Message`."""
        return self.get_selected_message_widget().get_message()

    def get_selected_attachment(self):
        """
        If an attachment widget is currently in focus, return the associated
        Attachment. Otherwise return None.
        """
        msg_wgt = self.get_selected_message_widget()
        att = msg_wgt.get_selected_attachment()
        if att is not None:
            return att
        return None

    def message_widgets(self):
        """
        Iterate over all the message widgets in this buffer
        """
        for w in self._msg_widgets:
            yield w

    def set_focus(self, pos):
        "Set the focus in the underlying body widget."
        logging.debug('setting focus to %s ', pos)
        self._msgtree_widget.set_focus(pos)

    def focus_first(self):
        """set focus to first message of thread"""
        self.set_focus(0)

    def focus_last(self):
        self.set_focus(max(self.thread.total_messages - 1, 0))

    def focus_selected_message(self):
        """focus the summary line of currently focused message"""
        self.set_focus(self.get_selected_message_position())

    def focus_parent(self):
        """move focus to parent of currently focused message"""
        msg = self.get_selected_message()
        if msg.parent:
            self.set_focus(self.thread.message_list.index(msg.parent))

    def focus_first_reply(self):
        """move focus to first reply to currently focused message"""
        msg = self.get_selected_message()
        if len(msg.replies) > 0:
            new_focus = self.thread.message_list.index(msg.replies[0])
            self.set_focus(new_focus)

    def focus_last_reply(self):
        """move focus to last reply to currently focused message"""
        msg = self.get_selected_message()
        if len(msg.replies) > 0:
            new_focus = self.thread.message_list.index(msg.replies[-1])
            self.set_focus(new_focus)

    def focus_next_sibling(self):
        """focus next sibling of currently focussed message in thread tree"""
        pos_next = self.get_selected_message_position() + 1
        depth = self.get_selected_message().depth
        if (pos_next < self.thread.total_messages and
            self.thread.message_list[pos_next].depth == depth):
            self.set_focus(pos_next)

    def focus_prev_sibling(self):
        """
        focus previous sibling of currently focussed message in thread tree
        """
        pos_next = self.get_selected_message_position() - 1
        depth = self.get_selected_message().depth
        if (pos_next < self.thread.total_messages and
            self.thread.message_list[pos_next].depth == depth):
            self.set_focus(pos_next)

    def focus_next(self):
        """focus next message in depth first order"""
        next_focus = self.get_selected_message_position() + 1
        if next_focus >= 0 and next_focus < self.thread.total_messages:
            self.set_focus(next_focus)

    def focus_prev(self):
        """focus previous message in depth first order"""
        next_focus = self.get_selected_message_position() - 1
        if next_focus >= 0 and next_focus < self.thread.total_messages:
            self.set_focus(next_focus)

    _DIR_NEXT  = 0
    _DIR_PREV  = 1
    _DIR_FIRST = 2
    _DIR_LAST  = 3

    def _focus_property(self, prop, direction):
        """does a walk in the given direction and focuses the
        first message that matches the given property"""
        cur_pos   = self.get_selected_message_position()

        if direction == self._DIR_NEXT:
            walk = range(cur_pos + 1, self.thread.total_messages)
        elif direction == self._DIR_FIRST:
            walk = range(0, self.thread.total_messages)
        elif direction == self._DIR_PREV:
            walk = reversed(range(0, cur_pos))
        elif direction == self._DIR_LAST:
            walk = reversed(range(0, self.thread.total_messages))
        else:
            raise ValueError('Invalid focus_propery direction: ' + str(direction))

        for pos in walk:
            if prop(self._msg_widgets[pos]):
                self.set_focus(pos)
                break

    def focus_next_matching(self, querystring):
        """focus next matching message in depth first order"""
        self._focus_property(lambda x: x.get_message().matches(querystring), self._DIR_NEXT)
    def focus_prev_matching(self, querystring):
        """focus previous matching message in depth first order"""
        self._focus_property(lambda x: x.get_message().matches(querystring), self._DIR_PREV)
    def focus_first_matching(self, querystring):
        """focus first matching message in depth first order"""
        self._focus_property(lambda x: x.get_message().matches(querystring), self._DIR_FIRST)
    def focus_last_matching(self, querystring):
        """focus last matching message in depth first order"""
        self._focus_property(lambda x: x.get_message().matches(querystring), self._DIR_LAST)

    def focus_thread_widget(self):
        """set focus on the thread widget"""
        logging.debug('setting focus to thread widget')
        self.body.focus_position             = 0
        self._divider_holder.original_widget = self._divider_up
    def focus_msg_widget(self):
        """set focus on the message widget"""
        logging.debug('setting focus to message widget')
        self.body.focus_position             = 2
        self._divider_holder.original_widget = self._divider_down
    def focus_toggle(self):
        if self.body.focus_position == 0:
            self.focus_msg_widget()
        elif self.body.focus_position == 2:
            self.focus_thread_widget()
        else:
            raise ValueError('Invalid focus position: %s' % str(self.body.focus_position))