-
Notifications
You must be signed in to change notification settings - Fork 119
/
main.go
executable file
·422 lines (338 loc) · 10.5 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
package main
import (
"errors"
"fmt"
"io/ioutil"
standardLog "log"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/gtk"
"github.com/sirupsen/logrus"
"github.com/Z-Bolt/OctoScreen/logger"
// "github.com/Z-Bolt/OctoScreen/octoprintApis"
"github.com/Z-Bolt/OctoScreen/ui"
"github.com/Z-Bolt/OctoScreen/utils"
"gopkg.in/yaml.v1"
)
var (
BaseURL string
APIKey string
ConfigFile string
Resolution string
initSucceeded bool
)
func init() {
logger.Debug("-")
logger.Debug("-")
logger.TraceEnter("OctoScreen - main.init()")
initSucceeded = false
ConfigFile = os.Getenv(utils.EnvConfigFile)
if ConfigFile == "" {
ConfigFile = findConfigFile()
}
cfg := readConfig(ConfigFile)
if cfg == nil {
initSucceeded = false
return
}
setApiKey(cfg)
setLogLevel()
utils.StylePath = os.Getenv(utils.EnvStylePath)
Resolution = os.Getenv(utils.EnvResolution)
setBaseUrl(cfg)
initSucceeded = true
logger.TraceLeave("OctoScreen - main.init()")
logger.Debug("-")
logger.Debug("-")
}
func main() {
defer func() {
standardLog.Println("main's defer() was called, now calling recover()")
rec := recover();
if rec != nil {
standardLog.Println("main's defer() - recover:", rec)
} else {
standardLog.Println("main's defer() - recover was nil")
}
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
/*
programCounter, fileName, lineNumber, infoWasRecovered := runtime.Caller(2)
standardLog.Println("main's defer() - programCounter:", programCounter)
standardLog.Println("main's defer() - fileName:", fileName)
standardLog.Println("main's defer() - lineNumber:", lineNumber)
standardLog.Println("main's defer() - infoWasRecovered:", infoWasRecovered)
*/
pc := make([]uintptr, 20)
numberOfPcEntries := runtime.Callers(0, pc)
if numberOfPcEntries > 10 {
numberOfPcEntries = 10
}
for i := 1; i < numberOfPcEntries; i++ {
/*
standardLog.Printf("main's defer() - [%d]", i)
standardLog.Printf("main's defer() - [%d]", numberOfPcEntries)
programCounter, fileName, lineNumber, infoWasRecovered := runtime.Caller(i)
standardLog.Printf("main's defer() - programCounter[%d]: %v", i, programCounter)
standardLog.Printf("main's defer() - fileName[%d]: %v", i, fileName)
standardLog.Printf("main's defer() - lineNumber[%d]: %v", i, lineNumber)
standardLog.Printf("main's defer() - infoWasRecovered[%d]: %v", i, infoWasRecovered)
standardLog.Println("")
*/
_, fileName, lineNumber, infoWasRecovered := runtime.Caller(i)
if infoWasRecovered {
standardLog.Printf("main's defer() - [%d] %s, line %d", i, fileName, lineNumber)
}
}
standardLog.Println("main's defer() was called, now exiting func()")
}()
logger.Debug("+")
logger.Debug("+")
logger.TraceEnter("OctoScreen - main.main()")
gtk.Init(nil)
settings, _ := gtk.SettingsGetDefault()
settings.SetProperty("gtk-application-prefer-dark-theme", true)
utils.DumpSystemInformation()
utils.DumpEnvironmentVariables()
setCursor()
if initSucceeded != true {
// readConfig() logs any errors it encounters. Don't display
// the error here, because the error could be long, and we don't
// want to display a long message and have the screen resize.
fatalErrorWindow := ui.CreateFatalErrorWindow(
"Initialization failed:",
"readConfig() failed, see log for errors",
)
fatalErrorWindow.ShowAll()
} else {
if utils.RequiredEnvironmentVariablesAreSet(APIKey) {
width, height, err := getSize()
if err == nil {
// width and height come from EnvResolution/OCTOSCREEN_RESOLUTION
// and aren't required - if not set, ui.New() will use the default
// values (defined in globalVars.go).
_ = ui.New(BaseURL, APIKey, width, height)
} else {
// But if there is an error while parsing OCTOSCREEN_RESOLUTION,
// then display the error.
fatalErrorWindow := ui.CreateFatalErrorWindow(
"getSize() failed",
err.Error(),
)
fatalErrorWindow.ShowAll()
}
} else {
fatalErrorWindow := ui.CreateFatalErrorWindow(
"Required environment variable is not set:",
utils.NameOfMissingRequiredEnvironmentVariable(APIKey),
)
fatalErrorWindow.ShowAll()
}
}
gtk.Main()
logger.TraceLeave("OctoScreen - main.main()")
logger.Debug("+")
logger.Debug("+")
}
func setLogLevel() {
logLevel := strings.ToLower(os.Getenv(utils.EnvLogLevel))
switch logLevel {
case "debug":
logger.SetLogLevel(logrus.DebugLevel)
case "info":
logger.SetLogLevel(logrus.InfoLevel)
case "warn":
logger.SetLogLevel(logrus.WarnLevel)
case "":
logLevel = "error"
os.Setenv(utils.EnvLogLevel, "error")
fallthrough
case "error":
logger.SetLogLevel(logrus.ErrorLevel)
default:
// unknown log level
logLevel = "error"
logger.Errorf("main.setLogLevel() - unknown logLevel: %q, defaulting to error", logLevel)
}
standardLog.Printf("main.SetLogLevel() - logLevel is now set to: %q", logLevel)
}
func setBaseUrl(cfg *config) {
BaseURL = os.Getenv(utils.EnvBaseURL)
if BaseURL == "" {
if cfg.Server.Host != "" {
BaseURL = fmt.Sprintf("http://%s:%d", cfg.Server.Host, cfg.Server.Port)
} else {
BaseURL = "http://0.0.0.0:5000"
}
} else {
url := strings.ToLower(BaseURL)
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
logger.Warn("WARNING! OCTOPRINT_HOST requires the transport protocol ('http://' or 'https://') but is missing. 'http://' is being added to BaseURL.");
BaseURL = fmt.Sprintf("http://%s", BaseURL)
}
}
logger.Infof("main.setBaseUrl() - using %q as server address", BaseURL)
}
func setApiKey(cfg *config) {
logger.TraceEnter("main.setApiKey()")
APIKey = os.Getenv(utils.EnvAPIKey)
if APIKey == "" {
logger.Debug("main.setApiKey() - APIKey is empty, now using cfg.API.Key")
APIKey = cfg.API.Key
}
if APIKey == "" {
logger.Debug("main.setApiKey() - APIKey is empty!")
} else {
obfuscatedApiKey := utils.GetObfuscatedValue(APIKey)
logger.Debugf("main.setApiKey() - APIKey is %q", obfuscatedApiKey)
}
logger.TraceLeave("main.setApiKey()")
}
var (
configLocation = ".octoprint/config.yaml"
homeOctoPi = "/home/pi/"
)
type config struct {
// API Settings.
API struct {
// Key is the current API key needed for accessing the API.
Key string
}
// Server settings.
Server struct {
// Hosts define the host to which to bind the server, defaults to "0.0.0.0".
Host string
// Port define the port to which to bind the server, defaults to 5000.
Port int
}
}
func readConfig(configFile string) *config {
logger.TraceEnter("main.readConfig()")
if configFile == "" {
logger.Info("main.readConfig() - configFile is empty")
logger.TraceLeave("main.readConfig()")
return nil
}
logger.Infof("Path to OctoPrint's config file: %q", configFile)
data, err := ioutil.ReadFile(configFile)
if err != nil {
logger.Errorf("main.readConfig() - ReadFile() returned an error: %q", err)
logger.TraceLeave("main.readConfig()")
return nil
}
cfg := &config{}
if err := yaml.Unmarshal([]byte(data), cfg); err != nil {
logger.Errorf("main.readConfig() - error decoding YAML config file %q: %s", configFile, err)
logger.TraceLeave("main.readConfig()")
return nil
}
if cfg.Server.Host == "" {
cfg.Server.Host = "localhost"
}
logger.Infof("main.readConfig() - server host is: %q", cfg.Server.Host)
if cfg.Server.Port == 0 {
cfg.Server.Port = 5000
}
logger.Infof("main.readConfig() - server port is: %d", cfg.Server.Port)
logger.TraceLeave("main.readConfig()")
return cfg
}
func findConfigFile() string {
logger.TraceEnter("main.findConfigFile()")
if file := doFindConfigFile(homeOctoPi); file != "" {
logger.Info("main.findConfigFile() - doFindConfigFile() found a file")
logger.TraceLeave("main.findConfigFile(), returning the file")
return file
}
usr, err := user.Current()
if err != nil {
logger.LogError("main.findConfigFile()", "Current()", err)
logger.TraceLeave("main.findConfigFile(), returning an empty string")
return ""
}
configFile := doFindConfigFile(usr.HomeDir)
logger.TraceLeave("main.findConfigFile(), returning configFile")
return configFile
}
func doFindConfigFile(home string) string {
logger.TraceEnter("main.doFindConfigFile()")
path := filepath.Join(home, configLocation)
if _, err := os.Stat(path); err == nil {
logger.LogError("main.doFindConfigFile()", "Stat()", err)
logger.TraceLeave("main.doFindConfigFile(), returning path")
return path
}
logger.TraceLeave("main.doFindConfigFile(), returning an empty string")
return ""
}
func getSize() (width int, height int, err error) {
logger.TraceEnter("main.getSize()")
if Resolution == "" {
logger.Info("main.getSize() - Resolution is empty, returning 0 for width and height, and will default to the default values defined in globalVars.go")
logger.TraceLeave("main.getSize()")
return
}
parts := strings.SplitN(Resolution, "x", 2)
if len(parts) != 2 {
logger.Error("main.getSize() - SplitN() - len(parts) != 2")
err = errors.New(fmt.Sprintf("%s is malformed\nvalue: %q", utils.EnvResolution, Resolution))
}
if err == nil {
width, err = strconv.Atoi(parts[0])
if err != nil {
logger.LogError("main.getSize()", "Atoi(parts[0])", err)
err = errors.New(fmt.Sprintf("%s is malformed\nAtoi(0) failed\nvalue: %q", utils.EnvResolution, Resolution))
}
}
if err == nil {
height, err = strconv.Atoi(parts[1])
if err != nil {
logger.LogError("main.getSize()", "Atoi(parts[1])", err)
err = errors.New(fmt.Sprintf("%s is malformed\nAtoi(1) failed\nvalue: %q", utils.EnvResolution, Resolution))
}
}
logger.TraceLeave("main.getSize()")
return
}
func setCursor() {
// For reference, see "How to turn on a pointer"
// https://github.com/Z-Bolt/OctoScreen/issues/285
// and "No mouse pointer when running xinit"
// https://www.raspberrypi.org/forums/viewtopic.php?t=139546
displayCursor := strings.ToLower(os.Getenv("DISPLAY_CURSOR"))
if displayCursor != "true" {
return
}
window, err := getRootWindow()
if err != nil {
return
}
cursor, err := getDefaultCursor()
if err != nil {
return
}
window.SetCursor(cursor)
}
func getRootWindow() (*gdk.Window, error) {
screen, err := gdk.ScreenGetDefault()
if err != nil {
return nil, err
}
window, err := screen.GetRootWindow()
return window, err
}
func getDefaultCursor() (*gdk.Cursor, error) {
display, err := gdk.DisplayGetDefault()
if err != nil {
return nil, err
}
// Examples of the different cursors can be found at
// https://developer.gnome.org/gdk3/stable/gdk3-Cursors.html#gdk-cursor-new-from-name
cursor, err := gdk.CursorNewFromName(display, "default")
return cursor, err
}