-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
340 lines (300 loc) · 9.22 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
package main
import (
"embed"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"linux-windows-switcher/appindicator"
"linux-windows-switcher/gui"
"linux-windows-switcher/keyboard"
"linux-windows-switcher/libs/glibown"
"linux-windows-switcher/libs/xlib"
"github.com/Xuanwo/go-locale"
"github.com/bigkevmcd/go-configparser"
"github.com/chigopher/pathlib"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
// Main struct, it has the main components of the application
type mainApplication struct {
application *gtk.Application
appIndicator *appindicator.Indicator
gui *gui.MainGUI
config *configparser.ConfigParser
keyboardListener *keyboard.ListenerKeyboard
}
// Constructor mainApplication
func newApplication(application *gtk.Application) *mainApplication {
return &mainApplication{application: application}
}
// This function is for configuration where all the custom signals are created and their callbacks.
// Callback of "startup" signal of the application.
func (app *mainApplication) startup() {
app.config = configparser.New()
if result, _ := configFile.IsFile(); result {
config, err := configparser.NewConfigParserFromFile(configFile.String())
if err == nil {
app.config = config
}
}
// --------------------------------- APPLICATION CUSTOM SIGNALS -----------------------------
// Signal to open main window
_, _ = glib.SignalNew("app-open-window")
// Handler
app.application.Connect("app-open-window", func(application *gtk.Application) {
app.gui.PresentWindow()
})
// Signal to restart application
_, _ = glib.SignalNew("app-restart")
// Handler
app.application.Connect("app-restart", func(application *gtk.Application) {
application.Quit()
command := fmt.Sprintf("'%s' %s", getPathExecutbale(false), strings.Join(os.Args[1:], " "))
fmt.Println(command)
_ = exec.Command("bash", "-c", command).Start()
})
// Signal to close app
_, _ = glib.SignalNew("app-exit")
// Handler
app.application.Connect("app-exit", func(application *gtk.Application) {
keyboard.ExitListener()
xlib.CloseDisplay() // Close connection to X server
application.Quit()
})
// Signal to get data from config file
_, _ = glibown.SignalNewV(
"app-get-config",
glib.TYPE_STRING,
2,
glib.TYPE_STRING,
glib.TYPE_STRING,
)
// Handler
app.application.Connect(
"app-get-config",
func(application *gtk.Application, section string, option string) string {
result := ""
if exists, _ := app.config.HasOption(section, option); exists {
result, _ = app.config.Get(section, option)
result = strings.ReplaceAll(result, " ", "")
}
return result
},
)
// Signal to update config file
_, _ = glibown.SignalNewV(
"app-update-config",
glib.TYPE_BOOLEAN,
3,
glib.TYPE_STRING,
glib.TYPE_STRING,
glib.TYPE_STRING,
)
// Handler
app.application.Connect(
"app-update-config",
func(application *gtk.Application, section string, option string, value string) bool {
err := app.updateConfig(section, option, value)
return err == nil
},
)
// Signal to synchronize the keyboard listener's state with the UI and AppIndicator
_, _ = glibown.SignalNewV("app-listener-sync-state", glib.TYPE_NONE, 1, glib.TYPE_BOOLEAN)
// Handler
app.application.Connect(
"app-listener-sync-state",
func(application *gtk.Application, state bool) {
app.gui.UpdateListenerState(state)
app.appIndicator.UpdateIconState(state)
},
)
// Signal to manage the keyboard listener
_, _ = glibown.SignalNewV(
"app-listener-keyboard",
glib.TYPE_NONE,
2,
glib.TYPE_BOOLEAN,
glib.TYPE_BOOLEAN,
)
// Signal to stabligh the global hotkey
_, _ = glib.SignalNew("app-listener-set-hotkeys")
// Signal to stablish the new windows order
_, _ = glibown.SignalNewV(
"app-set-order",
glib.TYPE_NONE,
3,
glib.TYPE_BOOLEAN,
glib.TYPE_BOOLEAN,
glib.TYPE_BOOLEAN,
)
// Signal to delete a window from the order
_, _ = glibown.SignalNewV("app-delete-window-order", glib.TYPE_NONE, 1, glib.TYPE_STRING)
}
// Callback of signal "activate" of the application
// This function initializes the UI and the app if it hasn't started yet otherwise it shows the main window
func (app *mainApplication) activate() {
if app.gui == nil {
app.keyboardListener = keyboard.NewListenerKeyBoard(app.application)
app.appIndicator = appindicator.NewAppIndicator(
app.application,
[]string{iconFileDisabled.String(), iconFile.String()},
gui.GetTitle(),
getStringResource,
)
app.gui = gui.NewMainGUI(app.application, showWindow, getResource, getStringResource)
} else {
app.gui.PresentWindow()
}
}
// Update config file
func (app *mainApplication) updateConfig(section string, option string, value string) error {
_ = app.config.AddSection(section)
_ = app.config.Set(section, option, value)
return app.config.SaveWithDelimiter(configFile.String(), "=")
}
/*
Function that returns path of executable.
Parameter:
- appimage: Whether to return the path of the APPDIR if it's running from the .AppImage
*/
func getPathExecutbale(appimage bool) string {
pathExecutable := ""
if value, exists := os.LookupEnv("APPIMAGE"); exists {
pathExecutable = value
if appimage {
if value, exists = os.LookupEnv("APPDIR"); exists {
path_ := pathlib.NewPath(value).Join("usr", "src", "linux-windows-switcher")
pathExecutable = path_.String()
}
}
} else {
path, _ := os.Executable()
pathExecutable = path
}
return pathExecutable
}
// Returns a resource from the embed filesystem
func getResource(filename string) []byte {
return func(content []byte, err error) []byte {
return content
}(resources.ReadFile(filepath.Join(resourcesFolderName, filename)))
}
// Returns a string using localizer
func getStringResource(id string) string {
msg, err := localizer.LocalizeMessage(&i18n.Message{ID: id})
if err != nil {
return ""
}
return msg
}
// Constants
const (
appId = "ahsand97.linux-windows-switcher-gotk3"
configFileName = "linux-windows-switcher-config.ini"
resourcesFolderName = "resources"
iconFileName = "tabs.png"
iconDisabledFileName = "tabs-disabled.png"
)
//go:embed resources/*
var resources embed.FS
// Globals
var (
configFile *pathlib.Path
iconFile *pathlib.Path
iconFileDisabled *pathlib.Path
showWindow = true
localizer *i18n.Localizer
)
// Function that sets-up the locale configuration
func initLocalization() {
// Default language
defaultLanguage := language.English
// Bundle
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
// String resources
stringResources := map[language.Tag]string{}
stringResources[language.English] = "strings-en.json"
stringResources[language.Spanish] = "strings-es.json"
stringResources[language.French] = "strings-fr.json"
// Load string resources
for language, stringResource := range stringResources {
messageFile, _ := bundle.LoadMessageFileFS(resources, filepath.Join(resourcesFolderName, stringResource))
_ = bundle.AddMessages(language, messageFile.Messages...)
}
// Languages
languages := []string{}
// Get current locale
tag, _ := locale.Detect()
currentLanguage, _ := tag.Base()
currentLanguageStr := currentLanguage.String()
languages = append(languages, currentLanguageStr)
// Get all allowed locales
tags, _ := locale.DetectAll()
for _, tag_ := range tags {
lang, _ := tag_.Base()
if lang.String() == currentLanguage.String() {
continue
}
langStr := lang.String()
languages = append(languages, langStr)
}
defaultLanguageAdded := false
for _, lang := range languages {
if lang == defaultLanguage.String() {
defaultLanguageAdded = true
break
}
}
if !defaultLanguageAdded {
languages = append(languages, defaultLanguage.String())
}
// Supported languages
supportedLanguages := []string{}
for _, lang := range languages {
for tag := range stringResources {
if tag.String() == lang {
supportedLanguages = append(supportedLanguages, lang)
break
}
}
}
// New localizer to get strings based on locale language
localizer = i18n.NewLocalizer(bundle, supportedLanguages...)
}
func main() {
var args []string
for index, value := range os.Args {
if value == "--hide" {
showWindow = false
} else {
args = append(args, os.Args[index])
}
}
// Init Localization
initLocalization()
// App creation
application, err := gtk.ApplicationNew(appId, glib.APPLICATION_FLAGS_NONE)
if err != nil {
log.Fatal("An error occurred creating the application. ", err)
}
xlib.OpenDisplay() // Open connection to X server
glib.SetPrgname(appId) // Setting the property "WM_CLASS"
configFile = pathlib.NewPath(getPathExecutbale(false)).Parent().Join(configFileName)
iconFile = pathlib.NewPath(getPathExecutbale(true)).Parent().Join(resourcesFolderName, iconFileName)
iconFileDisabled = pathlib.NewPath(getPathExecutbale(true)).Parent().Join(resourcesFolderName, iconDisabledFileName)
mainApplication := newApplication(application)
mainApplication.application.Connect("startup", func(application *gtk.Application) {
mainApplication.startup()
})
mainApplication.application.Connect("activate", func(application *gtk.Application) {
mainApplication.activate()
})
mainApplication.application.Run(args)
}