-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEmailViews.cpp
More file actions
8219 lines (7096 loc) · 316 KB
/
Copy pathEmailViews.cpp
File metadata and controls
8219 lines (7096 loc) · 316 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
/*
* EmailViews.cpp - Main window for EmailViews native email viewer for Haiku
* Distributed under the terms of the MIT License.
*
* This file contains three major classes:
* EmailViewsWindow - Three-pane main window (sidebar / email list / preview).
* Owns the query list, search bar, time range filter, and
* preview pane. Delegates email loading and list management
* to EmailListView.
* DeskbarReplicant - Tray icon showing new mail count with popup menu.
* Runs in the Deskbar process, loads its own resources
* from our binary image.
* EmailViewsApp - BApplication subclass. Manages compose windows, global
* settings (gReaderSettings), and spell-check dictionaries.
*
* Threading model:
* Several operations run on background threads to keep the UI responsive:
* - Zip backup (ZipWorkerThread) - pipes paths to zip via stdin
* - Trash emptying (TrashEmptyThread) - queries + deletes
* - Move to trash (MoveToTrashThread) - writes _trk/original_path, moves
* - Restore from trash (RestoreThread) - restores by original path or account
* - Permanent delete (PermanentDeleteThread)
* - Sidebar count updates (_QueryCountThread) - counts unread/draft/trash/custom
* - Background new-mail queries (_InitBackgroundQueriesThread) - live BQuery
* All communicate back to the window thread via BMessenger::SendMessage().
*/
#include "EmailViews.h"
#include "AppInfo.h"
#include "EmailAccountMap.h"
#include "QueryNameDialog.h"
#include "reader/EmailReaderWindow.h"
#include "reader/Messages.h"
#include "reader/ReaderSettings.h"
#include "reader/ReaderSupport.h"
#include "reader/Words.h"
#include "reader/Prefs.h"
#include <Catalog.h>
#include <Screen.h>
#include <FindDirectory.h>
#include <Volume.h>
#include <VolumeRoster.h>
#include <fs_attr.h>
#include <fs_index.h>
#include <Alert.h>
#include <Size.h>
#include <DateTimeFormat.h>
#include <parsedate.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#include <strings.h>
#include <Message.h>
#include <MessageFilter.h>
#include <Messenger.h>
#include <MessageRunner.h>
#include <IconUtils.h>
#include <Resources.h>
#include <MimeType.h>
#include <Notification.h>
#include <DataIO.h>
#include <Deskbar.h>
#include <Archivable.h>
#include <FilePanel.h>
#include <PropertyInfo.h>
#include <MailDaemon.h>
#include <MailAttachment.h>
#include <MailContainer.h>
#include <mail_util.h>
#include <cstdio>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <image.h>
#include <sys/resource.h>
#include <cmath>
#include <algorithm>
#include <OS.h>
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "EmailViewsWindow"
// Deskbar replicant exports
extern "C" _EXPORT BView* instantiate_deskbar_item(float maxWidth, float maxHeight);
// Application identifiers
static const char* kAppSignature = "application/x-vnd.EmailViews";
static const char* kDeskbarReplicantName = "EmailViews";
// Mail app operation codes for inter-application communication
const int32 OP_REPLY = 1;
const int32 OP_REPLY_ALL = 2;
const int32 OP_FORWARD = 3;
// Internal message for Alt+Up/Down sidebar navigation
static const uint32 MSG_NAVIGATE_QUERY_LIST = 'nqls';
// Message filter that intercepts Alt+Up/Down to navigate the query sidebar.
// Installed on the window so it fires regardless of which child view has focus.
class QueryNavFilter : public BMessageFilter {
public:
QueryNavFilter(BWindow* window)
: BMessageFilter(B_KEY_DOWN),
fWindow(window)
{
}
virtual filter_result Filter(BMessage* message, BHandler** _target)
{
int32 modifiers;
if (message->FindInt32("modifiers", &modifiers) != B_OK)
return B_DISPATCH_MESSAGE;
// Only act on Alt (Command key on Haiku) without other modifiers
// (allow Alt+Shift etc. to pass through)
if ((modifiers & (B_COMMAND_KEY | B_CONTROL_KEY | B_SHIFT_KEY | B_OPTION_KEY))
!= B_COMMAND_KEY)
return B_DISPATCH_MESSAGE;
int32 rawChar;
if (message->FindInt32("raw_char", &rawChar) != B_OK)
return B_DISPATCH_MESSAGE;
int32 direction = 0;
if (rawChar == B_UP_ARROW)
direction = -1;
else if (rawChar == B_DOWN_ARROW)
direction = 1;
if (direction == 0)
return B_DISPATCH_MESSAGE;
// Post navigation message to the window
BMessage nav(MSG_NAVIGATE_QUERY_LIST);
nav.AddInt32("direction", direction);
fWindow->PostMessage(&nav);
return B_SKIP_MESSAGE;
}
private:
BWindow* fWindow;
};
// Zip backup worker thread data (uses piped input to handle large file lists)
struct ZipWorkerData {
BString savePath;
BString* paths;
int32 count;
BMessenger messenger; // To notify window when done
};
static status_t ZipWorkerThread(void* data)
{
ZipWorkerData* wd = (ZipWorkerData*)data;
// Build command: zip -ry <archive> -@
// The -@ flag tells zip to read filenames from stdin
// Note: we don't use -j (junk paths) so directory structure is preserved,
// avoiding duplicate filename overwrites from different folders
BString command("zip -ry '");
command << wd->savePath << "' -@ > /dev/null 2>&1";
// Open pipe to zip process
FILE* zipPipe = popen(command.String(), "w");
if (zipPipe == NULL) {
delete[] wd->paths;
BNotification notification(B_ERROR_NOTIFICATION);
notification.SetGroup("EmailViews");
notification.SetTitle("EmailViews");
notification.SetContent("Failed to start zip process.");
notification.Send();
// Notify window that backup finished (even on failure)
BMessage doneMsg(MSG_BACKUP_FINISHED);
wd->messenger.SendMessage(&doneMsg);
delete wd;
return B_ERROR;
}
// Write each file path to zip's stdin
for (int32 i = 0; i < wd->count; i++) {
if (wd->paths[i].Length() > 0) {
fprintf(zipPipe, "%s\n", wd->paths[i].String());
}
}
// Close pipe and wait for zip to finish
int result = pclose(zipPipe);
// Send notification
BNotification notification(result == 0 ?
B_INFORMATION_NOTIFICATION : B_ERROR_NOTIFICATION);
notification.SetGroup("EmailViews");
notification.SetTitle("EmailViews");
if (result == 0) {
BString content;
content << "Successfully backed up " << wd->count << " emails.";
notification.SetContent(content.String());
} else {
notification.SetContent("Backup failed: could not create ZIP archive.");
}
notification.Send();
// Notify window that backup finished
BMessage doneMsg(MSG_BACKUP_FINISHED);
wd->messenger.SendMessage(&doneMsg);
delete[] wd->paths;
delete wd;
return B_OK;
}
// Trash empty thread data
struct TrashEmptyData {
BList* emailRefs; // List of entry_ref* to delete (may be NULL if query needed)
BMessenger messenger; // To notify window when done
#if B_HAIKU_VERSION > B_HAIKU_VERSION_1_BETA_5
BObjectList<BVolume, false> volumes; // Volumes to query (non-owning)
#else
BObjectList<BVolume> volumes; // Volumes to query (non-owning)
#endif
};
static status_t TrashEmptyThread(void* data)
{
TrashEmptyData* emptyData = (TrashEmptyData*)data;
// If no refs provided, query for them now (moved from window thread)
if (emptyData->emailRefs == NULL) {
emptyData->emailRefs = new BList();
for (int32 v = 0; v < emptyData->volumes.CountItems(); v++) {
BVolume* volume = emptyData->volumes.ItemAt(v);
if (volume == NULL)
continue;
BPath volumeTrashPath;
if (find_directory(B_TRASH_DIRECTORY, &volumeTrashPath, false, volume) != B_OK)
continue;
BString trashLower(volumeTrashPath.Path());
trashLower.ToLower();
BQuery trashQuery;
trashQuery.SetVolume(volume);
trashQuery.SetPredicate("MAIL:subject=**");
if (trashQuery.Fetch() == B_OK) {
entry_ref ref;
while (trashQuery.GetNextRef(&ref) == B_OK) {
BEntry entry(&ref);
BPath path;
entry.GetPath(&path);
BString pathStr(path.Path());
pathStr.ToLower();
if (pathStr.FindFirst(trashLower) >= 0) {
entry_ref* refCopy = new entry_ref(ref);
emptyData->emailRefs->AddItem(refCopy);
}
}
}
}
}
int32 count = emptyData->emailRefs->CountItems();
int32 deleted = 0;
// Delete all emails
for (int32 i = 0; i < count; i++) {
entry_ref* ref = (entry_ref*)emptyData->emailRefs->ItemAt(i);
BEntry entry(ref);
if (entry.Remove() == B_OK)
deleted++;
delete ref;
}
delete emptyData->emailRefs;
// Send notification
BNotification notification(B_INFORMATION_NOTIFICATION);
notification.SetGroup("EmailViews");
notification.SetTitle("EmailViews");
BString message;
message.SetToFormat("%ld email%s permanently deleted", deleted, deleted == 1 ? "" : "s");
notification.SetContent(message.String());
notification.Send();
// Notify window to update UI
BMessage doneMsg(MSG_TRASH_EMPTIED);
emptyData->messenger.SendMessage(&doneMsg);
delete emptyData;
return B_OK;
}
// Query count thread data (for counting unread/draft/trash in background)
struct QueryCountCustomQuery {
BString path; // File path to the query file
BString predicate; // Query predicate read from _trk/qrystr attribute
BString baseName; // Display name without count
};
struct QueryCountData {
BMessenger messenger;
#if B_HAIKU_VERSION > B_HAIKU_VERSION_1_BETA_5
BObjectList<BVolume, true> volumes;
BObjectList<QueryCountCustomQuery, true> customQueries;
#else
BObjectList<BVolume> volumes;
BObjectList<QueryCountCustomQuery> customQueries;
#endif
volatile bool* stopFlag;
bool showTrashOnly;
int32 listCount;
int32 generation;
};
// Extract bare email address from a MAIL:from field like
// "John Doe <john@example.com>" or just "john@example.com"
static BString
_ExtractEmailAddress(const char* fromField)
{
if (fromField == NULL)
return BString();
BString from(fromField);
int32 open = from.FindFirst('<');
int32 close = from.FindFirst('>', open);
if (open >= 0 && close > open) {
BString addr;
from.CopyInto(addr, open + 1, close - open - 1);
addr.Trim();
addr.ToLower();
return addr;
}
// No angle brackets — treat the whole thing as an address
from.Trim();
from.ToLower();
return from;
}
static int32 _CountWithExclusions(BQuery& query, const BString& trashLower,
volatile bool* stopFlag)
{
int32 count = 0;
entry_ref ref;
while (query.GetNextRef(&ref) == B_OK) {
if (stopFlag && *stopFlag)
return count;
BPath path(&ref);
BString pathStr(path.Path());
pathStr.ToLower();
// Exclude trash
if (trashLower.Length() > 0 && pathStr.FindFirst(trashLower) >= 0)
continue;
// Exclude spam
BNode node(&ref);
BString classification;
if (node.InitCheck() == B_OK
&& node.ReadAttrString("MAIL:classification", &classification) == B_OK
&& classification.ICompare("Spam") == 0)
continue;
count++;
}
return count;
}
struct PermanentDeleteData {
BList* emailPaths; // List of BString* paths to delete
BMessenger messenger; // To notify window when done
int32 firstSelectedIndex; // For repositioning selection after delete
};
// Message for permanent delete completion
const uint32 MSG_PERMANENT_DELETE_DONE = 'pddn';
// Background move-to-trash
struct MoveToTrashData {
BList* emailPaths; // List of BString* paths to move
BMessenger messenger; // To notify window when done
};
const uint32 MSG_MOVE_TO_TRASH_DONE = 'mtdn';
static status_t MoveToTrashThread(void* data)
{
MoveToTrashData* trashData = (MoveToTrashData*)data;
for (int32 i = 0; i < trashData->emailPaths->CountItems(); i++) {
BString* pathStr = (BString*)trashData->emailPaths->ItemAt(i);
if (!pathStr)
continue;
BEntry entry(pathStr->String());
if (entry.InitCheck() != B_OK) {
delete pathStr;
continue;
}
BVolume entryVolume;
if (entry.GetVolume(&entryVolume) != B_OK) {
delete pathStr;
continue;
}
BPath trashPath;
if (find_directory(B_TRASH_DIRECTORY, &trashPath, true, &entryVolume) != B_OK) {
delete pathStr;
continue;
}
BDirectory trashDir(trashPath.Path());
if (trashDir.InitCheck() != B_OK) {
delete pathStr;
continue;
}
// Store original path as _trk/original_path attribute before moving.
// This is the same attribute Tracker uses, enabling restore via either
// EmailViews or Tracker's "Restore" menu item.
BNode node(&entry);
if (node.InitCheck() == B_OK) {
node.WriteAttr("_trk/original_path", B_STRING_TYPE, 0,
pathStr->String(), pathStr->Length() + 1);
}
// Move to trash, handle name collision
status_t moveStatus = entry.MoveTo(&trashDir);
if (moveStatus == B_FILE_EXISTS) {
char originalName[B_FILE_NAME_LENGTH];
entry.GetName(originalName);
for (int32 suffix = 1; suffix < 1000; suffix++) {
BString newName(originalName);
newName << " " << suffix;
BEntry testEntry;
BPath testPath(trashPath.Path());
testPath.Append(newName.String());
if (testEntry.SetTo(testPath.Path()) != B_OK || !testEntry.Exists()) {
if (entry.Rename(newName.String()) == B_OK) {
entry.MoveTo(&trashDir);
break;
}
}
}
}
delete pathStr;
}
// Notify window that move is complete
BMessage doneMsg(MSG_MOVE_TO_TRASH_DONE);
trashData->messenger.SendMessage(&doneMsg);
delete trashData->emailPaths;
delete trashData;
return B_OK;
}
// Restore thread data (for restoring selected emails from Trash view)
struct RestoreThreadData {
BList* emailRefs; // List of entry_ref* to restore
BMessenger messenger; // To notify window when done
int32 firstSelectedIndex; // For repositioning selection after restore
std::map<int32, BString>* accountMap; // Copy of account map for lookups
};
// Message for restore completion
const uint32 MSG_RESTORE_DONE = 'rsdn';
// Structure to track restore results
struct RestoreResult {
node_ref nref;
bool success;
};
static status_t RestoreThread(void* data)
{
RestoreThreadData* restoreData = (RestoreThreadData*)data;
// Track results for UI update
BList* results = new BList(); // List of RestoreResult*
BList* orphanedRefs = new BList(); // List of entry_ref* for emails with unknown accounts
for (int32 i = 0; i < restoreData->emailRefs->CountItems(); i++) {
entry_ref* ref = (entry_ref*)restoreData->emailRefs->ItemAt(i);
if (!ref)
continue;
BNode node(ref);
if (node.InitCheck() != B_OK) {
delete ref;
continue;
}
node_ref nref;
node.GetNodeRef(&nref);
// Try to get original path first
char originalPath[B_PATH_NAME_LENGTH];
ssize_t size = node.ReadAttr("_trk/original_path", B_STRING_TYPE, 0,
originalPath, sizeof(originalPath) - 1);
// Restore destination priority:
// 1. _trk/original_path attribute (set by MoveToTrashThread or Tracker)
// 2. Account-based inbox path (~/mail/<account>/INBOX)
// 3. Orphaned list (account deleted - user picks folder via file panel)
BString destinationFolder;
if (size > 0) {
originalPath[size] = '\0';
BPath origPath(originalPath);
BPath parentPath;
if (origPath.GetParent(&parentPath) == B_OK) {
destinationFolder = parentPath.Path();
}
}
// If no original path, try account-based restoration
if (destinationFolder.IsEmpty()) {
int32 accountId = -1;
bool hasAccountAttr = false;
bool accountFound = false;
attr_info attrInfo;
if (node.GetAttrInfo("MAIL:account", &attrInfo) == B_OK) {
hasAccountAttr = true;
if (attrInfo.type == B_INT32_TYPE) {
node.ReadAttr("MAIL:account", B_INT32_TYPE, 0, &accountId, sizeof(accountId));
accountFound = (restoreData->accountMap->find(accountId) != restoreData->accountMap->end());
} else if (attrInfo.type == B_STRING_TYPE) {
char accountName[256];
ssize_t nameSize = node.ReadAttr("MAIL:account", B_STRING_TYPE, 0, accountName, sizeof(accountName) - 1);
if (nameSize > 0) {
accountName[nameSize] = '\0';
for (auto& pair : *restoreData->accountMap) {
if (pair.second == accountName) {
accountId = pair.first;
accountFound = true;
break;
}
}
}
}
}
if (hasAccountAttr && !accountFound) {
// Account not found - add to orphaned list for folder selection dialog
orphanedRefs->AddItem(new entry_ref(*ref));
delete ref;
continue;
}
// Get inbox path for account
if (accountFound && accountId >= 0) {
auto it = restoreData->accountMap->find(accountId);
if (it != restoreData->accountMap->end()) {
BPath mailPath;
if (find_directory(B_USER_DIRECTORY, &mailPath) == B_OK) {
mailPath.Append("mail");
mailPath.Append(it->second.String());
mailPath.Append("INBOX");
destinationFolder = mailPath.Path();
}
}
}
}
// Perform the restore
RestoreResult* result = new RestoreResult();
result->nref = nref;
result->success = false;
if (!destinationFolder.IsEmpty()) {
create_directory(destinationFolder.String(), 0755);
BEntry entry(ref);
if (entry.InitCheck() == B_OK) {
BDirectory destDir(destinationFolder.String());
if (destDir.InitCheck() == B_OK) {
result->success = (entry.MoveTo(&destDir) == B_OK);
}
}
}
results->AddItem(result);
delete ref;
}
delete restoreData->emailRefs;
delete restoreData->accountMap;
// Notify window to update UI
BMessage doneMsg(MSG_RESTORE_DONE);
doneMsg.AddInt32("first_index", restoreData->firstSelectedIndex);
doneMsg.AddPointer("results", results);
doneMsg.AddPointer("orphaned_refs", orphanedRefs);
restoreData->messenger.SendMessage(&doneMsg);
delete restoreData;
return B_OK;
}
static status_t PermanentDeleteThread(void* data)
{
PermanentDeleteData* deleteData = (PermanentDeleteData*)data;
int32 count = deleteData->emailPaths->CountItems();
int32 deleted = 0;
// Track successfully deleted paths to pass back for UI update
BList* deletedPaths = new BList();
// Delete all emails
for (int32 i = 0; i < count; i++) {
BString* path = (BString*)deleteData->emailPaths->ItemAt(i);
if (path) {
BEntry entry(path->String());
if (entry.InitCheck() == B_OK && entry.Remove() == B_OK) {
deleted++;
// Keep path for UI update
deletedPaths->AddItem(path);
} else {
// Delete failed - free the path
delete path;
}
}
}
delete deleteData->emailPaths;
// Send notification
BNotification notification(B_INFORMATION_NOTIFICATION);
notification.SetGroup("EmailViews");
notification.SetTitle("EmailViews");
BString message;
message.SetToFormat("%ld email%s permanently deleted", deleted, deleted == 1 ? "" : "s");
notification.SetContent(message.String());
notification.Send();
// Notify window to update UI - pass the deleted paths
BMessage doneMsg(MSG_PERMANENT_DELETE_DONE);
doneMsg.AddInt32("first_index", deleteData->firstSelectedIndex);
doneMsg.AddPointer("deleted_paths", deletedPaths);
deleteData->messenger.SendMessage(&doneMsg);
delete deleteData;
return B_OK;
}
// Background thread to initialize live queries for new mail count.
// BQuery::Fetch() returns initial results synchronously. With many emails,
// consuming these results can take several seconds. We do this on a background
// thread so the window doesn't block. After consuming all initial results,
// the query transitions to live mode and sends B_QUERY_UPDATE for new matches.
/*static*/ status_t
EmailViewsWindow::_InitBackgroundQueriesThread(void* data)
{
EmailViewsWindow* window = static_cast<EmailViewsWindow*>(data);
for (int32 i = 0; i < window->fSelectedVolumes.CountItems(); i++) {
BVolume* volume = window->fSelectedVolumes.ItemAt(i);
if (volume == NULL)
continue;
BQuery* query = new BQuery();
query->SetVolume(volume);
// Must lock window to access fBackgroundQueryHandler
if (!window->LockLooper()) {
delete query;
continue;
}
query->SetTarget(BMessenger(window->fBackgroundQueryHandler, window));
window->UnlockLooper();
query->SetPredicate("(BEOS:TYPE==\"text/x-email\")&&((MAIL:status==New)||(MAIL:status==Seen))");
if (query->Fetch() == B_OK) {
// Must consume all initial results before live updates are sent
entry_ref ref;
while (query->GetNextRef(&ref) == B_OK) {
// Just consume, don't process
}
if (window->LockLooper()) {
window->fBackgroundNewMailQueries.AddItem(query);
window->UnlockLooper();
} else {
delete query;
}
} else {
delete query;
}
}
// Trigger initial count update now that queries are primed
if (window->LockLooper()) {
window->ScheduleQueryCountUpdate();
window->UnlockLooper();
}
return B_OK;
}
// EmailViewsWindow implementation
EmailViewsWindow::EmailViewsWindow()
: BWindow(BRect(100, 100, 900, 700), kAppName,
B_DOCUMENT_WINDOW, B_AUTO_UPDATE_SIZE_LIMITS),
fBackgroundQueryHandler(NULL),
fShowTrashOnly(false),
fShowSpamOnly(false),
fTrashLoaderStop(false),
fEmptyingTrash(false),
fAttachmentsOnly(false),
fQueryReloadRunner(NULL),
fQueryCountRunner(NULL),
fQueryCountThread(-1),
fQueryCountStop(false),
fQueryCountGeneration(0),
fTimeRangeFilterRunner(NULL),
fShowInDeskbar(false),
fCachedNewCount(-1),
fCachedTrashCount(-1),
fSearchField(NULL),
fIsSearchActive(false),
fPendingBodySearch(false),
fPendingBodySearchCaseSensitive(false),
fPendingBodySearchFullText(false),
fTimeRangeSlider(NULL),
fTimeRangeLabel(NULL),
fTimeRangeGroup(NULL),
fEmptyListLabel(NULL),
fEmailListCardView(NULL),
fEmptyPreviewLabel(NULL),
fHtmlMessageButton(NULL),
fHtmlVersionButton(NULL),
fHtmlBodyContent(NULL),
fHtmlBodyContentSize(0),
fPreviewCardView(NULL),
fPreviewScrollView(NULL),
fTrashItem(NULL),
fDeskbarMenuItem(NULL),
fCurrentViewItem(NULL),
fAttachmentStrip(NULL),
fRestoreFolderPanel(NULL),
fVolumeMenu(NULL),
fSelectedVolumes(5)
{
// Find mail directory
BPath path;
if (find_directory(B_USER_DIRECTORY, &path) == B_OK) {
path.Append("mail");
fMailDirectory = path.Path();
}
// Find trash directory and get its node_ref for monitoring
BPath trashPath;
if (find_directory(B_TRASH_DIRECTORY, &trashPath) == B_OK) {
fTrashDirectory = trashPath.Path();
BDirectory trashDir(trashPath.Path());
if (trashDir.InitCheck() == B_OK) {
trashDir.GetNodeRef(&fTrashDirRef);
}
}
// Ensure FILE:starred index exists on the boot volume for starred email
// queries. EmailViews uses this custom attribute (not part of mail_daemon)
// to track starred status. Without the index, BQuery can't match on it.
// fs_create_index silently returns EEXIST if already present.
{
BVolumeRoster volumeRoster;
BVolume bootVolume;
volumeRoster.GetBootVolume(&bootVolume);
if (bootVolume.InitCheck() == B_OK) {
// Create index - ignore EEXIST (already exists)
fs_create_index(bootVolume.Device(), "FILE:starred", B_INT32_TYPE, 0);
fs_create_index(bootVolume.Device(), "MAIL:classification", B_STRING_TYPE, 0);
}
}
// Create menu bar
fMenuBar = new BMenuBar("menubar");
// Create EmailViews menu
BMenu* mailViewerMenu = new BMenu(B_TRANSLATE_SYSTEM_NAME(kAppName));
mailViewerMenu->AddItem(new BMenuItem(B_TRANSLATE("About EmailViews" B_UTF8_ELLIPSIS),
new BMessage(MSG_ABOUT)));
mailViewerMenu->AddSeparatorItem();
BMenuItem* emailSettingsItem = new BMenuItem(B_TRANSLATE("Email preferences" B_UTF8_ELLIPSIS),
new BMessage(M_PREFS),',');
emailSettingsItem->SetTarget(be_app);
mailViewerMenu->AddItem(emailSettingsItem);
mailViewerMenu->AddItem(new BMenuItem(B_TRANSLATE("Email accounts" B_UTF8_ELLIPSIS),
new BMessage(MSG_EMAIL_SETTINGS)));
fDeskbarMenuItem = new BMenuItem(B_TRANSLATE("Show in Deskbar"), new BMessage(MSG_TOGGLE_DESKBAR));
mailViewerMenu->AddItem(fDeskbarMenuItem);
mailViewerMenu->AddSeparatorItem();
mailViewerMenu->AddItem(new BMenuItem(B_TRANSLATE("Quit"), new BMessage(MSG_QUIT), 'Q'));
fMenuBar->AddItem(mailViewerMenu);
// Create Messages menu
BMenu* messagesMenu = new BMenu(B_TRANSLATE("Messages"));
messagesMenu->AddItem(new BMenuItem(B_TRANSLATE("New email"), new BMessage(MSG_CREATE_EMAIL), 'N'));
messagesMenu->AddSeparatorItem();
messagesMenu->AddItem(new BMenuItem(B_TRANSLATE("Reply"), new BMessage(MSG_REPLY), 'R'));
messagesMenu->AddItem(new BMenuItem(B_TRANSLATE("Reply all"), new BMessage(MSG_REPLY_ALL), 'R', B_SHIFT_KEY));
messagesMenu->AddItem(new BMenuItem(B_TRANSLATE("Forward"), new BMessage(MSG_FORWARD), 'F', B_SHIFT_KEY));
messagesMenu->AddSeparatorItem();
fMarkReadMenuItem = new BMenuItem(B_TRANSLATE("Mark as read"), new BMessage(MSG_MARK_READ),'M');
fMarkReadMenuItem->SetEnabled(false);
messagesMenu->AddItem(fMarkReadMenuItem);
fMarkUnreadMenuItem = new BMenuItem(B_TRANSLATE("Mark as unread"), new BMessage(MSG_MARK_UNREAD));
fMarkUnreadMenuItem->SetEnabled(false);
messagesMenu->AddItem(fMarkUnreadMenuItem);
messagesMenu->AddSeparatorItem();
BMenuItem* item = new BMenuItem(B_TRANSLATE("Move to Trash"), new BMessage(MSG_DELETE_EMAIL));
item->SetEnabled(false);
messagesMenu->AddItem(item);
fMarkSpamMenuItem = new BMenuItem(B_TRANSLATE("Mark as spam"), new BMessage(MSG_MARK_SPAM));
fMarkSpamMenuItem->SetEnabled(false);
messagesMenu->AddItem(fMarkSpamMenuItem);
fUnmarkSpamMenuItem = new BMenuItem(B_TRANSLATE("Not spam"), new BMessage(MSG_UNMARK_SPAM));
fUnmarkSpamMenuItem->SetEnabled(false);
messagesMenu->AddItem(fUnmarkSpamMenuItem);
messagesMenu->AddSeparatorItem();
fUndoMenuItem = new BMenuItem(B_TRANSLATE("Undo Move to Trash"), new BMessage(MSG_UNDO_DELETE), 'Z');
fUndoMenuItem->SetEnabled(false);
messagesMenu->AddItem(fUndoMenuItem);
messagesMenu->AddSeparatorItem();
messagesMenu->AddItem(new BMenuItem(B_TRANSLATE("Backup emails to ZIP" B_UTF8_ELLIPSIS), new BMessage(MSG_BACKUP_EMAILS)));
fMenuBar->AddItem(messagesMenu);
// Create Filter menu
BMenu* filterMenu = new BMenu(B_TRANSLATE("Filter"));
filterMenu->AddItem(new BMenuItem(B_TRANSLATE("Filter by 'Sender'"), new BMessage(MSG_FILTER_EXACT_SENDER)));
filterMenu->AddItem(new BMenuItem(B_TRANSLATE("Filter by 'Recipient'"), new BMessage(MSG_FILTER_EXACT_RECIPIENT)));
filterMenu->AddItem(new BMenuItem(B_TRANSLATE("Filter by 'Subject'"), new BMessage(MSG_FILTER_EXACT_SUBJECT)));
filterMenu->AddItem(new BMenuItem(B_TRANSLATE("Filter by 'Account'"), new BMessage(MSG_FILTER_EXACT_ACCOUNT)));
filterMenu->AddSeparatorItem();
filterMenu->AddItem(new BMenuItem(B_TRANSLATE("Clear filter"), new BMessage(MSG_SEARCH_CLEAR)));
filterMenu->AddSeparatorItem();
fTimeRangeMenuItem = new BMenuItem(B_TRANSLATE("Show time range"),
new BMessage(MSG_TOGGLE_TIME_RANGE), 'T', B_SHIFT_KEY);
fTimeRangeMenuItem->SetMarked(true);
filterMenu->AddItem(fTimeRangeMenuItem);
fMenuBar->AddItem(filterMenu);
// Create Queries menu
BMenu* queriesMenu = new BMenu(B_TRANSLATE("Queries"));
queriesMenu->AddItem(new BMenuItem(B_TRANSLATE("Add 'From' query"), new BMessage(MSG_FILTER_BY_SENDER)));
queriesMenu->AddItem(new BMenuItem(B_TRANSLATE("Add 'To' query"), new BMessage(MSG_FILTER_BY_RECIPIENT)));
queriesMenu->AddItem(new BMenuItem(B_TRANSLATE("Add 'Account' query"), new BMessage(MSG_FILTER_BY_ACCOUNT)));
queriesMenu->AddSeparatorItem();
queriesMenu->AddItem(new BMenuItem(B_TRANSLATE("Open queries folder"), new BMessage(MSG_OPEN_QUERIES_FOLDER)));
fMenuBar->AddItem(queriesMenu);
// Create Volumes menu (will be populated by BuildVolumeMenu)
fVolumeMenu = new BMenu(B_TRANSLATE("Volumes"));
fMenuBar->AddItem(fVolumeMenu);
// Helper function to load HVIF icon from app resources by numeric ID
auto LoadIconById = [](int32 id) -> BBitmap* {
BResources* resources = BApplication::AppResources();
if (resources == NULL)
return nullptr;
size_t size;
const void* data = resources->LoadResource(B_VECTOR_ICON_TYPE, id, &size);
if (data == NULL || size == 0)
return nullptr;
BBitmap* icon = new BBitmap(BRect(BPoint(0, 0),
be_control_look->ComposeIconSize(31)), B_RGBA32);
if (BIconUtils::GetVectorIcon((const uint8*)data, size, icon) == B_OK) {
return icon;
}
delete icon;
return nullptr;
};
// Resource IDs for toolbar icons (from EmailViews.rdef)
const int32 kIconCheckEmail = 205;
const int32 kIconNewEmail = 201;
const int32 kIconReply = 1008;
const int32 kIconForward = 1009;
const int32 kIconMarkRead = 202;
const int32 kIconMarkUnread = 203;
const int32 kIconDelete = 204;
// Create toolbar
fToolBar = new ToolBarView();
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Toolbar"
fToolBar->AddAction(MSG_CHECK_EMAIL, this, LoadIconById(kIconCheckEmail), NULL, B_TRANSLATE_COMMENT("Check email", "As short as possible"));
fToolBar->AddAction(MSG_NEW_EMAIL, this, LoadIconById(kIconNewEmail), NULL, B_TRANSLATE_COMMENT("New email", "As short as possible"));
fToolBar->AddAction(MSG_REPLY, this, LoadIconById(kIconReply), NULL, B_TRANSLATE_COMMENT("Reply", "As short as possible"));
fToolBar->AddAction(MSG_FORWARD, this, LoadIconById(kIconForward), NULL, B_TRANSLATE_COMMENT("Forward", "As short as possible"));
fToolBar->AddAction(MSG_MARK_READ, this, LoadIconById(kIconMarkRead), NULL, B_TRANSLATE_COMMENT("Mark read", "As short as possible"));
fToolBar->AddAction(MSG_MARK_UNREAD, this, LoadIconById(kIconMarkUnread), NULL, B_TRANSLATE_COMMENT("Mark unread", "As short as possible"));
fToolBar->AddAction(MSG_DELETE_EMAIL, this, LoadIconById(kIconDelete), NULL, B_TRANSLATE_COMMENT("Trash", "As short as possible"));
fToolBar->AddSeparator();
const int32 kIconNext = 1013;
const int32 kIconPrevious = 1012;
fToolBar->AddAction(MSG_NEXT_EMAIL, this, LoadIconById(kIconNext), NULL, B_TRANSLATE_COMMENT("Next", "As short as possible"));
fToolBar->AddAction(MSG_PREV_EMAIL, this, LoadIconById(kIconPrevious), NULL, B_TRANSLATE_COMMENT("Previous", "As short as possible"));
_DisableToolBarIcons();
fToolBar->AddGlue(); // Glue at end like reader window
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "EmailViewsWindow"
// Apply toolbar button bar preference (icons only vs icons & labels)
_UpdateToolBar();
// Create the query list (no border - toolbar separator provides top line)
fQueryList = new QueryListView("queryList", this);
fQueryList->SetSelectionMessage(new BMessage(MSG_QUERY_SELECTED));
BScrollView* queryScroll = new BScrollView("queryScroll", fQueryList,
0, false, true, B_NO_BORDER);
// Create the fixed trash item at bottom
fTrashItem = new TrashItemView(this);
BScrollView* trashScroll = new BScrollView("trashScroll", fTrashItem,
0, false, false, B_PLAIN_BORDER); // No scrollbars
// Height matches the built-in sidebar row height: ComposeIconSize(31) + one label spacing
float trashIconSize = (float)be_control_look->ComposeIconSize(31).width + 1;
float trashRowHeight = trashIconSize + be_control_look->DefaultLabelSpacing();
trashScroll->SetExplicitMinSize(BSize(B_SIZE_UNSET, trashRowHeight));
trashScroll->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, trashRowHeight));
// Create container for query list + trash item
// Use -1 top inset on trashScroll to merge with queryScroll's bottom border
BGroupView* queryContainer = new BGroupView(B_VERTICAL, 0);
BLayoutBuilder::Group<>(queryContainer, B_VERTICAL, 0)
.Add(queryScroll, 1.0f)
.AddGroup(B_VERTICAL, 0)
.Add(trashScroll, 0.0f)
.SetInsets(0, -1, 0, 0)
.End()
.SetInsets(0, -1, 0, -1);
// Create the email list view - self-contained high-performance component
// Includes column headers, scrollbars, status bar, query execution, live queries
fEmailList = new EmailListView("emailList", this);
fEmailList->SetSelectionMessage(new BMessage(MSG_EMAIL_SELECTED));
fEmailList->SetInvocationMessage(new BMessage(MSG_EMAIL_INVOKED));
// Create empty list message (shown when no emails match)
// Use BStringView in a centered layout for automatic positioning
fEmptyListLabel = new BStringView("emptyListLabel",
B_TRANSLATE("No emails found."));
fEmptyListLabel->SetAlignment(B_ALIGN_CENTER);
fEmptyListLabel->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));
// Create a container for the empty message with centered layout
BGroupView* emptyListInner = new BGroupView(B_VERTICAL);
emptyListInner->SetViewUIColor(B_LIST_BACKGROUND_COLOR);
emptyListInner->SetExplicitMinSize(BSize(0, 0));
emptyListInner->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
BLayoutBuilder::Group<>(emptyListInner, B_VERTICAL)
.AddGlue()
.Add(fEmptyListLabel)
.AddGlue()
.SetInsets(B_USE_DEFAULT_SPACING);
// Wrap in scroll view for border matching the email list (B_FANCY_BORDER)
BScrollView* emptyListContainer = new BScrollView("emptyListScroll", emptyListInner,
0, false, false, B_FANCY_BORDER);
emptyListContainer->SetExplicitMinSize(BSize(0, 0));
emptyListContainer->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
// Create card view to switch between empty message and email list
fEmailListCardView = new BCardView("emailListCards");
fEmailListCardView->SetExplicitMinSize(BSize(0, 0));
fEmailListCardView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
fEmailListCardView->AddChild(emptyListContainer); // Card 0: empty message
fEmailListCardView->AddChild(fEmailList); // Card 1: email list
fEmailListCardView->CardLayout()->SetVisibleItem((int32)0); // Start with empty message;
// Create the preview pane for displaying email content
fPreviewPane = new BTextView("previewPane");
fPreviewPane->MakeEditable(false);
fPreviewPane->SetStylable(true);
fPreviewPane->SetWordWrap(true);
fPreviewPane->SetViewUIColor(B_DOCUMENT_BACKGROUND_COLOR);
fPreviewPane->SetLowUIColor(B_DOCUMENT_BACKGROUND_COLOR);
fPreviewPane->SetHighUIColor(B_DOCUMENT_TEXT_COLOR);
fPreviewScrollView = new BScrollView("previewScroll", fPreviewPane,