-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsearch_mailing_list.py
More file actions
executable file
·1430 lines (1193 loc) · 55.2 KB
/
search_mailing_list.py
File metadata and controls
executable file
·1430 lines (1193 loc) · 55.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import subprocess
import json
import sys
import shutil
import os
import re
import threading
from datetime import datetime, timedelta
from collections import defaultdict
from typing import Optional, List, Dict, Any, Tuple
try:
import curses
except ImportError:
print("Error: 'curses' module not found.", file=sys.stderr)
print("On Windows, install it with: pip install windows-curses", file=sys.stderr)
sys.exit(1)
import git_ml_converter
# --- Configuration ---
MIN_MSG_COUNT = 5
MAX_MSG_COUNT = 40
MIN_AGE_DAYS = 21
MAX_AGE_DAYS = 90
GIT_ML_URL = "https://lore.kernel.org/git/"
DEFAULT_CLONE_PATH = os.path.expanduser("~/git/git-mailing-list-public-inbox")
def compute_edition(date: datetime) -> int:
"""Compute the Git Rev News edition number being prepared for a given date.
Editions are monthly. Edition 1 was published March 2015.
Each edition covers two months and is published at the end of the second.
If today is strictly before the 10th of the month, we are still working
on the edition whose second covered month is the previous month.
Otherwise, we are working on the edition whose second covered month is
the current month.
"""
if date.day < 10:
ref = (date.replace(day=1) - timedelta(days=1))
else:
ref = date
return (ref.year - 2015) * 12 + ref.month - 2
def get_threads_dir(edition: int) -> str:
"""Return the path of the threads directory for the given edition."""
return f"threads_{edition}"
def find_or_create_threads_dir(edition: int) -> str:
"""Return the threads directory for the given edition, creating it if needed."""
threads_dir = get_threads_dir(edition)
os.makedirs(threads_dir, exist_ok=True)
return threads_dir
def sanitize_filename(name: str) -> str:
"""Sanitize a string to be used as a filename."""
name = re.sub(r'[^\w\s-]', '', name)
name = re.sub(r'[-\s]+', '-', name)
return name.strip('-')[:50]
INDEX_FILENAME = "index.md"
def load_index(threads_dir: str) -> Dict[str, Any]:
"""Load the index.md from a threads directory.
Returns a dict with:
- 'edition': int
- 'created': str (YYYY-MM-DD)
- 'done_mids': set of Message-IDs already recorded
"""
index_path = os.path.join(threads_dir, INDEX_FILENAME)
result: Dict[str, Any] = {'edition': None, 'created': None, 'done_mids': set()}
if not os.path.exists(index_path):
return result
with open(index_path, 'r', encoding='utf-8') as f:
content = f.read()
fm_match = re.search(r'^---\n(.*?)\n---', content, re.DOTALL)
if fm_match:
fm = fm_match.group(1)
m = re.search(r'^edition:\s*(\d+)', fm, re.MULTILINE)
if m:
result['edition'] = int(m.group(1))
m = re.search(r'^created:\s*(\S+)', fm, re.MULTILINE)
if m:
result['created'] = m.group(1)
for m in re.finditer(r'^\s+-\s+Message-ID:\s+`([^`]+)`', content, re.MULTILINE):
result['done_mids'].add(m.group(1))
return result
def save_index(threads_dir: str, edition: int, threads: List[Dict[str, Any]],
existing: Optional[Dict[str, Any]] = None) -> None:
"""Write or update index.md in the given threads directory.
New threads are appended; threads already in the existing index are kept.
"""
index_path = os.path.join(threads_dir, INDEX_FILENAME)
created = existing.get('created') if existing else None
if not created:
created = datetime.now().strftime('%Y-%m-%d')
already_done = existing.get('done_mids', set()) if existing else set()
new_threads = [t for t in threads if t['root_mid'] not in already_done]
existing_body = ""
if os.path.exists(index_path):
with open(index_path, 'r', encoding='utf-8') as f:
content = f.read()
fm_end = content.find('\n---\n', content.find('---\n'))
if fm_end != -1:
after_fm = content[fm_end + 5:]
lines = after_fm.splitlines(keepends=True)
existing_body = ''.join(
l for l in lines if not l.startswith('# Git Rev News')
)
new_entries = ""
for t in new_threads:
blob = t.get('blob', '')[:8]
filename = f"{sanitize_filename(t['subject'])}_{blob}.txt"
mid = t['root_mid']
subject = t['subject']
new_entries += (
f"\n- **{subject}**\n"
f" - File: `{filename}`\n"
f" - Message-ID: `{mid}`\n"
f" - Notes:\n"
)
if not existing_body.strip():
body = f"## Selected Threads\n{new_entries}"
else:
body = existing_body.strip() + "\n" + new_entries
front_matter = f"---\nedition: {edition}\ncreated: {created}\n---\n"
header = f"\n# Git Rev News Edition {edition} - Raw Materials\n\n"
with open(index_path, 'w', encoding='utf-8') as f:
f.write(front_matter + header + body + "\n")
class MailingListStore:
"""Encapsulates all interactions with lei and the local git repository."""
def __init__(self):
self.min_msg_count = MIN_MSG_COUNT
self.max_msg_count = MAX_MSG_COUNT
self.min_age_days = MIN_AGE_DAYS
self.max_age_days = MAX_AGE_DAYS
def get_repo_path(self) -> Optional[str]:
"""Get the first local repo path from lei externals."""
try:
proc = subprocess.run(["lei", "ls-external"], capture_output=True, text=True)
externals = proc.stdout.strip()
if not externals:
return None
local_paths = [line.split()[0] for line in externals.splitlines() if line.strip().startswith('/')]
for path in local_paths:
if os.path.isdir(path):
return path
except subprocess.CalledProcessError:
pass
return None
def get_latest_message_date(self, repo_path: str) -> Optional[str]:
"""Queries lei for the most recent message date in the given repository."""
cmd = [
"lei", "q", "--only", repo_path,
"-n", "1", "-s", "received", "dt:1.month.ago..", "-f", "json"
]
try:
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
if not result.stdout.strip():
return None
data = json.loads(result.stdout)
if not data:
return None
latest_dt_str = data[0].get('dt')
if isinstance(latest_dt_str, list):
return latest_dt_str[0]
return latest_dt_str
except (subprocess.CalledProcessError, json.JSONDecodeError, IndexError, KeyError):
return None
def parse_date(self, date_str: str) -> Optional[datetime]:
"""Parses the 'dt' field from lei JSON."""
try:
return datetime.strptime(date_str[:19].replace('T', ' '), "%Y-%m-%d %H:%M:%S")
except (ValueError, TypeError):
return None
def is_recent(self, date_str: Optional[str]) -> bool:
"""Check if the given date string is less than 1 day old."""
if not date_str:
return False
dt = self.parse_date(date_str)
if dt:
return (datetime.now() - dt).days < 1
return False
def get_lei_results(self) -> List[Dict[str, Any]]:
"""Executes lei q to find candidate messages."""
date_query = f"d:{self.max_age_days}.days.ago..{self.min_age_days}.days.ago"
cmd = [
"lei", "q",
"-t",
"-f", "json",
date_query
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
if not result.stdout.strip():
return []
return json.loads(result.stdout)
except (subprocess.CalledProcessError, json.JSONDecodeError) as e:
raise RuntimeError(f"Error running lei: {e}") from e
def analyze_threads(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Groups messages by thread_id and filters based on user criteria."""
threads = defaultdict(list)
for msg in messages:
if not msg:
continue
refs = msg.get('refs', [])
if refs:
t_id = refs[0]
else:
t_id = msg.get('m')
if t_id:
threads[t_id].append(msg)
valid_threads = []
now = datetime.now()
dropped_counts = {"count": 0, "age": 0}
for t_id, msgs in threads.items():
count = len(msgs)
if not (self.min_msg_count <= count <= self.max_msg_count):
dropped_counts["count"] += 1
continue
dates = []
for m in msgs:
d = self.parse_date(m.get('dt'))
if d:
dates.append(d)
if not dates:
continue
last_email_date = max(dates)
age = (now - last_email_date).days
participants = set()
for m in msgs:
for sender in m.get('f', []):
if len(sender) > 1:
participants.add(sender[1])
if self.min_age_days <= age <= self.max_age_days:
msgs.sort(key=lambda x: x.get('dt', ''))
root_subject = msgs[0].get('s', '(No Subject)')
valid_threads.append({
'thread_id': t_id,
'subject': root_subject,
'count': count,
'last_activity': last_email_date.strftime("%Y-%m-%d"),
'participants': len(participants),
'age_days': age,
'blob': msgs[0].get('blob', ''),
'root_mid': msgs[0].get('m', '')
})
else:
dropped_counts["age"] += 1
print(f"Filtered out: {dropped_counts['count']} by size, {dropped_counts['age']} by date.", file=sys.stderr)
return valid_threads
def _decode_header(value: str) -> str:
"""Decode an RFC 2047 encoded email header value to a plain string."""
try:
from email.header import decode_header, make_header
return str(make_header(decode_header(value)))
except Exception:
return value
def _parse_overview_date(date_str: str) -> str:
"""Parse an RFC 2822 date string into YYYY-MM-DD, or return blanks on failure."""
from email.utils import parsedate
date_str = date_str.strip()
if not date_str:
return ' '
parsed = parsedate(date_str)
if parsed:
try:
return datetime(*parsed[:3]).strftime('%Y-%m-%d')
except Exception:
pass
return ' '
def _normalize_msgid(value: str) -> str:
"""Normalize a Message-ID for in-thread matching.
Strips angle brackets and whitespace, and lowercases the host part
after the first '@' so References/In-Reply-To matches survive minor
casing inconsistencies in the domain.
"""
if not value:
return ''
s = value.strip().strip('<>').strip()
if '@' in s:
local, host = s.split('@', 1)
s = local + '@' + host.lower()
return s
def _thread_sort(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Re-order messages into JWZ-style tree-traversal order.
Each message is annotated in place with `_depth` (int) reflecting its
position in the reply tree. Parents come before children; siblings
are sorted by Date header ascending. Cycles in malformed input are
broken via a visited set.
"""
from email.utils import parsedate_tz, mktime_tz
if not messages:
return []
# Index by normalized Message-ID.
by_id: Dict[str, Dict[str, Any]] = {}
for m in messages:
mid = _normalize_msgid(m.get('id', ''))
if mid and mid not in by_id:
by_id[mid] = m
# Resolve each message's parent. Prefer In-Reply-To; fall back to
# walking References from rightmost to leftmost looking for the
# first ancestor present in this thread.
children: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
roots: List[Dict[str, Any]] = []
for m in messages:
mid = _normalize_msgid(m.get('id', ''))
irt = _normalize_msgid(m.get('in_reply_to', ''))
parent = irt if irt and irt in by_id and irt != mid else ''
if not parent:
for ref in reversed((m.get('references', '') or '').split()):
cand = _normalize_msgid(ref)
if cand and cand in by_id and cand != mid:
parent = cand
break
if parent:
children[parent].append(m)
else:
roots.append(m)
def _ts(m: Dict[str, Any]) -> float:
try:
t = parsedate_tz(m.get('date', '') or '')
if t:
return float(mktime_tz(t))
except Exception:
pass
return float('inf')
for kids in children.values():
kids.sort(key=_ts)
roots.sort(key=_ts)
ordered: List[Dict[str, Any]] = []
visited: set = set()
def _walk(msg: Dict[str, Any], depth: int) -> None:
mid = _normalize_msgid(msg.get('id', ''))
if mid and mid in visited:
return
if mid:
visited.add(mid)
msg['_depth'] = depth
ordered.append(msg)
for child in children.get(mid, []):
_walk(child, depth + 1)
for r in roots:
_walk(r, 0)
# Paranoia: append any messages missed by the walk (e.g. orphan with
# an unresolved parent that wasn't classified as a root for some
# reason).
seen_ids = {id(m) for m in ordered}
for m in messages:
if id(m) not in seen_ids:
m.setdefault('_depth', 0)
ordered.append(m)
return ordered
class ThreadWorkspace:
"""Manages thread list state, selection, navigation and data fetching.
Owns all state independent of how the UI is rendered: thread list,
selection, search, message navigation within a thread, and data cache.
Has no dependency on curses.
"""
def __init__(self, threads: List[Dict[str, Any]], repo_path: Optional[str],
edition: Optional[int], done_mids: Optional[set]):
self.threads = threads
self.selected = [False] * len(threads)
self.cursor = 0
self.offset = 0
self.repo_path = repo_path
self.edition = edition
self.done_mids = done_mids or set()
self.search_term = ""
self.search_matches: List[int] = []
self.current_match_idx = -1
self.searching = False
self.thread_cursor = 0
self.thread_scroll_offset = 0
self.message_scroll_offset = 0
self.preview_searching = False
self.preview_search_term = ""
self.preview_search_matches: List[int] = []
self.preview_current_match = -1
self._preview_cache: Dict[str, List[str]] = {}
self._overview_cache: Dict[str, List[Dict[str, Any]]] = {}
self._overview_loading: set = set()
self._fetch_done = threading.Event()
@property
def is_loading(self) -> bool:
"""True if any background thread fetch is in progress."""
return bool(self._overview_loading)
def consume_fetch_done(self) -> bool:
"""Return True and clear the flag if a background fetch just completed."""
if self._fetch_done.is_set():
self._fetch_done.clear()
return True
return False
def fetch_email_body(self, blob_id: str, max_lines: int = 20) -> List[str]:
"""Fetch the email body using git show, with caching."""
cache_key = f"{blob_id}:{max_lines}"
if cache_key in self._preview_cache:
return self._preview_cache[cache_key]
if not self.repo_path:
return []
try:
cmd = ["git", "show", blob_id]
cwd = None
if os.path.isdir(self.repo_path):
v2_all = os.path.join(self.repo_path, "all.git")
if os.path.isdir(v2_all):
cwd = v2_all
else:
cwd = self.repo_path
result = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd, errors='replace', timeout=10)
lines = result.stdout.splitlines()
body_lines = []
header_ended = False
for idx, line in enumerate(lines):
if not header_ended:
if line == '':
next_line = lines[idx + 1] if idx + 1 < len(lines) else ''
if not next_line or next_line[0] not in ' \t':
header_ended = True
if not header_ended:
continue
body_lines.append(line)
self._preview_cache[cache_key] = body_lines[:max_lines]
return self._preview_cache[cache_key]
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
return []
def fetch_thread_overview(self, root_mid: str) -> Optional[List[Dict[str, Any]]]:
"""Fetch the full thread messages for the given root Message-ID.
Returns the list of message dicts if cached, or None if still loading.
Fetching is done in a background thread; the result is cached.
"""
if root_mid in self._overview_cache:
return self._overview_cache[root_mid]
if root_mid in self._overview_loading:
return None
self._overview_loading.add(root_mid)
def _fetch():
try:
messages = git_ml_converter.fetch_lei_thread(root_mid, self.repo_path, quiet=True)
messages = _thread_sort(messages)
except Exception:
messages = []
self._overview_cache[root_mid] = messages
self._overview_loading.discard(root_mid)
self._fetch_done.set()
threading.Thread(target=_fetch, daemon=True).start()
return None
def find_matches(self, term: str) -> List[int]:
"""Find thread indices whose subject contains term (case-insensitive)."""
if not term:
return []
term_lower = term.lower()
return [i for i, t in enumerate(self.threads) if term_lower in t['subject'].lower()]
def get_selected_mids(self) -> List[str]:
"""Return the root Message-IDs of all selected threads."""
return [self.threads[i]['root_mid'] for i in range(len(self.threads)) if self.selected[i]]
def move_cursor(self, delta: int) -> None:
"""Move the thread list cursor by delta, clamped to valid range.
Resets in-thread navigation state since we are now on a different thread.
"""
self.cursor = max(0, min(len(self.threads) - 1, self.cursor + delta))
self.thread_cursor = 0
self.thread_scroll_offset = 0
self.message_scroll_offset = 0
self.cancel_preview_search()
def move_thread_cursor(self, delta: int, msg_count: int) -> None:
"""Move the message cursor within the thread overview by delta."""
self.thread_cursor = max(0, min(max(0, msg_count - 1), self.thread_cursor + delta))
def scroll_message(self, delta: int) -> None:
"""Scroll the message body by delta lines (upper clamping at render time)."""
self.message_scroll_offset = max(0, self.message_scroll_offset + delta)
def toggle_selection(self) -> None:
"""Toggle selection state of the thread under the cursor."""
self.selected[self.cursor] = not self.selected[self.cursor]
def select_all(self) -> None:
"""Select all threads, or deselect all if all are already selected."""
all_selected = all(self.selected)
self.selected = [not all_selected] * len(self.threads)
def start_search(self) -> None:
"""Enter search mode with an empty term."""
self.searching = True
self.search_term = ""
self.search_matches = []
self.current_match_idx = -1
def update_search(self, term: str) -> None:
"""Update the search term and recompute matches."""
self.search_term = term
self.search_matches = self.find_matches(term)
self.current_match_idx = 0 if self.search_matches else -1
def confirm_search(self) -> None:
"""Exit search mode, keeping the cursor on the current match."""
self.searching = False
if self.search_matches:
self.cursor = self.search_matches[self.current_match_idx]
def cancel_search(self) -> None:
"""Exit search mode, clearing the search term and matches."""
self.searching = False
self.search_term = ""
self.search_matches = []
self.current_match_idx = -1
def next_match(self) -> None:
"""Advance to the next search match, wrapping around."""
if self.search_matches:
self.current_match_idx = (self.current_match_idx + 1) % len(self.search_matches)
self.cursor = self.search_matches[self.current_match_idx]
def prev_match(self) -> None:
"""Go back to the previous search match, wrapping around."""
if self.search_matches:
self.current_match_idx = (self.current_match_idx - 1) % len(self.search_matches)
self.cursor = self.search_matches[self.current_match_idx]
def start_preview_search(self) -> None:
"""Enter preview-pane search mode with an empty term."""
self.preview_searching = True
self.preview_search_term = ""
self.preview_search_matches = []
self.preview_current_match = -1
def update_preview_search(self, term: str, lines: List[str]) -> None:
"""Update the preview search term and recompute line-index matches."""
self.preview_search_term = term
if term:
tl = term.lower()
self.preview_search_matches = [i for i, l in enumerate(lines) if tl in l.lower()]
self.preview_current_match = 0 if self.preview_search_matches else -1
else:
self.preview_search_matches = []
self.preview_current_match = -1
def confirm_preview_search(self) -> None:
"""Exit preview search mode, keeping the current match highlighted."""
self.preview_searching = False
def cancel_preview_search(self) -> None:
"""Exit preview search mode and clear all match state."""
self.preview_searching = False
self.preview_search_term = ""
self.preview_search_matches = []
self.preview_current_match = -1
def next_preview_match(self) -> None:
"""Advance to the next preview search match, wrapping around."""
if self.preview_search_matches:
self.preview_current_match = (self.preview_current_match + 1) % len(self.preview_search_matches)
def prev_preview_match(self) -> None:
"""Go back to the previous preview search match, wrapping around."""
if self.preview_search_matches:
self.preview_current_match = (self.preview_current_match - 1) % len(self.preview_search_matches)
class ThreadSelectorTUI:
"""Manages the curses-based thread selection interface."""
def __init__(self, threads: List[Dict[str, Any]], repo_path: Optional[str] = None,
edition: Optional[int] = None, done_mids: Optional[set] = None):
self.ws = ThreadWorkspace(threads, repo_path, edition, done_mids)
self.show_help_overlay = False
self.show_preview = True
self.preview_mode = 'THREAD' # 'MESSAGE' or 'THREAD'
self.view_mode = 'SPLIT' # 'SPLIT' or 'FULLSCREEN'
self.focus = 'THREAD_LIST' # 'THREAD_LIST' or 'PREVIEW'
self._last_preview_plain_lines: List[str] = []
def _sanitize_for_curses(self, text: str) -> str:
"""Remove non-printable and control characters for curses display."""
return ''.join(c if 32 <= ord(c) < 127 else '?' for c in text)
def _toggle_preview_mode(self, mode: str) -> None:
"""Toggle preview visibility and mode for the given mode ('MESSAGE' or 'THREAD').
Logic:
- If preview is showing the requested mode: hide preview
- If preview is showing the other mode: switch to requested mode
- If preview is hidden: show in requested mode
"""
if self.show_preview and self.preview_mode == mode:
self.show_preview = False
self.focus = 'THREAD_LIST' # Reset focus when preview hidden
elif self.show_preview:
self.preview_mode = mode
else:
self.show_preview = True
self.preview_mode = mode
self.ws.cancel_preview_search()
def show_help(self, stdscr):
"""Display help screen overlay."""
h, w = stdscr.getmaxyx()
stdscr.clear()
lines = [
"Help - Key Bindings",
"=" * 45,
"",
"Focus (split-pane mode):",
" Tab - Toggle focus between thread list and preview",
" Escape - Return focus to thread list (or exit full-screen)",
" ► - Indicates which pane has focus",
"",
"Thread List (when thread list is focused):",
" k / Up - Move cursor up",
" j / Down - Move cursor down",
" Space - Toggle selection of current thread",
" a - Toggle select all / deselect all",
" Enter - View highlighted message of preview thread overview",
" / - Search thread subjects",
" n / p - Next / previous search match",
"",
"Preview Pane (when preview is focused or full-screen):",
" k / Up - Scroll up (message body) or move up (thread overview)",
" j / Down - Scroll down (message body) or move down (thread overview)",
" Enter - View selected message (when in thread overview)",
" Escape - Back to thread overview (when viewing a message)",
" or cancel preview search (or return focus to thread list)",
" / - Search within preview (subjects or message body)",
" n / p - Next / previous preview search match",
" Ctrl+P - View selected message (alternative; toggles)",
"",
"Preview Modes:",
" Ctrl+P - Message preview (toggle/show/switch)",
" Ctrl+T - Thread overview (toggle/show/switch)",
" Ctrl+F - Toggle full-screen mode",
"",
"Markers:",
" [ ] - Not selected",
" [X] - Selected for processing",
" [D] - Already processed in a previous run",
"",
"Other:",
" ? - Show this help",
" Q - Quit and return selected threads",
"",
"Press any key to return...",
]
block_width = max(len(line) for line in lines)
start_x = max(0, (w - block_width) // 2)
start_y = max(0, (h - len(lines)) // 2)
for i, line in enumerate(lines):
stdscr.addstr(start_y + i, start_x, line)
curses.doupdate()
def _build_body_preview(self, thread: Dict[str, Any], preview_width: int,
h: int) -> Tuple[List[Tuple[str, int]], bool, bool]:
"""Return (lines, more_above, more_below) for a scrollable message body.
Uses thread_cursor to select which message in the thread to show,
and message_scroll_offset for vertical scrolling within that message.
"""
messages = self.ws.fetch_thread_overview(thread['root_mid'])
if messages:
msg = messages[min(self.ws.thread_cursor, len(messages) - 1)]
from_hdr = _decode_header(msg.get('from', ''))
date_hdr = msg.get('date', '')
subject_hdr = _decode_header(msg.get('subject', ''))
body_lines = [self._sanitize_for_curses(l[:preview_width-1]) for l in msg.get('body', [])]
else:
from_hdr = ''
date_hdr = ''
subject_hdr = thread['subject']
body_lines = [self._sanitize_for_curses(l[:preview_width-1])
for l in self.ws.fetch_email_body(thread['blob'], 10000)]
header: List[Tuple[str, int]] = [
(f"From: {from_hdr[:preview_width-2]}", 0),
(f"Date: {date_hdr[:preview_width-2]}", 0),
(f"Subject: {subject_hdr[:preview_width-2]}", 0),
("─" * min(preview_width - 1, 80), 0),
]
available = max(1, h - len(header) - 4)
self.ws.message_scroll_offset = min(self.ws.message_scroll_offset,
max(0, len(body_lines) - available))
offset = self.ws.message_scroll_offset
visible = body_lines[offset:offset + available]
matches = set(self.ws.preview_search_matches)
current = (self.ws.preview_search_matches[self.ws.preview_current_match]
if self.ws.preview_current_match >= 0 else -1)
result_body: List[Tuple[str, int]] = []
for local_idx, line in enumerate(visible):
abs_idx = offset + local_idx
if abs_idx == current:
attr = curses.A_BOLD | curses.A_REVERSE
elif abs_idx in matches:
attr = curses.A_BOLD
else:
attr = 0
result_body.append((line, attr))
more_above = offset > 0
more_below = offset + available < len(body_lines)
return header + result_body, more_above, more_below
def _build_thread_overview(self, messages: List[Dict[str, Any]],
preview_width: int,
h: int) -> Tuple[List[Tuple[str, int]], bool, bool]:
"""Return (lines, more_above, more_below) for the thread overview."""
available = h - 5 # Lines available for messages (below header row)
# Adjust scroll offset to keep thread_cursor visible
if self.ws.thread_cursor < self.ws.thread_scroll_offset:
self.ws.thread_scroll_offset = self.ws.thread_cursor
elif self.ws.thread_cursor >= self.ws.thread_scroll_offset + available:
self.ws.thread_scroll_offset = self.ws.thread_cursor - available + 1
offset = self.ws.thread_scroll_offset
header = f"Thread overview: {len(messages)} messages"
lines: List[Tuple[str, int]] = [(header, 0), ("", 0)]
matches = set(self.ws.preview_search_matches)
current = (self.ws.preview_search_matches[self.ws.preview_current_match]
if self.ws.preview_current_match >= 0 else -1)
search_active = bool(matches)
for idx in range(offset, min(len(messages), offset + available)):
msg = messages[idx]
subject = _decode_header(msg.get('subject', '(No Subject)').strip())
sender = _decode_header(msg.get('from', '').strip())
date_fmt = _parse_overview_date(msg.get('date', ''))
depth = msg.get('_depth', 0)
indent = '` ' * depth
show_cursor = idx == self.ws.thread_cursor and not search_active
cursor_marker = '►' if show_cursor else ' '
entry = f"{cursor_marker} {date_fmt} {indent}{subject} {sender}"
if idx == current:
attr = curses.A_BOLD | curses.A_REVERSE
elif idx in matches:
attr = curses.A_BOLD
elif idx == self.ws.thread_cursor and not search_active:
attr = curses.A_REVERSE
else:
attr = 0
lines.append((self._sanitize_for_curses(entry[:preview_width-1]), attr))
more_above = offset > 0
more_below = offset + available < len(messages)
return lines, more_above, more_below
def _plain_body_lines(self, thread: Dict[str, Any]) -> List[str]:
"""Return all plain-text body lines for the currently selected message."""
messages = self.ws.fetch_thread_overview(thread['root_mid'])
if messages:
msg = messages[min(self.ws.thread_cursor, len(messages) - 1)]
return [self._sanitize_for_curses(l) for l in msg.get('body', [])]
return [self._sanitize_for_curses(l)
for l in self.ws.fetch_email_body(thread['blob'], 10000)]
def _plain_overview_lines(self, messages: List[Dict[str, Any]]) -> List[str]:
"""Return all plain-text entry strings for the thread overview."""
result = []
for msg in messages:
subject = _decode_header(msg.get('subject', '(No Subject)').strip())
sender = _decode_header(msg.get('from', '').strip())
date_fmt = _parse_overview_date(msg.get('date', ''))
depth = msg.get('_depth', 0)
indent = '` ' * depth
result.append(self._sanitize_for_curses(f" {date_fmt} {indent}{subject} {sender}"))
return result
def _get_preview_lines(self, thread: Dict[str, Any], preview_width: int,
h: int) -> Tuple[List[Tuple[str, int]], bool, bool]:
"""Return (lines, more_above, more_below) for the preview pane.
Also updates _last_preview_plain_lines for use by preview search input handling.
"""
if self.preview_mode == 'MESSAGE':
self._last_preview_plain_lines = self._plain_body_lines(thread)
return self._build_body_preview(thread, preview_width, h)
messages = self.ws.fetch_thread_overview(thread['root_mid'])
if messages is None:
self._last_preview_plain_lines = []
return [("Loading...", 0)], False, False
self._last_preview_plain_lines = self._plain_overview_lines(messages)
return self._build_thread_overview(messages, preview_width, h)
def _render_fullscreen(self, stdscr, h: int, w: int) -> None:
"""Render full-screen mode: preview/overview takes entire terminal."""
current_thread = self.ws.threads[self.ws.cursor] if self.ws.threads else None
if not current_thread:
return
edition_prefix = f"Edition {self.ws.edition} | " if self.ws.edition is not None else ""
mode_name = "Thread Overview" if self.preview_mode == 'THREAD' else "Message Preview"
if self.ws.preview_searching:
n = len(self.ws.preview_search_matches)
idx = self.ws.preview_current_match + 1 if n else 0
title = f"{edition_prefix}{mode_name} - Search: {self.ws.preview_search_term} [{idx}/{n}] n/p: match Esc: cancel"
else:
if self.preview_mode == 'THREAD':
hint = "Enter: view msg, Ctrl+F: exit, Ctrl+P/T: switch, /: search"
else:
hint = "Esc: back, Ctrl+F: exit, Ctrl+P/T: switch, /: search"
title = f"{edition_prefix}{mode_name} - Full Screen ({hint})"
stdscr.addstr(0, 0, title[:w-1], curses.A_BOLD)
subject_line = f"Thread: {current_thread['subject']}"
stdscr.addstr(1, 0, subject_line[:w-1])
stdscr.addstr(2, 0, "─" * min(w - 1, 120))
preview_lines, more_above, more_below = self._get_preview_lines(current_thread, w - 2, h)
for i, (line, attr) in enumerate(preview_lines):
try:
if 3 + i < h - 1:
stdscr.addstr(3 + i, 0, line[:w-1], attr)
except curses.error:
pass
if more_above:
try:
stdscr.addstr(3, w - 2, "▲")
except curses.error:
pass
if more_below:
try:
stdscr.addstr(h - 2, w - 2, "▼")
except curses.error:
pass
status = f"Selected: {sum(self.ws.selected)}/{len(self.ws.threads)} | Thread {self.ws.cursor + 1}/{len(self.ws.threads)}"
stdscr.addstr(h-1, 0, status[:w-1])
def render(self, stdscr):
"""Render the TUI."""
if self.show_help_overlay:
self.show_help(stdscr)
return
stdscr.erase()
h, w = stdscr.getmaxyx()
if self.view_mode == 'FULLSCREEN':
self._render_fullscreen(stdscr, h, w)
return
self._render_split(stdscr, h, w)
def _render_split(self, stdscr, h: int, w: int) -> None:
"""Render split-pane mode: thread list on the left, optional preview on the right."""
if self.show_preview and w >= 105:
list_width = max(55, min(w // 2, 140))
preview_width = w - list_width - 1
show_preview = True
else:
list_width = w - 1
preview_width = 0
show_preview = False
fixed_width = 3 + 4 + 3 + 12 + 2
subject_width = max(20, list_width - fixed_width - 1)
edition_prefix = f"Edition {self.ws.edition} | " if self.ws.edition is not None else ""
list_focus = self.focus == 'THREAD_LIST'
list_marker = "►" if list_focus else " "
if self.ws.searching:
title = f"{edition_prefix}Search: {self.ws.search_term} (Enter: done, Esc: cancel, n/p next/prev, Ctrl+F full)"
else:
title = f"{list_marker} {edition_prefix}Select threads (? help, / search, Ctrl+F full, Space toggle, Q quit)"
title_attr = curses.A_BOLD if list_focus else 0
stdscr.addstr(0, 0, title[:list_width-1], title_attr)
if show_preview:
stdscr.addstr(0, list_width, "│")
preview_focus = self.focus == 'PREVIEW'
preview_marker = "►" if preview_focus else " "
if self.ws.preview_searching:
n = len(self.ws.preview_search_matches)
idx = self.ws.preview_current_match + 1 if n else 0
preview_label = f"{preview_marker} Search: {self.ws.preview_search_term} [{idx}/{n}] n/p: match Esc: cancel"
else:
if self.preview_mode == 'THREAD':
mode_label = "Thread overview (Enter: view msg, Ctrl+T/P)"
else:
mode_label = "Message preview (Esc: back, Ctrl+P/T)"
preview_label = f"{preview_marker} {mode_label} (Tab: focus, /: search)"
preview_attr = curses.A_BOLD if preview_focus else 0
stdscr.addstr(0, list_width + 1, preview_label[:preview_width - 1], preview_attr)
header = f"{'Age':<3} | {'Msgs':<4} | {'Ppl':<3} | {'Subject':<{subject_width}}"
stdscr.addstr(1, 0, header[:list_width-1])
if show_preview: