-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEmailListView.cpp
More file actions
5055 lines (4259 loc) · 153 KB
/
Copy pathEmailListView.cpp
File metadata and controls
5055 lines (4259 loc) · 153 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
/*
* EmailListView.cpp - High-performance email list view implementation
* Distributed under the terms of the MIT License.
*
* Architecture overview:
* - EmailListView is a BGroupView containing a column header, a scrollable
* ContentView (draws rows), scrollbars, and a status label with loading dots.
* - Only visible rows are drawn (virtual scrolling via _FirstVisibleIndex).
* - A HashMap (node_ref → index) provides O(1) lookup. During loading,
* the HashMap may have stale indices for shifted items (see AddEmailSorted).
* - Node monitors (B_WATCH_ATTR) track only the ~30-50 visible rows to stay
* within the system-wide 4096 monitor limit.
*
* Two-phase query loading:
* Phase 1: Recent emails (last 30 days) loaded with sorted insertion.
* Live queries start at end of Phase 1 so new mail appears immediately.
* Phase 2: Older emails loaded at low priority into the same list.
* HashMap rebuilt at Phase 2 completion.
* Single-phase: Queries involving MAIL:draft skip the time split because
* draft emails may lack MAIL:when.
*
* Threading model:
* Loader thread creates EmailRef objects (disk I/O) and posts batches to
* the window thread via BMessenger. The window thread inserts items into
* the list. A shared_ptr<volatile bool> stop flag allows safe cancellation.
*/
#include "EmailColumnHeader.h"
#include "EmailListView.h"
#include "EmailAccountMap.h"
#include <Box.h>
#include <Bitmap.h>
#include <Catalog.h>
#include <ControlLook.h>
#include <DateFormat.h>
#include <DateTimeFormat.h>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <GroupLayout.h>
#include <GroupView.h>
#include <IconUtils.h>
#include <LayoutBuilder.h>
#include <MenuItem.h>
#include <Node.h>
#include <NodeInfo.h>
#include <NodeMonitor.h>
#include <Path.h>
#include <PopUpMenu.h>
#include <Resources.h>
#include <Roster.h>
#include <Volume.h>
#include <VolumeRoster.h>
#include <Window.h>
#include <MessageRunner.h>
#include <mail_encoding.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <memory>
#include <vector>
#include <set>
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "EmailListView"
#include "LoadingDots.h"
// A view that draws only a left border line. Used as the outermost
// container so the left border spans the full height of the email list.
class LeftBorderView : public BView {
public:
LeftBorderView(const char* name)
: BView(name, B_WILL_DRAW | B_DRAW_ON_CHILDREN | B_FRAME_EVENTS)
{
SetViewUIColor(B_PANEL_BACKGROUND_COLOR);
SetLayout(new BGroupLayout(B_VERTICAL, 0));
}
virtual void DrawAfterChildren(BRect updateRect)
{
BRect bounds = Bounds();
SetHighColor(tint_color(ui_color(B_PANEL_BACKGROUND_COLOR),
B_DARKEN_2_TINT));
StrokeLine(bounds.LeftTop(), bounds.LeftBottom());
}
};
// A wrapper view for the status label and loading dots that draws
// top and bottom borders to match the scrollbar border lines.
class StatusAreaView : public BView {
public:
StatusAreaView(const char* name)
: BView(name, B_WILL_DRAW | B_DRAW_ON_CHILDREN | B_FRAME_EVENTS)
{
SetViewUIColor(B_PANEL_BACKGROUND_COLOR);
}
virtual void DrawAfterChildren(BRect updateRect)
{
BRect bounds = Bounds();
SetHighColor(tint_color(ui_color(B_PANEL_BACKGROUND_COLOR),
B_DARKEN_2_TINT));
StrokeLine(bounds.LeftTop(), bounds.RightTop());
StrokeLine(bounds.LeftBottom(), bounds.RightBottom());
}
};
// A spacer view for the corner below the vertical scrollbar.
// Draws bottom and right borders to complete the border frame.
class CornerSpacerView : public BView {
public:
CornerSpacerView(const char* name)
: BView(name, B_WILL_DRAW)
{
SetViewUIColor(B_PANEL_BACKGROUND_COLOR);
}
virtual void Draw(BRect updateRect)
{
BRect bounds = Bounds();
SetHighColor(tint_color(ui_color(B_PANEL_BACKGROUND_COLOR),
B_DARKEN_2_TINT));
// Bottom border
StrokeLine(bounds.LeftBottom(), bounds.RightBottom());
// Right border
StrokeLine(bounds.RightTop(), bounds.RightBottom());
}
};
// Internal message codes for loader thread → window thread communication.
// kMsgLoaderBatch carries a batch of EmailRef pointers.
// kMsgPhase1Done / kMsgPhase2Done signal phase completion (trigger next phase or finalize).
static const uint32 kMsgLoaderBatch = 'ldbh';
static const uint32 kMsgLoaderDone = 'lddn';
static const uint32 kMsgPhase1Done = 'ph1d';
static const uint32 kMsgPhase2Done = 'ph2d';
// Icon resource IDs (must match .rdef)
static const int32 kResStarred = 402;
static const int32 kResAttachment = 401;
static const int32 kResAttachmentWhite = 403;
// Cached icons (loaded once, shared by all instances)
static BBitmap* sStarIcon = NULL;
static BBitmap* sAttachmentIcon = NULL;
static BBitmap* sAttachmentWhiteIcon = NULL;
static bool sIconsLoaded = false;
// ============================================================================
// Body text extraction helpers (for body/full-text search)
// ============================================================================
// Strip HTML tags from a string in-place, decode common HTML entities,
// and collapse excessive whitespace. Only applied when the content is
// detected as HTML. Preserves all text between tags so code examples
// in entity-encoded form (e.g. <div>) come through correctly.
static void
StripHtmlTags(BString* text)
{
if (text == NULL || text->Length() == 0)
return;
const char* src = text->String();
int32 srcLen = text->Length();
BString result;
result.SetTo("", srcLen); // Pre-allocate
bool inTag = false;
bool inScript = false; // Inside <script> or <style> blocks
for (int32 i = 0; i < srcLen; i++) {
char c = src[i];
if (inScript) {
// Look for closing </script> or </style>
if (c == '<' && i + 2 < srcLen && src[i + 1] == '/') {
// Check for </script or </style (case-insensitive)
BString closing;
int32 end = i + 2;
while (end < srcLen && src[end] != '>' && (end - i) < 12)
end++;
if (end < srcLen) {
text->CopyInto(closing, i + 2, end - i - 2);
closing.ToLower();
if (closing == "script" || closing == "style") {
inScript = false;
i = end; // Skip past the closing tag
}
}
}
continue;
}
if (c == '<') {
// Check for <script or <style (case-insensitive)
if (i + 7 < srcLen) {
BString tagName;
int32 end = i + 1;
while (end < srcLen && src[end] != '>' && src[end] != ' '
&& (end - i) < 10)
end++;
text->CopyInto(tagName, i + 1, end - i - 1);
tagName.ToLower();
if (tagName == "script" || tagName == "style") {
inScript = true;
// Skip to end of opening tag
while (i < srcLen && src[i] != '>')
i++;
continue;
}
}
inTag = true;
// Insert a space for block-level tags to prevent word joining
if (result.Length() > 0) {
char last = result.ByteAt(result.Length() - 1);
if (last != ' ' && last != '\n')
result << ' ';
}
continue;
}
if (c == '>') {
inTag = false;
continue;
}
if (inTag)
continue;
// Decode HTML entities
if (c == '&' && i + 1 < srcLen) {
// Find the semicolon
int32 semi = -1;
for (int32 j = i + 1; j < srcLen && j < i + 10; j++) {
if (src[j] == ';') {
semi = j;
break;
}
}
if (semi > i + 1) {
BString entity;
text->CopyInto(entity, i + 1, semi - i - 1);
bool decoded = false;
if (entity == "amp") {
result << '&'; decoded = true;
} else if (entity == "lt") {
result << '<'; decoded = true;
} else if (entity == "gt") {
result << '>'; decoded = true;
} else if (entity == "quot") {
result << '"'; decoded = true;
} else if (entity == "apos") {
result << '\''; decoded = true;
} else if (entity == "nbsp") {
result << ' '; decoded = true;
} else if (entity.ByteAt(0) == '#') {
// Numeric entity: &#nnn; or &#xHHH;
int32 codePoint = 0;
if (entity.ByteAt(1) == 'x' || entity.ByteAt(1) == 'X') {
codePoint = (int32)strtol(
entity.String() + 2, NULL, 16);
} else {
codePoint = atoi(entity.String() + 1);
}
if (codePoint > 0 && codePoint < 128) {
result << (char)codePoint;
decoded = true;
} else if (codePoint >= 128) {
// Non-ASCII: replace with space to avoid
// broken UTF-8 sequences in search matching
result << ' ';
decoded = true;
}
}
if (decoded) {
i = semi; // Skip past the entity
continue;
}
}
}
result << c;
}
*text = result;
}
// Search a header block for a specific header field (case-insensitive).
// Returns the value (trimmed) or empty string if not found.
// headerStart/headerEnd define the region to search (exclusive of the
// blank-line separator).
static BString
_FindHeader(const char* headerStart, const char* headerEnd,
const char* fieldName)
{
int32 fieldLen = strlen(fieldName);
for (const char* p = headerStart; p + fieldLen < headerEnd; p++) {
// Only match at the start of a line (or start of the header block).
// Without this check we can falsely match header names embedded
// inside values — e.g. ARC-Message-Signature's "h=" field lists
// header names like "content-type" as plain text.
if (p != headerStart && p[-1] != '\n')
continue;
if ((*p == fieldName[0] || *p == (fieldName[0] ^ 0x20))
&& strncasecmp(p, fieldName, fieldLen) == 0) {
// Found — extract value (skip whitespace after the field name)
const char* value = p + fieldLen;
while (value < headerEnd && (*value == ' ' || *value == '\t'))
value++;
// Collect until end of line (handling header folding: if the
// next line starts with whitespace, it's a continuation)
char result[512];
int32 j = 0;
while (value < headerEnd && j < (int32)sizeof(result) - 1) {
if (*value == '\r' || *value == '\n') {
// Skip the line ending
const char* next = value;
if (*next == '\r') next++;
if (next < headerEnd && *next == '\n') next++;
// Check for folded header (next line starts with space/tab)
if (next < headerEnd
&& (*next == ' ' || *next == '\t')) {
result[j++] = ' ';
value = next;
// Skip leading whitespace of continuation
while (value < headerEnd
&& (*value == ' ' || *value == '\t'))
value++;
continue;
}
break; // Not folded — end of this header
}
result[j++] = *value++;
}
// Trim trailing whitespace
while (j > 0 && (result[j - 1] == ' ' || result[j - 1] == '\t'))
j--;
result[j] = '\0';
return BString(result);
}
}
return BString();
}
// Extract the boundary string from a Content-Type header value.
// e.g. from "multipart/alternative; boundary=\"----=_Part_123\""
// returns "----=_Part_123".
static BString
_ExtractBoundary(const BString& contentType)
{
// Find "boundary=" (case-insensitive)
int32 pos = contentType.IFindFirst("boundary=");
if (pos < 0)
return BString();
const char* start = contentType.String() + pos + 9; // skip "boundary="
BString boundary;
if (*start == '"') {
// Quoted boundary — collect until closing quote
start++;
while (*start != '\0' && *start != '"')
boundary << *start++;
} else {
// Unquoted — collect until whitespace, semicolon, or end
while (*start != '\0' && *start != ' ' && *start != '\t'
&& *start != ';' && *start != '\r' && *start != '\n')
boundary << *start++;
}
return boundary;
}
// Decode a MIME part body given its encoding and length.
// Sets outText and returns true on success.
static bool
_DecodePart(const char* bodyStart, int32 bodyLen,
mail_encoding encoding, bool isHtml, BString* outText)
{
if (bodyLen <= 0)
return false;
if (encoding == base64 || encoding == quoted_printable
|| encoding == uuencode) {
char* decoded = new(std::nothrow) char[bodyLen + 1];
if (decoded == NULL)
return false;
ssize_t decodedLen = decode(encoding, decoded, bodyStart,
bodyLen, 0);
if (decodedLen > 0) {
decoded[decodedLen] = '\0';
*outText = decoded;
}
delete[] decoded;
} else {
// 7bit, 8bit, or no encoding — use raw bytes
outText->SetTo(bodyStart, bodyLen);
}
if (outText->Length() == 0)
return false;
if (isHtml)
StripHtmlTags(outText);
return true;
}
// Find the first text part (text/plain preferred, text/html as fallback)
// inside a multipart body. boundary is the MIME boundary string.
// regionStart/regionEnd delimit the body area to search.
// Sets outText and returns true if a text part was found and decoded.
// If recurse is true, handles one level of nested multipart.
static bool
_FindTextPart(const char* regionStart, const char* regionEnd,
const BString& boundary, bool recurse, BString* outText)
{
// Build the boundary delimiter: "--" + boundary
BString delim("--");
delim << boundary;
int32 delimLen = delim.Length();
// Collect all part start positions by scanning for the delimiter.
// Each part starts after the delimiter line; the closing delimiter
// has "--" appended (e.g. "--boundary--").
struct PartInfo {
const char* headerStart;
const char* headerEnd; // blank line
const char* bodyStart;
const char* bodyEnd;
};
// We only need to track a modest number of parts (most emails have
// 2-5 parts). Use a fixed array to avoid heap allocation.
static const int32 kMaxParts = 16;
PartInfo parts[kMaxParts];
int32 partCount = 0;
const char* pos = regionStart;
while (pos < regionEnd && partCount < kMaxParts) {
// Find next boundary
const char* found = NULL;
for (const char* p = pos; p + delimLen <= regionEnd; p++) {
if (*p == '-' && *(p + 1) == '-'
&& strncmp(p, delim.String(), delimLen) == 0) {
found = p;
break;
}
}
if (found == NULL)
break;
// Check if this is the closing delimiter (--boundary--)
const char* afterDelim = found + delimLen;
if (afterDelim + 1 < regionEnd
&& afterDelim[0] == '-' && afterDelim[1] == '-')
break; // End of multipart
// Skip past the delimiter line (to the start of part headers)
const char* lineEnd = afterDelim;
while (lineEnd < regionEnd && *lineEnd != '\n')
lineEnd++;
if (lineEnd < regionEnd)
lineEnd++; // skip the '\n'
const char* partStart = lineEnd;
// Find the next boundary to know where this part ends
const char* nextBoundary = NULL;
for (const char* p = partStart; p + delimLen <= regionEnd; p++) {
if (*p == '-' && *(p + 1) == '-'
&& strncmp(p, delim.String(), delimLen) == 0) {
nextBoundary = p;
break;
}
}
if (nextBoundary == NULL)
nextBoundary = regionEnd;
// Within this part, find the blank line separating part headers
// from part body
const char* partHeaderEnd = NULL;
int32 partSepLen = 0;
// Try \r\n\r\n first
for (const char* p = partStart; p + 3 < nextBoundary; p++) {
if (p[0] == '\r' && p[1] == '\n'
&& p[2] == '\r' && p[3] == '\n') {
partHeaderEnd = p;
partSepLen = 4;
break;
}
}
if (partHeaderEnd == NULL) {
// Try \n\n
for (const char* p = partStart; p + 1 < nextBoundary; p++) {
if (p[0] == '\n' && p[1] == '\n') {
partHeaderEnd = p;
partSepLen = 2;
break;
}
}
}
if (partHeaderEnd != NULL) {
PartInfo& part = parts[partCount++];
part.headerStart = partStart;
part.headerEnd = partHeaderEnd;
part.bodyStart = partHeaderEnd + partSepLen;
// Trim trailing \r\n before the next boundary
part.bodyEnd = nextBoundary;
while (part.bodyEnd > part.bodyStart
&& (part.bodyEnd[-1] == '\r' || part.bodyEnd[-1] == '\n'))
part.bodyEnd--;
}
pos = nextBoundary;
}
// Now scan parts: prefer text/plain, fall back to text/html.
// If a part is itself multipart and recurse is true, descend into it.
int32 htmlPartIndex = -1;
for (int32 i = 0; i < partCount; i++) {
BString ct = _FindHeader(parts[i].headerStart,
parts[i].headerEnd, "Content-Type:");
ct.ToLower();
if (ct.FindFirst("text/plain") >= 0) {
// Found text/plain — decode and return immediately
BString cte = _FindHeader(parts[i].headerStart,
parts[i].headerEnd, "Content-Transfer-Encoding:");
mail_encoding enc = cte.Length() > 0
? encoding_for_cte(cte.String()) : no_encoding;
int32 partBodyLen = parts[i].bodyEnd - parts[i].bodyStart;
if (_DecodePart(parts[i].bodyStart, partBodyLen, enc, false,
outText))
return true;
}
if (ct.FindFirst("text/html") >= 0 && htmlPartIndex < 0)
htmlPartIndex = i;
// Handle one level of nested multipart
if (recurse && ct.FindFirst("multipart/") >= 0) {
BString innerBoundary = _ExtractBoundary(ct);
if (innerBoundary.Length() > 0) {
// The inner multipart's body starts at parts[i].bodyStart
// and ends at parts[i].bodyEnd (approximately — the body
// extends to the outer boundary, so use nextBoundary region).
// Actually, the inner body includes everything from the
// part body start up to where the outer part ends.
if (_FindTextPart(parts[i].bodyStart, parts[i].bodyEnd,
innerBoundary, false, outText))
return true;
}
}
}
// No text/plain found — try text/html fallback
if (htmlPartIndex >= 0) {
BString cte = _FindHeader(parts[htmlPartIndex].headerStart,
parts[htmlPartIndex].headerEnd,
"Content-Transfer-Encoding:");
mail_encoding enc = cte.Length() > 0
? encoding_for_cte(cte.String()) : no_encoding;
int32 partBodyLen = parts[htmlPartIndex].bodyEnd
- parts[htmlPartIndex].bodyStart;
if (_DecodePart(parts[htmlPartIndex].bodyStart, partBodyLen, enc,
true, outText))
return true;
}
return false;
}
// Extract the plain text body from an email file. Returns true if text
// was successfully extracted. Uses lightweight mail_encoding decode()
// functions instead of BEmailMessage to avoid expensive MIME object
// construction. Handles:
// - Single-part emails (7bit, 8bit, quoted-printable, base64)
// - Multipart emails (finds the text/plain or text/html part)
// - One level of nested multipart (e.g. multipart/mixed containing
// multipart/alternative — the most common structure for emails
// with attachments)
static bool
ExtractBodyText(const entry_ref& ref, BString* outText)
{
if (outText == NULL)
return false;
outText->SetTo("");
// Read the raw file
BFile file(&ref, B_READ_ONLY);
if (file.InitCheck() != B_OK)
return false;
off_t fileSize;
file.GetSize(&fileSize);
if (fileSize <= 0 || fileSize > 1024 * 1024)
return false; // Skip files > 1 MB
char* buffer = new(std::nothrow) char[fileSize + 1];
if (buffer == NULL)
return false;
ssize_t bytesRead = file.Read(buffer, fileSize);
if (bytesRead <= 0) {
delete[] buffer;
return false;
}
buffer[bytesRead] = '\0';
const char* bufferEnd = buffer + bytesRead;
// Find the blank line separating headers from body
const char* headerEnd = strstr(buffer, "\r\n\r\n");
int32 separatorLen = 4;
if (headerEnd == NULL) {
headerEnd = strstr(buffer, "\n\n");
separatorLen = 2;
}
if (headerEnd == NULL) {
delete[] buffer;
return false;
}
const char* bodyStart = headerEnd + separatorLen;
if (bodyStart >= bufferEnd) {
delete[] buffer;
return false;
}
// Check if this is a multipart message
BString contentType = _FindHeader(buffer, headerEnd, "Content-Type:");
BString ctLower(contentType);
ctLower.ToLower();
bool ok = false;
bool isMultipart = (ctLower.FindFirst("multipart/") >= 0);
if (isMultipart) {
// Multipart — extract boundary and find the text part
BString boundary = _ExtractBoundary(contentType);
if (boundary.Length() > 0)
ok = _FindTextPart(bodyStart, bufferEnd, boundary, true, outText);
}
if (!ok && !isMultipart) {
// Single-part email only — decode the whole body using the
// top-level Content-Transfer-Encoding. Do NOT fall through here
// for multipart messages: the raw body contains undecoded base64
// blobs, boundary markers, and part headers that would cause
// false-positive search matches.
BString cte = _FindHeader(buffer, headerEnd,
"Content-Transfer-Encoding:");
mail_encoding encoding = cte.Length() > 0
? encoding_for_cte(cte.String()) : no_encoding;
int32 bodyLen = bufferEnd - bodyStart;
bool isHtml = (ctLower.FindFirst("text/html") >= 0);
ok = _DecodePart(bodyStart, bodyLen, encoding, isHtml, outText);
// If Content-Type wasn't explicit, check content for HTML
if (ok && !isHtml && outText->Length() > 0) {
BString lower(*outText);
lower.ToLower();
if (lower.FindFirst("<!doctype html") >= 0
|| lower.FindFirst("<html") >= 0
|| (lower.FindFirst("<head") >= 0
&& lower.FindFirst("<body") >= 0)) {
StripHtmlTags(outText);
}
}
}
delete[] buffer;
return ok;
}
// Background item disposal to avoid UI stalls when clearing large lists.
// Deleting 20,000+ EmailItem/EmailRef objects plus clearing a large HashMap
// can take >1s on the UI thread. This moves both costs to a background thread.
struct _DisposerData {
EmailItem** items;
int32 count;
std::unordered_map<node_ref, int32, NodeRefHash, NodeRefEqual>* hashMap;
};
static int32
_ItemDisposerThread(void* data)
{
_DisposerData* d = (_DisposerData*)data;
for (int32 i = 0; i < d->count; i++)
delete d->items[i];
delete[] d->items;
delete d->hashMap;
delete d;
return 0;
}
static BBitmap*
_LoadIconFromResource(int32 resourceId, float size)
{
BResources* resources = BApplication::AppResources();
if (resources == NULL)
return NULL;
size_t dataSize;
const void* data = resources->LoadResource('VICN', resourceId, &dataSize);
if (data == NULL)
return NULL;
BBitmap* bitmap = new BBitmap(BRect(0, 0, size - 1, size - 1), B_RGBA32);
if (bitmap->InitCheck() != B_OK) {
delete bitmap;
return NULL;
}
if (BIconUtils::GetVectorIcon((const uint8*)data, dataSize, bitmap) != B_OK) {
delete bitmap;
return NULL;
}
return bitmap;
}
static void
_LoadIcons(float size)
{
if (sIconsLoaded)
return;
sIconsLoaded = true;
sStarIcon = _LoadIconFromResource(kResStarred, size);
sAttachmentIcon = _LoadIconFromResource(kResAttachment, size);
sAttachmentWhiteIcon = _LoadIconFromResource(kResAttachmentWhite, size);
if (sStarIcon == NULL)
fprintf(stderr, "Warning: Star icon (resource %d) not found\n", kResStarred);
if (sAttachmentIcon == NULL)
fprintf(stderr, "Warning: Attachment icon (resource %d) not found\n", kResAttachment);
}
// Data passed to loader thread. Owns its own copies of volumes and shares
// the stop flag with EmailListView via shared_ptr (so the flag stays alive
// even if a new query replaces fCurrentStopFlag before this thread exits).
struct LoaderData {
EmailListView* view;
BMessenger messenger;
BString predicate;
#if B_HAIKU_VERSION > B_HAIKU_VERSION_1_BETA_5
BObjectList<BVolume, false> volumes; // Does NOT own items - we delete manually
#else
BObjectList<BVolume> volumes; // Does NOT own items - we delete manually
#endif
bool showTrash;
bool showSpam;
bool attachmentsOnly;
std::set<BString> spamBlocklist; // copy of sender blocklist for background filtering
std::shared_ptr<volatile bool> stopFlag; // Shared ownership with EmailListView
volatile int32* currentQueryId; // Points to EmailListView::fCurrentQueryId for staleness check
time_t cutoffTime; // 30 days ago timestamp
int32 phase; // 1 = recent, 2 = older
int32 queryId; // Unique ID to identify this query session
~LoaderData() {
// Manually delete volumes since we set owning to false
for (int32 i = 0; i < volumes.CountItems(); i++) {
delete volumes.ItemAt(i);
}
// stopFlag shared_ptr releases automatically
}
};
// =============================================================================
// EmailRef out-of-line method
// Defined here (not in EmailRef.h) to break the circular dependency:
// EmailRef.h → EmailAccountMap.h → (large include chain). Keeping EmailRef.h
// lightweight is important because it's included everywhere.
// =============================================================================
void
EmailRef::_ResolveAccountName(int32 accountId)
{
account = EmailAccountMap::Instance().GetAccountName(accountId);
}
// =============================================================================
// EmailItem implementation
// =============================================================================
EmailItem::EmailItem(EmailRef* ref)
:
fRef(ref),
fSelected(false),
fPathValid(false),
fDateStringValid(false)
{
}
EmailItem::~EmailItem()
{
delete fRef;
}
// === EmailViews API accessors ===
const char*
EmailItem::GetPath() const
{
if (fRef == NULL)
return "";
if (!fPathValid) {
BEntry entry(&fRef->entryRef);
if (entry.InitCheck() == B_OK) {
BPath path;
if (entry.GetPath(&path) == B_OK) {
fPath = path.Path();
}
}
fPathValid = true;
}
return fPath.String();
}
const char*
EmailItem::GetStatus() const
{
if (fRef == NULL)
return "";
return fRef->status.String();
}
const char*
EmailItem::GetAccount() const
{
if (fRef == NULL)
return "";
return fRef->account.String();
}
const char*
EmailItem::GetFrom() const
{
if (fRef == NULL)
return "";
return fRef->from.String();
}
const char*
EmailItem::GetTo() const
{
if (fRef == NULL)
return "";
return fRef->to.String();
}
const char*
EmailItem::GetSubject() const
{
if (fRef == NULL)
return "";
return fRef->subject.String();
}
time_t
EmailItem::GetWhen() const
{
if (fRef == NULL)
return 0;
return fRef->when;
}
const timespec&
EmailItem::GetCrtime() const
{
static timespec empty = {0, 0};
if (fRef == NULL)
return empty;
return fRef->crtime;
}
const node_ref*
EmailItem::GetNodeRef() const
{
if (fRef == NULL)
return NULL;
return &fRef->nodeRef;
}
const entry_ref&
EmailItem::GetEntryRef() const
{
static entry_ref empty;
if (fRef == NULL)
return empty;
return fRef->entryRef;
}
bool
EmailItem::IsRead() const
{
if (fRef == NULL)
return true;
return fRef->isRead;
}
bool
EmailItem::HasAttachment() const
{
if (fRef == NULL)
return false;
return fRef->hasAttachment;
}
bool
EmailItem::IsStarred() const
{
if (fRef == NULL)
return false;
return fRef->isStarred;
}
void
EmailItem::SetRead(bool read)
{
if (fRef != NULL) {
fRef->isRead = read;
// Update status string to match
if (read && fRef->status.ICompare("New") == 0) {
fRef->status = "Read";
} else if (!read) {
fRef->status = "New";
}
}
}
void
EmailItem::SetStatus(const char* status)
{
if (fRef != NULL && status != NULL) {
fRef->status = status;
fRef->isRead = (fRef->status.ICompare("New") != 0);
}
}
void
EmailItem::SetStarred(bool starred)
{
if (fRef != NULL) {
fRef->isStarred = starred;
}
}
void
EmailItem::SetHasAttachment(bool hasAttachment)
{