~eliasnaur/gio

ref: 2c07b2dc0ea2 gio/app/window.go -rw-r--r-- 12.5 KiB
2c07b2dcElias Naur headless: clear background to transparent, not white 12 days ago
                                                                                
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// SPDX-License-Identifier: Unlicense OR MIT

package app

import (
	"errors"
	"fmt"
	"image"
	"image/color"
	"time"

	"gioui.org/io/event"
	"gioui.org/io/pointer"
	"gioui.org/io/profile"
	"gioui.org/io/router"
	"gioui.org/io/system"
	"gioui.org/op"
	"gioui.org/unit"

	_ "gioui.org/app/internal/log"
	"gioui.org/app/internal/wm"
)

// WindowOption configures a wm.
type Option func(opts *wm.Options)

// Window represents an operating system wm.
type Window struct {
	driver wm.Driver
	ctx    wm.Context
	loop   *renderLoop

	// driverFuncs is a channel of functions to run when
	// the Window has a valid driver.
	driverFuncs chan func()

	out         chan event.Event
	in          chan event.Event
	ack         chan struct{}
	invalidates chan struct{}
	frames      chan *op.Ops
	frameAck    chan struct{}
	// dead is closed when the window is destroyed.
	dead chan struct{}

	stage        system.Stage
	animating    bool
	hasNextFrame bool
	nextFrame    time.Time
	delayedDraw  *time.Timer

	queue  queue
	cursor pointer.CursorName

	callbacks callbacks
}

type callbacks struct {
	w *Window
}

// queue is an event.Queue implementation that distributes system events
// to the input handlers declared in the most recent frame.
type queue struct {
	q router.Router
}

// driverEvent is sent when a new native driver
// is available for the wm.
type driverEvent struct {
	driver wm.Driver
}

// Pre-allocate the ack event to avoid garbage.
var ackEvent event.Event

// NewWindow creates a new window for a set of window
// options. The options are hints; the platform is free to
// ignore or adjust them.
//
// If the current program is running on iOS and Android,
// NewWindow returns the window previously created by the
// platform.
//
// Calling NewWindow more than once is not supported on
// iOS, Android, WebAssembly.
func NewWindow(options ...Option) *Window {
	opts := new(wm.Options)
	// Default options.
	Size(unit.Px(800), unit.Px(600))(opts)
	Title("Gio")(opts)

	for _, o := range options {
		o(opts)
	}

	w := &Window{
		in:          make(chan event.Event),
		out:         make(chan event.Event),
		ack:         make(chan struct{}),
		invalidates: make(chan struct{}, 1),
		frames:      make(chan *op.Ops),
		frameAck:    make(chan struct{}),
		driverFuncs: make(chan func()),
		dead:        make(chan struct{}),
	}
	w.callbacks.w = w
	go w.run(opts)
	return w
}

// Events returns the channel where events are delivered.
func (w *Window) Events() <-chan event.Event {
	return w.out
}

// update updates the wm. Paint operations updates the
// window contents, input operations declare input handlers,
// and so on. The supplied operations list completely replaces
// the window state from previous calls.
func (w *Window) update(frame *op.Ops) {
	w.frames <- frame
	<-w.frameAck
}

func (w *Window) validateAndProcess(frameStart time.Time, size image.Point, sync bool, frame *op.Ops) error {
	for {
		if w.loop != nil {
			if err := w.loop.Flush(); err != nil {
				w.destroyGPU()
				if err == wm.ErrDeviceLost {
					continue
				}
				return err
			}
		}
		if w.loop == nil {
			var err error
			w.ctx, err = w.driver.NewContext()
			if err != nil {
				return err
			}
			w.loop, err = newLoop(w.ctx)
			if err != nil {
				w.ctx.Release()
				return err
			}
		}
		w.processFrame(frameStart, size, frame)
		if sync {
			if err := w.loop.Flush(); err != nil {
				w.destroyGPU()
				if err == wm.ErrDeviceLost {
					continue
				}
				return err
			}
		}
		return nil
	}
}

func (w *Window) processFrame(frameStart time.Time, size image.Point, frame *op.Ops) {
	sync := w.loop.Draw(size, frame)
	w.queue.q.Frame(frame)
	switch w.queue.q.TextInputState() {
	case router.TextInputOpen:
		w.driver.ShowTextInput(true)
	case router.TextInputClose:
		w.driver.ShowTextInput(false)
	}
	if txt, ok := w.queue.q.WriteClipboard(); ok {
		go w.WriteClipboard(txt)
	}
	if w.queue.q.ReadClipboard() {
		go w.ReadClipboard()
	}
	if w.queue.q.Profiling() {
		frameDur := time.Since(frameStart)
		frameDur = frameDur.Truncate(100 * time.Microsecond)
		q := 100 * time.Microsecond
		timings := fmt.Sprintf("tot:%7s %s", frameDur.Round(q), w.loop.Summary())
		w.queue.q.Queue(profile.Event{Timings: timings})
	}
	if t, ok := w.queue.q.WakeupTime(); ok {
		w.setNextFrame(t)
	}
	// Opportunistically check whether Invalidate has been called, to avoid
	// stopping and starting animation mode.
	select {
	case <-w.invalidates:
		w.setNextFrame(time.Time{})
	default:
	}
	w.updateAnimation()
	// Wait for the GPU goroutine to finish processing frame.
	<-sync
}

