summaryrefslogtreecommitdiff
path: root/alot/widgets/thread.py
blob: 0b4e2404d55154718a4c361fe33bb5b58385df39 (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
# Copyright (C) 2011-2012  Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
"""
Widgets specific to thread mode
"""
import logging
import urwid

from .globals import TagWidget
from .globals import AttachmentWidget
from ..settings.const import settings
from ..db.utils import decode_header, X_SIGNATURE_MESSAGE_HEADER
from ..helper import string_sanitize


class MessageSummaryWidget(urwid.WidgetWrap):
    """
    one line summary of a :class:`~alot.db.message.Message`.
    """

    def __init__(self, message, odd):
        """
        :param message: a message
        :type message: alot.db.Message
        :param odd: odd entry in a pile of messages? Used for theming.
        :type odd: bool
        """
        self.message = message
        self.odd = odd
        if odd:
            attr = settings.get_theming_attribute('thread', 'summary', 'odd')
        else:
            attr = settings.get_theming_attribute('thread', 'summary', 'even')
        focus_att = settings.get_theming_attribute('thread', 'summary',
                                                   'focus')
        cols = []

        sumstr = self.__str__()
        txt = urwid.Text(sumstr)
        cols.append(txt)

        if settings.get('msg_summary_hides_threadwide_tags'):
            thread_tags = message.thread.get_tags(intersection=True)
            outstanding_tags = set(message.get_tags()).difference(thread_tags)
            tag_widgets = sorted(TagWidget(t, attr, focus_att)
                                 for t in outstanding_tags)
        else:
            tag_widgets = sorted(TagWidget(t, attr, focus_att)
                                 for t in message.get_tags())
        for tag_widget in tag_widgets:
            if not tag_widget.hidden:
                cols.append(('fixed', tag_widget.width(), tag_widget))
        line = urwid.AttrMap(urwid.Columns(cols, dividechars=1), attr,
                             focus_att)
        super().__init__(line)

    def __str__(self):
        mail = self.message.get_email()

        subj = mail.get_all('subject', [''])
        subj = ','.join([decode_header(s, normalize = True) for s in subj])

        author, address = self.message.get_author()
        date = self.message.get_datestring()
        rep = '%s: %s' % (author if author != '' else address, subj)
        if date is not None:
            rep += " (%s)" % date
        return rep

    def selectable(self):
        return True

    def keypress(self, size, key):
        return key


class FocusableText(urwid.WidgetWrap):
    """Selectable Text used for nodes in our example"""
    def __init__(self, txt, att, att_focus):
        t = urwid.Text(txt)
        w = urwid.AttrMap(t, att, att_focus)
        super().__init__(w)

    def selectable(self):
        return True

    def keypress(self, size, key):
        return key


class HeadersWidget(urwid.WidgetWrap):
    """
    A flow widget displaying message headers.
    """

    _key_attr   = None
    _value_attr = None
    _gaps_attr  = None

    def __init__(self, key_attr, value_attr, gaps_attr):
        """
        :param headerslist: list of key/value pairs to display
        :type headerslist: list of (str, str)
        :param key_attr: theming attribute to use for keys
        :type key_attr: urwid.AttrSpec
        :param value_attr: theming attribute to use for values
        :type value_attr: urwid.AttrSpec
        :param gaps_attr: theming attribute to wrap lines in
        :type gaps_attr: urwid.AttrSpec
        """
        self._key_attr   = key_attr
        self._value_attr = value_attr
        self._gaps_attr  = gaps_attr

        super().__init__(urwid.Pile([]))

    def set_headers(self, headers):
        if len(headers) == 0:
            self._w.contents.clear()
            return

        max_key_len = max(map(lambda x: len(x[0]), headers))

        widgets = []
        for key, value in headers:
            # TODO even/odd
            keyw   = ('fixed', max_key_len + 1,
                      urwid.Text((self._key_attr, key)))
            valuew = urwid.Text((self._value_attr, decode_header(value)))
            linew  = urwid.AttrMap(urwid.Columns([keyw, valuew]), self._gaps_attr)
            widgets.append(linew)

        self._w.contents = [(w, ('pack', None)) for w in widgets]

class MessageWidget(urwid.WidgetWrap):
    """
    A flow widget displaying the contents of a single :class:`alot.db.Message`.

    Collapsing this message corresponds to showing the summary only.
    """

    _display_all_headers = None
    _display_content     = None
    _display_source      = None

    _headers_wgt = None
    _summary_wgt = None
    _source_wgt  = None
    _body_wgt    = None
    _attach_wgt  = None

    def __init__(self, message, odd):
        """
        :param message: Message to display
        :type message: alot.db.Message
        :param odd: theme summary widget as if this is an odd line in the thread order
        :type odd: bool
        """
        self._message       = message

        self.display_attachments = True

        self._headers_wgt = self._get_headers()
        self._summary_wgt = MessageSummaryWidget(message, odd)
        self._source_wgt  = self._get_source()
        self._body_wgt    = self._get_body()
        self._attach_wgt  = self._get_attachments()

        super().__init__(urwid.Pile([]))

        self.display_all_headers = False
        self.display_source      = False
        self.display_content     = False

    def get_message(self):
        return self._message

    def _reassemble(self, display_content, display_source):
        widgets = [self._summary_wgt]

        if display_content:
            if display_source:
                widgets.append(self._source_wgt)
            else:
                widgets.append(self._headers_wgt)

                if self._attach_wgt is not None:
                    widgets.append(self._attach_wgt)

                widgets.append(self._body_wgt)

        self._w.contents = [(w, ('pack', None)) for w in widgets]

    def _get_source(self):
        sourcetxt = self._message.get_email().as_string()
        sourcetxt = string_sanitize(sourcetxt)
        att = settings.get_theming_attribute('thread', 'body')
        att_focus = settings.get_theming_attribute('thread', 'body_focus')
        return FocusableText(sourcetxt, att, att_focus)

    def _get_body(self):
        bodytxt = self._message.get_body_text()
        att = settings.get_theming_attribute('thread', 'body')
        att_focus = settings.get_theming_attribute(
            'thread', 'body_focus')
        return FocusableText(bodytxt, att, att_focus)

    def _get_headers(self):
        key_attr   = settings.get_theming_attribute('thread', 'header_key')
        value_attr = settings.get_theming_attribute('thread', 'header_value')
        gaps_attr  = settings.get_theming_attribute('thread', 'header')
        return HeadersWidget(key_attr, value_attr, gaps_attr)

    def _get_attachments(self):
        alist = []
        for a in self._message.get_attachments():
            alist.append(AttachmentWidget(a))
        if alist:
            return urwid.Pile(alist)
        return None

    @property
    def display_all_headers(self):
        return self._display_all_headers
    @display_all_headers.setter
    def display_all_headers(self, val):
        val = bool(val)

        if val == self._display_all_headers:
            return

        mail = self._message.get_email()
        lines = []

        if val:
            # collect all header/value pairs in the order they appear
            lines = list(mail.items())
        else:
            # only a selection of headers should be displayed.
            # use order of the `headers` parameter
            for key in settings.get('displayed_headers'):
                if key in mail:
                    if key.lower() in ['cc', 'bcc', 'to']:
                        lines.append((key, ', '.join(mail.get_all(key))))
                    else:
                        for value in mail.get_all(key):
                            lines.append((key, value))
                elif key.lower() == 'tags':
                    # TODO this should be in a separate widget
                    logging.debug('want tags header')
                    values = []
                    for t in self._message.get_tags():
                        tagrep = settings.get_tagstring_representation(t)
                        if t is not tagrep['translated']:
                            t = '%s (%s)' % (tagrep['translated'], t)
                        values.append(t)
                    lines.append((key, ', '.join(values)))

        # OpenPGP pseudo headers
        # TODO this should be in a separate widget
        if mail[X_SIGNATURE_MESSAGE_HEADER]:
            lines.append(('PGP-Signature', mail[X_SIGNATURE_MESSAGE_HEADER]))

        self._headers_wgt.set_headers(lines)

        self._display_all_headers = val

    @property
    def display_content(self):
        return self._display_content
    @display_content.setter
    def display_content(self, val):
        val = bool(val)

        if val == self._display_content:
            return

        self._reassemble(val, self.display_source)
        self._display_content = val

    def expand(self):
        self.display_content = True
    def collapse(self):
        self.display_content = False

    def collapse_if_matches(self, querystring):
        """
        collapse (and show summary only) if the :class:`alot.db.Message`
        matches given `querystring`
        """
        self.display_content = not self._message.matches(querystring)