Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
269 lines (235 loc) · 5.95 KB
/
Copy pathmain.go
File metadata and controls
269 lines (235 loc) · 5.95 KB
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
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"syscall"
"github.com/BurntSushi/toml"
"go.i3wm.org/i3/v4"
)
type Config struct {
Separator string `toml:"separator"`
Unique bool `toml:"unique"`
Ignore map[string]struct{} `toml:"-"`
IgnoreList []string `toml:"ignore"`
AppNames map[string]string `toml:"app_names"`
}
func loadConfig(path string) (*Config, error) {
var cfg Config
if _, err := toml.DecodeFile(path, &cfg); err != nil {
return nil, err
}
// Convert all keys to lowercase for case-insensitive lookup
lower := make(map[string]string, len(cfg.AppNames))
for k, v := range cfg.AppNames {
lower[strings.ToLower(k)] = v
}
cfg.AppNames = lower
cfg.Ignore = make(map[string]struct{}, len(cfg.IgnoreList))
for _, s := range cfg.IgnoreList {
cfg.Ignore[strings.ToLower(s)] = struct{}{}
}
return &cfg, nil
}
func getDefaultConfigPath() string {
configDir := os.Getenv("XDG_CONFIG_HOME")
if configDir == "" {
if home, err := os.UserHomeDir(); err == nil {
configDir = filepath.Join(home, ".config")
}
}
if configDir == "" {
return ""
}
return filepath.Join(configDir, "i3-glance", "config.toml")
}
func main() {
pathFlag := flag.String("config", "", "path to config file")
flag.Parse()
cfg := &Config{
Separator: "|",
Unique: false,
AppNames: map[string]string{},
}
cfgPath := *pathFlag
if cfgPath == "" {
cfgPath = getDefaultConfigPath()
}
if cfgPath != "" {
c, err := loadConfig(cfgPath)
if err != nil {
if *pathFlag != "" || !errors.Is(err, os.ErrNotExist) {
log.Printf("failed to load config: %v", err)
os.Exit(1)
}
} else {
cfg = c
}
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
log.Println("received shutdown signal, restoring workspace names...")
if err := restoreWorkspaceNames(); err != nil {
log.Printf("failed to restore workspace names: %s", err)
}
os.Exit(0)
}()
for sub := i3.Subscribe(i3.WindowEventType); sub.Next(); {
event := sub.Event()
if winEvent, ok := event.(*i3.WindowEvent); ok {
switch winEvent.Change {
case "move", "new", "title", "close":
err := rename(cfg)
if err != nil {
log.Printf("failed to rename workspaces: %s", err)
}
}
}
}
}
func rename(cfg *Config) error {
wsNum, err := getWorkspaceNumberMap()
if err != nil {
return err
}
tree, err := i3.GetTree()
if err != nil {
return err
}
workspaces := findWorkspace(tree.Root)
commands := make([]string, 0, len(workspaces))
for _, ws := range workspaces {
if ws.Workspace.Name == "__i3_scratch" {
continue
}
num := int64(0)
if n, ok := wsNum[i3.WorkspaceID(ws.Workspace.ID)]; ok {
num = n
} else {
return fmt.Errorf("workspace %s not found in workspace map", ws.Workspace.Name)
}
windowNames := make([]string, 0, len(ws.Windows))
for _, w := range ws.Windows {
name := w.WindowProperties.Class
if _, ok := cfg.Ignore[strings.ToLower(name)]; ok {
continue
}
if nm, ok := cfg.AppNames[strings.ToLower(name)]; ok {
name = nm
}
if cfg.Unique && slices.Contains(windowNames, name) {
continue
}
windowNames = append(windowNames, name)
}
newName := fmt.Sprintf("%d: %s", num, strings.Join(windowNames, cfg.Separator))
if ws.Workspace.Name != newName {
commands = append(commands, buildRenameCommand(ws.Workspace.Name, newName))
}
}
if len(commands) > 0 {
fullCmd := strings.Join(commands, "; ")
_, err := i3.RunCommand(fullCmd)
if err != nil {
return fmt.Errorf("failed to run i3 command: %w", err)
}
}
return nil
}
const (
NodeTypeRoot = "root"
NodeTypeOutput = "output"
NodeTypeWorkspace = "workspace"
NodeTypeCon = "con"
NodeTypeDockArea = "dockarea"
)
type workspaceInfo struct {
Workspace *i3.Node
Windows []*i3.Node
}
func findWorkspace(n *i3.Node) []workspaceInfo {
var result []workspaceInfo
if n.Type != NodeTypeWorkspace {
for _, child := range n.Nodes {
result = append(result, findWorkspace(child)...)
}
return result
}
// This is a workspace node, collect all windows in it.
windows := []*i3.Node{}
for _, child := range n.Nodes {
windows = append(windows, visitWindow(child)...)
}
for _, child := range n.FloatingNodes {
windows = append(windows, visitWindow(child)...)
}
result = append(result, workspaceInfo{
Workspace: n,
Windows: windows,
})
return result
}
func visitWindow(n *i3.Node) []*i3.Node {
if isLeafNode(n) {
return []*i3.Node{n}
}
leaves := []*i3.Node{}
for _, child := range n.Nodes {
leaves = append(leaves, visitWindow(child)...)
}
for _, child := range n.FloatingNodes {
leaves = append(leaves, visitWindow(child)...)
}
return leaves
}
func isLeafNode(n *i3.Node) bool {
return len(n.Nodes) == 0 && len(n.FloatingNodes) == 0 && n.Type == NodeTypeCon
}
func getWorkspaceNumberMap() (map[i3.WorkspaceID]int64, error) {
workspaces, err := i3.GetWorkspaces()
if err != nil {
return nil, err
}
wsNum := map[i3.WorkspaceID]int64{}
for _, w := range workspaces {
wsNum[w.ID] = w.Num
}
return wsNum, nil
}
func buildRenameCommand(oldName, newName string) string {
oldNameEscaped := strings.ReplaceAll(oldName, "\"", "\\\"")
newNameEscaped := strings.ReplaceAll(newName, "\"", "\\\"")
return fmt.Sprintf("rename workspace \"%s\" to \"%s\"", oldNameEscaped, newNameEscaped)
}
func restoreWorkspaceNames() error {
workspaces, err := i3.GetWorkspaces()
if err != nil {
return err
}
commands := make([]string, 0, len(workspaces))
for _, ws := range workspaces {
if ws.Name == "__i3_scratch" {
continue
}
newName := fmt.Sprintf("%d", ws.Num)
if ws.Name != newName {
commands = append(commands, buildRenameCommand(ws.Name, newName))
}
}
if len(commands) > 0 {
fullCmd := strings.Join(commands, "; ")
_, err := i3.RunCommand(fullCmd)
if err != nil {
return fmt.Errorf("failed to run i3 command: %w", err)
}
}
return nil
}