-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
658 lines (553 loc) · 18.3 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/allan-simon/go-singleinstance"
"github.com/dlasky/gotk3-layershell/layershell"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const version = "0.4.1"
type WindowState int
const (
WindowShow WindowState = iota
WindowHide
)
var (
appDirs []string
dataHome string
configDirectory string
pinnedFile string
pinned []string
oldTasks []task
mainBox *gtk.Box
src glib.SourceHandle
refreshMainBoxChannel chan struct{} = make(chan struct{}, 1)
outerOrientation, innerOrientation gtk.Orientation
widgetAnchor, menuAnchor gdk.Gravity
imgSizeScaled int
currentWsNum, targetWsNum int64
win *gtk.Window
windowStateChannel chan WindowState = make(chan WindowState, 1)
detectorEnteredAt int64
)
// Flags
var cssFileName = flag.String("s", "style.css", "Styling: css file name")
var targetOutput = flag.String("o", "", "name of Output to display the dock on")
var displayVersion = flag.Bool("v", false, "display Version information")
var autohide = flag.Bool("d", false, "auto-hiDe: show dock when hotspot hovered, close when left or a button clicked")
var full = flag.Bool("f", false, "take Full screen width/height")
var numWS = flag.Int64("w", 8, "number of Workspaces you use")
var position = flag.String("p", "bottom", "Position: \"bottom\", \"top\" or \"left\"")
var exclusive = flag.Bool("x", false, "set eXclusive zone: move other windows aside; overrides the \"-l\" argument")
var imgSize = flag.Int("i", 48, "Icon size")
var layer = flag.String("l", "overlay", "Layer \"overlay\", \"top\" or \"bottom\"")
var launcherCmd = flag.String("c", "", "Command assigned to the launcher button")
var launcherPos = flag.String("lp", "end", "Launcher button position, 'start' or 'end'")
var alignment = flag.String("a", "center", "Alignment in full width/height: \"start\", \"center\" or \"end\"")
var marginTop = flag.Int("mt", 0, "Margin Top")
var marginLeft = flag.Int("ml", 0, "Margin Left")
var marginRight = flag.Int("mr", 0, "Margin Right")
var marginBottom = flag.Int("mb", 0, "Margin Bottom")
var hotspotDelay = flag.Int64("hd", 20, "Hotspot Delay [ms]; the smaller, the faster mouse pointer needs to enter hotspot for the dock to appear; set 0 to disable")
var noWs = flag.Bool("nows", false, "don't show the workspace switcher")
var noLauncher = flag.Bool("nolauncher", false, "don't show the launcher button")
var resident = flag.Bool("r", false, "Leave the program resident, but w/o hotspot")
var debug = flag.Bool("debug", false, "turn on debug messages")
func buildMainBox(tasks []task, vbox *gtk.Box) {
mainBox.Destroy()
mainBox, _ = gtk.BoxNew(innerOrientation, 0)
if *alignment == "start" {
vbox.PackStart(mainBox, false, true, 0)
} else if *alignment == "end" {
vbox.PackEnd(mainBox, false, true, 0)
} else {
vbox.PackStart(mainBox, true, false, 0)
}
var err error
pinned, err = loadTextFile(pinnedFile)
if err != nil {
pinned = nil
}
var allItems []string
for _, cntPin := range pinned {
if !isIn(allItems, cntPin) {
allItems = append(allItems, cntPin)
}
}
for _, cntTask := range tasks {
if !isIn(allItems, cntTask.ID) && !strings.Contains(*launcherCmd, cntTask.ID) {
allItems = append(allItems, cntTask.ID)
}
}
divider := 1
if len(allItems) > 0 {
divider = len(allItems)
}
// scale icons down when their number increases
if *imgSize*6/(divider) < *imgSize {
overflow := (len(allItems) - 6) / 3
imgSizeScaled = *imgSize * 6 / (6 + overflow)
} else {
imgSizeScaled = *imgSize
}
if *launcherPos == "start" {
button := launcherButton()
if button != nil {
mainBox.PackStart(button, false, false, 0)
}
}
var alreadyAdded []string
for _, pin := range pinned {
if !inTasks(tasks, pin) {
button := pinnedButton(pin)
mainBox.PackStart(button, false, false, 0)
} else {
instances := taskInstances(pin, tasks)
task := instances[0]
if len(instances) == 1 {
button := taskButton(task, instances)
mainBox.PackStart(button, false, false, 0)
} else if !isIn(alreadyAdded, task.ID) {
button := taskButton(task, instances)
mainBox.PackStart(button, false, false, 0)
alreadyAdded = append(alreadyAdded, task.ID)
taskMenu(task.ID, instances)
} else {
continue
}
}
}
alreadyAdded = nil
for _, task := range tasks {
if !inPinned(task.ID) {
instances := taskInstances(task.ID, tasks)
if len(instances) == 1 {
button := taskButton(task, instances)
mainBox.PackStart(button, false, false, 0)
} else if !isIn(alreadyAdded, task.ID) {
button := taskButton(task, instances)
mainBox.PackStart(button, false, false, 0)
alreadyAdded = append(alreadyAdded, task.ID)
taskMenu(task.ID, instances)
} else {
continue
}
}
}
if !*noWs {
wsButton, e := gtk.ButtonNew()
if e != nil {
return
}
wsPixbuf, e := gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, fmt.Sprintf("nwg-dock/images/%v.svg", currentWsNum)),
imgSizeScaled, imgSizeScaled)
if e == nil {
wsImage, _ := gtk.ImageNewFromPixbuf(wsPixbuf)
wsButton.SetImage(wsImage)
wsButton.SetAlwaysShowImage(true)
wsButton.AddEvents(int(gdk.SCROLL_MASK))
wsUpdateChannel := getWorkspaceChangesChannel(context.Background())
go func() {
for {
activeWorkspace := <-wsUpdateChannel
targetWsNum = activeWorkspace
glib.TimeoutAdd(0, func() bool {
wsPixbuf, e = gdk.PixbufNewFromFileAtSize(filepath.Join(dataHome, fmt.Sprintf("nwg-dock/images/%v.svg", activeWorkspace)),
imgSizeScaled, imgSizeScaled)
if e == nil {
wsImage, _ = gtk.ImageNewFromPixbuf(wsPixbuf)
wsButton.SetImage(wsImage)
} else {
log.Warnf("Unable set set workspace image: %v", activeWorkspace)
}
return false
})
}
}()
wsButton.Connect("clicked", func() {
focusWorkspace(targetWsNum)
})
wsButton.Connect("enter-notify-event", cancelClose)
wsButton.Connect("scroll-event", func(btn *gtk.Button, e *gdk.Event) bool {
event := gdk.EventScrollNewFromEvent(e)
if event.Direction() == gdk.SCROLL_UP {
if targetWsNum < *numWS && targetWsNum < 20 {
targetWsNum++
} else {
targetWsNum = 1
}
wsUpdateChannel <- targetWsNum
return true
} else if event.Direction() == gdk.SCROLL_DOWN {
if targetWsNum > 1 {
targetWsNum--
} else {
targetWsNum = *numWS
}
wsUpdateChannel <- targetWsNum
return true
}
return false
})
}
if wsButton != nil {
mainBox.PackStart(wsButton, false, false, 0)
}
}
if *launcherPos == "end" {
button := launcherButton()
if button != nil {
mainBox.PackStart(button, false, false, 0)
}
}
mainBox.ShowAll()
}
func setupHotSpot(monitor gdk.Monitor, dockWindow *gtk.Window) gtk.Window {
w, h := dockWindow.GetSize()
win, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
layershell.InitForWindow(win)
layershell.SetMonitor(win, &monitor)
var box *gtk.Box
if *position == "bottom" || *position == "top" {
box, _ = gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
} else {
box, _ = gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 0)
}
win.Add(box)
detectorBox, _ := gtk.EventBoxNew()
_ = detectorBox.SetProperty("name", "detector-box")
if *position == "bottom" {
box.PackStart(detectorBox, false, false, 0)
} else {
box.PackEnd(detectorBox, false, false, 0)
}
detectorBox.Connect("enter-notify-event", func() {
detectorEnteredAt = time.Now().UnixNano() / 1000000
})
hotspotBox, _ := gtk.EventBoxNew()
_ = hotspotBox.SetProperty("name", "hotspot-box")
if *position == "bottom" {
box.PackStart(hotspotBox, false, false, 0)
} else {
box.PackEnd(hotspotBox, false, false, 0)
}
hotspotBox.Connect("enter-notify-event", func() {
hotspotEnteredAt := time.Now().UnixNano() / 1000000
delay := hotspotEnteredAt - detectorEnteredAt
layershell.SetMonitor(dockWindow, &monitor)
if delay <= *hotspotDelay || *hotspotDelay == 0 {
log.Debugf("Delay %v < %v ms, let's show the window!", delay, *hotspotDelay)
dockWindow.Hide()
dockWindow.Show()
} else {
log.Debugf("Delay %v > %v ms, don't show the window :/", delay, *hotspotDelay)
}
})
if *position == "bottom" || *position == "top" {
detectorBox.SetSizeRequest(w, h/3)
hotspotBox.SetSizeRequest(w, 2)
if *position == "bottom" {
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_BOTTOM, true)
} else {
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_TOP, true)
}
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_LEFT, *full)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_RIGHT, *full)
}
if *position == "left" {
detectorBox.SetSizeRequest(w/3, h)
hotspotBox.SetSizeRequest(2, h)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_LEFT, true)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_TOP, *full)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_BOTTOM, *full)
}
layershell.SetLayer(win, layershell.LAYER_SHELL_LAYER_TOP)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_TOP, *marginTop)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_LEFT, *marginLeft)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_RIGHT, *marginRight)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_BOTTOM, *marginBottom)
layershell.SetExclusiveZone(win, -1)
return *win
}
func main() {
flag.Parse()
if *debug {
log.SetLevel(log.DebugLevel)
}
if *autohide && *resident {
log.Warn("autohiDe and Resident arguments are mutually exclusive, ignoring -d!")
*autohide = false
}
if *displayVersion {
fmt.Printf("nwg-dock version %s\n", version)
os.Exit(0)
}
if *autohide {
log.Info("Starting in autohiDe mode")
}
if *resident {
log.Info("Starting in resident mode")
}
// Gentle SIGTERM handler thanks to reiki4040 https://gist.github.com/reiki4040/be3705f307d3cd136e85
// v0.2: we also need to support SIGUSR from now on.
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGUSR1)
go func() {
for {
s := <-signalChan
switch s {
case syscall.SIGTERM:
log.Info("SIGTERM received, bye bye!")
gtk.MainQuit()
case syscall.SIGUSR1:
if *resident || *autohide {
// As win.Show() called from inside a goroutine randomly crashes GTK,
// let's just set e helper variable here. We'll be checking it with glib.TimeoutAdd.
if !win.IsVisible() {
log.Debug("SIGUSR1 received, showing the window")
windowStateChannel <- WindowShow
} else {
log.Debug("SIGUSR1 received, hiding the window")
windowStateChannel <- WindowHide
}
} else {
log.Info("SIGUSR1 received, and I'm not resident, bye bye!")
gtk.MainQuit()
}
default:
log.Warn("Unknown signal")
}
}
}()
// Unless we are in autohide/resident mode, we probably want the same key/mouse binding to turn the dock off.
// Since v0.2 we can't just send SIGKILL if running instance found. We'll send SIGUSR1 instead.
// If it's running with `-r` or `-d` flag, it'll show the window. If not - it will die.
// Use md5-hashed $USER name to create unique lock files for multiple users
lockFilePath := fmt.Sprintf("%s/nwg-dock-%s.lock", tempDir(), md5Hash(os.Getenv("USER")))
lockFile, err := singleinstance.CreateLockFile(lockFilePath)
if err != nil {
pid, err := readTextFile(lockFilePath)
if err == nil {
i, err := strconv.Atoi(pid)
if err == nil {
if *autohide || *resident {
log.Info("Running instance found, terminating...")
} else {
_ = syscall.Kill(i, syscall.SIGUSR1)
log.Info("Sending SIGUSR1 to running instance and bye, bye!")
}
}
}
os.Exit(0)
}
defer lockFile.Close()
if !*noLauncher && *launcherCmd == "" {
if isCommand("nwg-drawer") {
*launcherCmd = "nwg-drawer"
} else if isCommand("nwggrid") {
*launcherCmd = "nwggrid -p"
}
if *launcherCmd != "" {
log.Infof("Using auto-detected launcher command: '%s'", *launcherCmd)
} else {
log.Info("Neither 'nwg-drawer' nor 'nwggrid' command found, and no other launcher specified; hiding the launcher button.")
}
}
dataHome = getDataHome()
configDirectory = configDir()
// if it doesn't exist:
createDir(configDirectory)
if !pathExists(fmt.Sprintf("%s/style.css", configDirectory)) {
err := copyFile(filepath.Join(dataHome, "nwg-dock/style.css"), fmt.Sprintf("%s/style.css", configDirectory))
if err != nil {
log.Warnf("Error copying file: %s", err)
}
}
cacheDirectory := cacheDir()
if cacheDirectory == "" {
log.Panic("Couldn't determine cache directory location")
}
pinnedFile = filepath.Join(cacheDirectory, "nwg-dock-pinned")
cssFile := filepath.Join(configDirectory, *cssFileName)
appDirs = getAppDirs()
gtk.Init(nil)
cssProvider, _ := gtk.CssProviderNew()
err = cssProvider.LoadFromPath(cssFile)
if err != nil {
log.Warnf("%s file not found, using GTK styling\n", cssFile)
} else {
log.Printf("Using style: %s\n", cssFile)
screen, _ := gdk.ScreenGetDefault()
gtk.AddProviderForScreen(screen, cssProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
}
win, err = gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
if err != nil {
log.Fatal("Unable to create window:", err)
}
layershell.InitForWindow(win)
var output2mon map[string]*gdk.Monitor
if *targetOutput != "" {
// We want to assign layershell to a monitor, but we only know the output name!
output2mon, err = mapOutputs()
if err == nil {
layershell.SetMonitor(win, output2mon[*targetOutput])
} else {
log.Warn(fmt.Sprintf("%s", err))
}
}
if *exclusive {
layershell.AutoExclusiveZoneEnable(win)
*layer = "top"
}
if *position == "bottom" || *position == "top" {
if *position == "bottom" {
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_BOTTOM, true)
widgetAnchor = gdk.GDK_GRAVITY_NORTH
menuAnchor = gdk.GDK_GRAVITY_SOUTH
} else {
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_TOP, true)
widgetAnchor = gdk.GDK_GRAVITY_SOUTH
menuAnchor = gdk.GDK_GRAVITY_NORTH
}
outerOrientation = gtk.ORIENTATION_VERTICAL
innerOrientation = gtk.ORIENTATION_HORIZONTAL
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_LEFT, *full)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_RIGHT, *full)
}
if *position == "left" {
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_LEFT, true)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_TOP, *full)
layershell.SetAnchor(win, layershell.LAYER_SHELL_EDGE_BOTTOM, *full)
outerOrientation = gtk.ORIENTATION_HORIZONTAL
innerOrientation = gtk.ORIENTATION_VERTICAL
widgetAnchor = gdk.GDK_GRAVITY_EAST
menuAnchor = gdk.GDK_GRAVITY_WEST
}
if *layer == "top" {
layershell.SetLayer(win, layershell.LAYER_SHELL_LAYER_TOP)
} else if *layer == "bottom" {
layershell.SetLayer(win, layershell.LAYER_SHELL_LAYER_BOTTOM)
} else {
layershell.SetLayer(win, layershell.LAYER_SHELL_LAYER_OVERLAY)
layershell.SetExclusiveZone(win, -1)
}
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_TOP, *marginTop)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_LEFT, *marginLeft)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_RIGHT, *marginRight)
layershell.SetMargin(win, layershell.LAYER_SHELL_EDGE_BOTTOM, *marginBottom)
win.Connect("destroy", func() {
gtk.MainQuit()
})
// Close the window on leave, but not immediately, to avoid accidental closes
win.Connect("leave-notify-event", func() {
if *autohide {
src = glib.TimeoutAdd(uint(1000), func() bool {
win.Hide()
src = 0
return false
})
}
})
win.Connect("enter-notify-event", func() {
cancelClose()
})
outerBox, _ := gtk.BoxNew(outerOrientation, 0)
_ = outerBox.SetProperty("name", "box")
win.Add(outerBox)
alignmentBox, _ := gtk.BoxNew(innerOrientation, 0)
outerBox.PackStart(alignmentBox, true, true, 0)
mainBox, _ = gtk.BoxNew(innerOrientation, 0)
// We'll pack mainBox later, in buildMainBox
tasks, err := listTasks()
if err != nil {
log.Fatal("Couldn't list tasks:", err)
}
oldTasks = tasks
var oldWsNum int64
buildMainBox(tasks, alignmentBox)
refreshMainBox := func(currentTasks []task, forceRefresh bool) {
if forceRefresh || (len(currentTasks) != len(oldTasks) || currentWsNum != oldWsNum) {
glib.TimeoutAdd(0, func() bool {
log.Debug("refreshing...")
buildMainBox(currentTasks, alignmentBox)
oldTasks = currentTasks
oldWsNum = currentWsNum
targetWsNum = currentWsNum
return false
})
}
}
go func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
taskChannel, err := getTaskChangesChannel(ctx)
if err != nil {
log.Fatal("Unable to process sway tasks:", err)
}
for {
select {
// Refresh if any pin/unpin action happened
case <-refreshMainBoxChannel:
currentTasks, err := listTasks()
if err != nil {
log.Fatal("Unable to retrieve task list from sway!")
}
refreshMainBox(currentTasks, true)
// Refresh if the state of the workspace changes
case currentTasks := <-taskChannel:
refreshMainBox(currentTasks, false)
}
}
}()
win.ShowAll()
if *autohide {
glib.TimeoutAdd(uint(500), win.Hide)
mRefProvider, _ := gtk.CssProviderNew()
if err := mRefProvider.LoadFromPath(filepath.Join(dataHome, "nwg-dock/hotspot.css")); err != nil {
log.Errorf("%s", err)
}
if *targetOutput == "" {
// hot spots on all displays
monitors, _ := listMonitors()
for _, monitor := range monitors {
win := setupHotSpot(monitor, win)
ctx, _ := win.GetStyleContext()
ctx.AddProvider(mRefProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
win.ShowAll()
}
} else {
// hot spot on the selected display only
monitor := output2mon[*targetOutput]
win := setupHotSpot(*monitor, win)
ctx, _ := win.GetStyleContext()
ctx.AddProvider(mRefProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
win.ShowAll()
}
}
go func() {
for {
windowState := <-windowStateChannel
glib.TimeoutAdd(0, func() bool {
if windowState == WindowShow && win != nil && !win.IsVisible() {
win.ShowAll()
}
if windowState == WindowHide && win != nil && win.IsVisible() {
win.Hide()
}
return false
})
}
}()
gtk.Main()
}