summaryrefslogtreecommitdiff
path: root/init.go
blob: 871dbd6ea5a97e6e9c4d43cb9abfede856b503e5 (plain)
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0

// Copyright 2014 The gocui Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"os"
	"runtime"
	"runtime/debug"
	"runtime/pprof"
	"strconv"
	"strings"
	"time"

	"github.com/awesome-gocui/gocui"
	"go.wit.com/log"
	"go.wit.com/toolkits/tree"
)

// sent via -ldflags
var VERSION string
var BUILDTIME string

var PLUGIN string = "gocui"

// this is called at the very initial connection
// between the app and this gocui plugin
// this is a good place to initialize gocui's default behavior
func toolkitInit() {
	log.Log(INFO, "gocui toolkitInit() me.ok =", me.ok)
	if me.baseGui == nil {
		log.Info("gocui baseGui is still nil")
		standardExit()
	}
	if me.treeRoot == nil {
		log.Info("gocui treeRoot is still nil")
		standardExit()
	}
	// w := me.treeRoot.TK.(*guiWidget)
	// w.dumpTree("MM")
	// w.dumpWindows("WW")

	// SETUP HELP START
	me.baseGui.Update(testRefresh)
	log.Log(INFO, "gocui toolkitInit() trying showHelp() me.ok =", me.ok)
	showHelp()
	hideHelp()
	// SETUP HELP END

	// SETUP STDOUT START
	if me.stdout.tk == nil {
		makeOutputWidget(me.baseGui, "from setThingsOnTop()")
	}

	// time.Sleep(300 * time.Millisecond)
	log.Log(INFO, "gocui toolkitInit() me.ok =", me.ok)
	me.baseGui.Update(testRefresh)
	if !me.stdout.init {
		log.Log(INFO, "gocui toolkitInit() stdout.Init me.ok =", me.ok)
		me.stdout.init = true
		relocateStdoutOffscreen()
	}
	// time.Sleep(1 * time.Second)
	me.stdout.outputOnTop = false
	setThingsOnTop()
	// SETUP STDOUT END

	// SETUP BG
	if me.BG.tk == nil {
		me.BG.tk = makeNewInternalWidget(me.BG.wId)
	}

	// SETUP libnotify clock and menu
	me.notify.clock.once.Do(makeNotifyClock)
	me.notify.icon.once.Do(makeNotifyIcon)

	// TODO: for some reason, this makes the background doesn't display
	// PUT INIT DEBUG COOE HERE
	var toggle bool
	for i := 0; i < 4; i++ {
		// enable this to show early debugging
		// w := me.treeRoot.TK.(*guiWidget)
		// w.dumpTree("MM")
		// w.dumpWindows("WW")

		time.Sleep(100 * time.Millisecond)
		if toggle {
			toggle = false
			// log.Info("gocui toolkitInit() put testing true stuff here")
		} else {
			toggle = true
			// log.Info("gocui toolkitInit() put testing false stuff here")
		}
		setBottomBG()
	}
	// PUT INIT DEBUG COOE HERE END

	// TEST TEXTBOX START
	// time.Sleep(1 * time.Second)
	log.Log(INFO, "gocui toolkitInit() me.ok =", me.ok)
	me.baseGui.Update(testRefresh)
	if me.textbox.tk == nil {
		log.Log(INFO, "gocui toolkitInit() initTextbox me.ok =", me.ok)
		initTextbox()
	}
	// TEST TEXTBOX END
}

func toolkitClose() {
	me.baseGui.Close()
}

// a GO GUI plugin should initTree in init()
// this should be done before the application
// starts trying to open up a channel
func init() {
	me.myTree = initTree()

}

