-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChat.qml
More file actions
3923 lines (3601 loc) · 158 KB
/
Copy pathChat.qml
File metadata and controls
3923 lines (3601 loc) · 158 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.Layouts
import QtMultimedia
import Quickshell
import Quickshell.Io
import Quickshell.Wayland
import qs.Commons
import qs.Ui
import "Model.js" as Model
// The client proper: conversations on the left, one of them on the right, a
// line to type in at the bottom.
//
// Summoned with an optional payload — by the bar panel, by the "Open" action
// on a notification, or by hand:
// omarchy-shell shell summon megamvb.omawhats '{}'
// {"chat": "<jid>"} open that conversation
// {"action": "new"} the new-chat dialog ("logout" and "help" work too)
//
// With the daemon switched off it still opens, read-only, on what was stored.
// Every action has a key; F1 lists them (Model.SHORTCUTS).
Item {
id: root
property var shell: null
property var manifest: null
property bool opened: false
// Shown as an ordinary window instead of the full-screen popup; see
// open(), payload "window".
property bool asWindow: false
property string currentChat: ""
property string query: ""
property int listIndex: 0
property double nowMs: Date.now()
property var widgetSettings: ({})
// Paging back through a conversation; see Model.historyHeader.
// "local" a page of the stored copy is on its way
// "phone" the daemon asked the phone for older messages
// "idle" free to load more when the reader nears the top
// "end" | "timeout" | "offline-end" nothing more for now
property string historyPhase: "idle"
property bool initialLoad: false
// The phone said this was its last batch; the page reading it ends paging.
property bool _phoneEnd: false
// "" | "new" | "logout" | "help" | "image" | "react" | "emoji"
property string dialog: ""
// Keyboard selection in the conversation; -1 when typing.
property int msgCursor: -1
// Names learned while starting a chat that is not in the list yet.
property var knownNames: ({})
// Audio played in the window: one at a time, by message id.
property string audioId: ""
property real audioRate: 1.0
// Audio waiting for its download to finish before it plays.
property var _playAfter: ({})
// The message the next one sent answers (Model.replyTarget), or null.
property var replyTo: null
// Files waiting to be sent with the next Enter: {path, name, size, photo}.
property var attachments: []
property bool attachAsFiles: false
// The file chooser is open. It is an ordinary window, which would open
// underneath the full-screen popup, so the popup steps aside meanwhile.
property bool picking: false
property var _statQueue: []
// A quoted message being looked for further back (see jumpToMessage), and
// the message briefly outlined once found.
property string _jumpTarget: ""
property int _jumpTries: 0
property string flashId: ""
// Reaction bar: the message it is for, this account's current reaction to
// it, and the keyboard cursor over the choices (the last one is "+").
property string reactFor: ""
property string reactMine: ""
property int reactCursor: 0
property var _reactAnchor: null
// Reactions shown before the daemon confirmed them, by request id, to put
// back if it fails.
property var _reactUndo: ({})
// Emoji picker: for the message box or for a reaction.
property string pickerFor: "composer"
property string pickerQuery: ""
property int pickerIndex: 0
readonly property int pickerColumns: 8
property var emojiAll: Model.fallbackEmojis()
property var recentEmoji: []
// The recent list as it was when the picker opened, so the grid does not
// shift under the pointer while emojis are being picked.
property var pickerRecent: []
readonly property var pickerItems: Model.pickerList(emojiAll, pickerRecent, pickerQuery, pickerColumns)
onPickerQueryChanged: pickerIndex = 0
readonly property color background: Color.menu.background
// The theme's menu background is often translucent; things floating over
// the conversation need it opaque.
readonly property color solidBackground: Qt.rgba(background.r, background.g, background.b, 1)
readonly property color foreground: Color.menu.text
readonly property color borderColor: Color.menu.border
readonly property color scrim: Color.menu.scrim
readonly property color accent: Color.accent
readonly property var borderSpec: Border.surfaceSpec("menu", "border", borderColor, Math.max(1, Style.space(2)))
readonly property color dim: Qt.darker(foreground, 1.5)
readonly property string fontFamily: Style.font.menuFamily
readonly property var filtered: Model.filterChats(wa.chats, query)
readonly property var current: Model.findChat(wa.chats, currentChat)
readonly property bool currentPinned: Model.isPinned(wa.pins, currentChat)
// Typing a number that matches no conversation offers to start one.
readonly property string newChatJid: Model.jidFromPhone(query) !== "" && !Model.findChat(wa.chats, Model.jidFromPhone(query))
? Model.jidFromPhone(query) : ""
readonly property bool pairingView: Model.needsPairing(wa.daemonState, wa.live)
readonly property string currentTitle: current ? Model.chatName(current)
: (knownNames[currentChat] || Model.chatName({ jid: currentChat }))
readonly property string currentSubtitle: {
if (!currentChat) return ""
if (current && current.group) return "Group"
return Model.formatPhone(currentChat.split("@")[0])
}
function open(payloadJson) {
var payload = {}
try { payload = JSON.parse(String(payloadJson || "{}")) || {} } catch (e) { payload = {} }
// "window": true or false picks the mode; without it an open client keeps
// its mode (a notification's "Open" goes to the window) and a closed one
// comes up as the popup.
var wantWindow = typeof payload.window === "boolean" ? payload.window : (opened && asWindow)
asWindow = wantWindow
opened = true
syncAppWindow()
nowMs = Date.now()
dialog = ""
wa.refresh()
var chat = String(payload.chat || "")
if (chat !== "") selectChat(chat)
else if (currentChat !== "") selectChat(currentChat)
else Qt.callLater(function() { search.forceActiveFocus() })
var action = String(payload.action || "")
if (action === "new" || action === "logout" || action === "help") Qt.callLater(function() { root.openDialog(action) })
}
function close() {
audioPlayer.pause()
opened = false
syncAppWindow()
dialog = ""
msgCursor = -1
wa.focusOn("")
}
function dismiss() {
if (shell && typeof shell.hide === "function" && manifest && manifest.id) shell.hide(manifest.id)
else close()
}
// Esc with nothing left to cancel: the popup closes, a window stays
// (Super+W closes it, like any other).
function escapeOut() {
if (!asWindow) dismiss()
}
// A new window does not always take the focus (and one already open may be
// on another workspace), so each time it is shown it is also raised.
function syncAppWindow() {
appWindow.visible = opened && asWindow
if (appWindow.visible) raiseTimer.restart()
}
// Popup ⇄ window, keeping the open chat and what was typed.
function switchMode() {
asWindow = !asWindow
syncAppWindow()
Qt.callLater(function() {
if (root.currentChat !== "") composer.forceActiveFocus()
else search.forceActiveFocus()
})
}
// Bring the window forward, switching to its workspace — the way
// omarchy-launch-or-focus does. The shell's own
// windows are not in Quickshell's toplevel list, so it asks Hyprland.
function raiseWindow() {
Quickshell.execDetached(["sh", "-c",
'a=$(hyprctl clients -j | jq -r --arg t "$1" \'first(.[] | select(.class == "org.quickshell" and .title == $t) | .address) // empty\')\n' +
'[ -n "$a" ] || exit 0\n' +
'hyprctl dispatch "hl.dsp.focus({ window = \\"address:$a\\" })" >/dev/null 2>&1 || hyprctl dispatch focuswindow "address:$a"',
"sh", appWindow.title])
}
function selectChat(jid) {
if (!jid) return
if (jid !== currentChat) { stopAudio(); replyTo = null; clearAttachments() }
_jumpTarget = ""
currentChat = jid
messages.clear()
_mediaAsked = ({})
msgCursor = -1
historyPhase = "local"
_phoneEnd = false
initialLoad = true
sendError.text = ""
wa.focusOn(jid)
wa.requestHistory(jid, 0, "")
Qt.callLater(function() { composer.forceActiveFocus() })
}
function closeChat() {
if (currentChat === "") return
stopAudio()
replyTo = null
clearAttachments()
_jumpTarget = ""
currentChat = ""
messages.clear()
msgCursor = -1
wa.focusOn("")
Qt.callLater(function() { search.forceActiveFocus() })
}
function activateListIndex() {
if (listIndex < filtered.length) selectChat(filtered[listIndex].jid)
else if (newChatJid !== "") { openDialog("new", query); return }
query = ""
search.text = ""
}
function moveList(dy) {
var n = filtered.length + (newChatJid !== "" ? 1 : 0)
if (n === 0) return
listIndex = Math.max(0, Math.min(n - 1, listIndex + dy))
chatList.positionViewAtIndex(Math.min(listIndex, filtered.length - 1), ListView.Contain)
}
// Alt+Up/Down: the previous or next chat in the list as it is shown.
function stepChat(delta) {
var list = filtered
if (list.length === 0) return
var i = -1
for (var k = 0; k < list.length; k++) if (list[k].jid === currentChat) { i = k; break }
var next = i === -1 ? (delta > 0 ? 0 : list.length - 1) : Math.max(0, Math.min(list.length - 1, i + delta))
if (list[next].jid !== currentChat) selectChat(list[next].jid)
listIndex = next
chatList.positionViewAtIndex(next, ListView.Contain)
}
function openPinned(n) {
var shown = []
for (var i = 0; i < wa.chats.length; i++) if (wa.chats[i].pinned) shown.push(wa.chats[i].jid)
if (n < shown.length) selectChat(shown[n])
}
function togglePinCurrent() {
if (currentChat !== "") wa.togglePin(currentChat)
}
// Ctrl+U: flag a chat to come back to. With the keyboard cursor in the chat
// list it is that chat, which is never opened — opening one sends the read
// receipt the mark is often there to avoid.
function markUnreadTarget() {
if (search.activeFocus && listIndex < filtered.length) {
var c = filtered[listIndex]
wa.markUnread(c.jid, !Model.isManualUnread(c))
return
}
markUnreadCurrent()
}
// The open chat is a read one, so marking it unread closes it.
function markUnreadCurrent() {
if (currentChat === "") return
var jid = currentChat
closeChat()
wa.markUnread(jid, true)
}
function moveCurrentPin(delta) {
if (currentPinned) wa.movePin(currentChat, delta)
}
function toRow(m) {
return {
mid: String(m.id || ""),
sender: String(m.sender || ""),
senderName: String(m.senderName || ""),
fromMe: m.fromMe === true,
ts: Number(m.ts) || 0,
body: String(m.text || ""),
kind: String(m.kind || "text"),
status: String(m.status || ""),
edited: m.edited === true,
// JSON strings: a ListModel turns nested objects into sub-models.
mediaJson: m.media ? JSON.stringify(m.media) : "",
linkJson: m.link ? JSON.stringify(m.link) : "",
quoteJson: m.quote ? JSON.stringify(m.quote) : "",
reactionsJson: m.reactions && m.reactions.length ? JSON.stringify(m.reactions) : "",
mediaState: "",
req: "",
error: ""
}
}
// ---- older messages
// Loads the page before the oldest message held, once the reader is within
// half a screen of the top (or the conversation does not fill the view).
function maybeLoadOlder() {
if (historyPhase !== "idle" || messages.count === 0 || currentChat === "" || dialog !== "") return
var nearTop = messageList.contentY - messageList.originY < messageList.height * 0.5
var fits = messageList.contentHeight <= messageList.height
if (!nearTop && !fits) return
// In a conversation barely taller than the view, "near the top" and "at the
// newest message" are the same place: dropping the follow there left a
// just-opened chat a little short of its last message (and pictures still
// loading make the content look shorter than it turns out to be). The page
// arrives above the reader either way, so only a reader who has scrolled
// away from the end stops following it.
loadOlder(false, fits || messageList.atYEnd)
}
function loadOlder(noAsk, keepFollow) {
if (messages.count === 0) return
var oldest = messages.get(0)
historyPhase = "local"
if (keepFollow !== true) messageList.follow = false
wa.requestHistory(currentChat, oldest.ts, oldest.mid, noAsk === true)
}
// Header click after the phone did not answer.
function retryOlder() {
if (historyPhase !== "timeout") return
historyPhase = "idle"
loadOlder(false)
}
// The message the reader is looking at, and where it sits on screen, so
// rows inserted above it do not move it.
function captureAnchor() {
var idx = messageList.indexAt(Style.space(20), messageList.contentY + Style.space(2))
if (idx < 0) idx = 0
var item = messageList.itemAtIndex(idx)
return { index: idx, offset: item ? item.y - messageList.contentY : 0 }
}
function restoreAnchor(anchor, inserted) {
messageList.positionViewAtIndex(anchor.index + inserted, ListView.Beginning)
var item = messageList.itemAtIndex(anchor.index + inserted)
if (item) messageList.contentY = item.y - anchor.offset
}
function historyPhaseAfter(info, count, before) {
if (!before) return info.offline && !info.more && count > 0 ? "offline-end" : "idle"
if (info.asked) return "phone"
if (info.end) return "end"
if (!info.more && _phoneEnd) return "end"
if (info.offline && !info.more) return "offline-end"
return "idle"
}
// ---- media and links
// Ids already asked for, so a delegate scrolled in and out of view does not
// ask again.
property var _mediaAsked: ({})
function autoFetch(id, media) {
if (!media || !Model.isAutoDownload(media) || !wa.live || root.autoDownload !== true) return
if (media.type === "gif" ? media.anim : media.file) return
if (_mediaAsked[id]) return
_mediaAsked[id] = true
var idx = indexOfId(id)
if (idx >= 0) messages.setProperty(idx, "mediaState", "loading")
wa.requestMedia(currentChat, id, false)
}
// Click on an attachment: open what is on disk, or fetch it first.
function openMedia(id, media) {
if (!media) return
if (Model.isAudio(media)) { toggleAudio(id, media); return }
if (Model.isViewable(media)) { openViewer(id); return }
if (media.file) { openFile(media.file); return }
var idx = indexOfId(id)
if (!wa.live) {
if (idx >= 0) messages.setProperty(idx, "mediaState", "Turn OmaWhats on to download")
return
}
if (idx >= 0) messages.setProperty(idx, "mediaState", "loading")
wa.requestMedia(currentChat, id, true)
}
// Ask for an attachment again after a download failed, or was never made:
// the note saying it was already asked for has to go, or the next scroll
// past it would take this for a repeat and drop it. When a file is already
// here and still nothing can be shown, the ask goes with force, so the
// daemon drops that copy instead of handing the same one back.
function retryMedia(id) {
if (!id) return
var idx = indexOfId(id)
if (idx < 0) return
if (!wa.live) {
messages.setProperty(idx, "mediaState", "Turn OmaWhats on to download")
return
}
var media = Model.parseJson(messages.get(idx).mediaJson)
delete _mediaAsked[id]
messages.setProperty(idx, "mediaState", "loading")
wa.requestMedia(currentChat, id, false, Model.hasCachedFile(media))
}
// Anything opened outside the shell would land underneath the full-screen
// popup, so the popup steps aside first (a window stays). Links go through
// Omarchy's browser launcher, which also focuses the browser window.
function openLink(url) {
url = String(url || "")
if (url === "") return
if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) url = "http://" + url
if (!asWindow) dismiss()
Quickshell.execDetached(["sh", "-c",
'if command -v omarchy-launch-browser >/dev/null 2>&1; then exec omarchy-launch-browser "$1"; else exec xdg-open "$1"; fi',
"sh", url])
}
function openFile(path) {
if (!asWindow) dismiss()
Qt.openUrlExternally(Model.fileUrl(path))
}
// ---- audio
MediaPlayer {
id: audioPlayer
audioOutput: AudioOutput { }
playbackRate: root.audioRate
onErrorOccurred: function(error, errorString) {
root.showToast("Could not play this audio" + (errorString ? ": " + errorString : ""))
}
onMediaStatusChanged: if (mediaStatus === MediaPlayer.EndOfMedia) root.audioEnded()
}
// Play, pause or resume a message's audio, downloading it first if needed.
function toggleAudio(id, media) {
if (!Model.isAudio(media)) return
if (audioId === id && audioPlayer.source.toString() !== "") {
if (audioPlayer.playbackState === MediaPlayer.PlayingState) audioPlayer.pause()
else audioPlayer.play()
return
}
var idx = indexOfId(id)
if (!media.file) {
if (!wa.live) {
if (idx >= 0) messages.setProperty(idx, "mediaState", "Turn OmaWhats on to download")
return
}
_playAfter[id] = true
if (idx >= 0) messages.setProperty(idx, "mediaState", "loading")
wa.requestMedia(currentChat, id, false)
return
}
audioPlayer.stop()
audioId = id
audioPlayer.source = Model.fileUrl(media.file)
audioPlayer.play()
}
function toggleCurrentAudio() {
if (audioId === "") { showToast("No audio playing"); return }
if (audioPlayer.playbackState === MediaPlayer.PlayingState) audioPlayer.pause()
else audioPlayer.play()
}
function stopAudio() {
audioPlayer.stop()
audioPlayer.source = ""
audioId = ""
_playAfter = ({})
}
function seekAudio(id, media, fraction) {
if (audioId !== id) { toggleAudio(id, media); return }
if (audioPlayer.duration > 0) audioPlayer.position = Math.max(0, Math.min(1, fraction)) * audioPlayer.duration
if (audioPlayer.playbackState !== MediaPlayer.PlayingState) audioPlayer.play()
}
function cycleAudioRate() {
audioRate = Model.nextRate(audioRate)
showToast("Audio speed " + Model.rateLabel(audioRate))
}
// Like WhatsApp: a voice message that ends plays the next one, if the next
// message is a voice message too.
function audioEnded() {
var id = audioId
audioPlayer.stop()
var i = indexOfId(id)
if (i < 0 || i + 1 >= messages.count) return
var cur = Model.parseJson(messages.get(i).mediaJson)
var next = messages.get(i + 1)
var nm = Model.parseJson(next.mediaJson)
if (cur && cur.voice && nm && nm.type === "audio" && nm.voice) toggleAudio(next.mid, nm)
}
// ---- image viewer (photos, stickers and GIFs, inside the client)
property string viewerId: ""
property string viewerMediaJson: ""
property var viewerIds: []
readonly property var viewerMedia: Model.parseJson(viewerMediaJson)
readonly property var viewerSrc: Model.viewerSource(viewerMedia)
readonly property int viewerPos: viewerIds.indexOf(viewerId)
function openViewer(id) {
var ids = []
for (var i = 0; i < messages.count; i++)
if (Model.isViewable(Model.parseJson(messages.get(i).mediaJson))) ids.push(messages.get(i).mid)
if (ids.indexOf(id) === -1) return
viewerIds = ids
msgCursor = -1
dialog = "image"
showInViewer(id)
Qt.callLater(function() { viewerKeys.forceActiveFocus() })
}
function showInViewer(id) {
var idx = indexOfId(id)
if (idx < 0) return
viewerId = id
viewerMediaJson = messages.get(idx).mediaJson
viewer.zoom = 1
// Only the thumbnail is here yet: fetch the real picture; the viewer
// swaps it in when onMediaResult arrives.
if (!Model.viewerSource(viewerMedia).full && wa.live && messages.get(idx).mediaState !== "loading") {
messages.setProperty(idx, "mediaState", "loading")
wa.requestMedia(currentChat, id, false)
}
}
function viewerStep(delta) {
var i = viewerPos + delta
if (i >= 0 && i < viewerIds.length) showInViewer(viewerIds[i])
}
function viewerRow() {
var idx = indexOfId(viewerId)
return idx >= 0 ? messages.get(idx) : null
}
readonly property bool autoDownload: widgetSettings.autoDownloadMedia !== false
readonly property string linkColor: String(root.accent)
// See Model.makeRowIndex: row numbers by id, forgotten whenever rows move.
readonly property var _rowIndex: Model.makeRowIndex()
function forgetRowIndex() { _rowIndex.forget() }
function indexOfId(id) {
return _rowIndex.find(id,
function() { return messages.count },
function(i) { return messages.get(i).mid })
}
function indexOfPending(field, value) {
for (var i = messages.count - 1; i >= 0; i--) {
var r = messages.get(i)
if (r.status === "pending" && r[field] === value) return i
}
return -1
}
function followEnd() {
if (messageList.follow) messageList.positionViewAtEnd()
}
function scrollToEnd() {
messageList.follow = true
Qt.callLater(function() { messageList.positionViewAtEnd() })
}
function sendComposer() {
if (attachments.length > 0 && currentChat) { sendAttachments(); return }
var text = composer.text
if (text.trim() === "" || !currentChat) return
if (!wa.canSend) {
sendError.text = "Turn OmaWhats on and wait for it to connect to send."
return
}
var quote = replyTo
var req = wa.send(currentChat, text, quote ? quote.id : "")
if (req === "") {
sendError.text = "Could not reach the daemon."
return
}
sendError.text = ""
// Shown straight away with a clock; the daemon's echo replaces it.
var row = toRow({ id: "pending-" + req, text: text, fromMe: true, ts: Math.floor(Date.now() / 1000), status: "pending", senderName: "You", quote: quote })
row.req = req
messages.append(row)
composer.text = ""
replyTo = null
scrollToEnd()
}
// ---- attachments
function pickFiles() {
if (currentChat === "" || picking || pickProc.running) return
msgCursor = -1
if (dialog !== "") dialog = ""
picking = true
pickProc.command = ["omarchy-file-select", "--title", "Send to " + currentTitle, "--multiple"]
pickProc.running = true
}
function pickDone(exitCode, text) {
if (!picking) return
picking = false
if (exitCode === 2) showToast("The file chooser did not open")
var paths = String(text || "").split("\n").filter(function(p) { return p !== "" })
if (paths.length > 0) addFiles(paths)
Qt.callLater(function() { if (root.currentChat !== "") composer.forceActiveFocus() })
}
// Paths from the chooser, a drop or the clipboard: checked (size, folders)
// and added to the tray above the message box.
function addFiles(paths) {
if (!paths || paths.length === 0) return
if (currentChat === "") { showToast("Open a chat first"); return }
_statQueue = _statQueue.concat(paths)
if (!statProc.running) runStat()
}
function runStat() {
if (_statQueue.length === 0) return
statProc.command = ["stat", "-L", "--printf", "%s\t%F\t%n\n", "--"].concat(_statQueue)
_statQueue = []
statProc.running = true
}
function statDone(text) {
var r = Model.parseStat(text)
var added = Model.addAttachments(attachments, r.files)
if (currentChat !== "") attachments = added.list
var problems = added.problems.slice()
if (r.skipped.length === 1) problems.push(Model.baseName(r.skipped[0]) + " is a folder, not a file")
else if (r.skipped.length > 1) problems.push(r.skipped.length + " folders left out")
if (problems.length > 0) showToast(problems.join(" · "))
if (_statQueue.length > 0) runStat()
else if (currentChat !== "" && dialog === "") composer.forceActiveFocus()
}
function removeAttachment(i) {
var list = attachments.slice()
list.splice(i, 1)
attachments = list
if (list.length === 0) attachAsFiles = false
composer.forceActiveFocus()
}
function clearAttachments() {
attachments = []
attachAsFiles = false
}
function toggleAttachAsFiles() {
if (!Model.attachmentsSummary(attachments, false).match(/photo/)) { showToast("No photos attached"); return }
attachAsFiles = !attachAsFiles
showToast(attachAsFiles ? "Photos go as files, uncompressed" : "Photos go as photos")
}
// One message per file, in order; what was typed is the first one's
// caption, and a reply being written answers with the first one.
function sendAttachments() {
if (!wa.canSend) {
sendError.text = "Turn OmaWhats on and wait for it to connect to send."
return
}
var caption = composer.text.trim()
var quote = replyTo
var now = Math.floor(Date.now() / 1000)
var list = attachments
for (var i = 0; i < list.length; i++) {
var f = list[i]
var cap = i === 0 ? caption : ""
var q = i === 0 ? quote : null
var req = wa.sendFile(currentChat, f.path, cap, q ? q.id : "", attachAsFiles && f.photo)
if (req === "") {
sendError.text = "Could not reach the daemon."
attachments = list.slice(i)
return
}
var row = toRow({ id: "pending-" + req, text: cap, fromMe: true, ts: now, status: "pending", senderName: "You",
quote: q, media: Model.pendingMedia(f, cap, attachAsFiles) })
row.req = req
row.mediaState = "sending"
messages.append(row)
}
sendError.text = ""
composer.text = ""
replyTo = null
clearAttachments()
scrollToEnd()
}
// Ctrl+V: a screenshot or copied picture, or files copied in the file
// manager, are attached; anything else is pasted as text.
function pasteClipboard() {
if (pasteTypes.running || pasteUris.running || pasteImage.running) return
pasteTypes.running = true
}
function pasteTypesDone(types) {
var kind = Model.pasteKind(types)
if (kind === "files" && currentChat !== "") {
pasteUris.running = true
} else if (kind === "image" && currentChat !== "") {
var type = Model.pasteImageType(types)
pasteImage.dest = wa.cacheDir + "/" + Model.pastedName(new Date(), type)
pasteImage.command = ["sh", "-c", 'umask 077 && mkdir -p "$1" && wl-paste --no-newline --type "$2" > "$3"', "sh", wa.cacheDir, type, pasteImage.dest]
pasteImage.running = true
} else {
composer.paste()
}
}
function pasteUrisDone(text) {
var paths = Model.pathsFromUris(text)
if (paths.length > 0) addFiles(paths)
else composer.paste()
}
// ---- replies
// Pending, failed and deleted messages cannot be answered or reacted to.
function canAct(r) {
return !!r && r.status !== "pending" && r.status !== "failed" && r.kind !== "revoked" && String(r.mid).indexOf("pending-") !== 0
}
function startReply(i) {
if (i < 0 || i >= messages.count) return
var r = messages.get(i)
if (!canAct(r)) { showToast("Can't reply to this message"); return }
var target = Model.replyTarget(r)
if (target.name === "") target.name = current && current.group ? "" : currentTitle
replyTo = target
msgCursor = -1
composer.forceActiveFocus()
}
function cancelReply() { replyTo = null }
// Scrolls to a quoted message, paging back through the stored copy (never
// the phone) for a few pages if it is not loaded yet.
function jumpToMessage(id) {
if (!id) return
var idx = indexOfId(id)
if (idx >= 0) { showMessage(idx); return }
_jumpTarget = id
_jumpTries = 6
continueJump()
}
function showMessage(idx) {
messageList.follow = false
messageList.positionViewAtIndex(idx, ListView.Center)
flashId = messages.get(idx).mid
flashTimer.restart()
}
function continueJump() {
if (_jumpTarget === "") return
var idx = indexOfId(_jumpTarget)
if (idx >= 0) { _jumpTarget = ""; showMessage(idx); return }
if (historyPhase === "local") return // a page is on its way
if (_jumpTries > 0 && historyPhase === "idle") { _jumpTries -= 1; loadOlder(true); return }
_jumpTarget = ""
showToast("The original message is not stored here")
}
Timer { id: flashTimer; interval: 1400; onTriggered: root.flashId = "" }
// ---- reactions
function openReactions(i) {
if (i < 0 || i >= messages.count) return
var r = messages.get(i)
if (!canAct(r)) { showToast("Can't react to this message"); return }
if (!wa.canSend) { showToast("Turn OmaWhats on to react"); return }
reactFor = r.mid
reactMine = Model.myReaction(Model.parseJson(r.reactionsJson) || [])
var mine = Model.QUICK_REACTIONS.indexOf(reactMine)
reactCursor = mine >= 0 ? mine : 0
var item = messageList.itemAtIndex(i)
_reactAnchor = item ? { rect: item.bubbleRect(popupLayer), fromMe: r.fromMe } : null
var p = placePopup(reactBar.implicitWidth, reactBar.implicitHeight, _reactAnchor)
popupLayer.barX = p.x
popupLayer.barY = p.y
dialog = "react"
Qt.callLater(function() { reactBar.forceActiveFocus() })
}
// Sets this account's reaction on a message, or takes it back when it is the
// one already there. Shown at once; put back if the daemon says no.
function react(id, emoji) {
var idx = indexOfId(id)
if (idx < 0 || !emoji) return
var r = messages.get(idx)
var list = Model.parseJson(r.reactionsJson) || []
var send = Model.reactionToggle(Model.myReaction(list), emoji)
var req = wa.react(currentChat, id, send)
if (req === "") { showToast("Turn OmaWhats on to react"); return }
_reactUndo[req] = { id: id, json: r.reactionsJson }
messages.setProperty(idx, "reactionsJson", JSON.stringify(Model.withMyReaction(list, send)))
}
function pickReaction(emoji) {
var id = reactFor
closeDialog()
react(id, emoji)
}
// Where a popup of size w×h goes: above the anchor (below it when there is
// no room), aligned with the side the message sits on, kept on the card.
function placePopup(w, h, anchor) {
var m = Style.space(8)
var x = (popupLayer.width - w) / 2
var y = (popupLayer.height - h) / 2
if (anchor && anchor.rect) {
var a = anchor.rect
x = anchor.fromMe ? a.x + a.width - w : a.x
y = a.y - h - Style.space(6)
if (y < m) y = a.y + a.height + Style.space(6)
}
return {
x: Math.max(m, Math.min(popupLayer.width - w - m, x)),
y: Math.max(m, Math.min(popupLayer.height - h - m, y))
}
}
// ---- emoji picker
// forWhat: "composer" inserts into the message box (the picker stays open
// for more); "react" reacts to reactFor with the one picked.
function openEmojiPicker(forWhat) {
if (currentChat === "") return
pickerFor = forWhat === "react" ? "react" : "composer"
pickerQuery = ""
pickerIndex = 0
pickerRecent = recentEmoji
var anchor = pickerFor === "react" ? _reactAnchor
: { rect: composer.mapToItem(popupLayer, 0, 0, composer.width, composer.height), fromMe: false }
var p = placePopup(pickerPanel.width, pickerPanel.height, anchor)
popupLayer.pickX = p.x
popupLayer.pickY = p.y
msgCursor = pickerFor === "react" ? msgCursor : -1
dialog = "emoji"
Qt.callLater(function() { pickerGrid.positionViewAtBeginning(); pickerKeys.forceActiveFocus() })
}
function pickEmoji(e) {
if (!e) return
recentEmoji = Model.pushRecent(recentEmoji, e, 24)
recentFile.setText(JSON.stringify(recentEmoji) + "\n")
if (pickerFor === "react") { pickReaction(e); return }
composer.insert(composer.cursorPosition, e)
}
// Arrow keys over the grid, stepping over the blank cells that pad the
// recent row.
function movePicker(delta) {
var items = pickerItems
if (items.length === 0) return
var i = Math.max(0, Math.min(items.length - 1, pickerIndex + delta))
var step = delta > 0 ? 1 : -1
while (i > 0 && i < items.length - 1 && items[i].e === "") i += step
if (items[i].e === "") return
pickerIndex = i
pickerGrid.positionViewAtIndex(i, GridView.Contain)
}
// ---- keyboard selection of messages
function enterMessageCursor() {
if (currentChat === "" || messages.count === 0) return
msgCursor = messages.count - 1
messageList.follow = false
messageList.forceActiveFocus()
messageList.positionViewAtIndex(msgCursor, ListView.Contain)
}
function leaveMessageCursor() {
msgCursor = -1
composer.forceActiveFocus()
}
function moveMessageCursor(delta) {
if (msgCursor < 0) return
msgCursor = Math.max(0, Math.min(messages.count - 1, msgCursor + delta))
messageList.positionViewAtIndex(msgCursor, ListView.Contain)
if (msgCursor < 3) maybeLoadOlder()
}
function activateMessage(i) {
if (i < 0 || i >= messages.count) return
var r = messages.get(i)
var media = Model.parseJson(r.mediaJson)
if (media) { openMedia(r.mid, media); return }
var url = Model.firstLink(r.body, Model.parseJson(r.linkJson))
if (url !== "") openLink(url)
else showToast("Nothing to open in this message")
}
function copyMessage(i) {
if (i < 0 || i >= messages.count) return
var r = messages.get(i)
var text = Model.bubbleText(r.body, Model.parseJson(r.mediaJson))
if (text === "") { showToast("No text to copy"); return }
Quickshell.execDetached(["wl-copy", "--", text])
showToast("Copied")
}
property string toastText: ""
function showToast(t) {
toastText = t
toastTimer.restart()
}
Timer { id: toastTimer; interval: 1600; onTriggered: root.toastText = "" }
// ---- dialogs
function openDialog(name, prefill) {
if (name === "logout" && !wa.daemonState.paired && !wa.live) { showToast("Not linked to an account"); return }
msgCursor = -1
dialog = name
if (name === "new") {
newChatField.text = prefill ? String(prefill) : ""
newChat.error = ""
newChat.req = ""
Qt.callLater(function() { newChatField.forceActiveFocus(); if (prefill) root.checkNewChat() })
} else if (name === "logout") {
logoutSheet.wipe = false
logoutSheet.choice = 0
logoutSheet.error = ""
Qt.callLater(function() { logoutSheet.forceActiveFocus() })
} else if (name === "help") {
Qt.callLater(function() { helpSheet.forceActiveFocus() })
}
}
function closeDialog() {
dialog = ""
Qt.callLater(function() {
if (root.msgCursor >= 0) messageList.forceActiveFocus()
else if (root.currentChat !== "") composer.forceActiveFocus()
else search.forceActiveFocus()
})
}
function checkNewChat() {
if (!wa.online) { newChat.error = "Turn OmaWhats on and wait for it to connect first."; return }
if (Model.jidFromPhone(newChatField.text) === "") {
newChat.error = "Type the full number, with country and area code (e.g. +55 11 98765-4321)."
return
}
newChat.error = ""
newChat.req = wa.checkNumber(newChatField.text)
if (newChat.req === "") newChat.error = "Could not reach the daemon."
}
// ---- keys
//
// One handler for every shortcut, called by whichever item has focus (both
// text fields, the message list, the card) before it handles the key itself.
function handleKey(event) {
if (dialog !== "") return false
var mods = event.modifiers
var ctrl = (mods & Qt.ControlModifier) !== 0
var alt = (mods & Qt.AltModifier) !== 0
var shift = (mods & Qt.ShiftModifier) !== 0
var k = event.key
if (k === Qt.Key_F1 || (ctrl && (k === Qt.Key_Slash || k === Qt.Key_Question))) { openDialog("help"); return true }
if (ctrl && !alt) {
if (k === Qt.Key_F && !shift) { search.forceActiveFocus(); search.selectAll(); return true }
if (k === Qt.Key_N && !shift) { openDialog("new"); return true }
if (k === Qt.Key_P && !shift) { togglePinCurrent(); return true }
if (k === Qt.Key_P && shift) { if (!wa.starting && !wa.stopping) wa.togglePower(); return true }
if (k === Qt.Key_L && shift) { openDialog("logout"); return true }
if (k === Qt.Key_R && !shift) {
if (pairingView && wa.daemonState.state !== "pairing") wa.pair()
else wa.refresh()
return true
}
if (k === Qt.Key_U && !shift) { markUnreadTarget(); return true }
if (k === Qt.Key_W && !shift) { closeChat(); return true }
if (k === Qt.Key_W && shift) { switchMode(); return true }
if (k === Qt.Key_E && !shift) { openEmojiPicker("composer"); return true }