-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
281 lines (233 loc) · 5.74 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
package main
import (
_ "embed"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/emersion/go-autostart"
"github.com/fsnotify/fsnotify"
hook "github.com/robotn/gohook"
"github.com/spf13/cobra"
"github.com/xeipuuv/gojsonschema"
)
//go:embed shortcut.schema.json
var jsonSchema string
type Shortcut struct {
Name string
Keys []string
Command string
HideWindow *bool // Pointer to bool for optional field
}
var installFlag bool
var versionFlag bool
// commit revision will be set during the build process
var rev string
var version = "1.0.0"
func main() {
if runtime.GOOS == "windows" {
attachConsoleIfPossible()
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() {
<-sig
fmt.Println("Received SIGINT. Exiting...")
os.Exit(0)
}()
cobra.MousetrapHelpText = "" // allow running by clicking .exe file from GUI
var rootCmd = &cobra.Command{
Use: "shortcut",
Short: "Shortcuts manager",
Run: run,
}
rootCmd.Flags().BoolVarP(&installFlag, "install", "i", false, "Install the application")
rootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "Get version")
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func handleConfigError(err error) {
fmt.Println("Failed to read config:", err)
os.Exit(1)
}
func setupWatcher(configPath string) (*fsnotify.Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
err = watcher.Add(configPath)
if err != nil {
return nil, err
}
return watcher, nil
}
func blockForever() {
// Block main goroutine forever.
<-make(chan struct{})
}
func run(cmd *cobra.Command, args []string) {
if installFlag {
install()
os.Exit(0)
}
fmt.Printf("🚀 Shortcut version %v (%v)\n", version, rev)
if versionFlag {
os.Exit(0)
}
configPath, err := getConfigPath()
if err != nil {
handleConfigError(err)
}
watcher, err := setupWatcher(*configPath)
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
jsonConfig, err := readConfig(*configPath)
if err != nil {
handleConfigError(err)
}
shortcuts, err := parseShortcuts(jsonConfig)
if err != nil {
fmt.Println("🚨 Unable to parse shortcuts, blocking forever...")
blockForever()
} else {
registerAndWatch(shortcuts, watcher)
}
}
func registerAndWatch(shortcuts []Shortcut, watcher *fsnotify.Watcher) {
registerShortcuts(shortcuts)
s := hook.Start()
go func() {
<-hook.Process(s)
}()
var debounceTimer *time.Timer
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if debounceTimer != nil {
debounceTimer.Stop()
}
debounceTimer = time.AfterFunc(50*time.Millisecond, func() {
handleFileEvent(event, shortcuts)
})
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}
func handleFileEvent(event fsnotify.Event, shortcuts []Shortcut) {
if event.Has(fsnotify.Write) {
fmt.Println("🔥 Hot Reload triggered")
hook.End()
configPath, _ := getConfigPath()
jsonConfig, _ := readConfig(*configPath)
shortcuts, _ := parseShortcuts(jsonConfig)
registerShortcuts(shortcuts)
s := hook.Start()
go func() {
<-hook.Process(s)
}()
}
}
func install() error {
exePath, err := os.Executable()
if err != nil {
fmt.Println("Error getting executable path:", err)
return err
}
app := &autostart.App{
Name: "shortcuts",
DisplayName: "Shortcuts Manager",
Exec: []string{exePath},
}
if app.IsEnabled() {
log.Println("Shortcut already installed, removing it...")
if err := app.Disable(); err != nil {
log.Fatal(err)
}
} else {
log.Printf("Installing shortcut to be run at boot from %v...\n", exePath)
if err := app.Enable(); err != nil {
log.Fatal(err)
}
}
return nil
}
func registerShortcuts(shortcuts []Shortcut) {
for _, shortcut := range shortcuts {
hook.Register(hook.KeyDown, shortcut.Keys, func(e hook.Event) {
fmt.Printf("Shortcut '%s' activated ✅\n", shortcut.Name)
command := strings.Split(shortcut.Command, " ")
cmd := exec.Command(command[0], command[1:]...)
prepareCommand(cmd, shortcut)
if err := cmd.Start(); err != nil {
fmt.Printf("Error executing command for shortcut <%s>: %v\n", shortcut.Name, err)
}
})
}
}
func getConfigPath() (*string, error) {
exePath, err := os.Executable()
if err != nil {
fmt.Println("Error getting executable path:", err)
return nil, err
}
configPath := filepath.Join(filepath.Dir(exePath), "shortcut.conf.json")
if _, err := os.Stat(configPath); err == nil {
return &configPath, nil
}
cwd, err := os.Getwd()
if err != nil {
fmt.Println("Error getting current working directory:", err)
return nil, err
}
configPath = filepath.Join(cwd, "shortcut.conf.json")
if _, err := os.Stat(configPath); err != nil {
return nil, fmt.Errorf("config file not found")
}
return &configPath, nil
}
func readConfig(path string) ([]byte, error) {
jsonConfig, err := os.ReadFile(path)
if err != nil {
fmt.Println("Error reading file:", err)
return nil, err
}
return jsonConfig, nil
}
func parseShortcuts(jsonConfig []byte) ([]Shortcut, error) {
schemaLoader := gojsonschema.NewBytesLoader([]byte(jsonSchema))
documentLoader := gojsonschema.NewBytesLoader([]byte(jsonConfig))
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return nil, err
}
if !result.Valid() {
fmt.Printf("🚨 The JSON data is invalid: %s\n", result.Errors())
return nil, fmt.Errorf("invalid JSON data")
}
var data struct {
Version string `json:"version"`
Shortcuts []Shortcut `json:"shortcuts"`
}
err = json.Unmarshal([]byte(jsonConfig), &data)
if err != nil {
return nil, err
}
return data.Shortcuts, nil
}