summaryrefslogtreecommitdiff
path: root/alot/buffers/thread.py
blob: 33245879bfd162f999558ebca661f37958bde0e8 (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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# 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 enum
from   functools import cached_property
import logging

import urwid

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

class _ThreadBufFocus(enum.Enum):
    TREE    = enum.auto()
    MESSAGE = enum.auto()

class _LazyMessageWidget:
    msg = None

    def __init__(self, msg):
        self.msg = msg

    @cached_property
    def wgt(self):
        return MessageWidget(self.msg)

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

    modename = 'thread'

    ui     = None
    thread = None

    # list of the widgets containing the message body
    # indexed by its depth-first position in the thread tree
    _messages       = None
    # widget showing the thread tree
    _msgtree_widget = None
    # decorations around the msgtree widget
    _msgtree_deco   = None

    # WidgetPlaceholder that wraps currently displayed message
    _cur_msg_holder = None

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

        attr       = settings.get_theming_attribute('thread', 'frame')
        attr_focus = settings.get_theming_attribute('thread', 'frame_focus')

        # create the widgets composing the buffer
        self._msgtree_widget = urwid.ListBox(urwid.SimpleFocusListWalker([]))
        self._msgtree_deco   = urwid.AttrMap(urwid.LineBox(self._msgtree_widget),
                                             attr, attr_focus)

        # initial placeholder has to be selectable
        self._cur_msg_holder = urwid.WidgetPlaceholder(urwid.SelectableIcon(''))

        cur_msg_deco = urwid.AttrMap(urwid.LineBox(self._cur_msg_holder),
                                     attr, attr_focus)

        self.body = urwid.Pile([
            ('weight', 0.5, self._msgtree_deco),
            ('weight', 0.5, cur_msg_deco),
            ])

        # clear the command map to prevent cursor movements from switching focus
        self.body._command_map = self.body._command_map.copy()
        self.body._command_map._command = {}

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

        self.rebuild()

        super().__init__()

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

    @property
    def _focus(self):
        if self.body.focus_position == 0:
            return _ThreadBufFocus.TREE
        elif self.body.focus_position == 1:
            return _ThreadBufFocus.MESSAGE
        else:
            raise ValueError('Invalid focus position: %s' % str(self.body.focus_position))

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

    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)

    async def get_info(self):
        info = {}
        info['subject']           = self.thread.subject.translate(settings.sanitize_header_table)
        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._messages = []
        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):
            self._messages.append(_LazyMessageWidget(msg))
            list_walker.append(ThreadNode(msg, self.thread, pos, self._indent_width))

        # approximate weight for one terminal line
        # substract 3 for decoration and panels
        line_weight = 1.0 / max(self.ui.get_cols_rows()[1] - 3, 1)

        # the default weight given to the thread-tree widget is proportional to
        # the number of messages in it plus 2 (for surrounding decoration) -
        # scaled to approximately one line per message - up to maximum weight of
        # half the screen
        tree_weight = min(line_weight * (len(self._messages) + 2), 0.5)
        self.msgtree_weight = tree_weight

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

    @property
    def msgtree_weight(self):
        return self.body.contents[0][1][1]
    @msgtree_weight.setter
    def msgtree_weight(self, weight):
        weight = min(1.0, max(weight, 0.0))
        self.body.contents[0] = (self.body.contents[0][0], ('weight', weight))
        self.body.contents[1] = (self.body.contents[1][0], ('weight', 1.0 - weight))

    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._messages[pos].wgt

    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.
        """
        if self._focus == _ThreadBufFocus.MESSAGE:
            msg_wgt = self.get_selected_message_widget()
            return msg_wgt.get_selected_attachment()

        return None

    def message_widgets(self):
        """
        Iterate over all the message widgets in this buffer
        """
        for m in self._messages:
            yield m.wgt

    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_sibling(self, offset):
        msg      = self.get_selected_message()
        siblings = msg.parent.replies if msg.depth > 0 else self.thread.toplevel_messages
        self_idx = siblings.index(msg)

        new_idx = self_idx + offset
        if new_idx >= 0 and new_idx < len(siblings):
            self.set_focus(self.thread.message_list.index(siblings[new_idx]))

    def focus_next_sibling(self):
        """focus next sibling of currently focussed message in thread tree"""
        self._focus_sibling(1)
    def focus_prev_sibling(self):
        """
        focus previous sibling of currently focussed message in thread tree
        """
        self._focus_sibling(-1)

    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._messages[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.msg.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.msg.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.msg.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.msg.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
    def focus_msg_widget(self):
        """set focus on the message widget"""
        logging.debug('setting focus to message widget')
        self.body.focus_position             = 1
    def focus_toggle(self):
        if self._focus == _ThreadBufFocus.TREE:
            self.focus_msg_widget()
        else:
            self.focus_thread_widget()