-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
tools.go
1163 lines (1018 loc) · 27.3 KB
/
tools.go
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
package main
import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
"github.com/joshuarubin/go-sway"
)
var descendants []sway.Node
type task struct {
conID int64
ID string // will be created out of app_id or window class
Name string
PID uint32
WsNum int64
}
func taskInstances(ID string, tasks []task) []task {
var found []task
for _, t := range tasks {
if strings.Contains(strings.ToUpper(t.ID), strings.ToUpper(ID)) {
found = append(found, t)
}
}
return found
}
type TaskChange struct {
Change sway.WindowEventChange
Task *task
}
type swayEventHandler struct {
taskUpdateChannel chan TaskChange
workspaceUpdateChannel chan int64
}
func (t swayEventHandler) Workspace(ctx context.Context, event sway.WorkspaceEvent) {
if event.Change == "focus" {
// TODO: sway.WorkspaceEvent.Current should contain a Workspace, but contains Node,
// this may be an error of the used library ...
t.workspaceUpdateChannel <- 0
}
}
func (t swayEventHandler) Mode(ctx context.Context, event sway.ModeEvent) {}
func (t swayEventHandler) BarConfigUpdate(ctx context.Context, event sway.BarConfigUpdateEvent) {}
func (t swayEventHandler) Binding(ctx context.Context, event sway.BindingEvent) {}
func (t swayEventHandler) Shutdown(ctx context.Context, event sway.ShutdownEvent) {}
func (t swayEventHandler) Tick(ctx context.Context, event sway.TickEvent) {}
func (t swayEventHandler) BarStateUpdate(ctx context.Context, event sway.BarStateUpdateEvent) {}
func (t swayEventHandler) BarStatusUpdate(ctx context.Context, event sway.BarStateUpdateEvent) {}
func (t swayEventHandler) Input(ctx context.Context, event sway.InputEvent) {}
func (t swayEventHandler) Window(ctx context.Context, window sway.WindowEvent) {
if window.Change == "new" || window.Change == "close" {
t.taskUpdateChannel <- TaskChange{
Change: window.Change,
// TODO: gather enough details form sway.WindowEvent to create the task
// structure and pass it on for smarter modifying the task array
Task: nil,
}
}
}
// TODO: The channel should *not* return a []task, but rather a TaskChange event which should
// be used to modify the list in the frontend ...
func getTaskChangesChannel(ctx context.Context) (chan []task, error) {
taskArrayChannel := make(chan []task, 1)
eventHandler := swayEventHandler{
taskUpdateChannel: make(chan TaskChange, 1),
}
go func() {
// Blocks execution until we cancel the context
if err := sway.Subscribe(ctx, eventHandler, sway.EventTypeWindow); err != nil {
log.Fatal("Unable to subscribe to sway event:", err)
}
}()
// Pretty hacky, but is simply used to convert a TaskChange to a task struct
go func() {
for {
<-eventHandler.taskUpdateChannel
tasks, err := listTasks()
if err != nil {
log.Errorf("Unable to process tasks from sway: %s", err.Error())
return
}
taskArrayChannel <- tasks
}
}()
return taskArrayChannel, nil
}
func getWorkspaceChangesChannel(ctx context.Context) chan int64 {
workspaceUpdateChannel := make(chan int64, 1)
eventHandler := swayEventHandler{
workspaceUpdateChannel: make(chan int64, 1),
}
go func() {
// Blocks execution until we cancel the context
if err := sway.Subscribe(ctx, eventHandler, sway.EventTypeWorkspace); err != nil {
log.Fatal("Unable to subscribe to sway event:", err)
}
}()
go func() {
ipc, _ := sway.New(ctx)
for {
<-eventHandler.workspaceUpdateChannel
workspaces, _ := ipc.GetWorkspaces(ctx)
for _, workspace := range workspaces {
if workspace.Focused {
workspaceUpdateChannel <- workspace.Num
break
}
}
}
}()
return workspaceUpdateChannel
}
// list sway tree, return tasks sorted by workspace numbers
func listTasks() ([]task, error) {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client, err := sway.New(ctx)
if err != nil {
return nil, err
}
tree, err := client.GetTree(ctx)
if err != nil {
return nil, err
}
workspaces, _ := client.GetWorkspaces(ctx)
if err != nil {
return nil, err
}
// In order not to add a separate function, let's set the global currentWsNum variable we need here
for _, ws := range workspaces {
if ws.Focused {
currentWsNum = ws.Num
break
}
}
// all nodes in the tree
nodes := tree.Nodes
// find outputs in all nodes
var outputs []*sway.Node
for _, n := range nodes {
if n.Type == "output" && !strings.HasPrefix(n.Name, "__") {
outputs = append(outputs, n)
}
}
// find workspaces in outputs
var workspaceNodes []*sway.Node
for _, o := range outputs {
nodes = o.Nodes
for _, n := range nodes {
if n.Type == "workspace" {
workspaceNodes = append(workspaceNodes, n)
}
}
}
var tasks []task
// find cons in workspaces recursively
for _, w := range workspaceNodes {
wsNum := workspaceNum(workspaces, w.Name)
descendants = nil
for _, con := range w.Nodes {
findDescendants(*con)
}
// create tasks from cons which represent tasks
for _, con := range descendants {
t, err := createTask(con, wsNum)
if err == nil {
tasks = append(tasks, *t)
} else {
log.Warn(err)
}
}
fNodes := w.FloatingNodes
for _, con := range fNodes {
t, err := createTask(*con, wsNum)
if err == nil {
tasks = append(tasks, *t)
} else {
log.Warn(err)
}
}
}
sort.Slice(tasks, func(i int, j int) bool {
return tasks[i].WsNum < tasks[j].WsNum
})
return tasks, nil
}
func findDescendants(con sway.Node) {
if len(con.Nodes) > 0 {
for _, node := range con.Nodes {
findDescendants(*node)
}
} else {
descendants = append(descendants, con)
}
}
func createTask(con sway.Node, wsNum int64) (*task, error) {
t := &task{}
t.conID = con.ID
if con.AppID != nil {
t.ID = *con.AppID
} else if con.WindowProperties != nil {
wp := *con.WindowProperties
t.ID = wp.Class
} else {
return nil, errors.New("damaged Node data received, task skipped")
}
t.Name = con.Name
if con.PID != nil {
t.PID = *con.PID
} else {
return nil, errors.New("damaged Node data received, task skipped")
}
t.WsNum = wsNum
return t, nil
}
func workspaceNum(workspaces []sway.Workspace, name string) int64 {
for _, ws := range workspaces {
if ws.Name == name {
return ws.Num
}
}
return 0
}
func pinnedButton(ID string) *gtk.Box {
box, _ := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
button, _ := gtk.ButtonNew()
box.PackStart(button, false, false, 0)
image, err := createImage(ID, imgSizeScaled)
if err != nil {
pixbuf, err := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/icon-missing.svg"),
imgSizeScaled, imgSizeScaled)
if err == nil {
image, _ = gtk.ImageNewFromPixbuf(pixbuf)
} else {
image, _ = gtk.ImageNew()
}
}
if image != nil {
button.SetImage(image)
button.SetImagePosition(gtk.POS_TOP)
button.SetAlwaysShowImage(true)
}
button.SetTooltipText(getName(ID))
pixbuf, _ := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/task-empty.svg"),
imgSizeScaled, imgSizeScaled/8)
img, _ := gtk.ImageNewFromPixbuf(pixbuf)
box.PackStart(img, false, false, 0)
button.Connect("clicked", func() {
launch(ID)
})
button.Connect("button-release-event", func(btn *gtk.Button, e *gdk.Event) bool {
btnEvent := gdk.EventButtonNewFromEvent(e)
if btnEvent.Button() == 1 {
launch(ID)
return true
} else if btnEvent.Button() == 3 {
contextMenu := pinnedMenuContext(ID)
contextMenu.PopupAtWidget(button, widgetAnchor, menuAnchor, nil)
return true
}
return false
})
button.Connect("enter-notify-event", cancelClose)
return box
}
func pinnedMenuContext(taskID string) gtk.Menu {
menu, _ := gtk.MenuNew()
menuItem, _ := gtk.MenuItemNewWithLabel("Unpin")
menuItem.Connect("activate", func() {
unpinTask(taskID)
})
menu.Append(menuItem)
menu.ShowAll()
return *menu
}
func launcherButton() *gtk.Button {
if !*noLauncher && *launcherCmd != "" {
button, _ := gtk.ButtonNew()
pixbuf, err := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/grid.svg"), imgSizeScaled, imgSizeScaled)
if err == nil {
image, _ := gtk.ImageNewFromPixbuf(pixbuf)
button.SetImage(image)
button.SetAlwaysShowImage(true)
button.Connect("clicked", func() {
elements := strings.Split(*launcherCmd, " ")
cmd := exec.Command(elements[0], elements[1:]...)
go func() {
err := cmd.Run()
if err != nil {
log.Warnf("Unable to start program: %s", err.Error())
}
}()
if *autohide {
win.Hide()
}
})
button.Connect("enter-notify-event", cancelClose)
} else {
log.Errorf("Unable to show grid button: %s", err.Error())
}
return button
}
return nil
}
/*
Window on-leave-notify event hides the dock with glib Timeout 1000 ms.
We might have left the window by accident, so let's clear the timeout if window re-entered.
Furthermore - hovering a button triggers window on-leave-notify event, and the timeout
needs to be cleared as well.
*/
func cancelClose() {
if src > 0 {
glib.SourceRemove(src)
src = 0
}
}
func taskButton(t task, instances []task) *gtk.Box {
box, _ := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
button, _ := gtk.ButtonNew()
box.PackStart(button, false, false, 0)
image, err := createImage(t.ID, imgSizeScaled)
if err != nil {
pixbuf, err := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/icon-missing.svg"),
imgSizeScaled, imgSizeScaled)
if err == nil {
image, _ = gtk.ImageNewFromPixbuf(pixbuf)
} else {
image, _ = gtk.ImageNew()
}
}
if image != nil {
button.SetImage(image)
button.SetImagePosition(gtk.POS_TOP)
button.SetAlwaysShowImage(true)
}
button.SetTooltipText(getName(t.ID))
var img *gtk.Image
if len(instances) < 2 {
pixbuf, _ := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/task-single.svg"),
imgSizeScaled, imgSizeScaled/8)
img, _ = gtk.ImageNewFromPixbuf(pixbuf)
} else {
pixbuf, _ := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, "nwg-dock/images/task-multiple.svg"),
imgSizeScaled, imgSizeScaled/8)
img, _ = gtk.ImageNewFromPixbuf(pixbuf)
}
box.PackStart(img, false, false, 0)
button.Connect("enter-notify-event", cancelClose)
if len(instances) == 1 {
button.Connect("event", func(btn *gtk.Button, e *gdk.Event) bool {
btnEvent := gdk.EventButtonNewFromEvent(e)
/* EVENT_BUTTON_PRESS would be more obvious, but it causes the misbehaviour:
if con is located on an external display, after pressing the button, the conID value
"freezes", and stays the same for all taskButtons, until the right mouse click.
A gotk3 bug or WTF? */
if btnEvent.Type() == gdk.EVENT_BUTTON_RELEASE || btnEvent.Type() == gdk.EVENT_TOUCH_END {
if btnEvent.Button() == 1 || btnEvent.Type() == gdk.EVENT_TOUCH_END {
focusCon(t.conID)
return true
} else if btnEvent.Button() == 3 {
contextMenu := taskMenuContext(t.ID, instances)
contextMenu.PopupAtWidget(button, widgetAnchor, menuAnchor, nil)
return true
}
}
return false
})
} else {
button.Connect("button-release-event", func(btn *gtk.Button, e *gdk.Event) bool {
btnEvent := gdk.EventButtonNewFromEvent(e)
if btnEvent.Button() == 1 {
menu := taskMenu(t.ID, instances)
menu.PopupAtWidget(button, widgetAnchor, menuAnchor, nil)
return true
} else if btnEvent.Button() == 3 {
contextMenu := taskMenuContext(t.ID, instances)
contextMenu.PopupAtWidget(button, widgetAnchor, menuAnchor, nil)
return true
}
return false
})
}
return box
}
func taskMenu(taskID string, instances []task) gtk.Menu {
menu, _ := gtk.MenuNew()
iconName, _ := getIcon(taskID)
for _, instance := range instances {
menuItem, _ := gtk.MenuItemNew()
hbox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 6)
image, _ := gtk.ImageNewFromIconName(iconName, gtk.ICON_SIZE_MENU)
hbox.PackStart(image, false, false, 0)
title := instance.Name
if len(title) > 20 {
title = title[:20]
}
label, _ := gtk.LabelNew(fmt.Sprintf("%s (%v)", title, instance.WsNum))
hbox.PackStart(label, false, false, 0)
menuItem.Add(hbox)
menu.Append(menuItem)
conID := instance.conID
menuItem.Connect("activate", func() {
focusCon(conID)
})
}
menu.ShowAll()
return *menu
}
func taskMenuContext(taskID string, instances []task) gtk.Menu {
menu, _ := gtk.MenuNew()
iconName, err := getIcon(taskID)
if err != nil {
log.Warnf("%s %s", err, taskID)
}
for _, instance := range instances {
menuItem, _ := gtk.MenuItemNew()
hbox, _ := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 6)
image, _ := gtk.ImageNewFromIconName(iconName, gtk.ICON_SIZE_MENU)
hbox.PackStart(image, false, false, 0)
title := instance.Name
if len(title) > 20 {
title = title[:20]
}
label, _ := gtk.LabelNew(fmt.Sprintf("%s (%v)", title, instance.WsNum))
hbox.PackStart(label, false, false, 0)
menuItem.Add(hbox)
menu.Append(menuItem)
submenu, _ := gtk.MenuNew()
subitem, _ := gtk.MenuItemNewWithLabel("Close")
submenu.Append(subitem)
conID := instance.conID
subitem.Connect("activate", func() {
killCon(conID)
})
for i := 1; i < int(*numWS)+1; i++ {
subitem, _ := gtk.MenuItemNewWithLabel(fmt.Sprintf("To WS %v", i))
target := i
subitem.Connect("activate", func() {
con2WS(conID, target)
})
submenu.Append(subitem)
}
menuItem.SetSubmenu(submenu)
}
separator, _ := gtk.SeparatorMenuItemNew()
menu.Append(separator)
item, _ := gtk.MenuItemNewWithLabel("New window")
item.Connect("activate", func() {
launch(taskID)
})
menu.Append(item)
pinItem, _ := gtk.MenuItemNew()
if !inPinned(taskID) {
pinItem.SetLabel("Pin")
pinItem.Connect("activate", func() {
log.Infof("pin %s", taskID)
pinTask(taskID)
})
} else {
pinItem.SetLabel("Unpin")
pinItem.Connect("activate", func() {
log.Infof("unpin %s", taskID)
unpinTask(taskID)
})
}
menu.Append(pinItem)
menu.ShowAll()
return *menu
}
func inPinned(taskID string) bool {
for _, id := range pinned {
if strings.TrimSpace(taskID) == strings.TrimSpace(id) {
return true
}
}
return false
}
func inTasks(tasks []task, pinID string) bool {
for _, task := range tasks {
if strings.TrimSpace(task.ID) == strings.TrimSpace(pinID) {
return true
}
}
return false
}
func createImage(appID string, size int) (*gtk.Image, error) {
name, err := getIcon(appID)
if err != nil {
name = appID
}
pixbuf, err := createPixbuf(name, size)
if err != nil {
return nil, err
}
image, _ := gtk.ImageNewFromPixbuf(pixbuf)
return image, nil
}
func createPixbuf(icon string, size int) (*gdk.Pixbuf, error) {
if strings.HasPrefix(icon, "/") {
pixbuf, err := gdk.PixbufNewFromFileAtSize(icon, size, size)
if err != nil {
log.Errorf("%s", err)
return nil, err
}
return pixbuf, nil
}
iconTheme, err := gtk.IconThemeGetDefault()
if err != nil {
log.Fatal("Couldn't get default theme: ", err)
}
pixbuf, err := iconTheme.LoadIcon(icon, size, gtk.ICON_LOOKUP_FORCE_SIZE)
if err != nil {
ico, err := getIcon(icon)
if err != nil {
return nil, err
}
if strings.HasPrefix(ico, "/") {
pixbuf, err := gdk.PixbufNewFromFileAtSize(ico, size, size)
if err != nil {
return nil, err
}
return pixbuf, nil
}
pixbuf, err := iconTheme.LoadIcon(ico, size, gtk.ICON_LOOKUP_FORCE_SIZE)
if err != nil {
return nil, err
}
return pixbuf, nil
}
return pixbuf, nil
}
func cacheDir() string {
if os.Getenv("XDG_CACHE_HOME") != "" {
return os.Getenv("XDG_CONFIG_HOME")
}
if os.Getenv("HOME") != "" && pathExists(filepath.Join(os.Getenv("HOME"), ".cache")) {
p := filepath.Join(os.Getenv("HOME"), ".cache")
return p
}
return ""
}
func tempDir() string {
if os.Getenv("TMPDIR") != "" {
return os.Getenv("TMPDIR")
} else if os.Getenv("TEMP") != "" {
return os.Getenv("TEMP")
} else if os.Getenv("TMP") != "" {
return os.Getenv("TMP")
}
return "/tmp"
}
func readTextFile(path string) (string, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
func configDir() string {
if os.Getenv("XDG_CONFIG_HOME") != "" {
return (fmt.Sprintf("%s/nwg-dock", os.Getenv("XDG_CONFIG_HOME")))
}
return fmt.Sprintf("%s/.config/nwg-dock", os.Getenv("HOME"))
}
func createDir(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
if err == nil {
log.Infof("Creating dir: %s", dir)
}
}
}
func copyFile(src, dst string) error {
log.Infof("Copying file: %s", dst)
var err error
var srcfd *os.File
var dstfd *os.File
var srcinfo os.FileInfo
if srcfd, err = os.Open(src); err != nil {
return err
}
defer srcfd.Close()
if dstfd, err = os.Create(dst); err != nil {
return err
}
defer dstfd.Close()
if _, err = io.Copy(dstfd, srcfd); err != nil {
return err
}
if srcinfo, err = os.Stat(src); err != nil {
return err
}
return os.Chmod(dst, srcinfo.Mode())
}
func getDataHome() string {
if os.Getenv("XDG_DATA_HOME") != "" {
return os.Getenv("XDG_DATA_HOME")
}
return "/usr/share/"
}
func getAppDirs() []string {
var dirs []string
xdgDataDirs := ""
home := os.Getenv("HOME")
xdgDataHome := os.Getenv("XDG_DATA_HOME")
if os.Getenv("XDG_DATA_DIRS") != "" {
xdgDataDirs = os.Getenv("XDG_DATA_DIRS")
} else {
xdgDataDirs = "/usr/local/share/:/usr/share/"
}
if xdgDataHome != "" {
dirs = append(dirs, filepath.Join(xdgDataHome, "applications"))
} else if home != "" {
dirs = append(dirs, filepath.Join(home, ".local/share/applications"))
}
for _, d := range strings.Split(xdgDataDirs, ":") {
dirs = append(dirs, filepath.Join(d, "applications"))
}
flatpakDirs := []string{filepath.Join(home, ".local/share/flatpak/exports/share/applications"),
"/var/lib/flatpak/exports/share/applications"}
for _, d := range flatpakDirs {
if !isIn(dirs, d) {
dirs = append(dirs, d)
}
}
return dirs
}
func isIn(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
func getIcon(appName string) (string, error) {
appName = strings.Split(appName, " ")[0]
if strings.HasPrefix(strings.ToUpper(appName), "GIMP") {
return "gimp", nil
}
p := ""
for _, d := range appDirs {
path := filepath.Join(d, fmt.Sprintf("%s.desktop", appName))
if pathExists(path) {
p = path
break
} else if pathExists(strings.ToLower(path)) {
p = strings.ToLower(path)
break
}
}
/* Some apps' app_id varies from their .desktop file name, e.g. 'gimp-2.9.9' or 'pamac-manager'.
Let's try to find a matching .desktop file name */
if !strings.HasPrefix(appName, "/") && p == "" { // skip icon paths given instead of names
p = searchDesktopDirs(appName)
}
if p != "" {
lines, err := loadTextFile(p)
if err != nil {
return "", err
}
for _, line := range lines {
if strings.HasPrefix(strings.ToUpper(line), "ICON") {
return strings.Split(line, "=")[1], nil
}
}
}
return "", errors.New(fmt.Sprintf("couldn't find the icon for %s", appName))
}
func searchDesktopDirs(badAppID string) string {
b4Separator := strings.Split(badAppID, "-")[0]
for _, d := range appDirs {
items, _ := os.ReadDir(d)
for _, item := range items {
if strings.Contains(item.Name(), b4Separator) {
//Let's check items starting from 'org.' first
if strings.Count(item.Name(), ".") > 1 && strings.HasSuffix(item.Name(),
fmt.Sprintf("%s.desktop", badAppID)) {
return filepath.Join(d, item.Name())
}
}
}
}
// exceptions like "class": "VirtualBox Manager" & virtualbox.desktop
b4Separator = strings.Split(badAppID, " ")[0]
for _, d := range appDirs {
items, _ := os.ReadDir(d)
for _, item := range items {
if strings.Contains(strings.ToUpper(item.Name()), strings.ToUpper(b4Separator)) {
return filepath.Join(d, item.Name())
}
}
}
return ""
}
func getExec(appName string) (string, error) {
cmd := appName
if strings.HasPrefix(strings.ToUpper(appName), "GIMP") {
cmd = "gimp"
}
for _, d := range appDirs {
files, _ := os.ReadDir(d)
path := ""
for _, f := range files {
if strings.HasSuffix(f.Name(), ".desktop") {
if f.Name() == fmt.Sprintf("%s.desktop", appName) ||
f.Name() == fmt.Sprintf("%s.desktop", strings.ToLower(appName)) {
path = filepath.Join(d, f.Name())
break
}
}
}
// as above in getIcon - for tasks w/ improper app_id
if path == "" {
path = searchDesktopDirs(appName)
}
if path != "" {
lines, err := loadTextFile(path)
if err != nil {
return "", err
}
for _, line := range lines {
if strings.HasPrefix(strings.ToUpper(line), "EXEC") {
l := line[5:]
cutAt := strings.Index(l, "%")
if cutAt != -1 {
l = l[:cutAt-1]
}
cmd = l
break
}
}
return cmd, nil
}
}
return cmd, nil
}
func getName(appName string) string {
name := appName
for _, d := range appDirs {
files, _ := os.ReadDir(d)
path := ""
for _, f := range files {
if strings.HasSuffix(f.Name(), ".desktop") {
if f.Name() == fmt.Sprintf("%s.desktop", appName) ||
f.Name() == fmt.Sprintf("%s.desktop", strings.ToLower(appName)) {
path = filepath.Join(d, f.Name())
break
}
}
}
if path != "" {
lines, err := loadTextFile(path)
if err != nil {
return name
}
for _, line := range lines {
if strings.HasPrefix(strings.ToUpper(line), "NAME") {
name = line[5:]
break
}
}
}
}
return name
}
func pathExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func loadTextFile(path string) ([]string, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
lines := strings.Split(string(bytes), "\n")
var output []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
output = append(output, line)
}
}
return output, nil
}
func pinTask(itemID string) {
for _, item := range pinned {
if item == itemID {
println(item, "already pinned")
return
}
}
pinned = append(pinned, itemID)
savePinned()
refreshMainBoxChannel <- struct{}{}
}
func unpinTask(itemID string) {
pinned = remove(pinned, itemID)
savePinned()
refreshMainBoxChannel <- struct{}{}
}
func remove(s []string, r string) []string {
for i, v := range s {
if v == r {
return append(s[:i], s[i+1:]...)
}
}
return s
}
func savePinned() {
f, err := os.OpenFile(pinnedFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
log.Fatal(err)
}
defer f.Close()
for _, line := range pinned {
if line != "" {
_, err := f.WriteString(line + "\n")
if err != nil {
log.Errorf("Error saving pinned", err)
}
}
}
}
func launch(ID string) {
command, err := getExec(ID)
if err != nil {
log.Errorf("%s", err)
}
// remove quotation marks if any
if strings.Contains(command, "\"") {
command = strings.ReplaceAll(command, "\"", "")
}
elements := strings.Split(command, " ")
// find prepended env variables, if any
envVarsNum := strings.Count(command, "=")
var envVars []string
cmdIdx := -1
if envVarsNum > 0 {
for idx, item := range elements {
if strings.Contains(item, "=") {
envVars = append(envVars, item)
} else if !strings.HasPrefix(item, "-") && cmdIdx == -1 {
cmdIdx = idx
}
}
}
if cmdIdx == -1 {
cmdIdx = 0
}
var args []string
for _, arg := range elements[1+cmdIdx:] {
if !strings.Contains(arg, "=") {
args = append(args, arg)
}
}
cmd := exec.Command(elements[cmdIdx], elements[1+cmdIdx:]...)
// set env variables
if len(envVars) > 0 {
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, envVars...)
}
msg := fmt.Sprintf("env vars: %s; command: '%s'; args: %s\n", envVars, elements[cmdIdx], args)
log.Info(msg)
if err := cmd.Start(); err != nil {
log.Error("Unable to launch command!", err.Error())
}