summaryrefslogtreecommitdiff
path: root/alot/buffers/thread.py
blob: bc467ded2b5cc880e2a59a5b7988b5989b0c7781 (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
# 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
from .. import commands
from ..db.errors import NonexistantObjectError


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

    modename = 'thread'

    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')
        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 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):
        try:
            self.thread.refresh()
        except NonexistantObjectError:
            self.body = urwid.SolidFill()
            return

        self._msg_walker = urwid.SimpleFocusListWalker(
            [MessageWidget(msg, idx & 1) for (idx, msg) in
                enumerate(self.thread.message_list)])

        self.body = urwid.ListBox(self._msg_walker)

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

    def get_selected_message_widget(self):
        """Return currently focused :class:`MessageWidget`."""
        return self.body.focus

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

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

    # needed for ui.get_deep_focus..
    def get_focus(self):
        "Get the focus from the underlying body widget."
        return self.body.focus

    def set_focus(self, pos):
        "Set the focus in the underlying body widget."
        logging.debug('setting focus to %s ', pos)
        self.body.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"""
        pos = self.get_selected_message_position()
        cur_depth = self.get_selected_message().depth

        for idx in reversed(range(0, pos)):
            msg = self.thread.message_list[idx]
            if msg.depth < cur_depth:
                self.set_focus(idx)
                break

    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)

    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 > 0:
            walk = range(cur_pos + 1, self.thread.total_messages) 
        else:
            walk = reversed(range(0, cur_pos))

        for pos in walk:
            if prop(self._msg_walker[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), 1)

    def focus_prev_matching(self, querystring):
        """focus previous matching message in depth first order"""
        self._focus_property(lambda x: x.get_message().matches(querystring), -1)

    def focus_next_unfolded(self):
        """focus next unfolded message in depth first order"""
        self._focus_property(lambda x: x.display_content, 1)

    def focus_prev_unfolded(self):
        """focus previous unfolded message in depth first order"""
        self._focus_property(lambda x: x.display_content, -1)

    def expand(self, msgpos):
        """expand message at given position"""
        self.body.body[msgpos].expand()

    def expand_all(self):
        """expand all messages in thread"""
        for msg in self.message_widgets():
            msg.expand()

    def collapse(self, msgpos):
        """collapse message at given position"""
        self.body.body[msgpos].collapse()
        self.focus_selected_message()

    def collapse_all(self):
        """collapse all messages in thread"""
        for msg in self.message_widgets():
            msg.collapse()
        self.focus_selected_message()

    def unfold_matching(self, querystring, focus_first=True):
        """
        expand all messages that match a given querystring.

        :param querystring: query to match
        :type querystring: str
        :param focus_first: set the focus to the first matching message
        :type focus_first: bool
        """
        focus_set = False
        first = None
        for pos, msg_wgt in enumerate(self.message_widgets()):
            msg = msg_wgt.get_message()
            if msg.matches(querystring):
                msg_wgt.expand()
                if focus_first and not focus_set:
                    self.set_focus(pos)
                    focus_set = True
            else:
                msg_wgt.collapse()