// Invalidate the window such that a FrameEvent will be generated immediately.
// If the window is inactive, the event is sent when the window becomes active.
//
// Note that Invalidate is intended for externally triggered updates, such as a
// response from a network request. InvalidateOp is more efficient for animation
// and similar internal updates.
//
// Invalidate is safe for concurrent use.
func (w *Window) Invalidate() {
	select {
	case w.invalidates <- struct{}{}:
	default:
	}
}

// Option applies the options to the window.
func (w *Window) Option(opts ...Option) {
	go w.driverDo(func() {
		o := new(wm.Options)
		for _, opt := range opts {
			opt(o)
		}
		w.driver.Option(o)
	})
}

// ReadClipboard initiates a read of the clipboard in the form
// of a clipboard.Event. Multiple reads may be coalesced
// to a single event.
func (w *Window) ReadClipboard() {
	go w.driverDo(func() {
		w.driver.ReadClipboard()
	})
}

// WriteClipboard writes a string to the clipboard.
func (w *Window) WriteClipboard(s string) {
	go w.driverDo(func() {
		w.driver.WriteClipboard(s)
	})
}

// SetCursorName changes the current window cursor to name.
func (w *Window) SetCursorName(name pointer.CursorName) {
	go w.driverDo(func() {
		w.driver.SetCursor(name)
	})
}

// Close the wm. The window's event loop should exit when it receives
// system.DestroyEvent.
//
// Currently, only macOS, Windows and X11 drivers implement this functionality,
// all others are stubbed.
func (w *Window) Close() {
	go w.driverDo(func() {
		w.driver.Close()
	})
}

// driverDo waits for the window to have a valid driver attached and calls f.
// It does nothing if the if the window was destroyed while waiting.
func (w *Window) driverDo(f func()) {
	select {
	case w.driverFuncs <- f:
	case <-w.dead:
	}
}

func (w *Window) updateAnimation() {
	animate := false
	if w.delayedDraw != nil {
		w.delayedDraw.Stop()
		w.delayedDraw = nil
	}
	if w.stage >= system.StageRunning && w.hasNextFrame {
		if dt := time.Until(w.nextFrame); dt <= 0 {
			animate = true
		} else {
			w.delayedDraw = time.NewTimer(dt)
		}
	}
	if animate != w.animating {
		w.animating = animate
		w.driver.SetAnimating(animate)
	}
}

func (w *Window) setNextFrame(at time.Time) {
	if !w.hasNextFrame || at.Before(w.nextFrame) {
		w.hasNextFrame = true
		w.nextFrame = at
	}
}

func (c *callbacks) SetDriver(d wm.Driver) {
	c.Event(driverEvent{d})
}

func (c *callbacks) Event(e event.Event) {
	select {
	case c.w.in <- e:
		<-c.w.ack
	case <-c.w.dead:
	}
}

func (w *Window) waitAck() {
	// Send a dummy event; when it gets through we
	// know the application has processed the previous event.
	w.out <- ackEvent
}

// Prematurely destroy the window and wait for the native window
// destroy event.
func (w *Window) destroy(err error) {
	w.destroyGPU()
	// Ack the current event.
	w.ack <- struct{}{}
	w.out <- system.DestroyEvent{Err: err}
	close(w.dead)
	for e := range w.in {
		w.ack <- struct{}{}
		if _, ok := e.(system.DestroyEvent); ok {
			return
		}
	}
}

func (w *Window) destroyGPU() {
	if w.loop != nil {
		w.loop.Release()
		w.loop = nil
	}
	if w.ctx != nil {
		w.ctx.Release()
		w.ctx = nil
	}
}

// waitFrame waits for the client to either call FrameEvent.Frame
// or to continue event handling. It returns whether the client
// called Frame or not.
func (w *Window) waitFrame() (*op.Ops, bool) {
	select {
	case frame := <-w.frames:
		// The client called FrameEvent.Frame.
		return frame, true
	case w.out <- ackEvent:
		// The client ignored FrameEvent and continued processing
		// events.
		return nil, false
	}
}

