-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewer.py
More file actions
2318 lines (2018 loc) · 95.4 KB
/
Copy pathviewer.py
File metadata and controls
2318 lines (2018 loc) · 95.4 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""PySide6 desktop mail client.
Layout
------
+---------------------------------------------------------------------------+
| toolbar: Sync | Compose | Reply | Reply all | Forward | Delete | flags ... |
+------------+--------------------------+---------------------------------- +
| folder | message list | header block |
| tree with | (sender, subject, +----------------------------------- +
| unread | preview, date, star) | body (QtWebEngine / QTextBrowser) |
| counts | +----------------------------------- +
| | | attachments |
+------------+--------------------------+------------------------------------+
| status bar: message | progress | unread count | sync indicator |
+---------------------------------------------------------------------------+
Threading: this module never performs a network call. Everything goes through
:class:`mail_sync.SyncController`, which owns a worker thread; results come back
as Qt signals and are applied to the models here, on the UI thread.
"""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
from typing import Optional, Sequence
import qt_bootstrap
qt_bootstrap.prepare()
from PySide6.QtCore import ( # noqa: E402
QAbstractListModel,
QByteArray,
QModelIndex,
QObject,
QRect,
QSize,
QSortFilterProxyModel,
Qt,
QThread,
QTimer,
QUrl,
Signal,
)
from PySide6.QtGui import ( # noqa: E402
QAction,
QColor,
QDesktopServices,
QFont,
QFontMetrics,
QGuiApplication,
QKeySequence,
QPainter,
QPalette,
QPixmap,
)
from PySide6.QtWidgets import ( # noqa: E402
QAbstractItemView,
QApplication,
QComboBox,
QDialog,
QDialogButtonBox,
QFileDialog,
QFormLayout,
QFrame,
QHBoxLayout,
QLabel,
QLineEdit,
QListView,
QListWidget,
QListWidgetItem,
QMainWindow,
QMenu,
QMessageBox,
QPlainTextEdit,
QProgressBar,
QPushButton,
QSplitter,
QStyle,
QStyledItemDelegate,
QStyleOptionViewItem,
QTextBrowser,
QToolBar,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from attachment_manager import ( # noqa: E402
human_size,
make_data_uri_resolver,
make_passthrough_resolver,
sanitize_filename,
save_all,
save_attachment,
)
from config import AppSettings # noqa: E402
from html_processor import ( # noqa: E402
SanitizedHtml,
build_document,
html_to_text,
sanitize_html,
text_to_html,
)
from logging_setup import get_logger # noqa: E402
from mail_parser import find_inline_attachment, parse_email # noqa: E402
from mail_receiver import FILTERS, EmlFileSource, FolderInfo # noqa: E402
from mail_sender import ( # noqa: E402
Draft,
SendError,
SmtpSender,
build_forward,
build_reply,
)
from mail_storage import MailStore # noqa: E402
from mail_sync import SyncController # noqa: E402
from models import Attachment, Email, format_addresses # noqa: E402
from notifications import NotificationCenter, make_mail_icon # noqa: E402
import theme # noqa: E402
from outbox import Outbox, QueuedMessage # noqa: E402
logger = get_logger("ui")
APP_NAME = "Mail Viewer"
# QtWebEngine is optional: it renders mail HTML far better, but it is a large
# component and is missing from some installs. The import must happen before
# a QApplication exists, hence at module import time. Set
# MAILVIEWER_NO_WEBENGINE=1 to force the QTextBrowser renderer.
try:
if os.environ.get("MAILVIEWER_NO_WEBENGINE") == "1":
raise ImportError("disabled by MAILVIEWER_NO_WEBENGINE")
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings
from PySide6.QtWebEngineWidgets import QWebEngineView
WEBENGINE_AVAILABLE = True
except Exception as _exc: # pragma: no cover - depends on environment
logging.getLogger(__name__).info(
"QtWebEngine unavailable (%s); using QTextBrowser instead", _exc
)
WEBENGINE_AVAILABLE = False
EMAIL_ROLE = int(Qt.UserRole) + 1
SEARCH_ROLE = int(Qt.UserRole) + 2
SORT_FIELDS: tuple[tuple[str, str], ...] = (
("date", "Date"),
("from", "Sender"),
("subject", "Subject"),
("size", "Size"),
("unread", "Read status"),
)
SEARCH_FIELDS: tuple[tuple[str, str], ...] = (
("all", "Everything"),
("subject", "Subject"),
("from", "Sender"),
("to", "Recipient"),
("date", "Date"),
("body", "Body"),
("attachment", "Attachment name"),
)
def _sort_value(mail: Email, key: str):
if key == "from":
return mail.sender_short.lower()
if key == "subject":
return mail.display_subject.lower()
if key == "size":
return mail.raw_size
if key == "unread":
return (mail.is_read, mail.sort_key)
return mail.sort_key
# ---------------------------------------------------------------------- model
class MessageListModel(QAbstractListModel):
"""Sorted list of the current folder's messages, updated in place."""
def __init__(self, parent: Optional[QObject] = None) -> None:
super().__init__(parent)
self._emails: list[Email] = []
self._by_uid: dict[str, int] = {}
self._sort_key = "date"
self._descending = True
# ------------------------------------------------------------ Qt model
def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: # noqa: N802
return 0 if parent.isValid() else len(self._emails)
def data(self, index: QModelIndex, role: int = Qt.DisplayRole):
if not index.isValid() or not 0 <= index.row() < len(self._emails):
return None
mail = self._emails[index.row()]
if role == Qt.DisplayRole:
return mail.display_subject
if role == EMAIL_ROLE:
return mail
if role == Qt.ToolTipRole:
return (f"{mail.sender}\n{mail.display_subject}\n{mail.display_date}\n"
f"{human_size(mail.raw_size)}\n\n{mail.preview(200)}")
return None
# -------------------------------------------------------------- content
def set_sort(self, key: str, descending: bool) -> None:
if key == self._sort_key and descending == self._descending:
return
self._sort_key, self._descending = key, descending
self.beginResetModel()
self._resort()
self.endResetModel()
def set_messages(self, emails: Sequence[Email]) -> None:
self.beginResetModel()
self._emails = list(emails)
self._resort()
self.endResetModel()
def clear(self) -> None:
self.set_messages([])
def _resort(self) -> None:
self._emails.sort(key=lambda m: _sort_value(m, self._sort_key),
reverse=self._descending)
self._reindex()
def _reindex(self) -> None:
self._by_uid = {mail.uid: row for row, mail in enumerate(self._emails)}
def _insert_position(self, mail: Email) -> int:
value = _sort_value(mail, self._sort_key)
for row, existing in enumerate(self._emails):
other = _sort_value(existing, self._sort_key)
if (value > other) if self._descending else (value < other):
return row
return len(self._emails)
def upsert(self, mail: Email) -> None:
"""Insert a new message or refresh an existing one, keeping the order."""
row = self._by_uid.get(mail.uid)
if row is not None and 0 <= row < len(self._emails):
self._emails[row] = mail
index = self.index(row, 0)
self.dataChanged.emit(index, index)
return
position = self._insert_position(mail)
self.beginInsertRows(QModelIndex(), position, position)
self._emails.insert(position, mail)
self._reindex()
self.endInsertRows()
def refresh_uid(self, uid: str) -> None:
row = self._by_uid.get(str(uid))
if row is None:
return
index = self.index(row, 0)
self.dataChanged.emit(index, index)
def apply_flags(self, uid: str, flags: frozenset[str]) -> None:
"""Update the flags of a displayed row.
The rows come from the index as independent objects, so a flag change
reported by the sync worker has to be written into *this* copy - just
repainting would show the old state (and "unstar" would star again).
"""
row = self._by_uid.get(str(uid))
if row is None:
return
self._emails[row].flags = frozenset(flags)
if self._sort_key == "unread":
self._resort()
self.layoutChanged.emit()
return
index = self.index(row, 0)
self.dataChanged.emit(index, index)
def remove_uids(self, uids: Sequence[int]) -> None:
for uid in uids:
row = self._by_uid.get(str(uid))
if row is None:
continue
self.beginRemoveRows(QModelIndex(), row, row)
del self._emails[row]
self._reindex()
self.endRemoveRows()
def email_at(self, row: int) -> Optional[Email]:
return self._emails[row] if 0 <= row < len(self._emails) else None
def row_for_uid(self, uid: str) -> int:
return self._by_uid.get(str(uid), -1)
@property
def emails(self) -> list[Email]:
return list(self._emails)
class SearchProxy(QSortFilterProxyModel):
"""Incremental search over the loaded messages, optionally per field."""
def __init__(self, parent: Optional[QObject] = None) -> None:
super().__init__(parent)
self._query = ""
self._field = "all"
self._quick = "all"
def set_query(self, text: str) -> None:
self._query = (text or "").strip()
self.invalidateFilter()
def set_field(self, field: str) -> None:
self._field = field or "all"
if self._query:
self.invalidateFilter()
def set_quick_filter(self, quick: str) -> None:
self._quick = quick or "all"
self.invalidateFilter()
def filterAcceptsRow(self, row: int, parent: QModelIndex) -> bool: # noqa: N802
model = self.sourceModel()
index = model.index(row, 0, parent)
mail: Optional[Email] = index.data(EMAIL_ROLE)
if mail is None:
return False
if self._quick == "unread" and mail.is_read:
return False
if self._quick == "flagged" and not mail.is_starred:
return False
if self._quick == "today" and mail.date is not None:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
when = mail.date if mail.date.tzinfo else mail.date.replace(tzinfo=timezone.utc)
if (now - when).days > 0:
return False
if not self._query:
return True
return mail.matches(self._query, self._field)
class MessageDelegate(QStyledItemDelegate):
"""Three-line row with unread, star and attachment indicators."""
PADDING = 8
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: # noqa: N802
metrics = QFontMetrics(option.font)
return QSize(240, metrics.height() * 3 + self.PADDING * 2 + 4)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
mail: Optional[Email] = index.data(EMAIL_ROLE)
if mail is None:
super().paint(painter, option, index)
return
painter.save()
selected = bool(option.state & QStyle.State_Selected)
palette = option.palette
if selected:
painter.fillRect(option.rect, palette.highlight())
primary = palette.highlightedText().color()
secondary = QColor(primary)
secondary.setAlpha(190)
else:
painter.fillRect(option.rect, palette.base())
primary = palette.text().color()
secondary = palette.color(QPalette.Disabled, QPalette.Text)
rect = option.rect.adjusted(self.PADDING, self.PADDING, -self.PADDING, -self.PADDING)
metrics = QFontMetrics(option.font)
line_height = metrics.height()
# Unread marker: a coloured bar on the left edge.
if not mail.is_read:
marker = QColor(theme.current().accent) if not selected else primary
painter.fillRect(QRect(option.rect.left(), option.rect.top() + 6,
3, option.rect.height() - 12), marker)
bold = QFont(option.font)
bold.setBold(not mail.is_read)
small = QFont(option.font)
small.setPointSizeF(max(7.0, option.font.pointSizeF() - 1))
small_metrics = QFontMetrics(small)
# Line 1: sender (left), star + date (right).
date_text = mail.display_date
star_text = "★ " if mail.is_starred else ""
right_text = star_text + date_text
right_width = small_metrics.horizontalAdvance(right_text) + 6
painter.setFont(small)
painter.setPen(QColor("#e8a13a") if mail.is_starred and not selected else secondary)
painter.drawText(
QRect(rect.right() - right_width, rect.top(), right_width, line_height),
int(Qt.AlignRight | Qt.AlignVCenter), right_text,
)
painter.setFont(bold)
painter.setPen(primary)
sender_rect = QRect(rect.left(), rect.top(), rect.width() - right_width - 6, line_height)
painter.drawText(
sender_rect, int(Qt.AlignLeft | Qt.AlignVCenter),
QFontMetrics(bold).elidedText(mail.sender_short, Qt.ElideRight, sender_rect.width()),
)
# Line 2: attachment icon + subject.
painter.setFont(option.font)
subject_left = rect.left()
if mail.has_attachments:
icon_size = line_height - 4
icon = QApplication.style().standardIcon(QStyle.SP_FileIcon)
icon.paint(painter, QRect(rect.left(), rect.top() + line_height + 2,
icon_size, icon_size), Qt.AlignCenter)
subject_left += icon_size + 4
subject_rect = QRect(subject_left, rect.top() + line_height,
rect.right() - subject_left, line_height)
painter.drawText(
subject_rect, int(Qt.AlignLeft | Qt.AlignVCenter),
metrics.elidedText(mail.display_subject, Qt.ElideRight, subject_rect.width()),
)
# Line 3: preview.
painter.setFont(small)
painter.setPen(secondary)
preview_rect = QRect(rect.left(), rect.top() + line_height * 2, rect.width(), line_height)
painter.drawText(
preview_rect, int(Qt.AlignLeft | Qt.AlignVCenter),
small_metrics.elidedText(mail.preview(160), Qt.ElideRight, preview_rect.width()),
)
painter.restore()
# ------------------------------------------------------------------ body view
class _MailTextBrowser(QTextBrowser):
"""Fallback renderer; resolves ``cid:`` images from the current message."""
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self._mail: Optional[Email] = None
self.setOpenExternalLinks(False)
self.setOpenLinks(False)
self.anchorClicked.connect(_open_external)
def set_mail(self, mail: Optional[Email]) -> None:
self._mail = mail
def loadResource(self, resource_type: int, url: QUrl): # noqa: N802 - Qt API
if self._mail is not None and url.scheme() == "cid":
attachment = find_inline_attachment(self._mail, url.path() or url.toString()[4:])
if attachment is not None:
try:
return QByteArray(attachment.data)
except Exception:
logger.debug("Inline image failed to decode", exc_info=True)
if url.scheme() in ("http", "https"):
return QByteArray() # never fetch remote content from the text view
return super().loadResource(resource_type, url)
if WEBENGINE_AVAILABLE:
_SHARED_PROFILE: Optional["QWebEngineProfile"] = None
def _mail_profile() -> "QWebEngineProfile":
"""One off-the-record profile for the whole application.
It must outlive every page that uses it (Qt prints "Release of profile
requested but WebEnginePage still not deleted" otherwise), so it is
owned by the QApplication rather than by a widget.
"""
global _SHARED_PROFILE
if _SHARED_PROFILE is None:
_SHARED_PROFILE = QWebEngineProfile(QApplication.instance())
_SHARED_PROFILE.setHttpCacheType(QWebEngineProfile.HttpCacheType.MemoryHttpCache)
_SHARED_PROFILE.setPersistentCookiesPolicy(
QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies
)
return _SHARED_PROFILE
class _MailPage(QWebEnginePage):
"""Opens clicked links in the real browser; blocks in-place navigation."""
def acceptNavigationRequest(self, url: QUrl, nav_type, is_main_frame: bool) -> bool: # noqa: N802
if nav_type == QWebEnginePage.NavigationType.NavigationTypeLinkClicked:
_open_external(url)
return False
return True
def javaScriptConsoleMessage(self, level, message, line, source) -> None: # noqa: N802
logger.debug("JS console (%s:%s): %s", source, line, message)
class BodyView(QWidget):
"""Renders a message body with whichever engine is available.
Links are never followed inside the viewer: a click hands the URL to the
desktop browser, hovering shows the target (so a link cannot pretend to go
somewhere else), and the context menu can copy it.
"""
#: URL under the cursor, or "" when the cursor left the link.
link_hovered = Signal(str)
#: URL that was opened in the external browser.
link_opened = Signal(str)
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self._mail: Optional[Email] = None
self._allow_remote = False
self._web: Optional[QWidget] = None
self._text: Optional[_MailTextBrowser] = None
self._hovered = ""
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
if WEBENGINE_AVAILABLE:
self._web = QWebEngineView(self)
page = _MailPage(_mail_profile(), self._web)
self._web.setPage(page)
settings = page.settings()
for attribute, value in (
(QWebEngineSettings.WebAttribute.JavascriptEnabled, False),
(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, False),
(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, False),
(QWebEngineSettings.WebAttribute.ErrorPageEnabled, False),
(QWebEngineSettings.WebAttribute.PluginsEnabled, False),
(QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, False),
):
try:
settings.setAttribute(attribute, value)
except Exception:
logger.debug("Could not set web attribute %s", attribute)
page.linkHovered.connect(self._on_link_hovered)
self._web.setContextMenuPolicy(Qt.CustomContextMenu)
self._web.customContextMenuRequested.connect(self._context_menu)
layout.addWidget(self._web)
else:
self._text = _MailTextBrowser(self)
self._text.highlighted.connect(self._on_link_hovered)
self._text.anchorClicked.connect(lambda url: self.link_opened.emit(url.toString()))
self._text.setContextMenuPolicy(Qt.CustomContextMenu)
self._text.customContextMenuRequested.connect(self._context_menu)
layout.addWidget(self._text)
@property
def backend(self) -> str:
return "QtWebEngine" if self._web is not None else "QTextBrowser"
def show_email(self, mail: Optional[Email], allow_remote_images: bool) -> SanitizedHtml:
self._mail = mail
self._allow_remote = allow_remote_images
if mail is None:
self._render(build_document("", dark=_is_dark()))
return SanitizedHtml(html="")
if mail.has_html:
resolver = (make_data_uri_resolver(mail) if self._web is not None
else make_passthrough_resolver(mail))
result = sanitize_html(mail.html_body, resolver, allow_remote_images)
# A message must never look empty while it has content. If the HTML
# part yields no readable text (malformed markup, everything inside
# a dropped element), fall back to the plain-text alternative.
if mail.text_body and not html_to_text(result.html).strip():
logger.warning("HTML part rendered empty; showing the text part",
extra={"event": "html_empty_fallback",
"uid": mail.uid, "folder": mail.folder})
result = SanitizedHtml(html=text_to_html(mail.text_body),
trackers_removed=result.trackers_removed,
remote_images_blocked=result.remote_images_blocked)
elif mail.text_body:
result = SanitizedHtml(html=text_to_html(mail.text_body))
else:
result = SanitizedHtml(
html='<p style="color:#5f6368">This message has no readable body.</p>'
)
self._render(build_document(result.html, dark=_is_dark()))
return result
def _render(self, document: str) -> None:
if self._web is not None:
# setContent avoids setHtml's ~2 MB limit (big inline images).
self._web.page().setContent(
QByteArray(document.encode("utf-8")), "text/html;charset=utf-8",
QUrl("about:blank"),
)
elif self._text is not None:
self._text.set_mail(self._mail)
self._text.setHtml(document)
def _on_link_hovered(self, url) -> None:
"""Qt hands us a QUrl (text browser) or a str (web engine)."""
target = url.toString() if hasattr(url, "toString") else str(url or "")
self._hovered = target
self.link_hovered.emit(target)
def current_link(self, position=None) -> str:
"""The link under the cursor, for the context menu."""
if self._text is not None and position is not None:
anchor = self._text.anchorAt(position)
if anchor:
return anchor
return self._hovered
def _context_menu(self, position) -> None:
menu = QMenu(self)
link = self.current_link(position)
if link:
shown = link if len(link) <= 60 else link[:57] + "…"
menu.addAction(f"Open {shown}", lambda: self.open_link(link))
menu.addAction("Copy link address",
lambda: QApplication.clipboard().setText(link))
menu.addSeparator()
menu.addAction("Copy selected text", self.copy_selection)
menu.addAction("Select all", self.select_all)
widget = self._web if self._web is not None else self._text
if widget is not None:
menu.exec(widget.mapToGlobal(position))
def open_link(self, url: str) -> None:
_open_external(QUrl(url))
self.link_opened.emit(url)
def copy_selection(self) -> None:
if self._web is not None:
self._web.page().triggerAction(QWebEnginePage.WebAction.Copy)
elif self._text is not None:
self._text.copy()
def select_all(self) -> None:
if self._web is not None:
self._web.page().triggerAction(QWebEnginePage.WebAction.SelectAll)
elif self._text is not None:
self._text.selectAll()
def shutdown(self) -> None:
"""Release the web page before the shared profile goes away.
Qt prints "Release of profile requested but WebEnginePage still not
deleted" when a page outlives its profile, which happens at exit unless
the page is destroyed explicitly.
"""
if self._web is not None:
web, self._web = self._web, None
web.setParent(None)
web.deleteLater()
def find(self, text: str) -> None:
if self._web is not None:
self._web.page().findText(text)
elif self._text is not None and text:
if not self._text.find(text):
cursor = self._text.textCursor()
cursor.setPosition(0)
self._text.setTextCursor(cursor)
self._text.find(text)
def _open_external(url: QUrl) -> None:
if url.scheme() in ("http", "https", "mailto", "tel", "ftp", "ftps"):
QDesktopServices.openUrl(url)
else:
logger.info("Refused to open link with scheme %r", url.scheme())
def _dim(label: QLabel, alpha: int = 150) -> None:
"""Secondary text colour, taken from the active theme.
An alpha channel was used here before; a real muted colour is safer,
because some styles ignore alpha on palette roles.
"""
palette = label.palette()
colour = QColor(theme.current().text_muted)
palette.setColor(QPalette.WindowText, colour)
palette.setColor(QPalette.Text, colour)
label.setPalette(palette)
def _is_dark() -> bool:
return theme.is_dark()
# ---------------------------------------------------------------- header pane
class HeaderPane(QWidget):
"""From / To / Cc / Subject / Date block, plus all raw headers on demand."""
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(12, 10, 12, 6)
layout.setSpacing(4)
self._subject = QLabel()
subject_font = self._subject.font()
subject_font.setPointSizeF(subject_font.pointSizeF() + 3)
subject_font.setBold(True)
self._subject.setFont(subject_font)
self._subject.setWordWrap(True)
self._subject.setTextInteractionFlags(Qt.TextSelectableByMouse)
layout.addWidget(self._subject)
self._form = QFormLayout()
self._form.setContentsMargins(0, 4, 0, 0)
self._form.setHorizontalSpacing(12)
self._form.setVerticalSpacing(2)
self._fields: dict[str, QLabel] = {}
for name in ("From", "Reply-To", "To", "Cc", "Bcc", "Date", "Message-ID"):
value = QLabel()
value.setWordWrap(True)
value.setTextInteractionFlags(Qt.TextSelectableByMouse)
label = QLabel(f"{name}:")
_dim(label)
self._fields[name] = value
self._form.addRow(label, value)
layout.addLayout(self._form)
self._warning = QLabel()
self._warning.setWordWrap(True)
colours = theme.current()
self._warning.setStyleSheet(
f"background:{colours.warning_bg}; color:{colours.warning_text};"
f"border:1px solid {colours.border}; border-radius:6px; padding:5px 9px;"
)
self._warning.hide()
layout.addWidget(self._warning)
controls = QHBoxLayout()
self._details_button = QPushButton("Show all headers")
self._details_button.setCheckable(True)
self._details_button.setFlat(True)
self._details_button.toggled.connect(self._toggle_details)
controls.addWidget(self._details_button)
controls.addStretch(1)
layout.addLayout(controls)
self._details = QPlainTextEdit()
self._details.setReadOnly(True)
self._details.setMaximumHeight(180)
self._details.hide()
layout.addWidget(self._details)
self.clear()
def refresh_theme(self) -> None:
"""Re-colour the parts that carry their own stylesheet."""
colours = theme.current()
self._warning.setStyleSheet(
f"background:{colours.warning_bg}; color:{colours.warning_text};"
f"border:1px solid {colours.border}; border-radius:6px; padding:5px 9px;"
)
for row in range(self._form.rowCount()):
item = self._form.itemAt(row, QFormLayout.LabelRole)
if item is not None and isinstance(item.widget(), QLabel):
_dim(item.widget())
def clear(self) -> None:
self._subject.setText("")
for label in self._fields.values():
label.setText("")
self._warning.hide()
self._details.setPlainText("")
self._set_row_visibility({})
def show_email(self, mail: Email) -> None:
self._subject.setText(mail.display_subject)
values = {
"From": format_addresses(mail.from_addrs),
"Reply-To": format_addresses(mail.reply_to),
"To": format_addresses(mail.to_addrs),
"Cc": format_addresses(mail.cc_addrs),
"Bcc": format_addresses(mail.bcc_addrs),
"Date": f"{mail.display_date}" + (f" ({mail.date_raw})" if mail.date_raw else ""),
"Message-ID": mail.message_id,
}
for name, text in values.items():
self._fields[name].setText(text)
self._set_row_visibility(values)
self._details.setPlainText("\n".join(f"{name}: {value}" for name, value in mail.headers))
if mail.warnings:
self._warning.setText("⚠ " + " • ".join(mail.warnings[:4]))
self._warning.show()
else:
self._warning.hide()
def _set_row_visibility(self, values: dict[str, str]) -> None:
for name, widget in self._fields.items():
visible = bool(values.get(name)) or name in ("From", "To")
label = self._form.labelForField(widget)
widget.setVisible(visible)
if label is not None:
label.setVisible(visible)
def _toggle_details(self, checked: bool) -> None:
self._details.setVisible(checked)
self._details_button.setText("Hide all headers" if checked else "Show all headers")
# ----------------------------------------------------------- attachment panel
class AttachmentPane(QWidget):
"""Bottom strip listing attachments, with saving."""
def __init__(self, settings: AppSettings, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self._settings = settings
self._mail: Optional[Email] = None
layout = QVBoxLayout(self)
layout.setContentsMargins(8, 4, 8, 8)
layout.setSpacing(4)
header = QHBoxLayout()
self._title = QLabel("Attachments")
self._title.setStyleSheet("font-weight: bold;")
header.addWidget(self._title)
header.addStretch(1)
self._save_all_button = QPushButton("Save all…")
self._save_all_button.clicked.connect(self.save_all)
header.addWidget(self._save_all_button)
layout.addLayout(header)
self._list = QListWidget()
self._list.setMaximumHeight(110)
self._list.setAlternatingRowColors(True)
self._list.setContextMenuPolicy(Qt.CustomContextMenu)
self._list.customContextMenuRequested.connect(self._context_menu)
self._list.itemDoubleClicked.connect(lambda _: self.save_selected())
layout.addWidget(self._list)
self.show_email(None)
def show_email(self, mail: Optional[Email]) -> None:
self._mail = mail
self._list.clear()
attachments = list(mail.attachments) if mail else []
icon = self.style().standardIcon(QStyle.SP_FileIcon)
for attachment in attachments:
item = QListWidgetItem(
icon,
f"{attachment.filename} {human_size(attachment.size)} "
f"{attachment.content_type}",
)
item.setData(Qt.UserRole, attachment)
self._list.addItem(item)
inline_count = len(mail.inline_images) if mail else 0
title = f"Attachments ({len(attachments)})" if attachments else "Attachments (none)"
if inline_count:
title += f" · {inline_count} inline image(s)"
self._title.setText(title)
self._save_all_button.setEnabled(bool(attachments))
def _context_menu(self, position) -> None:
item = self._list.itemAt(position)
if item is None:
return
menu = QMenu(self)
menu.addAction("Save as…", self.save_selected)
menu.addAction("Save to downloads folder", self.save_selected_quick)
attachment: Attachment = item.data(Qt.UserRole)
if attachment.is_image:
menu.addAction("Preview image", self.preview_selected)
menu.exec(self._list.mapToGlobal(position))
def _selected(self) -> Optional[Attachment]:
item = self._list.currentItem()
return item.data(Qt.UserRole) if item else None
def save_selected(self) -> None:
attachment = self._selected()
if attachment is None:
return
suggested = str(self._settings.download_path() / sanitize_filename(attachment.filename))
path, _ = QFileDialog.getSaveFileName(self, "Save attachment", suggested)
if not path:
return
try:
Path(path).write_bytes(attachment.data)
self._info(f"Saved to {path}")
except Exception as exc:
logger.exception("Saving attachment failed")
QMessageBox.warning(self, APP_NAME, f"Could not save the attachment:\n{exc}")
def save_selected_quick(self) -> None:
attachment = self._selected()
if attachment is None:
return
try:
path = save_attachment(attachment, self._settings.download_path())
self._info(f"Saved to {path}")
except Exception as exc:
QMessageBox.warning(self, APP_NAME, f"Could not save the attachment:\n{exc}")
def save_all(self) -> None:
if self._mail is None or not self._mail.attachments:
return
folder = QFileDialog.getExistingDirectory(
self, "Save all attachments", str(self._settings.download_path())
)
if not folder:
return
results = save_all(self._mail.attachments, folder)
failures = [(a.filename, err) for a, path, err in results if path is None]
if failures:
details = "\n".join(f"• {name}: {err}" for name, err in failures)
QMessageBox.warning(
self, APP_NAME,
f"Saved {len(results) - len(failures)} of {len(results)} attachments.\n\n"
f"Failed:\n{details}",
)
else:
self._info(f"Saved {len(results)} attachment(s) to {folder}")
def preview_selected(self) -> None:
attachment = self._selected()
if attachment is None:
return
pixmap = QPixmap()
if not pixmap.loadFromData(QByteArray(attachment.data)):
QMessageBox.information(self, APP_NAME, "This image cannot be displayed.")
return
dialog = QDialog(self)
dialog.setWindowTitle(attachment.filename)
layout = QVBoxLayout(dialog)
label = QLabel()
screen = QGuiApplication.primaryScreen().availableGeometry()
label.setPixmap(pixmap.scaled(
min(pixmap.width(), int(screen.width() * 0.8)),
min(pixmap.height(), int(screen.height() * 0.8)),
Qt.KeepAspectRatio, Qt.SmoothTransformation,
))
layout.addWidget(label)
buttons = QDialogButtonBox(QDialogButtonBox.Close)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
dialog.exec()
def _info(self, message: str) -> None:
window = self.window()
if isinstance(window, QMainWindow):
window.statusBar().showMessage(message, 6000)
# ------------------------------------------------------------------- folders
class FolderTree(QTreeWidget):
"""Accounts and their mailboxes, with unread counts.
Every account is a root node, so several accounts are visible at once and
switching between them is just selecting a folder under another root.
"""
folder_selected = Signal(str, str) # account, folder
ICONS = {"inbox": "📥", "sent": "📤", "drafts": "📝", "trash": "🗑",
"spam": "⚠", "archive": "📦", "all": "🗂", "other": "📁"}
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setHeaderHidden(True)
self.setMinimumWidth(200)
self.setRootIsDecorated(True)
self._accounts: dict[str, QTreeWidgetItem] = {}
self._items: dict[tuple[str, str], QTreeWidgetItem] = {}
self._single_account = True
self.itemSelectionChanged.connect(self._on_selection)
# ------------------------------------------------------------- accounts
def set_accounts(self, names: Sequence[str]) -> None:
"""Create (or prune) the root node of every configured account."""
self._single_account = len(names) <= 1
for name in names:
if name not in self._accounts:
item = QTreeWidgetItem([f"👤 {name}"])
item.setData(0, Qt.UserRole, "")
item.setData(0, Qt.UserRole + 1, name)
font = item.font(0)
font.setBold(True)
item.setFont(0, font)
self.addTopLevelItem(item)
item.setExpanded(True)
self._accounts[name] = item
self._accounts[name].setHidden(self._single_account)
for name in list(self._accounts):
if name not in names:
index = self.indexOfTopLevelItem(self._accounts[name])
if index >= 0:
self.takeTopLevelItem(index)
del self._accounts[name]
for key in [k for k in self._items if k[0] == name]:
del self._items[key]
def set_folders(self, account: str, folders: Sequence[FolderInfo]) -> None:
"""Fill one account's subtree, keeping the current selection."""
current = self.current_target()