// sets defaults and establishes communication
// to this toolkit from the wit/gui golang package
func initPlugin() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(me.outf, "PANIC: initPlugin() recovered %v\n", r)
			return
		}
	}()

	var err error

	// read in defaults from config protobuf
	if val, err := me.myTree.ConfigFind("stdout"); err == nil {
		if val == "true" {
			me.stdout.startOnscreen = true
			// me.stdout.Write([]byte("starting with stdout onscreen\n"))
		}
		if val == "disable" {
			log.Log(INFO, "gocui: attempt to COMPLETELY DISABLE STDOUT LOG")
			me.stdout.disable = true
		}
	}
	if val, err := me.myTree.ConfigFind("stdoutoffscreen"); err == nil {
		if val == "false" {
			// log.Log(NOW, "gocui: START ON SCREEN TRUE")
			me.stdout.startOnscreen = true
		}
	}
	if val, err := me.myTree.ConfigFind("dark"); err == nil {
		if val == "true" {
			me.dark = true
		}
	} else {
		// macos iterm2 really only works with dark mode right now
		if runtime.GOOS == "macos" {
			me.dark = true
		}
	}
	// todo: make this a tmp file that goes away
	if !me.stdout.disable {
		tmpFile, err := os.CreateTemp("", "gocui-*.log")
		if err != nil {
			fmt.Println("Error creating temp file:", err)
			standardExit()
		}
		// defer os.Remove(tmpFile.Name())

		log.Log(INFO, "stdout.disable == true. writing to", tmpFile.Name())
		me.outf = tmpFile
		// todo: some early output still goes to the /tmp/ file
		//time.Sleep(200 * time.Millisecond)
		log.CaptureMode(me.stdout)
	}
	me.starttime = time.Now()
	log.Log(INFO, "Init() of awesome-gocui")

	// init the config struct default values
	Set(&me, "default")

	// initial app window settings

	// initial stdout window settings
	me.stdout.w = 180
	me.stdout.h = 40
	me.stdout.lastW = 4
	me.stdout.lastH = 20

	if val, err := me.myTree.ConfigFind("stdoutsize"); err == nil {
		parts := strings.Fields(val)
		if len(parts) == 4 {
			log.Info("initial stdout settings:", parts, "setting startOnscreen = true")
			me.stdout.w, _ = strconv.Atoi(parts[0])
			me.stdout.h, _ = strconv.Atoi(parts[1])
			me.stdout.lastW, _ = strconv.Atoi(parts[2])
			me.stdout.lastH, _ = strconv.Atoi(parts[3])
			me.stdout.startOnscreen = true
		} else {
			log.Info("initial stdout settings parse error:", parts)
		}
	}

	// just make up unique values for these
	me.dropdown.wId = -77
	me.textbox.wId = -55
	me.stdout.wId = -4
	me.BG.wId = -22

	// the clock widget id and offset
	me.notify.clock.wId = -5
	me.notify.clock.offsetW = 13
	me.notify.clock.offsetH = 1

	me.notify.icon.wId = -6
	me.notify.icon.offsetW = 4
	me.notify.icon.offsetH = 1

	me.notify.help.wId = -7
	me.notify.help.offsetH = 3

	Set(&me.dropdown, "default")
	// s := fmt.Sprintln("fake default check =", me.FakeW, "dropdown.Id", me.dropdown.Id)
	// me.stdout.Write([]byte(s))

	me.mouse.mouseUp = true
	me.mouse.clicktime = time.Millisecond * 200
	me.mouse.doubletime = time.Millisecond * 400

	me.newWindowTrigger = make(chan *guiWidget, 1)
	go newWindowTrigger()
	go refreshGocui()

	log.Log(NOW, "Init() start pluginChan")
	if me.stdout.disable {
		log.Info("Using STDOUT")
	} else {
		log.Info("Using gocui STDOUT")
		os.Stdout = me.outf
		log.CaptureMode(me.outf)
	}

	// init gocui
	g, err := gocui.NewGui(gocui.OutputNormal, true)
	if err != nil {
		os.Exit(-1)
		return
	}
	me.baseGui = g
	g.Cursor = true
	g.Mouse = true

	// this sets the function that is run on every event. For example:
	// When you click the mouse, move the mouse, or press a key on the keyboard
	// This is equivalent to xev or similar to cat /dev/input on linux
	g.SetManagerFunc(gocuiEvent)

	// register how the 'gocui' will work as a GO toolkit plugin
	// all applications will use these keys. they are universal.
	// registered event handlers still have the events sent to gocuiEvent() above
	registerHandlers(g)

	time.Sleep(100 * time.Millisecond)

	if me.outf != nil {
		fmt.Fprintln(me.outf, "hello world", time.Since(me.starttime))
	}

	// coreStdout()
	// createStdout(g)
	// tell 'tree' that we are okay to start talking to
	me.myTree.InitOK()
	me.ok = true // this tells init() it's okay to work with gocui

	go gocuiMain()
}

// This goroutine sits in gocui's MainLoop()
func gocuiMain() {
	defer func() {
		if r := recover(); r != nil {
			log.Warn("PANIC ecovered in gocuiMain()", r)
			if me.outf == nil {
				debug.PrintStack()
				pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
				panic(os.Stdout)
			} else {
				fmt.Fprintf(me.outf, "PANIC recovered in r = %v", r)
				os.Stderr = me.outf
				os.Stdout = me.outf
				debug.PrintStack()
				pprof.Lookup("goroutine").WriteTo(me.outf, 1)
				panic(me.outf)
			}
		}
	}()

	// me.stdout.Write([]byte("begin gogui.MainLoop()\n"))
	if err := me.baseGui.MainLoop(); err != nil && !errors.Is(err, gocui.ErrQuit) {
		log.Log(NOW, "g.MainLoop() panic err =", err)
		// normally panic here
		panic("gocuiTKmainloop OOPS")
	}
}

