-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacme-focused.go
111 lines (96 loc) · 2.12 KB
/
acme-focused.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
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"9fans.net/go/acme"
)
// name of the text file generated
const logName = "acme-focused"
type focusedWin struct {
id int
mu sync.Mutex
}
// open acme's log and save it's $winid to fw.id everytime a "focus" event happens
func (fw *focusedWin) readLog() {
alog, err := acme.Log()
if err != nil {
log.Fatalf("failed to open acmelog: %v\n", err)
}
defer alog.Close()
for {
time.Sleep(2 * time.Second)
ev, err := alog.Read()
if err != nil {
log.Fatalf("failed to read log: %v\n", err)
}
if ev.Op == "focus" {
fw.mu.Lock()
fw.id = ev.ID
fw.mu.Unlock()
}
}
}
// makes the final path of the temporary file
func makeFilePath(path *string) {
sepIndex := strings.LastIndex(*path, "/")
if sepIndex != len(*path)-1 {
*path += "/"
}
*path += logName
}
// returns the current window ID
func (fw *focusedWin) ID() int {
fw.mu.Lock()
defer fw.mu.Unlock()
return fw.id
}
// func writeId(path string, id int) {
func writeId(path string, fw *focusedWin) {
lastVal := 0
makeFilePath(&path)
for {
if lastVal != fw.ID() {
lastVal = fw.ID()
/*
use os.WriteFile because it overwrites the previous text entered,
as opposed to a, say, os.Create and fmt.Fprintf(), which would
just append strings to the previous data entered
*/
err := os.WriteFile(path, []byte(strconv.Itoa(fw.ID())+"\n"), 0666)
if err != nil {
log.Fatalf("couldn't open/write file at '%s': %s", path, err)
}
}
}
}
func usage() {
fmt.Printf("Usage:\nacme-focused [-h, --h] [path]\n")
fmt.Printf("-h, --h: prints this message\n")
fmt.Printf("path: directory to store the file, defaults to /tmp/ if left blank\n")
os.Exit(1)
}
func main() {
var fw focusedWin
var path string
argLen := len(os.Args)
if argLen > 2 {
usage()
} else if argLen <= 1 {
path = os.TempDir()
} else if os.Args[1] == "-h" || os.Args[1] == "--h" {
usage()
} else {
path = os.Args[1]
}
_, err := os.ReadDir(path) // check if directory exists
if err != nil {
log.Fatalf("failed to open directory: '%s'\n", err)
}
go fw.readLog()
writeId(path, &fw)
}