func (w *Window) run(opts *wm.Options) {
	defer close(w.in)
	defer close(w.out)
	if err := wm.NewWindow(&w.callbacks, opts); err != nil {
		w.out <- system.DestroyEvent{Err: err}
		return
	}
	for {
		var driverFuncs chan func()
		if w.driver != nil {
			driverFuncs = w.driverFuncs
		}
		var timer <-chan time.Time
		if w.delayedDraw != nil {
			timer = w.delayedDraw.C
		}
		select {
		case <-timer:
			w.setNextFrame(time.Time{})
			w.updateAnimation()
		case <-w.invalidates:
			w.setNextFrame(time.Time{})
			w.updateAnimation()
		case f := <-driverFuncs:
			f()
		case e := <-w.in:
			switch e2 := e.(type) {
			case system.StageEvent:
				if w.loop != nil {
					if e2.Stage < system.StageRunning {
						w.destroyGPU()
					} else {
						w.loop.Refresh()
					}
				}
				w.stage = e2.Stage
				w.updateAnimation()
				w.out <- e
				w.waitAck()
			case wm.FrameEvent:
				if e2.Size == (image.Point{}) {
					panic(errors.New("internal error: zero-sized Draw"))
				}
				if w.stage < system.StageRunning {
					// No drawing if not visible.
					break
				}
				frameStart := time.Now()
				w.hasNextFrame = false
				e2.Frame = w.update
				e2.Queue = &w.queue
				w.out <- e2.FrameEvent
				if w.loop != nil {
					if e2.Sync {
						w.loop.Refresh()
					}
				}
				frame, gotFrame := w.waitFrame()
				err := w.validateAndProcess(frameStart, e2.Size, e2.Sync, frame)
				if gotFrame {
					// We're done with frame, let the client continue.
					w.frameAck <- struct{}{}
				}
				if err != nil {
					w.destroyGPU()
					w.destroy(err)
					return
				}
				w.updateCursor()
			case *system.CommandEvent:
				w.out <- e
				w.waitAck()
			case driverEvent:
				w.driver = e2.driver
			case system.DestroyEvent:
				w.destroyGPU()
				w.out <- e2
				w.ack <- struct{}{}
				return
			case event.Event:
				if w.queue.q.Queue(e2) {
					w.setNextFrame(time.Time{})
					w.updateAnimation()
				}
				w.updateCursor()
				w.out <- e
			}
			w.ack <- struct{}{}
		}
	}
}

func (w *Window) updateCursor() {
	if c := w.queue.q.Cursor(); c != w.cursor {
		w.cursor = c
		w.SetCursorName(c)
	}
}

func (q *queue) Events(k event.Tag) []event.Event {
	return q.q.Events(k)
}

var (
	// Windowed is the normal window mode with OS specific window decorations.
	Windowed = windowMode(wm.Windowed)
	// Fullscreen is the full screen window mode.
	Fullscreen = windowMode(wm.Fullscreen)
)

// windowMode sets the window mode.
//
// Supported platforms are macOS, X11, Windows and JS.
func windowMode(mode wm.WindowMode) Option {
	return func(opts *wm.Options) {
		opts.WindowMode = &mode
	}
}

var (
	// AnyOrientation allows the window to be freely orientated.
	AnyOrientation = orientation(wm.AnyOrientation)
	// LandscapeOrientation constrains the window to landscape orientations.
	LandscapeOrientation = orientation(wm.LandscapeOrientation)
	// PortraitOrientation constrains the window to portrait orientations.
	PortraitOrientation = orientation(wm.PortraitOrientation)
)

// orientation sets the orientation of the app.
//
// Supported platforms are Android and JS.
func orientation(mode wm.Orientation) Option {
	return func(opts *wm.Options) {
		opts.Orientation = &mode
	}
}

// Title sets the title of the wm.
func Title(t string) Option {
	return func(opts *wm.Options) {
		opts.Title = &t
	}
}

// Size sets the size of the wm.
func Size(w, h unit.Value) Option {
	if w.V <= 0 {
		panic("width must be larger than or equal to 0")
	}
	if h.V <= 0 {
		panic("height must be larger than or equal to 0")
	}
	return func(opts *wm.Options) {
		opts.Size = &wm.Size{
			Width:  w,
			Height: h,
		}
	}
}

// MaxSize sets the maximum size of the wm.
func MaxSize(w, h unit.Value) Option {
	if w.V <= 0 {
		panic("width must be larger than or equal to 0")
	}
	if h.V <= 0 {
		panic("height must be larger than or equal to 0")
	}
	return func(opts *wm.Options) {
		opts.MaxSize = &wm.Size{
			Width:  w,
			Height: h,
		}
	}
}

// MinSize sets the minimum size of the wm.
func MinSize(w, h unit.Value) Option {
	if w.V <= 0 {
		panic("width must be larger than or equal to 0")
	}
	if h.V <= 0 {
		panic("height must be larger than or equal to 0")
	}
	return func(opts *wm.Options) {
		opts.MinSize = &wm.Size{
			Width:  w,
			Height: h,
		}
	}
}

// StatusColor sets the color of the Android status bar.
func StatusColor(color color.NRGBA) Option {
	return func(opts *wm.Options) {
		opts.StatusColor = &color
	}
}

// NavigationColor sets the color of the navigation bar on Android, or the address bar in browsers.
func NavigationColor(color color.NRGBA) Option {
	return func(opts *wm.Options) {
		opts.NavigationColor = &color
	}
}

func (driverEvent) ImplementsEvent() {}