forked from aarzilli/nucular
/
shiny.go
497 lines (420 loc) · 10.9 KB
/
shiny.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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package nucular
import (
"bytes"
"errors"
"fmt"
"image"
"image/draw"
"io"
"os"
"sync"
"sync/atomic"
"time"
"github.com/Varunram/nucular/clipboard"
"github.com/Varunram/nucular/command"
"github.com/Varunram/nucular/rect"
nstyle "github.com/Varunram/nucular/style"
"golang.org/x/exp/shiny/driver"
"golang.org/x/exp/shiny/screen"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"golang.org/x/mobile/event/key"
"golang.org/x/mobile/event/lifecycle"
"golang.org/x/mobile/event/mouse"
"golang.org/x/mobile/event/paint"
"golang.org/x/mobile/event/size"
)
//go:generate go-bindata -o internal/assets/assets.go -pkg assets DroidSansMono.ttf
const perfUpdate = false
var UnknownCommandErr = errors.New("unknown command")
var clipboardStarted bool = false
var clipboardMu sync.Mutex
type MasterWindow interface {
context() *context
Main()
Changed()
Close()
Closed() bool
ActivateEditor(ed *TextEditor)
Style() *nstyle.Style
SetStyle(*nstyle.Style)
GetPerf() bool
SetPerf(bool)
PopupOpen(title string, flags WindowFlags, rect rect.Rect, scale bool, updateFn UpdateFn)
}
type masterWindow struct {
Title string
screen screen.Screen
wnd screen.Window
wndb screen.Buffer
bounds image.Rectangle
initialSize image.Point
// show performance counters
Perf bool
// window is focused
Focus bool
ctx *context
layout panel
prevCmds []command.Command
textbuffer bytes.Buffer
uilock sync.Mutex
closing bool
focusedOnce bool
}
func NewMasterWindow(flags WindowFlags, title string, updatefn UpdateFn) MasterWindow {
return NewMasterWindowSize(flags, title, image.Point{640, 480}, updatefn)
}
// Creates new master window
func NewMasterWindowSize(flags WindowFlags, title string, sz image.Point, updatefn UpdateFn) MasterWindow {
ctx := &context{}
ctx.Input.Mouse.valid = true
wnd := &masterWindow{ctx: ctx}
wnd.layout.Flags = flags
wnd.Title = title
wnd.initialSize = sz
clipboardMu.Lock()
if !clipboardStarted {
clipboardStarted = true
clipboard.Start()
}
clipboardMu.Unlock()
ctx.setupMasterWindow(&wnd.layout, updatefn)
ctx.mw = wnd
wnd.SetStyle(nstyle.FromTheme(nstyle.DefaultTheme, 1.0))
return wnd
}
// Shows window, runs event loop
func (mw *masterWindow) Main() {
driver.Main(mw.main)
}
func (mw *masterWindow) context() *context {
return mw.ctx
}
func (mw *masterWindow) main(s screen.Screen) {
var err error
mw.screen = s
width, height := mw.ctx.scale(mw.initialSize.X), mw.ctx.scale(mw.initialSize.Y)
mw.wnd, err = s.NewWindow(&screen.NewWindowOptions{width, height, mw.Title})
if err != nil {
fmt.Fprintf(os.Stderr, "could not create window: %v", err)
return
}
mw.setupBuffer(image.Point{width, height})
mw.Changed()
go mw.updater()
for {
ei := mw.wnd.NextEvent()
mw.uilock.Lock()
r := mw.handleEventLocked(ei)
mw.uilock.Unlock()
if !r {
break
}
}
}
func (w *masterWindow) handleEventLocked(ei interface{}) bool {
switch e := ei.(type) {
case paint.Event:
// On darwin we must respond to a paint.Event by reuploading the buffer or
// the appplication will freeze.
// On windows when the window goes off screen part of the window contents
// will be discarded and must be redrawn.
w.prevCmds = w.prevCmds[:0]
w.updateLocked()
case lifecycle.Event:
if e.Crosses(lifecycle.StageDead) == lifecycle.CrossOn || e.To == lifecycle.StageDead || w.closing {
w.closing = true
w.closeLocked()
return false
}
c := false
switch cross := e.Crosses(lifecycle.StageFocused); cross {
case lifecycle.CrossOn:
if !w.focusedOnce {
// on linux uploads that happen before this event don't get displayed
// for some reason, force a reupload
w.focusedOnce = true
w.prevCmds = w.prevCmds[:0]
}
w.Focus = true
c = true
case lifecycle.CrossOff:
w.Focus = false
c = true
}
if c {
if changed := atomic.LoadInt32(&w.ctx.changed); changed < 2 {
atomic.StoreInt32(&w.ctx.changed, 2)
}
}
case size.Event:
sz := e.Size()
bb := w.wndb.Bounds()
if sz.X <= bb.Dx() && sz.Y <= bb.Dy() {
w.bounds = w.wndb.Bounds()
w.bounds.Max.Y = w.bounds.Min.Y + sz.Y
w.bounds.Max.X = w.bounds.Min.X + sz.X
} else {
if w.wndb != nil {
w.wndb.Release()
}
w.setupBuffer(sz)
}
w.prevCmds = w.prevCmds[:0]
if changed := atomic.LoadInt32(&w.ctx.changed); changed < 2 {
atomic.StoreInt32(&w.ctx.changed, 2)
}
case mouse.Event:
changed := atomic.LoadInt32(&w.ctx.changed)
if changed < 2 {
atomic.StoreInt32(&w.ctx.changed, 2)
}
switch e.Direction {
case mouse.DirStep:
switch e.Button {
case mouse.ButtonWheelUp:
w.ctx.Input.Mouse.ScrollDelta++
case mouse.ButtonWheelDown:
w.ctx.Input.Mouse.ScrollDelta--
}
case mouse.DirPress, mouse.DirRelease:
down := e.Direction == mouse.DirPress
if e.Button >= 0 && int(e.Button) < len(w.ctx.Input.Mouse.Buttons) {
btn := &w.ctx.Input.Mouse.Buttons[e.Button]
if btn.Down == down {
break
}
if down {
btn.ClickedPos.X = int(e.X)
btn.ClickedPos.Y = int(e.Y)
}
btn.Clicked = true
btn.Down = down
}
case mouse.DirNone:
w.ctx.Input.Mouse.Pos.X = int(e.X)
w.ctx.Input.Mouse.Pos.Y = int(e.Y)
w.ctx.Input.Mouse.Delta = w.ctx.Input.Mouse.Pos.Sub(w.ctx.Input.Mouse.Prev)
}
case key.Event:
changed := atomic.LoadInt32(&w.ctx.changed)
if changed < 2 {
atomic.StoreInt32(&w.ctx.changed, 2)
}
w.ctx.processKeyEvent(e, &w.textbuffer)
}
return true
}
func (ctx *context) processKeyEvent(e key.Event, textbuffer *bytes.Buffer) {
if e.Direction == key.DirRelease {
return
}
evinNotext := func() {
for _, k := range ctx.Input.Keyboard.Keys {
if k.Code == e.Code {
k.Modifiers |= e.Modifiers
return
}
}
ctx.Input.Keyboard.Keys = append(ctx.Input.Keyboard.Keys, e)
}
evinText := func() {
if e.Modifiers == 0 || e.Modifiers == key.ModShift {
io.WriteString(textbuffer, string(e.Rune))
}
evinNotext()
}
switch {
case e.Code == key.CodeUnknown:
if e.Rune > 0 {
evinText()
}
case (e.Code >= key.CodeA && e.Code <= key.Code0) || e.Code == key.CodeSpacebar || e.Code == key.CodeHyphenMinus || e.Code == key.CodeEqualSign || e.Code == key.CodeLeftSquareBracket || e.Code == key.CodeRightSquareBracket || e.Code == key.CodeBackslash || e.Code == key.CodeSemicolon || e.Code == key.CodeApostrophe || e.Code == key.CodeGraveAccent || e.Code == key.CodeComma || e.Code == key.CodeFullStop || e.Code == key.CodeSlash || (e.Code >= key.CodeKeypadSlash && e.Code <= key.CodeKeypadPlusSign) || (e.Code >= key.CodeKeypad1 && e.Code <= key.CodeKeypadEqualSign):
evinText()
case e.Code == key.CodeTab:
e.Rune = '\t'
evinText()
case e.Code == key.CodeReturnEnter || e.Code == key.CodeKeypadEnter:
e.Rune = '\n'
evinText()
default:
evinNotext()
}
}
func (w *masterWindow) updater() {
for {
time.Sleep(20 * time.Millisecond)
func() {
w.uilock.Lock()
defer w.uilock.Unlock()
if w.closing {
return
}
changed := atomic.LoadInt32(&w.ctx.changed)
if changed > 0 {
atomic.AddInt32(&w.ctx.changed, -1)
w.updateLocked()
} else {
down := false
for _, btn := range w.ctx.Input.Mouse.Buttons {
if btn.Down {
down = true
}
}
if down {
w.updateLocked()
}
}
}()
}
}
// Forces an update of the window.
func (mw *masterWindow) Changed() {
atomic.AddInt32(&mw.ctx.changed, 1)
}
func (w *masterWindow) updateLocked() {
w.ctx.Windows[0].Bounds = rect.FromRectangle(w.bounds)
in := &w.ctx.Input
in.Mouse.clip = nk_null_rect
in.Keyboard.Text = w.textbuffer.String()
w.textbuffer.Reset()
var t0, t1, te time.Time
if perfUpdate || w.Perf {
t0 = time.Now()
}
w.ctx.Update()
if perfUpdate || w.Perf {
t1 = time.Now()
}
nprimitives := w.draw()
if perfUpdate {
te = time.Now()
fps := 1.0 / te.Sub(t0).Seconds()
fmt.Printf("Update %0.4f msec = %0.4f updatefn + %0.4f draw (%d primitives) [max fps %0.2f]\n", te.Sub(t0).Seconds()*1000, t1.Sub(t0).Seconds()*1000, te.Sub(t1).Seconds()*1000, nprimitives, fps)
}
if w.Perf && nprimitives > 0 {
te = time.Now()
fps := 1.0 / te.Sub(t0).Seconds()
s := fmt.Sprintf("%0.4fms + %0.4fms (%0.2f)", t1.Sub(t0).Seconds()*1000, te.Sub(t1).Seconds()*1000, fps)
img := w.wndb.RGBA()
d := font.Drawer{
Dst: img,
Src: image.White,
Face: w.ctx.Style.Font}
width := d.MeasureString(s).Ceil()
bounds := w.bounds
bounds.Min.X = bounds.Max.X - width
bounds.Min.Y = bounds.Max.Y - (w.ctx.Style.Font.Metrics().Ascent + w.ctx.Style.Font.Metrics().Descent).Ceil()
draw.Draw(img, bounds, image.Black, bounds.Min, draw.Src)
d.Dot = fixed.P(bounds.Min.X, bounds.Min.Y+w.ctx.Style.Font.Metrics().Ascent.Ceil())
d.DrawString(s)
}
if nprimitives > 0 {
w.wnd.Upload(w.bounds.Min, w.wndb, w.bounds)
w.wnd.Publish()
}
}
func (w *masterWindow) closeLocked() {
w.closing = true
if w.wndb != nil {
w.wndb.Release()
}
w.wnd.Release()
}
// Programmatically closes window.
func (mw *masterWindow) Close() {
mw.uilock.Lock()
defer mw.uilock.Unlock()
mw.closeLocked()
}
// Returns true if the window is closed.
func (mw *masterWindow) Closed() bool {
mw.uilock.Lock()
defer mw.uilock.Unlock()
return mw.closing
}
func (w *masterWindow) setupBuffer(sz image.Point) {
var err error
oldb := w.wndb
w.wndb, err = w.screen.NewBuffer(sz)
if err != nil {
fmt.Fprintf(os.Stderr, "could not setup buffer: %v", err)
w.wndb = oldb
}
w.bounds = w.wndb.Bounds()
}
func (w *masterWindow) draw() int {
wimg := w.wndb.RGBA()
contextAllCommands(w.ctx)
w.ctx.Reset()
if !w.drawChanged(w.ctx.cmds) {
return 0
}
w.prevCmds = append(w.prevCmds[:0], w.ctx.cmds...)
return w.ctx.Draw(wimg)
}
// compares cmds to the last draw frame, returns true if there is a change
func (w *masterWindow) drawChanged(cmds []command.Command) bool {
if len(cmds) != len(w.prevCmds) {
return true
}
for i := range cmds {
if cmds[i].Kind != w.prevCmds[i].Kind {
return true
}
cmd := &cmds[i]
pcmd := &w.prevCmds[i]
switch cmds[i].Kind {
case command.ScissorCmd:
if *pcmd != *cmd {
return true
}
case command.LineCmd:
if *pcmd != *cmd {
return true
}
case command.RectFilledCmd:
if i == 0 {
cmd.RectFilled.Color.A = 0xff
}
if *pcmd != *cmd {
return true
}
case command.TriangleFilledCmd:
if *pcmd != *cmd {
return true
}
case command.CircleFilledCmd:
if *pcmd != *cmd {
return true
}
case command.ImageCmd:
if *pcmd != *cmd {
return true
}
case command.TextCmd:
if *pcmd != *cmd {
return true
}
default:
panic(UnknownCommandErr)
}
}
return false
}
func (mw *masterWindow) ActivateEditor(ed *TextEditor) {
mw.ctx.activateEditor = ed
}
func (mw *masterWindow) Style() *nstyle.Style {
return &mw.ctx.Style
}
func (mw *masterWindow) SetStyle(style *nstyle.Style) {
mw.ctx.Style = *style
mw.ctx.Style.Defaults()
}
func (mw *masterWindow) GetPerf() bool {
return mw.Perf
}
func (mw *masterWindow) SetPerf(perf bool) {
mw.Perf = perf
}