-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPluginControl.qml
More file actions
1236 lines (1137 loc) · 43 KB
/
Copy pathPluginControl.qml
File metadata and controls
1236 lines (1137 loc) · 43 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 Quickshell
import Quickshell.Hyprland
import Quickshell.Io
import Quickshell.Wayland
import qs.Commons
import qs.Ui
import "Fuzzy.js" as Fuzzy
import "PaletteViewModel.js" as PaletteViewModel
import "lib/shortcuts" as Shortcuts
Item {
id: root
property string omarchyPath: Quickshell.env("OMARCHY_PATH")
property var shell: null
property var manifest: null
property var pluginRegistry: null
property var service: null
property bool opened: false
property bool surfaceVisible: false
property alias query: queryInput.text
property string mode: "browse"
property int selectedIndex: 0
property var filteredRecords: []
property var selectedRecord: null
property string pendingOperation: "browse"
property string pendingSnapshotId: ""
property string transientMessage: ""
property var targetScreen: null
property double filterStartedAt: 0
property bool installInTerminal: false
property bool settingsMenuOpen: false
property bool spaceActivatesSelection: false
property bool previewOpen: false
property string previewUrl: ""
property string previewName: ""
property int previewWidth: 0
property int previewHeight: 0
property var savedSettings: ({})
property color shortcutColor: Color.accent
property color successColor: Color.accent
property color marketplaceOrange: Color.accent
readonly property string pluginId: manifest && manifest.id
? String(manifest.id) : "io.github.ilyazar.plugin-control"
readonly property string configHome: Quickshell.env("XDG_CONFIG_HOME")
|| Quickshell.env("HOME") + "/.config"
readonly property string settingsPath: configHome
+ "/omarchy/ilyazar.plugin-control/settings.json"
readonly property string cacheHome: Quickshell.env("XDG_CACHE_HOME")
|| Quickshell.env("HOME") + "/.cache"
readonly property string previewCacheUrlPrefix: "file://" + cacheHome
+ "/omarchy/ilyazar.plugin-control/previews/"
readonly property string themeColorsPath: Color.currentThemePath
+ "/colors.toml"
readonly property color background: Color.menu.background
readonly property color foreground: Color.menu.text
readonly property color borderColor: Color.menu.border
readonly property color scrim: Color.menu.scrim
readonly property bool backgroundDim: service
&& service.backgroundDim === true
readonly property color selectedBackground: Color.menu.selectedBackground
readonly property color selectedText: Color.menu.selectedText
readonly property color accent: Color.accent
readonly property color urgent: Color.urgent
readonly property var borderSpec: Border.surfaceSpec(
"menu", "border", borderColor, Math.max(1, Style.space(2)))
readonly property int cardWidth: Math.min(Style.space(720),
Math.max(Style.space(320), panel.width - Style.gapsOut * 2))
readonly property int rowHeight: Style.space(60)
readonly property int headerHeight: Style.space(52)
readonly property int footerHeight: Style.space(42)
readonly property bool paletteChromeVisible: !settingsMenuOpen
readonly property int activeHeaderHeight: paletteChromeVisible
? headerHeight : 0
readonly property int activeFooterHeight: paletteChromeVisible
? footerHeight : 0
readonly property int statusHeight: paletteChromeVisible
&& (leftStatusText.length > 0 || rightStatusText.length > 0)
? Style.space(28) : 0
readonly property int visibleRows: Math.max(1,
Math.min(6, filteredRecords.length || 1))
readonly property int resultRowsHeight: visibleRows * rowHeight
+ Math.max(0, visibleRows - 1) * Style.space(2)
readonly property int chromeSpacingCount: paletteChromeVisible
? (statusHeight > 0 ? 3 : 2) : 0
readonly property int desiredCardHeight: Style.spacing.panelPadding * 2
+ activeHeaderHeight + resultRowsHeight
+ activeFooterHeight + statusHeight
+ Style.spacing.sm * chromeSpacingCount
readonly property int availableCardHeight: Math.max(Style.space(220),
panel.height - restingY - Style.gapsOut)
readonly property int actionCardHeight: actionDialog.readOnly
? Math.max(Style.space(360), actionDialog.preferredReadOnlyHeight)
: Style.space(540)
readonly property int cardHeight: actionDialog.opened
? Math.min(actionCardHeight, availableCardHeight)
: (selfRemovalDialog.opened
? Math.min(Style.space(280), availableCardHeight)
: Math.min(Style.space(600), Math.max(Style.space(220),
Math.min(desiredCardHeight, availableCardHeight))))
readonly property int topBarOffset: shell && shell.bar
&& shell.bar.position === "top" && shell.bar.barHidden !== true
? Number(shell.bar.barSize || 0) : 0
readonly property int restingY: topBarOffset + Style.gapsOut
readonly property var shortcutRecord: {
if (selectedIndex < 0 || selectedIndex >= filteredRecords.length)
return null
var record = filteredRecords[selectedIndex]
return record && record.id && !record.commandCompletion ? record : null
}
readonly property bool shortcutHasPluginPage: shortcutRecord
&& shortcutRecord.marketplaceListed === true
readonly property string marketplaceShortcutLabel: shortcutHasPluginPage
? "Plugin website" : "Marketplace"
readonly property bool actionDialogReadOnly: actionDialog.readOnly
readonly property bool modalDialogOpened: actionDialog.opened
|| selfRemovalDialog.opened || previewOpen
readonly property bool hasUpdateWarnings: service
&& service.updateWarnings && service.updateWarnings.length > 0
readonly property string updateWarningText: hasUpdateWarnings
? String(service.updateWarningText || "") : ""
readonly property bool hasRefreshWarnings: service
&& service.refreshWarnings && service.refreshWarnings.length > 0
readonly property string refreshWarningText: {
if (!hasRefreshWarnings) return ""
var lines = [service.refreshWarnings.length === 1
? "Catalog refresh warning" : "Catalog refresh warnings"]
for (var i = 0; i < service.refreshWarnings.length; i++) {
var warning = service.refreshWarnings[i]
var fallback = String(warning.fallback || "")
lines.push("")
lines.push(String(warning.channelName || warning.channelId
|| "Catalog source"))
if (fallback === "cache") {
lines.push("Could not refresh this source. Using its last valid cache.")
var retrievedAt = String(warning.cacheRetrievedAt || "")
if (retrievedAt)
lines.push("Last valid catalog: " + formatStatusTimestamp(retrievedAt))
} else if (fallback === "bundled") {
lines.push("Could not refresh this source. Using the bundled catalog.")
} else {
lines.push("Could not refresh this source. No cached records are available.")
}
}
return lines.join("\n")
}
readonly property string leftStatusText: {
if (transientMessage) return transientMessage
if (service && service.actionRunning)
return String(service.actionState.message || "Working...")
if (service && service.checkingUpdates) return "Checking for updates..."
if (service && service.actionState
&& service.actionState.acknowledged === false)
return String(service.actionState.message || "Action finished.")
if (service && service.lastUpdateCheckError)
return "Update check incomplete: " + service.lastUpdateCheckError
if (service && service.lastSuccessfulUpdateCheck) {
var timestamp = "Last update: "
+ formatStatusTimestamp(service.lastSuccessfulUpdateCheck)
if (service.updateCheckSuccessVisible
&& service.lastUpdateCheckNotice)
return timestamp + " " + service.lastUpdateCheckNotice
return timestamp
}
return "Updates not checked"
}
readonly property string rightStatusText: {
if (service && service.refreshing) return "Refreshing catalog..."
if (service && service.lastError) return service.lastError
if (service && service.lastSuccessfulRefresh)
return "Catalog refreshed: "
+ formatStatusTimestamp(service.lastSuccessfulRefresh)
return service && service.ready ? "Catalog cache ready" : "Loading local cache..."
}
readonly property bool leftStatusActive: service
&& (service.checkingUpdates
|| (service.actionRunning && ["Checking for updates...",
"Updating plugins..."].indexOf(leftStatusText) >= 0))
readonly property bool leftSuccessActive: service
&& ((service.updateCheckSuccessVisible === true
&& leftStatusText.indexOf("Last update: ") === 0)
|| (service.actionState && service.actionState.running !== true
&& service.actionState.acknowledged === false
&& service.actionState.ok === true))
readonly property bool leftUrgent: service
&& ((service.actionState && service.actionState.running !== true
&& service.actionState.acknowledged === false
&& service.actionState.ok === false)
|| service.lastUpdateCheckError)
readonly property color leftStatusColor: leftStatusActive
? shortcutColor : (leftSuccessActive ? successColor
: (leftUrgent ? urgent : foreground))
readonly property real leftStatusOpacity: leftStatusActive
|| leftSuccessActive || leftUrgent ? 1 : 0.70
readonly property bool refreshStatusActive:
rightStatusText === "Refreshing catalog..."
readonly property bool refreshSuccessActive: service
&& service.refreshSuccessVisible === true
&& rightStatusText.indexOf("Catalog refreshed: ") === 0
readonly property bool refreshStatusUrgent: service
&& service.refreshing !== true && String(service.lastError || "") !== ""
readonly property color rightStatusColor: refreshStatusActive
? shortcutColor : (refreshSuccessActive ? successColor
: (refreshStatusUrgent ? urgent : foreground))
readonly property real rightStatusOpacity: refreshStatusActive
|| refreshSuccessActive || refreshStatusUrgent ? 1 : 0.70
function resolveTargetScreen() {
var focused = Hyprland.focusedMonitor
var name = focused ? String(focused.name || "") : ""
var screens = Quickshell.screens || []
for (var i = 0; i < screens.length; i++) {
if (String(screens[i].name || "") === name) {
targetScreen = screens[i]
return
}
}
targetScreen = screens.length > 0 ? screens[0] : null
}
function open(payloadJson) {
var payload = ({})
try { payload = JSON.parse(String(payloadJson || "{}")) }
catch (error) { payload = ({}) }
resolveTargetScreen()
if (service) service.recordOpenRequest()
if (service) service.loadCached()
closeTimer.stop()
surfaceVisible = true
if (service) service.recordSurfaceVisible()
opened = true
transientMessage = ""
query = ""
selectedIndex = 0
selectedRecord = null
pendingSnapshotId = ""
settingsMenuOpen = false
previewOpen = false
previewUrl = ""
actionDialog.closeDialog()
if (payload.settings === true) showSettingsMenu()
else rebuildResults()
Qt.callLater(function() {
if (settingsMenuOpen) card.forceActiveFocus()
else queryInput.forceActiveFocus()
if (service) service.recordFocusReady()
})
}
function close() {
if (!surfaceVisible) return
opened = false
settingsMenuOpen = false
previewOpen = false
previewUrl = ""
actionDialog.closeDialog()
closeTimer.interval = service && service.animationsEnabled ? 80 : 0
closeTimer.restart()
}
function dismiss() {
close()
if (shell && typeof shell.hide === "function") shell.hide(pluginId)
}
function toggle() {
if (opened) dismiss()
else open("{}")
}
function debugMetrics() {
return JSON.stringify({
opened: opened,
surfaceVisible: surfaceVisible,
serviceReadyMs: service ? service.serviceReadyMs : -1,
openRequestMs: service ? service.lastOpenRequestMs : -1,
focusReadyMs: service ? service.lastFocusReadyMs : -1,
filterMs: service ? service.lastFilterMs : -1,
refreshMs: service ? service.lastRefreshDurationMs : -1,
recordCount: service ? service.catalogRecordCount : 0,
cacheAgeSeconds: service ? service.cacheAgeSeconds() : -1,
cacheRefreshedAt: service ? service.lastSuccessfulRefresh : "",
updateCheckedAt: service ? service.lastSuccessfulUpdateCheck : ""
})
}
function rebuildResults() {
filterStartedAt = Date.now()
var records = service && Array.isArray(service.records)
? service.records : []
var result = settingsMenuOpen ? PaletteViewModel.settingsResult()
: Fuzzy.search(records, query, 50)
mode = result.mode
filteredRecords = result.results
displayModel.clear()
spaceActivatesSelection = false
for (var i = 0; i < filteredRecords.length; i++) {
displayModel.append(PaletteViewModel.displayRecord(filteredRecords[i]))
}
selectedIndex = displayModel.count > 0
? Math.max(0, Math.min(selectedIndex, displayModel.count - 1)) : 0
if (service) service.recordFilterDuration(Date.now() - filterStartedAt)
Qt.callLater(positionSelection)
}
function positionSelection() {
if (displayModel.count > 0)
resultList.positionViewAtIndex(selectedIndex, ListView.Contain)
}
function select(index, byKeyboard) {
if (displayModel.count === 0) return
selectedIndex = Math.max(0, Math.min(index, displayModel.count - 1))
spaceActivatesSelection = byKeyboard === true
positionSelection()
}
function completeCommand(index) {
if (index < 0 || index >= filteredRecords.length) return false
var candidate = filteredRecords[index]
if (!candidate) return false
var completion = String(candidate.commandCompletion || "")
if (!completion) return false
queryInput.text = completion
queryInput.cursorPosition = queryInput.text.length
queryInput.forceActiveFocus()
if (String(candidate.operation || "") === "update"
&& service) service.requestUpdateCheck()
return true
}
function openDialogFor(record, readOnly) {
if (!record || !record.id || record.commandCompletion) return false
selectedRecord = JSON.parse(JSON.stringify(record))
pendingOperation = "browse"
pendingSnapshotId = readOnly === true ? ""
: (service && service.snapshot
? String(service.snapshot.snapshotId || "") : "")
actionDialog.readOnly = readOnly === true
if (readOnly === true && service) service.requestPreview(selectedRecord)
actionDialog.openDialog()
return true
}
function activateIndex(index) {
if (index < 0 || index >= filteredRecords.length) return
if (filteredRecords[index].settingsAction) {
activateSettings(filteredRecords[index].settingsAction)
return
}
if (completeCommand(index)) return
var record = filteredRecords[index]
openDialogFor(record, false)
}
function openSelectedInfo() {
return openDialogFor(shortcutRecord, true)
}
function validPreviewUrl(value) {
var url = String(value || "")
if (url.indexOf(previewCacheUrlPrefix) !== 0) return false
return /^[A-Za-z0-9._-]+-detail-[a-f0-9]{16}\.png$/.test(
url.slice(previewCacheUrlPrefix.length))
}
function openPreview(url, name, width, height) {
if (!actionDialog.readOnly || !validPreviewUrl(url)) return false
previewUrl = String(url)
previewName = String(name || "Plugin")
previewWidth = Math.max(0, Math.min(10000, Number(width || 0)))
previewHeight = Math.max(0, Math.min(10000, Number(height || 0)))
previewOpen = true
return true
}
function closePreview() {
if (!previewOpen) return
previewOpen = false
previewUrl = ""
}
function handlePreviewKey(event) {
if (!previewOpen) return false
if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter
|| event.key === Qt.Key_Space) closePreview()
return true
}
function confirmAction(operation) {
if (actionDialog.readOnly || !selectedRecord || !service) return
pendingOperation = String(operation || "")
if (["add", "remove", "update", "enable", "disable"]
.indexOf(pendingOperation) < 0) return
if (pendingOperation === "remove"
&& String(selectedRecord.id || "") === pluginId) {
actionDialog.closeDialog()
openSelfRemovalDialog()
return
}
if (!pendingSnapshotId) {
transientMessage = "No actionable catalog snapshot is available."
actionDialog.closeDialog()
return
}
var executionMode = actionDialog.terminalInstall
? "terminal" : "background"
if (service.startAction(pendingOperation,
String(selectedRecord.id || ""), pendingSnapshotId, executionMode)) {
transientMessage = executionMode === "terminal"
? "Opening Omarchy terminal..." : ""
actionDialog.closeDialog()
if (executionMode === "terminal") dismiss()
else Qt.callLater(queryInput.forceActiveFocus)
}
}
function deletePreviousWord(value) {
var text = String(value || "")
var trimmed = text.replace(/\s+$/, "")
return trimmed.replace(/\S+$/, "")
}
function loadSettings(raw) {
try {
var value = JSON.parse(String(raw || "{}"))
savedSettings = value && typeof value === "object"
&& !Array.isArray(value) ? value : ({})
} catch (error) {
savedSettings = ({})
}
installInTerminal = savedSettings.installInTerminal === true
}
function setInstallInTerminal(enabled) {
var next = ({ installInTerminal: enabled === true })
savedSettings = next
installInTerminal = next.installInTerminal
settingsFile.setText(JSON.stringify(next, null, 2) + "\n")
}
function padTimePart(value) {
return Number(value) < 10 ? "0" + Number(value) : String(Number(value))
}
function formatStatusTimestamp(value) {
var instant = new Date(String(value || ""))
if (!isFinite(instant.getTime())) return String(value || "")
var time = padTimePart(instant.getHours()) + ":"
+ padTimePart(instant.getMinutes()) + ":"
+ padTimePart(instant.getSeconds())
var date = instant.getFullYear() + "-"
+ padTimePart(instant.getMonth() + 1) + "-"
+ padTimePart(instant.getDate())
return time + " (" + date + ")"
}
function loadStatusColors(raw) {
var yellowMatch = String(raw || "").match(
/^\s*(?:yellow|color3)\s*=\s*["']?(#[0-9A-Fa-f]{6})/im)
var greenMatch = String(raw || "").match(
/^\s*(?:green|color2)\s*=\s*["']?(#[0-9A-Fa-f]{6})/im)
var orangeMatch = String(raw || "").match(
/^\s*orange\s*=\s*["']?(#[0-9A-Fa-f]{6})/im)
shortcutColor = yellowMatch ? yellowMatch[1] : accent
successColor = greenMatch ? greenMatch[1] : accent
marketplaceOrange = orangeMatch ? orangeMatch[1] : accent
}
function openWebsite(url) {
dismiss()
Quickshell.execDetached([omarchyPath + "/bin/omarchy", "launch",
"browser", url])
}
function validGithubRepository(value) {
return /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}\/?$/
.test(String(value || ""))
}
function marketplaceShortcutUrl() {
if (!shortcutHasPluginPage) return "https://omarchyplugins.com/"
return "https://omarchyplugins.com/plugin.html?id="
+ encodeURIComponent(String(shortcutRecord.id))
}
function githubShortcutUrl() {
if (shortcutRecord && validGithubRepository(shortcutRecord.repository))
return String(shortcutRecord.repository).replace(/\/$/, "")
return "https://github.com/HANCORE-linux/omarchy-plugin-marketplace"
}
function openMarketplaceShortcut() {
openWebsite(marketplaceShortcutUrl())
}
function openGithubShortcut() {
openWebsite(githubShortcutUrl())
}
function openSettings() {
showSettingsMenu()
}
function showSettingsMenu() {
settingsMenuOpen = true
queryInput.text = ""
selectedIndex = 0
rebuildResults()
Qt.callLater(card.forceActiveFocus)
}
function closeSettingsMenu() {
settingsMenuOpen = false
queryInput.text = ""
selectedIndex = 0
rebuildResults()
Qt.callLater(queryInput.forceActiveFocus)
}
function returnToMainMenu() {
if (!modalDialogOpened && !settingsMenuOpen) return false
var resetSelection = settingsMenuOpen
previewOpen = false
previewUrl = ""
selfRemovalDialog.closeDialog()
actionDialog.closeDialog()
settingsMenuOpen = false
if (resetSelection) {
selectedIndex = 0
rebuildResults()
}
Qt.callLater(queryInput.forceActiveFocus)
return true
}
function activateSettings(action) {
if (action === "cancel") {
closeSettingsMenu()
return
}
if (action === "remove-self") {
openSelfRemovalDialog()
return
}
if (["plugin", "keybindings"].indexOf(String(action)) < 0) return
dismiss()
Quickshell.execDetached([sourcePath("scripts/open-settings.sh"),
String(action), sourceDir()])
}
function openSelfRemovalDialog() {
if (!service || !Array.isArray(service.records) || !service.snapshot
|| !service.snapshot.snapshotId) {
transientMessage = "No current plugin snapshot is available."
return false
}
var record = PaletteViewModel.removableRecord(service.records, pluginId)
if (record) {
selectedRecord = JSON.parse(JSON.stringify(record))
pendingSnapshotId = String(service.snapshot.snapshotId)
selfRemovalDialog.openDialog()
return true
}
transientMessage = "Plugin Control is not available for removal."
return false
}
function confirmSelfRemoval(deleteUserData) {
if (!service || !selectedRecord || !pendingSnapshotId) return
var operation = deleteUserData === true ? "remove-purge" : "remove"
if (service.startAction(operation, pluginId, pendingSnapshotId,
"background")) {
transientMessage = deleteUserData === true
? "Cleaning user data and removing Plugin Control..."
: "Removing Plugin Control and preserving user data..."
selfRemovalDialog.closeDialog()
if (!settingsMenuOpen) Qt.callLater(queryInput.forceActiveFocus)
}
}
function dismissStatus() {
transientMessage = ""
if (service) service.acknowledgeAction()
}
function sourceDir() {
return manifest && manifest.__sourceDir
? String(manifest.__sourceDir) : ""
}
function sourcePath(relative) {
return sourceDir() + "/" + relative
}
function isControlShortcut(event, key) {
return event.modifiers === Qt.ControlModifier && event.key === key
}
function isCompletedCommandPrefix(value, cursor, selectionStart,
selectionEnd) {
var text = String(value || "")
return cursor === text.length && selectionStart === selectionEnd
&& ["plug-add:", "plug-remove:", "plug-enable:", "plug-disable:",
"plug-update:"].indexOf(text) >= 0
}
function clearCompletedCommandPrefix() {
if (!isCompletedCommandPrefix(queryInput.text, queryInput.cursorPosition,
queryInput.selectionStart, queryInput.selectionEnd)) return false
queryInput.text = ""
queryInput.cursorPosition = 0
return true
}
function startTypedUpdateCommand() {
var current = String(queryInput.text || "")
if (/\s$/.test(current) || current.trim().toLowerCase()
!== "plug-update:") return false
queryInput.text = "plug-update: "
queryInput.cursorPosition = queryInput.text.length
if (service) service.requestUpdateCheck()
return true
}
function handleKey(event) {
var returnKey = event.key === Qt.Key_Escape
|| (event.modifiers === Qt.NoModifier && event.key === Qt.Key_Q)
if (returnKey) {
if (returnToMainMenu()) return true
if (event.key === Qt.Key_Escape) {
dismiss()
return true
}
return false
}
if (previewOpen) return handlePreviewKey(event)
if (selfRemovalDialog.opened) return selfRemovalDialog.handleKey(event)
if (actionDialog.opened) return actionDialog.handleKey(event)
var control = (event.modifiers & Qt.ControlModifier) !== 0
var alt = (event.modifiers & Qt.AltModifier) !== 0
if (settingsMenuOpen) {
if (event.key === Qt.Key_Up
|| (event.modifiers === Qt.NoModifier && event.key === Qt.Key_K))
select(selectedIndex - 1, true)
else if (event.key === Qt.Key_Down
|| (event.modifiers === Qt.NoModifier && event.key === Qt.Key_J))
select(selectedIndex + 1, true)
else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter)
activateIndex(selectedIndex)
return true
}
if (isControlShortcut(event, Qt.Key_P)) {
dismiss()
} else if (isControlShortcut(event, Qt.Key_I)) {
openSelectedInfo()
} else if (isControlShortcut(event, Qt.Key_W)) {
openMarketplaceShortcut()
} else if (isControlShortcut(event, Qt.Key_G)) {
openGithubShortcut()
} else if (isControlShortcut(event, Qt.Key_S)) {
openSettings()
} else if (isControlShortcut(event, Qt.Key_R)) {
transientMessage = ""
if (service) service.requestRefresh(true)
} else if (isControlShortcut(event, Qt.Key_U)) {
transientMessage = ""
queryInput.text = "plug-update: "
queryInput.cursorPosition = queryInput.text.length
if (service) service.requestUpdateCheck()
} else if (isControlShortcut(event, Qt.Key_Backspace)) {
queryInput.text = deletePreviousWord(queryInput.text)
} else if (event.modifiers === Qt.NoModifier
&& event.key === Qt.Key_Backspace) {
return clearCompletedCommandPrefix()
} else if (event.key === Qt.Key_Up) {
select(selectedIndex - 1, true)
} else if (event.key === Qt.Key_Down) {
select(selectedIndex + 1, true)
} else if (event.key === Qt.Key_PageUp) {
select(selectedIndex - 5, true)
} else if (event.key === Qt.Key_PageDown) {
select(selectedIndex + 5, true)
} else if (event.key === Qt.Key_Home) {
select(0, true)
} else if (event.key === Qt.Key_End) {
select(displayModel.count - 1, true)
} else if (!control && !alt && event.key === Qt.Key_Tab) {
if (!startTypedUpdateCommand()) completeCommand(selectedIndex)
} else if (event.key === Qt.Key_Space) {
if (!startTypedUpdateCommand()) {
if (!spaceActivatesSelection) return false
activateIndex(selectedIndex)
}
} else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
if (!startTypedUpdateCommand()) activateIndex(selectedIndex)
} else {
return false
}
return true
}
ListModel { id: displayModel }
FileView {
id: settingsFile
path: root.settingsPath
watchChanges: true
atomicWrites: true
printErrors: false
onLoaded: root.loadSettings(text())
onLoadFailed: root.loadSettings("")
onFileChanged: reload()
}
FileView {
id: themeColorsFile
path: root.themeColorsPath
watchChanges: false
printErrors: false
onLoaded: root.loadStatusColors(text())
}
Connections {
target: Color
function onShellValuesChanged() { themeColorsFile.reload() }
}
Shortcuts.HyprlandBinding {
id: paletteBinding
actionDescription: "Plugin Control"
}
Connections {
target: root.service
function onRecordsChanged() { root.rebuildResults() }
function onActionFinished(state) {
root.transientMessage = ""
root.rebuildResults()
}
}
Timer {
id: closeTimer
repeat: false
onTriggered: root.surfaceVisible = false
}
PanelWindow {
id: panel
visible: root.surfaceVisible
screen: root.targetScreen
anchors { top: true; bottom: true; left: true; right: true }
color: "transparent"
exclusionMode: ExclusionMode.Ignore
WlrLayershell.namespace: "ilyazar.plugin-control"
WlrLayershell.layer: WlrLayer.Overlay
WlrLayershell.keyboardFocus: root.surfaceVisible
? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None
Rectangle {
anchors.fill: parent
visible: root.backgroundDim
color: root.scrim
opacity: card.reveal
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.ArrowCursor
onClicked: root.dismiss()
}
BorderSurface {
id: card
property real reveal: root.opened ? 1 : 0
width: root.cardWidth
height: root.cardHeight
x: Math.round((panel.width - width) / 2)
y: root.restingY - Math.round((1 - reveal) * Style.space(18))
opacity: reveal
radius: Style.cornerRadius
color: root.background
borderSpec: root.borderSpec
padding: Style.spacing.panelPadding
focus: true
Keys.priority: Keys.BeforeItem
Keys.onPressed: function(event) {
if (root.handleKey(event)) event.accepted = true
}
Behavior on reveal {
enabled: root.service ? root.service.animationsEnabled : true
NumberAnimation {
duration: root.opened ? 110 : 75
easing.type: Easing.OutCubic
}
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.ArrowCursor
onClicked: {}
}
ActionDialog {
id: actionDialog
anchors.fill: parent
z: 20
plugin: root.selectedRecord
selfId: root.pluginId
busy: root.service ? root.service.actionRunning : false
installInTerminal: root.installInTerminal
background: root.background
foreground: root.foreground
selectedBackground: root.selectedBackground
selectedText: root.selectedText
warningColor: root.urgent
marketplaceOrange: root.marketplaceOrange
marketplaceGreen: root.successColor
marketplaceYellow: root.shortcutColor
marketplaceRed: root.urgent
previewLoading: root.service ? root.service.previewLoading : false
previewFailed: root.service && root.service.previewState
&& root.selectedRecord
&& root.service.previewState.id === root.selectedRecord.id
&& root.service.previewState.failed === true
previewCardSource: root.service && root.service.previewState
&& root.selectedRecord
&& root.service.previewState.id === root.selectedRecord.id
? String(root.service.previewState.cardUrl || "") : ""
previewDetailSource: root.service && root.service.previewState
&& root.selectedRecord
&& root.service.previewState.id === root.selectedRecord.id
? String(root.service.previewState.detailUrl || "") : ""
onCanceled: {
closeDialog()
Qt.callLater(queryInput.forceActiveFocus)
}
onTerminalInstallToggled: function(enabled) {
root.setInstallInTerminal(enabled)
}
onPreviewRequested: function(url, name, width, height) {
root.openPreview(url, name, width, height)
}
onActionRequested: function(operation) {
root.confirmAction(operation)
}
}
SelfRemovalDialog {
id: selfRemovalDialog
anchors.fill: parent
z: 30
busy: root.service ? root.service.actionRunning : false
background: root.background
foreground: root.foreground
selectedBackground: root.selectedBackground
selectedText: root.selectedText
warningColor: root.urgent
onCanceled: {
closeDialog()
if (!root.settingsMenuOpen)
Qt.callLater(queryInput.forceActiveFocus)
}
onRemoveRequested: function(deleteUserData) {
root.confirmSelfRemoval(deleteUserData)
}
}
Column {
anchors.fill: parent
anchors.topMargin: card.contentTopInset
anchors.rightMargin: card.contentRightInset
anchors.bottomMargin: card.contentBottomInset
anchors.leftMargin: card.contentLeftInset
spacing: Style.spacing.sm
Rectangle {
visible: root.paletteChromeVisible
width: parent.width
height: root.activeHeaderHeight
radius: Style.cornerRadius
color: Util.alpha(root.foreground, 0.06)
Text {
id: searchIcon
anchors.left: parent.left
anchors.leftMargin: Style.spacing.md
anchors.verticalCenter: parent.verticalCenter
text: ""
color: root.foreground
opacity: 0.70
font.family: Style.font.family
font.pixelSize: Style.font.iconLarge
}
TextInput {
id: queryInput
anchors.left: searchIcon.right
anchors.leftMargin: Style.spacing.sm
anchors.right: shortcutLabel.left
anchors.rightMargin: Style.spacing.sm
anchors.verticalCenter: parent.verticalCenter
color: root.foreground
selectionColor: root.selectedBackground
selectedTextColor: root.selectedText
font.family: Style.font.menuFamily
font.pixelSize: Style.font.heading
clip: true
readOnly: root.settingsMenuOpen
selectByMouse: true
activeFocusOnTab: true
onTextChanged: {
root.selectedIndex = 0
root.transientMessage = ""
root.rebuildResults()
}
Keys.priority: Keys.BeforeItem
Keys.onPressed: function(event) {
if (root.handleKey(event)) event.accepted = true
}
TapHandler {
acceptedButtons: Qt.LeftButton
onTapped: root.spaceActivatesSelection = false
}
Text {
visible: !queryInput.text
anchors.fill: parent
text: "Search plugins (or type \"plug-...\" for direct plugin commands)."
textFormat: Text.PlainText
color: root.foreground
opacity: 0.48
font: queryInput.font
fontSizeMode: Text.HorizontalFit
minimumPixelSize: Math.max(Style.font.body,
queryInput.font.pixelSize - 1)
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
}
}
Text {
id: shortcutLabel
anchors.right: parent.right
anchors.rightMargin: Style.spacing.md
anchors.verticalCenter: parent.verticalCenter
text: paletteBinding.label
color: root.foreground
opacity: 0.55
font.family: Style.font.menuFamily
font.pixelSize: Style.font.body
}
}
Item {
width: parent.width
height: Math.max(root.rowHeight,
parent.height - root.activeHeaderHeight - root.activeFooterHeight
- root.statusHeight
- parent.spacing * root.chromeSpacingCount)
clip: true
ListView {
id: resultList
anchors.fill: parent
visible: displayModel.count > 0
model: displayModel
clip: true
boundsBehavior: Flickable.StopAtBounds
spacing: Style.space(2)
delegate: PaletteResultRow {
width: ListView.view.width
selected: index === root.selectedIndex
settingsMenuOpen: root.settingsMenuOpen
pointerInteractive: !root.modalDialogOpened
rowHeight: root.rowHeight
foreground: root.foreground
selectedBackground: root.selectedBackground
selectedText: root.selectedText
urgent: root.urgent
onHovered: root.select(index)
onActivated: {
root.select(index)
root.activateIndex(index)
}
onRepositoryRequested: function(url) { root.openWebsite(url) }
}
}