func standardExit() {
	log.Log(NOW, "standardExit() doing baseGui.Close()")
	me.baseGui.Close()
	if me.outf != nil {
		log.Log(NOW, "standardExit() doing outf.Close()")
		me.outf.Close()
		os.Remove(me.outf.Name())
	}
	// log(true, "standardExit() setOutput(os.Stdout)")
	// setOutput(os.Stdout)
	log.Log(NOW, "standardExit() send back Quit()")
	// go sendBackQuit() // don't stall here in case the
	// induces a delay in case the callback channel is broken
	time.Sleep(200 * time.Millisecond)
	log.Log(NOW, "standardExit() exit()")
	os.Exit(0)
}

func standardClose() {
	log.Log(NOW, "standardExit() doing baseGui.Close()")
	me.baseGui.Close()
	log.Log(NOW, "standardExit() doing outf.Close()")
	me.outf.Close()
	os.Remove(me.outf.Name())
	// os.Stdin = os.Stdin
	// os.Stdout = os.Stdout
	// os.Stderr = os.Stderr
	log.Log(NOW, "standardExit() send back Quit()")
}

func main() {
}

// this hack is to wait for the application to send something
// before trying to do anything. todo: rethink this someday
func waitOK() {
	for {
		if me.ok {
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// this hack is to wait for the application to send something
// before trying to do anything. todo: rethink this someday
func waitFirstWindow() {
	for {
		if me.firstWindowOk {
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// empty function. this triggers gocui to refresh the screen
func testRefresh(*gocui.Gui) error {
	// log.Info("in testRefresh")
	return nil
}

// refresh the screen 10 times a second
func refreshGocui() {
	defer func() {
		if r := recover(); r != nil {
			if me.outf == nil {
				log.Info("INIT PLUGIN recovered in r", r)
			} else {
				fmt.Fprintln(me.outf, "INIT PLUGIN recovered in r", r)
			}
			return
		}
	}()
	var lastRefresh time.Time
	lastRefresh = time.Now()
	me.refresh = false
	for {
		time.Sleep(100 * time.Millisecond)
		// log.Info("refresh checking ok")
		if !me.ok {
			continue
		}

		// redraw the windows if something has changed
		if time.Since(lastRefresh) > 1000*time.Millisecond {
			if me.refresh {
				log.Log(NOW, "newWindowTrigger() sending refresh to channel")
				me.newWindowTrigger <- me.treeRoot.TK.(*guiWidget)
				me.refresh = false
			}
			if me.stdout.changed {
				me.stdout.changed = false
				lastRefresh = time.Now()
				new1 := new(tree.ToolkitConfig)
				new1.Plugin = "gocui"
				new1.Name = "stdoutsize"
				width := me.stdout.tk.gocuiSize.w1 - me.stdout.tk.gocuiSize.w0
				height := me.stdout.tk.gocuiSize.h1 - me.stdout.tk.gocuiSize.h0
				new1.Value = fmt.Sprintf("%d %d %d %d", width, height, me.stdout.tk.gocuiSize.w0, me.stdout.tk.gocuiSize.h0)
				me.myTree.ConfigSave(new1)
				// log.Log(NOW, "newWindowTrigger() gocui setting stdout size =", new1.Value)
				// me.stdout.tk.dumpWidget("save")
			}
		}

		// this code updates the clock
		if time.Since(lastRefresh) > 1000*time.Millisecond {
			// artificially pause clock while dragging.
			// this is a reminder to make this refresh code smarter
			// after the switch to protocol buffers
			me.myTree.Lock()
			if me.mouse.mouseUp {
				// log.Info("refresh now on mouseUp")
				// todo: add logic here to see if the application has changed anything
				libNotifyUpdate()
				lastRefresh = time.Now()
			} else {
				if time.Since(lastRefresh) > 3*time.Second {
					libNotifyUpdate()
					lastRefresh = time.Now()
				}
			}
			me.myTree.Unlock()
		}
	}
}

// set the widget start width & height

func newWindowTrigger() {
	// log.Log(NOW, "newWindowTriggerl() START")
	for {
		// log.Log(NOW, "GO plugin toolkit made a new window")
		select {
		case tk := <-me.newWindowTrigger:
			// log.Log(NOW, "newWindowTrigger() got new window", tk.cuiName)
			// time.Sleep(200 * time.Millisecond)
			waitOK()
			me.myTree.Lock()
			// time.Sleep(200 * time.Millisecond)
			redoWindows(me.FirstWindowW, me.FirstWindowH)
			me.firstWindowOk = true
			if !me.stdout.init {
				me.stdout.init = true
				relocateStdoutOffscreen()
			}
			if me.textbox.tk == nil {
				initTextbox()
			}
			tk.makeWindowActive()
			me.myTree.Unlock()
		}
	}
}