forked from huacnlee/omamail
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.qml
More file actions
1762 lines (1632 loc) · 68 KB
/
Copy pathApp.qml
File metadata and controls
1762 lines (1632 loc) · 68 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
import QtQuick
import QtQuick.Controls
import QtQuick.Window
import Quickshell
import Quickshell.Io
import qs.Commons
import qs.Ui
import "account/Model.js" as Model
import "account/Accounts.js" as Accounts
import "compose/Recovery.js" as Recovery
import "keys/Keymap.js" as Keymap
import "message/Mailto.js" as Mailto
import "message/Message.js" as Message
import "components"
import "calendar"
// The application window. The shell loads this entry point when the plugin is
// summoned and calls open()/close() on it; the FloatingWindow follows.
//
// Compose takes over the content area of this same window rather than opening
// a second one; Omarchy's panel mechanism would give an extra window a region
// of its own, which is not what a reply is.
Item {
id: root
property var shell: null
property var manifest: null
property var service: null
property bool opened: false
property bool closingFromHost: false
property string draftSavedNotice: ""
readonly property string pluginId: manifest && manifest.id
? String(manifest.id) : "omamail"
readonly property string composeRecoveryPath: {
var config = Quickshell.env("XDG_CONFIG_HOME")
|| (Quickshell.env("HOME") + "/.config")
return config + "/omamail/compose.json"
}
property var composeRecovery: Recovery.empty()
property bool composeRecoveryLoaded: false
property bool composeRecoveryRestoring: false
property int composeRecoveryRevision: 0
property bool composeDetachingForSave: false
property string lastComposeRecoveryText: ""
property string composeWritePayload: ""
property bool composeWriteQueued: false
function loadComposeRecovery(raw) {
lastComposeRecoveryText = String(raw || "")
composeRecovery = Recovery.parse(raw)
composeRecoveryLoaded = true
Qt.callLater(root.restoreComposeRecovery)
}
function restoreComposeRecovery() {
if (!opened || !composeRecoveryLoaded || composeRecovery.active !== true
|| compose.opened || !composeRecovery.draft) return false
var accountId = String(composeRecovery.draft.accountId || "")
if (accountId !== "" && service
&& String(service.activeAccountId || "") !== accountId
&& typeof service.switchTo === "function") service.switchTo(accountId)
composeReturnView = String(composeRecovery.returnView || "list")
composeRecoveryRestoring = true
compose.restoreDraft(composeRecovery.draft)
composeRecoveryRestoring = false
return true
}
function saveComposeRecovery(saved) {
composeRecoveryTimer.stop()
var draft = saved || (compose.opened ? compose.snapshotDraft()
: (compose.parkedForSend ? compose.pendingDraft : null))
var raw = Recovery.serialize(composeReturnView, draft)
if (raw === "") {
clearComposeRecovery()
return composeRecoveryRevision
}
composeRecovery = Recovery.parse(raw)
if (raw === lastComposeRecoveryText) return composeRecoveryRevision
composeRecoveryRevision++
lastComposeRecoveryText = raw
writeComposeRecovery(raw)
return composeRecoveryRevision
}
function scheduleComposeRecovery() {
if (composeRecoveryRestoring) return
composeRecoveryTimer.restart()
}
function clearComposeRecovery(expectedRevision) {
if (expectedRevision !== undefined
&& Number(expectedRevision) !== composeRecoveryRevision) return false
composeRecoveryTimer.stop()
composeRecovery = Recovery.empty()
composeRecoveryRevision++
if (lastComposeRecoveryText === "") return true
lastComposeRecoveryText = ""
writeComposeRecovery('{"version":1,"active":false}')
return true
}
function writeComposeRecovery(raw) {
composeWritePayload = String(raw || "")
if (!service || String(service.pluginDir || "") === "") return
if (composeRecoveryWriter.running) {
composeWriteQueued = true
return
}
composeWriteQueued = false
composeRecoveryWriter.command = [String(service.pluginDir)
+ "/scripts/config-store.sh", "compose.json"]
composeRecoveryWriter.running = true
}
FileView {
id: composeRecoveryFile
path: root.composeRecoveryPath
printErrors: false
onLoaded: root.loadComposeRecovery(text())
onLoadFailed: root.loadComposeRecovery("")
}
Timer {
id: composeRecoveryTimer
interval: 300
repeat: false
onTriggered: root.saveComposeRecovery()
}
Process {
id: composeRecoveryWriter
stdinEnabled: true
stdout: StdioCollector { waitForEnd: true }
stderr: StdioCollector { waitForEnd: true }
onStarted: {
write(root.composeWritePayload + "\n")
root.composeWritePayload = ""
}
onExited: {
if (root.composeWriteQueued) {
root.composeWriteQueued = false
Qt.callLater(function() {
root.writeComposeRecovery(root.composeWritePayload)
})
} else root.composeWritePayload = ""
}
}
readonly property color foreground: Color.foreground
readonly property color background: Color.background
readonly property color accent: Color.accent
readonly property color urgent: Color.urgent
// Destructive controls consume a role named for their meaning. Omarchy's
// foundational palette currently calls that source `urgent`; keeping the
// mapping here stops account pages from confusing urgency with danger.
readonly property color danger: Color.urgent
readonly property color popupBackground: Color.popups.background
readonly property color popupBorder: Color.popups.border
readonly property color calendarBorder: Style.normalBorderColor
readonly property color calendarTodayBackground: Style.selectedAccentFill
readonly property int calendarBorderWidth: Style.normalBorderWidth
// Mixed toward the ground rather than Qt.darker: on a light theme darkening
// an almost-black foreground makes secondary text heavier than body text.
readonly property color dim: Qt.rgba(
foreground.r * 0.68 + background.r * 0.32,
foreground.g * 0.68 + background.g * 0.32,
foreground.b * 0.68 + background.b * 0.32, 1)
readonly property color dimmer: Qt.rgba(
foreground.r * 0.45 + background.r * 0.55,
foreground.g * 0.45 + background.g * 0.55,
foreground.b * 0.45 + background.b * 0.55, 1)
// Omarchy's palette has no separate "primary": `accent` is it. This theme's
// accent is near fully saturated, which is right for a 5px unread dot and
// wrong for a link sitting inside a paragraph. Same hue, same lightness,
// capped saturation — calm enough to read past, still clearly a link.
readonly property color link: Qt.hsla(accent.hslHue,
Math.min(accent.hslSaturation, 0.55),
accent.hslLightness, 1.0)
readonly property string fontFamily: Style.font.family
function copyText(text) {
clipboardProxy.text = String(text || "")
clipboardProxy.selectAll()
clipboardProxy.copy()
clipboardProxy.deselect()
}
TextEdit {
id: clipboardProxy
visible: false
readOnly: true
}
// Two breakpoints, not a continuum: three columns, list-plus-reader with the
// sidebar collapsed to a strip, and a single column that swaps list for
// reader.
readonly property bool wide: window.width >= Style.space(1000)
readonly property bool compact: window.width < Style.space(760)
property string currentView: "list"
readonly property bool calendarVisible: currentView === "calendar"
property string cursorId: ""
// Kept across messages, and across the window being closed: how somebody
// reads their mail is a fact about them, not about the message that made them
// reach for it. The service holds it because that is what writes it to disk.
readonly property string bodyMode: service ? service.bodyMode : "reader"
// Reading zoom for the message body only. The window's own chrome follows
// the theme's font scale, which is Omarchy's to set, not this app's. The
// service holds it because it is written to disk: a size somebody reached for
// is theirs until they change it, not until they close the window.
readonly property real bodyZoom: service ? service.bodyZoom : 1.0
// 0 means "proportional"; anything else is a width somebody dragged to.
property real listWidth: 0
function zoomBy(step) {
if (service) service.setBodyZoom(Model.zoomAfterStep(service.bodyZoom, step))
}
property bool shortcutHelpVisible: false
property bool setupVisible: false
// Which kind of mailbox is being added. Asked before either form, because the
// two have nothing in common and guessing from the address would be worse
// than asking — a Gmail address is a legitimate IMAP account too.
property bool pickingProvider: false
// Latched once the question has been answered, so the chooser does not come
// back every time a half-finished setup re-renders.
property bool providerChosen: false
// Latched while a setup or edit page is open. Service.providerId briefly
// falls back to Gmail while an account host is rebuilt after saving; that is
// transport lifecycle, not a request to replace an IMAP page with Gmail's.
property string editingProvider: ""
// Set while a picked provider is being turned into an account row, so the
// signal that normally lands the user in Settings leaves them on the form.
property bool openingNewMailbox: false
property bool accountDraftOpen: false
property bool settingsVisible: false
// Something the window needs to say that no account is reporting — refusing a
// duplicate mailbox, for one. Cleared on a timer so it cannot outlive its
// moment on the status line.
property string notice: ""
onNoticeChanged: if (notice !== "") noticeTimer.restart()
// Open by default, but narrow. The longest mailbox name is "All mail" — at
// 11px monospace that needs about 116px including the icon, the gaps and a
// count, so the rail costs little enough to leave standing.
//
// The service owns it, because the service is what outlives the window: the
// rail used to come back open on every restart, which is a preference the
// user had already expressed and the window kept forgetting.
readonly property bool sidebarCollapsed: !!service && service.sidebarCollapsed
function toggleSidebar() {
if (service) service.setSidebarCollapsed(!service.sidebarCollapsed)
}
function openSettings() {
shortcutHelpVisible = false
setupVisible = false
settingsVisible = true
}
readonly property bool ready: !!service && service.ready
// The walkthrough is for having no mailbox at all. A mailbox that has been
// added but not signed in yet belongs in settings, next to the ones that are.
readonly property bool anyReady: !!service && service.anyAccountReady
readonly property bool showSetup: setupVisible || !anyReady
// A setup already part-done answers the question by itself: an account with
// credentials has had its kind chosen, whether or not this window asked.
readonly property bool setupUnderway: !!service && !!service.auth
&& service.auth.credentialsPresent
readonly property bool showPicker: showSetup
&& (pickingProvider || (!providerChosen && !anyReady && !setupUnderway))
readonly property bool showSettings: settingsVisible && !showSetup
// Anything the window goes *into*. The mail chrome stands down for all of it.
readonly property bool showPage: showSetup || showSettings
readonly property bool composing: compose.opened || eventComposer.opened
function open(payloadJson) {
var payload = ({})
try { payload = JSON.parse(String(payloadJson || "{}")) || ({}) } catch (e) {}
closingFromHost = false
opened = true
if (service) service.windowOpen = true
if (payload.mailbox && service) service.selectMailbox(String(payload.mailbox))
if (payload.accountId && service) service.switchTo(String(payload.accountId))
if (payload.messageId) Qt.callLater(function() {
root.openMessage(String(payload.messageId))
})
if (payload.view === "calendar") {
currentView = "calendar"
Qt.callLater(function() {
calendarView.showEvent(String(payload.eventId || ""), Number(payload.eventStart || 0))
})
}
var draft = Mailto.draftFromPayload(payload)
if (draft) root.openDraft(draft)
Qt.callLater(root.restoreComposeRecovery)
// The list is usually already loaded by the time the window is summoned —
// the service keeps running while it is shut — so waiting for the next
// change to seat the cursor leaves the first j with nowhere to move from.
cursorId = Model.cursorAfterReload(service ? service.messages : [], cursorId)
Qt.callLater(function() { focusScope.applyContextFocus() })
}
function close() {
closingFromHost = true
if (compose.opened || compose.parkedForSend) saveComposeRecovery()
opened = false
if (service) service.windowOpen = false
closingFromHost = false
}
function requestClose() {
if (shell && typeof shell.hide === "function") shell.hide(pluginId)
else close()
}
// How a message is read is a preference and survives; the heavy-document
// override is a per-message decision about one specific message and does not.
function openMessage(id) {
if (!service) return
pendingComposeMode = ""
pendingDraftId = ""
reader.forceRichAnyway = false
cursorId = String(id || "")
service.select(cursorId)
currentView = "reader"
}
function editDraft(id) {
if (!service || service.mailboxKey !== "drafts") return false
var draftId = String(id || "")
if (draftId === "") return false
composeReturnView = currentView
pendingComposeMode = ""
pendingDraftId = draftId
if (service.selectedId !== draftId || service.detailLoading
|| !service.detailPainted || !service.selectedMessage) service.select(draftId)
resumeHeldDraft()
if (pendingDraftId !== "") Qt.callLater(root.resumeHeldDraft)
return true
}
function backToList() {
pendingComposeMode = ""
pendingDraftId = ""
if (service) service.clearSelection()
currentView = "list"
Qt.callLater(function() { focusScope.applyContextFocus() })
}
// Moving the cursor has to bring the row with it. The list is a Column in a
// Flickable rather than a ListView — the panel already owns a scroller — so
// there is no positionViewAtIndex and this has to be said out loud.
//
// Called from here rather than from cursorId changing, because hovering a row
// moves the cursor too, and scrolling a half-visible row into view under the
// pointer fights the mouse that is pointing at it.
function revealCursorRow() {
if (!listFlick.visible) return
var bounds = list.boundsFor(cursorId)
if (!bounds) return
listFlick.contentY = Model.contentYToReveal(listFlick.contentY,
listFlick.height, list.y + bounds.y, bounds.height,
listFlick.contentHeight, Style.space(8))
}
function moveCursor(delta) {
if (!service) return
var next = service.cursorOffset(cursorId, delta)
if (next === "") return
cursorId = next
revealCursorRow()
// Moving is not opening. This used to open whatever it landed on while the
// reader was up, which made stepping through a list a way to mark half of
// it read without having looked at any of it. Enter and "o" open.
}
// An answer needs the message it is answering, and opening one only starts
// the fetch — select() clears the summary and the body first. Beginning the
// draft in the same breath addressed nobody and quoted nothing, which is what
// the list row's own Reply menu did. Held until the fetch lands instead.
property string pendingComposeMode: ""
property string pendingDraftId: ""
// Where the draft was raised from, so that leaving it goes back there.
// Answering from the list opens the message being answered — that is the
// reply's doing, not somewhere the reader asked to be — so closing the draft
// has to leave the message with it. Anything raised while reading stays in
// the reader, which is where it came from.
property string composeReturnView: ""
function startCompose(mode) {
if (!service) return
pendingDraftId = ""
var next = String(mode || "new")
if (next !== "new" && !service.selectedMessage) {
pendingComposeMode = next
return
}
pendingComposeMode = ""
compose.begin(next, service.selectedMessage, service.selectedBody.text,
service.selectedAttachments)
}
// A mailto: URL, or the blank draft `compose: true` asks for. The window is
// already open when this runs — summon delivers the payload to open().
function openDraft(draft) {
if (!draft) return
pendingDraftId = ""
composeReturnView = currentView
compose.beginDraft(draft)
}
function resumeHeldCompose() {
if (pendingComposeMode === "" || !service || !service.selectedMessage) return
var mode = pendingComposeMode
pendingComposeMode = ""
startCompose(mode)
}
function resumeHeldDraft() {
if (pendingDraftId === "" || !service) return
if (service.selectedId !== pendingDraftId || service.detailLoading
|| !service.detailPainted || !service.selectedMessage) return
var messageId = pendingDraftId
pendingDraftId = ""
compose.beginDraft(Message.draftFields(service.selectedMessage,
service.selectedBody.text), messageId, service.selectedAttachments)
}
// Answering from the list opens what is being answered first, the way the
// row's own menu does. Anything already open is left alone: re-selecting it
// would throw away the body that is on screen and fetch it again.
function composeFromCursor(mode) {
if (!service || cursorId === "") return
composeReturnView = currentView
if (service.selectedId !== cursorId) openMessage(cursorId)
startCompose(mode)
}
// A draft closed by its own Back, by Escape, by Discard, or by having been
// sent. All four are the same question: where was this raised from.
function leaveCompose() {
var from = composeReturnView
composeReturnView = ""
if (from === "list" && currentView === "reader") backToList()
}
function saveAndLeaveCompose() {
if (!service || !compose.hasMeaningfulDraft()) {
compose.finish()
return
}
var saved = compose.snapshotDraft()
var recoveryRevision = saveComposeRecovery(saved)
composeDetachingForSave = true
compose.detachForSave()
composeDetachingForSave = false
var fields = compose.fieldsForDraft(saved)
service.saveDraft(fields, function(result, error) {
if (!root) return
if (error) {
compose.recoverDetachedSave(saved)
if (root.composeRecoveryRevision === recoveryRevision)
root.saveComposeRecovery(saved)
service.fail("Could not save draft: " + String(error))
return
}
compose.completeDetachedSave(saved)
if (compose.opened) root.scheduleComposeRecovery()
else root.clearComposeRecovery(recoveryRevision)
var warning = String(result && result.warning || "")
root.draftSavedNotice = warning === "" ? "Draft saved" : warning
if (warning !== "" && service && typeof service.note === "function")
service.note(warning)
draftSavedTimer.restart()
if (service.mailboxKey === "drafts") service.refresh()
})
}
function undoPendingSend() {
if (!service || !service.undoSend()) return false
if (!compose.resumePendingSend()) return true
var interrupted = compose.interruptedDraft
var fields = compose.interruptedFields()
if (!interrupted || !fields) return true
service.saveDraft(fields, function(saved, error) {
if (!root) return
if (error) {
service.fail("Could not save the newer draft: " + String(error))
return
}
if (!compose.completeInterruptedSave(interrupted)) return
root.draftSavedNotice = "Draft saved"
draftSavedTimer.restart()
})
return true
}
Timer {
id: draftSavedTimer
interval: 4000
repeat: false
onTriggered: root.draftSavedNotice = ""
}
// Acting on the open message closes it: it is about to leave this list.
function actOnCursor(action) {
if (!service || cursorId === "") return false
var acted = cursorId
var wasOpen = currentView === "reader" && service.selectedId === acted
// Worked out before the action, while the row still has neighbours.
var next = Model.cursorAfterRemoval(service.messages, acted)
var leaves = !Model.survivesAction(service.mailboxKey, action)
if (!service.act(acted, action)) return false
if (!leaves) return true
// The row is going and the cursor must not go with it: a cursor on a
// message that is no longer listed cannot be found, so the next j restarts
// at the top. Archiving one message used to send it back to the first row.
if (wasOpen) {
if (next !== "") openMessage(next)
else backToList()
return true
}
cursorId = next
revealCursorRow()
return true
}
function goMailbox(key) {
if (!service) return
service.selectMailbox(key)
backToList()
}
// The rail as the keys see it: one numbered list, the same one the badges
// are drawn from, so the number beside a row and the row a number opens are
// the same fact rather than two.
readonly property var sidebarSlots: service
? Model.sidebarSlots(service.mailboxes, service.labels, 10) : []
function goSlot(index) {
if (!service || index < 0 || index >= sidebarSlots.length) return
var slot = sidebarSlots[index]
if (slot.kind === "mailbox") return goMailbox(slot.key)
// Not a search: the provider decides what selecting a label means, and on
// IMAP it is a folder rather than a term to look for.
service.selectLabel(slot.name)
backToList()
}
// One answer per key id. The ids come from keys/Keymap.js; adding a key is a
// row there and a case here, and nothing else. The sequence says which key of
// a row fired, for the rows that bind more than one meaning.
function runShortcut(id, sequence) {
// The sheet is on top, so moving moves it. It is a plain overlay rather
// than a popup, which is why its keys can come from here at all — the
// switcher's cannot, and answers them itself.
if (shortcutHelpVisible) {
if (id === "cursorDown") return shortcutHelp.scrollBy(1)
if (id === "cursorUp") return shortcutHelp.scrollBy(-1)
}
if (id === "cursorDown") return moveCursor(1)
if (id === "cursorUp") return moveCursor(-1)
if (id === "open") return openMessage(cursorId)
if (id === "backToList") return backToList()
if (id === "archive") return actOnCursor("archive")
if (id === "trash") return actOnCursor("trash")
// Through the same guard actOnCursor applies rather than around it:
// starring with nothing selected used to call through with an empty id.
if (id === "star") {
if (service && cursorId !== "") service.toggleStar(cursorId)
return
}
if (id === "markRead") return actOnCursor("markRead")
if (id === "markUnread") return actOnCursor("markUnread")
if (id === "reply") return composeFromCursor("reply")
if (id === "replyAll") return composeFromCursor("replyAll")
if (id === "forward") return composeFromCursor("forward")
if (id === "compose") {
if (service && service.mailboxKey === "drafts" && editDraft(cursorId)) return
composeReturnView = currentView
return startCompose("new")
}
if (id === "createEvent") return eventComposer.begin()
if (id === "calendarNext") return calendarView.moveSelection(1)
if (id === "calendarPrevious") return calendarView.moveSelection(-1)
if (id === "openCalendarEvent") return calendarView.activateSelection()
if (id === "calendarPreviousPeriod") return calendarView.movePeriod(-1)
if (id === "calendarNextPeriod") return calendarView.movePeriod(1)
if (id === "calendarToday") return calendarView.goToday()
if (id === "calendarWeek") return calendarView.setView("week")
if (id === "calendarMonth") return calendarView.setView("month")
if (id === "send") return compose.submit()
if (id === "undoSend") { undoPendingSend(); return }
if (id === "search") return searchBar.focusField()
if (id === "goMailbox") return goSlot(Keymap.slotFor(id, sequence))
if (id === "goAccount") {
var accountIndex = Keymap.slotFor(id, sequence)
if (service && accountIndex >= 0 && accountIndex < service.accountCount)
root.switchAccount(accountIndex)
return
}
if (id === "switchAccount") return accountSwitcher.openCentered()
if (id === "calendar") {
if (calendarVisible) backToList()
else {
currentView = "calendar"
calendarView.refresh()
}
return
}
if (id === "mailView") return backToList()
if (id === "calendarView") {
currentView = "calendar"
calendarView.refresh()
return
}
if (id === "toggleSidebar") return toggleSidebar()
if (id === "zoomIn") return zoomBy(0.1)
if (id === "zoomOut") return zoomBy(-0.1)
if (id === "zoomReset") { if (service) service.setBodyZoom(1.0); return }
if (id === "refresh") {
if (calendarVisible) calendarView.refresh()
else if (service) service.refresh()
return
}
if (id === "settings") return openSettings()
if (id === "help") {
shortcutHelpVisible = !shortcutHelpVisible
return
}
if (id === "back") return goBack()
}
// What Escape means, in the order the window is stacked. The row menu, the
// app menu and the account switcher are absent on purpose: a QQC.Popup with
// CloseOnEscape consumes the key itself, so a branch for them here would
// never run.
function goBack() {
if (shortcutHelpVisible) shortcutHelpVisible = false
// A query being typed is the nearest thing to leave: clear it if there is
// one, then hand the keyboard back to the mailbox. This used to live in
// SearchBar as its own Keys handler, which a window Shortcut silently beats.
// A query being typed is the nearest thing to leave: clear it if there is
// one, then hand the keyboard back. Parked directly rather than through
// applyContextFocus, which would still read the context as "search" —
// the field has not lost the focus yet at this point.
else if (searchBar.fieldFocused) {
if (searchBar.queryText !== "") searchBar.clear()
focusScope.parkKeyboard()
}
else if (eventComposer.opened) eventComposer.close()
else if (compose.opened) saveAndLeaveCompose()
else if (setupVisible) setupVisible = false
else if (settingsVisible) settingsVisible = false
else if (currentView === "calendar" && calendarView.detailOpen) calendarView.closeDetail()
else if (currentView === "reader" || currentView === "calendar") backToList()
else if (service && service.searchQuery !== "") service.search("")
else requestClose()
}
Connections {
target: root.service
ignoreUnknownSignals: true
function onReplySent() {
if (!compose.completePendingSend()) return
if (compose.opened) root.scheduleComposeRecovery()
else root.clearComposeRecovery()
}
// Every time the list is replaced — first arrival, a mailbox switch, a
// search, a refresh that dropped things. A cursor whose message survived
// keeps its place; one whose message is gone would be unfindable, and an
// unfindable cursor sends the next j to the top of the list.
// The message a held draft was waiting for. Both halves have to have
// landed: the summary carries the addresses and the subject, and the body
// is what gets quoted — so whichever of them arrives last is what starts
// the draft, and `Qt.callLater` is what lets the fetch finish assigning the
// rest before either is believed.
//
// Watching the body alone was not enough, and the case it missed was every
// message that had been opened before. Those paint from the cache, so the
// body changes while the summary is still null; when the summary lands the
// markup has not changed, so the body is not written a second time and
// nothing fires again. Reply, reply-all and forward raised from the list
// opened the message and stopped there.
function onSelectedBodyChanged() { Qt.callLater(function() {
root.resumeHeldCompose()
root.resumeHeldDraft()
}) }
function onSelectedMessageChanged() { Qt.callLater(function() {
root.resumeHeldCompose()
root.resumeHeldDraft()
}) }
function onMessagesChanged() {
root.cursorId = Model.cursorAfterReload(
root.service ? root.service.messages : [], root.cursorId)
}
// A new account has no mailbox yet, so the only useful place to be is the
// page that gives it one.
// A new mailbox appears as a row in Settings, waiting to be signed in.
// Sending the window to the first-run walkthrough instead showed a setup
// that was already finished, for a different account.
function onDuplicateAccount(email) {
root.notice = email + " is already added"
}
function onAccountAdded() {
// A mailbox added through the chooser goes straight to its own form; the
// user has already said what they want and asking them to find the new
// row in Settings would be a step backwards. One added any other way
// still appears there, waiting to be signed in.
if (root.openingNewMailbox) {
root.openingNewMailbox = false
root.settingsVisible = false
root.setupVisible = true
return
}
root.setupVisible = false
root.settingsVisible = true
}
}
// The setup pages. Built by the Loader above, one at a time, so the ones not
// in use hold no half-typed fields and no state to go stale.
Component {
id: providerPickerPage
ProviderPicker {
textColor: root.foreground
dimColor: root.dim
accentColor: root.accent
panelFontFamily: root.fontFamily
canLeave: root.anyReady
onBackRequested: {
root.pickingProvider = false
root.editingProvider = ""
root.setupVisible = false
}
onChosen: function(providerId) {
root.pickingProvider = false
root.providerChosen = true
root.editingProvider = providerId
// On first run the row already exists and only needs its kind; after
// that, adding a mailbox is what makes one.
if (root.service && root.service.hasSavedAccounts) {
root.openingNewMailbox = true
root.accountDraftOpen = true
root.service.addAccount(providerId)
} else if (root.service) {
root.service.configureCurrentAccount({ provider: providerId })
}
}
}
}
Component {
id: gmailSetupPage
SetupPage {
service: root.service
textColor: root.foreground
dimColor: root.dim
dangerColor: root.danger
accentColor: root.accent
panelFontFamily: root.fontFamily
canLeave: root.anyReady
accountCount: root.service ? root.service.accountCount : 1
onBackRequested: root.leaveSetup()
onRemoveRequested: root.removeCurrentAccountFromEditor()
}
}
Component {
id: heySetupPage
HeySetupPage {
service: root.service
textColor: root.foreground
dimColor: root.dim
dangerColor: root.danger
accentColor: root.accent
panelFontFamily: root.fontFamily
canLeave: root.anyReady
accountCount: root.service ? root.service.accountCount : 1
onBackRequested: root.leaveSetup()
onRemoveRequested: root.removeCurrentAccountFromEditor()
}
}
Component {
id: imapSetupPage
ImapSetupPage {
service: root.service
textColor: root.foreground
dimColor: root.dim
dangerColor: root.danger
accentColor: root.accent
panelFontFamily: root.fontFamily
canLeave: root.anyReady
accountCount: root.service ? root.service.accountCount : 1
onBackRequested: root.leaveSetup()
onRemoveRequested: root.removeCurrentAccountFromEditor()
}
}
function switchAccount(index) {
if (!service) return false
var keepCalendar = calendarVisible
var mailbox = service.mailboxKey
if (service.switchToIndex(index) !== true) return false
if (keepCalendar) {
currentView = "calendar"
return true
}
var target = Model.mailboxAfterAccountSwitch(mailbox, service.mailboxes)
if (target !== "") service.selectMailbox(target)
backToList()
return true
}
function editAccount(index) {
if (!service) return
var accounts = service.accountSummaries || []
editingProvider = index >= 0 && index < accounts.length
? String(accounts[index].provider || "gmail") : "gmail"
if (!service.switchToIndex(index)) return
providerChosen = true
pickingProvider = false
settingsVisible = false
setupVisible = true
}
function leaveSetup() {
if (accountDraftOpen && service) service.discardCurrentDraft()
accountDraftOpen = false
setupVisible = false
editingProvider = ""
}
function removeCurrentAccountFromEditor() {
if (!service || service.accountCount <= 1) return
var index = service.indexOfActiveAccount()
if (index < 0) return
var values = service.accountSummaries || []
var request = Accounts.removalRequest({ accounts: values }, index)
if (request) accountRemovalDialog.openFor(request)
}
function confirmAccountRemoval(request) {
if (!service) return
var index = Accounts.confirmRemoval({ accounts: service.accountSummaries || [] }, request)
if (index < 0) return
service.removeAccountAt(index)
accountDraftOpen = false
leaveSetup()
settingsVisible = true
}
// A delete asks first, and asks naming the target. Only the confirmation
// reaches the controller, with the event the dialog named.
function requestEventDelete(sourceId, event) {
if (!event) return
confirmDeleteDialog.openFor({
kind: "event",
name: String(event.summary || "Untitled event"),
message: "This event will be permanently deleted.",
sourceId: String(sourceId || ""),
event: event
})
}
function confirmDelete(request) {
if (!service) return
if (request.kind === "event" && request.event) {
service.calendarController.deleteEvent(request.sourceId, request.event)
calendarView.closeDetail()
}
}
FloatingWindow {
id: window
visible: root.opened
title: "Omamail"
color: root.background
implicitWidth: Style.space(980)
implicitHeight: Style.space(720)
minimumSize: Qt.size(Style.space(760), Style.space(520))
onVisibleChanged: {
if (!visible && root.opened && !root.closingFromHost) root.requestClose()
}
FocusScope {
id: focusScope
anchors.fill: parent
focus: true
// Where the window is, and the only thing that says what a key means.
// A page is a form before it is anything else, a draft beats reading, a
// query being typed beats the list underneath it.
// Holding Ctrl names every row on the rail, so the digits are read rather
// than remembered. A `Keys` handler, which bindings may not use — but a
// modifier on its own cannot be a `Shortcut`, so there is no binding to
// route and nothing for `KeyRouter` to own. It accepts nothing: whatever
// follows Ctrl still goes exactly where it went before.
//
// `activeFocus` is what clears it. Ctrl+Tab can leave the window with Ctrl
// down and the release can land somewhere else, so waiting for a release
// that is never coming would paint the numbers on permanently.
property bool ctrlDown: false
readonly property bool ctrlHeld: ctrlDown && activeFocus
&& (keyContext === "list" || keyContext === "reader")
Keys.onPressed: function(event) {
if (event.key === Qt.Key_Control) focusScope.ctrlDown = true
}
Keys.onReleased: function(event) {
if (event.key === Qt.Key_Control) focusScope.ctrlDown = false
}
onActiveFocusChanged: if (!activeFocus) ctrlDown = false
readonly property string keyContext: Keymap.contextFor(({
showPage: root.showPage,
composing: root.composing,
searchFocused: searchBar.fieldFocused,
calendarVisible: root.calendarVisible,
currentView: root.currentView,
sendPending: !!root.service && root.service.sendPending
}))
// The context owns the keyboard. Changing it moves the focus to whatever
// that context types into, or parks it when the context types into
// nothing — so a field that has been dismissed cannot go on eating keys.
//
// Keeping these as two things is the bug this replaces: the context came
// from the screen while the focus stayed wherever the last click left it,
// and a closed compose field kept swallowing j and k. One mechanism now,
// and there is nothing to keep in step.
onKeyContextChanged: Qt.callLater(applyContextFocus)
function applyContextFocus() {
if (keyContext === "compose") {
if (eventComposer.opened) eventComposer.takeFocus()
else compose.takeFocus()
}
else if (keyContext === "search") searchBar.focusField()
else parkKeyboard()
}
// forceActiveFocus on the scope itself is a no-op: it re-elects the
// scope's current focus item, which is the very field being left. It has
// to land on a plain Item for the field to actually let go.
function parkKeyboard() {
keyboardHome.forceActiveFocus()
}
// Where the keyboard lives when nothing is being typed into.
Item {
id: keyboardHome
width: 1
height: 1
}
// ------------------------------------------------------------ header
Item {
id: header
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: Style.space(48)
visible: !root.composing
// Identity first, controls after, with a rule between them: the mark
// and the name say what this window is, and everything to their right
// does something.
Row {
id: headerLeft
anchors.left: parent.left
anchors.leftMargin: Style.space(14)
anchors.verticalCenter: parent.verticalCenter
spacing: Style.space(8)
ActionIcon {
anchors.verticalCenter: parent.verticalCenter
name: "gmail"
iconSize: Style.font.iconLarge
color: root.foreground
markColor: root.accent
brand: true
}
Text {
anchors.verticalCenter: parent.verticalCenter
visible: !root.compact
text: "Omamail"
color: root.foreground
font.family: root.fontFamily