forked from nwg-piotr/nwg-drawer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.go
791 lines (694 loc) · 17.9 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/joshuarubin/go-sway"
log "github.com/sirupsen/logrus"
"io"
"io/fs"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"time"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/gtk"
)
func wayland() bool {
return os.Getenv("WAYLAND_DISPLAY") != "" || os.Getenv("XDG_SESSION_TYPE") == "wayland"
}
func createPixbuf(icon string, size int) (*gdk.Pixbuf, error) {
iconTheme, err := gtk.IconThemeGetDefault()
if err != nil {
log.Fatal("Couldn't get default theme: ", err)
}
if strings.Contains(icon, "/") {
pixbuf, err := gdk.PixbufNewFromFileAtSize(icon, size, size)
if err != nil {
log.Errorf("%s", err)
return nil, err
}
return pixbuf, nil
} else if strings.HasSuffix(icon, ".svg") || strings.HasSuffix(icon, ".png") || strings.HasSuffix(icon, ".xpm") {
// for entries like "Icon=netflix-desktop.svg"
icon = strings.Split(icon, ".")[0]
}
pixbuf, err := iconTheme.LoadIcon(icon, size, gtk.ICON_LOOKUP_FORCE_SIZE)
if err != nil {
if strings.HasPrefix(icon, "/") {
pixbuf, err := gdk.PixbufNewFromFileAtSize(icon, size, size)
if err != nil {
return nil, err
}
return pixbuf, nil
}
pixbuf, err := iconTheme.LoadIcon(icon, size, gtk.ICON_LOOKUP_FORCE_SIZE)
if err != nil {
return nil, err
}
return pixbuf, nil
}
return pixbuf, nil
}
func mapXdgUserDirs() map[string]string {
result := make(map[string]string)
home := os.Getenv("HOME")
result["home"] = home
result["documents"] = filepath.Join(home, "Documents")
result["downloads"] = filepath.Join(home, "Downloads")
result["music"] = filepath.Join(home, "Music")
result["pictures"] = filepath.Join(home, "Pictures")
result["videos"] = filepath.Join(home, "Videos")
userDirsFile := filepath.Join(filepath.Join(configHome(), "user-dirs.dirs"))
if pathExists(userDirsFile) {
log.Debugf("userDirsFile found: %s", userDirsFile)
log.Info(fmt.Sprintf("Using XDG user dirs from %s", userDirsFile))
lines, _ := loadTextFile(userDirsFile)
for _, l := range lines {
if strings.HasPrefix(l, "XDG_DOCUMENTS_DIR") {
result["documents"] = getUserDir(home, l)
continue
}
if strings.HasPrefix(l, "XDG_DOWNLOAD_DIR") {
result["downloads"] = getUserDir(home, l)
continue
}
if strings.HasPrefix(l, "XDG_MUSIC_DIR") {
result["music"] = getUserDir(home, l)
continue
}
if strings.HasPrefix(l, "XDG_PICTURES_DIR") {
result["pictures"] = getUserDir(home, l)
continue
}
if strings.HasPrefix(l, "XDG_VIDEOS_DIR") {
result["videos"] = getUserDir(home, l)
}
}
} else {
log.Warnf("userDirsFile %s not found, using defaults", userDirsFile)
}
return result
}
func getUserDir(home, line string) string {
// line is supposed to look like XDG_DOCUMENTS_DIR="$HOME/Dokumenty"
result := strings.Split(line, "=")[1]
result = strings.Replace(result, "$HOME", home, 1)
// trim ""
return result[1 : len(result)-1]
}
func cacheDir() string {
if xdgCache := os.Getenv("XDG_CACHE_HOME"); xdgCache != "" {
return xdgCache
}
if home := os.Getenv("HOME"); home != "" && pathExists(filepath.Join(home, ".cache")) {
p := filepath.Join(home, ".cache")
return p
}
return ""
}
func readTextFile(path string) (string, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
func oldConfigDir() (string, error) {
if xdgConfig := os.Getenv("XDG_CONFIG_HOME"); xdgConfig != "" {
dir := path.Join(xdgConfig, "nwg-panel")
return dir, nil
} else if home := os.Getenv("HOME"); home != "" {
dir := path.Join(home, ".config/nwg-panel")
return dir, nil
}
return "", errors.New("old config dir not found")
}
func configDir() string {
var dir string
if xdgConfig := os.Getenv("XDG_CONFIG_HOME"); xdgConfig != "" {
dir = path.Join(xdgConfig, "nwg-drawer")
} else if home := os.Getenv("HOME"); home != "" {
dir = path.Join(home, ".config/nwg-drawer")
}
log.Infof("Config dir: %s", dir)
createDir(dir)
return dir
}
func configHome() string {
if os.Getenv("XDG_CONFIG_HOME") != "" {
return os.Getenv("XDG_CONFIG_HOME")
}
return path.Join(os.Getenv("HOME"), ".config")
}
func dataHome() string {
var dir string
if xdgData := os.Getenv("XDG_DATA_HOME"); xdgData != "" {
dir = path.Join(xdgData, "nwg-drawer")
} else if home := os.Getenv("HOME"); home != "" {
dir = path.Join(home, ".local/share/nwg-drawer")
}
log.Debugf("Data home: %s", dir)
createDir(dir)
return dir
}
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: '%s' => '%s'", src, 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 func(srcfd *os.File) {
err := srcfd.Close()
if err != nil {
log.Errorf("Error closing file: %v", srcfd)
}
}(srcfd)
if dstfd, err = os.Create(dst); err != nil {
return err
}
defer func(dstfd *os.File) {
err := dstfd.Close()
if err != nil {
log.Errorf("Error closing file: %v", dstfd)
}
}(dstfd)
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 dataDir() string {
xdgDataDirs := os.Getenv("XDG_DATA_DIRS")
if xdgDataDirs == "" {
xdgDataDirs = "/usr/local/share/:/usr/share/"
}
for _, d := range strings.Split(xdgDataDirs, ":") {
p := filepath.Join(d, "nwg-drawer")
q := filepath.Join(p, "desktop-directories")
if pathExists(q) {
log.Infof("Data dir: %v", p)
return p
}
}
log.Warnf("Data dir not found")
return ""
}
func getAppDirs() []string {
var dirs []string
home := os.Getenv("HOME")
xdgDataHome := os.Getenv("XDG_DATA_HOME")
xdgDataDirs := os.Getenv("XDG_DATA_DIRS")
if xdgDataDirs == "" {
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 pathExists(d) && !isIn(dirs, d) {
dirs = append(dirs, d)
}
}
var confirmedDirs []string
for _, d := range dirs {
if pathExists(d) {
confirmedDirs = append(confirmedDirs, d)
}
}
return confirmedDirs
}
func loadPreferredApps(path string) (map[string]interface{}, error) {
jsonFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer func(jsonFile *os.File) {
err := jsonFile.Close()
if err != nil {
log.Errorf("Error closing file: %v", jsonFile)
}
}(jsonFile)
byteValue, _ := io.ReadAll(jsonFile)
var result map[string]interface{}
err = json.Unmarshal(byteValue, &result)
if err != nil {
return nil, err
}
if len(result) == 0 {
return nil, errors.New("json invalid or empty")
}
return result, nil
}
func listFiles(dir string) ([]fs.DirEntry, error) {
files, err := os.ReadDir(dir)
if err == nil {
return files, nil
}
return nil, err
}
func listDesktopFiles() []string {
var paths []string
for _, dir := range appDirs {
dirs, err := listFiles(dir)
if err == nil {
for _, file := range dirs {
parts := strings.Split(file.Name(), ".")
if parts[len(parts)-1] == "desktop" {
paths = append(paths, filepath.Join(dir, file.Name()))
}
}
}
}
return paths
}
func setUpCategories() {
var other category
dDir := dataDir()
for _, cName := range categoryNames {
fileName := fmt.Sprintf("%s.directory", cName)
fp := filepath.Join(dDir, "desktop-directories", fileName)
lines, err := loadTextFile(fp)
if err == nil {
var cat category
cat.Name = cName
name := ""
nameLoc := ""
icon := ""
for _, l := range lines {
if strings.HasPrefix(l, "Name=") {
name = strings.Split(l, "=")[1]
continue
}
if strings.HasPrefix(l, fmt.Sprintf("Name[%s]=", strings.Split(*lang, "_")[0])) {
nameLoc = strings.Split(l, "=")[1]
continue
}
if strings.HasPrefix(l, "Icon=") {
icon = strings.Split(l, "=")[1]
continue
}
}
if nameLoc == "" {
for _, l := range lines {
if strings.HasPrefix(l, fmt.Sprintf("Name[%s]=", *lang)) {
nameLoc = strings.Split(l, "=")[1]
break
}
}
}
if nameLoc != "" {
cat.DisplayName = nameLoc
} else {
cat.DisplayName = name
}
cat.Icon = icon
// We want "other" to be the last one. Let's append it when already sorted
if fileName != "other.directory" {
categories = append(categories, cat)
} else {
other = cat
}
} else {
log.Errorf("Couldn't open %s", fp)
}
}
sort.Slice(categories, func(i, j int) bool {
return categories[i].DisplayName < categories[j].DisplayName
})
categories = append(categories, other)
}
func parseDesktopFiles(desktopFiles []string) string {
desktopEntries = nil
id2entry = make(map[string]desktopEntry)
skipped := 0
hidden := 0
for _, file := range desktopFiles {
id := filepath.Base(file)
if _, ok := id2entry[id]; ok {
skipped++
continue
}
entry, err := parseDesktopEntryFile(id, file)
if err != nil {
continue
}
if entry.NoDisplay {
hidden++
// We still need hidden entries, so `continue` is disallowed here
// Fixes bug introduced in #19
}
id2entry[entry.DesktopID] = entry
desktopEntries = append(desktopEntries, entry)
assignToLists(entry.DesktopID, entry.Category)
}
sort.Slice(desktopEntries, func(i, j int) bool {
return desktopEntries[i].NameLoc < desktopEntries[j].NameLoc
})
summary := fmt.Sprintf("%v entries (+%v hidden)", len(desktopEntries)-hidden, hidden)
log.Infof("Skipped %v duplicates; %v .desktop entries hidden by \"NoDisplay=true\"", skipped, hidden)
return summary
}
// freedesktop Main Categories list consists of 13 entries. Let's contract it to 8+1 ("Other").
func assignToLists(desktopID, categories string) {
cats := strings.Split(categories, ";")
assigned := false
for _, cat := range cats {
if cat == "Utility" && !isIn(listUtility, desktopID) {
listUtility = append(listUtility, desktopID)
assigned = true
continue
}
if cat == "Development" && !isIn(listDevelopment, desktopID) {
listDevelopment = append(listDevelopment, desktopID)
assigned = true
continue
}
if cat == "Game" && !isIn(listGame, desktopID) {
listGame = append(listGame, desktopID)
assigned = true
continue
}
if cat == "Graphics" && !isIn(listGraphics, desktopID) {
listGraphics = append(listGraphics, desktopID)
assigned = true
continue
}
if cat == "Network" && !isIn(listInternetAndNetwork, desktopID) {
listInternetAndNetwork = append(listInternetAndNetwork, desktopID)
assigned = true
continue
}
if isIn([]string{"Office", "Science", "Education"}, cat) && !isIn(listOffice, desktopID) {
listOffice = append(listOffice, desktopID)
assigned = true
continue
}
if isIn([]string{"AudioVideo", "Audio", "Video"}, cat) && !isIn(listAudioVideo, desktopID) {
listAudioVideo = append(listAudioVideo, desktopID)
assigned = true
continue
}
if isIn([]string{"Settings", "System", "DesktopSettings", "PackageManager"}, cat) && !isIn(listSystemTools, desktopID) {
listSystemTools = append(listSystemTools, desktopID)
assigned = true
continue
}
}
if categories != "" && !assigned && !isIn(listOther, desktopID) {
listOther = append(listOther, desktopID)
}
}
func isIn(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
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 != "" && !strings.HasPrefix(line, "#") {
output = append(output, line)
}
}
return output, nil
}
func pinItem(itemID string) {
for _, item := range pinned {
if item == itemID {
log.Warnf("%s already pinned", itemID)
return
}
}
pinned = append(pinned, itemID)
savePinned()
log.Infof("%s pinned", itemID)
}
func unpinItem(itemID string) {
if isIn(pinned, itemID) {
pinned = remove(pinned, itemID)
savePinned()
log.Infof("%s unpinned", itemID)
}
}
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 func(f *os.File) {
err := f.Close()
if err != nil {
log.Errorf("Error closing file: %v", f)
}
}(f)
for _, line := range pinned {
//skip invalid lines
if line != "" && id2entry[line].DesktopID != "" {
_, err := f.WriteString(line + "\n")
if err != nil {
log.Error("Error saving pinned", err)
}
}
}
}
func launch(command string, terminal bool, terminate bool) {
// trim % and everything afterwards
if strings.Contains(command, "%") {
cutAt := strings.Index(command, "%")
if cutAt != -1 {
command = command[:cutAt-1]
}
}
themeToPrepend := ""
// add "GTK_THEME=<default_gtk_theme>" environment variable
if *forceTheme {
settings, _ := gtk.SettingsGetDefault()
th, err := settings.GetProperty("gtk-theme-name")
if err == nil {
themeToPrepend = th.(string)
}
}
if themeToPrepend != "" {
command = fmt.Sprintf("GTK_THEME=%q %s", themeToPrepend, command)
}
var elements = []string{"/usr/bin/env", "-S", command}
cmd := exec.Command(elements[0], elements[1:]...)
if terminal {
var prefixCommand = *term
var args []string
if prefixCommand != "foot" {
args = []string{"-e", command}
} else {
args = elements
}
cmd = exec.Command(prefixCommand, args...)
} else if *wm == "sway" {
cmd = exec.Command("swaymsg", "exec", strings.Join(elements, " "))
} else if *wm == "hyprland" || *wm == "Hyprland" {
cmd = exec.Command("hyprctl", "dispatch", "exec", strings.Join(elements, " "))
} else if *wm == "river" {
cmd = exec.Command("riverctl", "spawn", strings.Join(elements, " "))
}
msg := fmt.Sprintf("Executing command: %q; args: %q\n", cmd.Args[0], cmd.Args[1:])
log.Info(msg)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
if cmd.Start() != nil {
log.Warn("Unable to launch terminal emulator!")
} else {
// Collect the exit code of the child process to prevent zombies
// if the drawer runs in resident mode
go func() {
_ = cmd.Wait()
}()
}
if terminate {
if *resident {
restoreStateAndHide()
} else {
gtk.MainQuit()
}
}
}
func open(filePath string, xdgOpen bool) {
var cmd *exec.Cmd
if xdgOpen {
cmd = exec.Command("xdg-open", filePath)
// Look for possible custom file association
for key, element := range preferredApps {
r, err := regexp.Compile(key)
if err == nil && r.MatchString(filePath) {
cmd = exec.Command(fmt.Sprintf("%v", element), filePath)
break
}
}
} else {
cmd = exec.Command(*fileManager, filePath)
}
log.Infof("Executing: %s", cmd)
if cmd.Start() != nil {
log.Warn("Unable to execute command!")
} else {
// Collect the exit code of the child process to prevent zombies
// if the drawer runs in resident mode
go func() {
_ = cmd.Wait()
}()
}
if *resident {
restoreStateAndHide()
} else {
gtk.MainQuit()
}
}
// Returns map output name -> gdk.Monitor
func mapOutputs() (map[string]*gdk.Monitor, error) {
result := make(map[string]*gdk.Monitor)
if os.Getenv("HYPRLAND_INSTANCE_SIGNATURE") != "" {
err := listHyprlandMonitors()
if err == nil {
display, err := gdk.DisplayGetDefault()
if err != nil {
return nil, err
}
num := display.GetNMonitors()
for i := 0; i < num; i++ {
mon, _ := display.GetMonitor(i)
output := hyprlandMonitors[i]
result[output.Name] = mon
}
} else {
return nil, err
}
} else if os.Getenv("SWAYSOCK") != "" {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client, err := sway.New(ctx)
if err != nil {
return nil, err
}
outputs, err := client.GetOutputs(ctx)
if err != nil {
return nil, err
}
display, err := gdk.DisplayGetDefault()
if err != nil {
return nil, err
}
num := display.GetNMonitors()
for i := 0; i < num; i++ {
mon, _ := display.GetMonitor(i)
output := outputs[i]
result[output.Name] = mon
}
} else {
return nil, errors.New("output assignment only supported on sway and Hyprland")
}
return result, nil
}
// KAdot / https://stackoverflow.com/a/38537764/4040598 - thanks!
func substring(s string, start int, end int) string {
startStrIdx := 0
i := 0
for j := range s {
if i == start {
startStrIdx = j
}
if i == end {
return s[startStrIdx:j]
}
i++
}
return s[startStrIdx:]
}
func hyprctl(cmd string) ([]byte, error) {
his := os.Getenv("HYPRLAND_INSTANCE_SIGNATURE")
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
hyprDir := ""
if xdgRuntimeDir != "" {
hyprDir = fmt.Sprintf("%s/hypr", xdgRuntimeDir)
} else {
hyprDir = "/tmp/hypr"
}
socketFile := fmt.Sprintf("%s/%s/.socket.sock", hyprDir, his)
conn, err := net.Dial("unix", socketFile)
if err != nil {
return nil, err
}
message := []byte(cmd)
_, err = conn.Write(message)
if err != nil {
return nil, err
}
reply := make([]byte, 102400)
n, err := conn.Read(reply)
if err != nil {
return nil, err
}
defer conn.Close()
return reply[:n], nil
}
func listHyprlandMonitors() error {
reply, err := hyprctl("j/monitors")
if err != nil {
return err
} else {
err = json.Unmarshal([]byte(reply), &hyprlandMonitors)
}
return err
}