~eliasnaur/gio

ref: 7aa7bb3be40858efe2a98f866fcc7db2026b02fd gio/ui/app/window.go -rw-r--r-- 5.3 KiB
7aa7bb3bElias Naur ui: rename ops to have Op suffixed, not prefixed 2 years 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
// SPDX-License-Identifier: Unlicense OR MIT

package app

import (
	"errors"
	"fmt"
	"image"
	"sync"
	"time"

	"gioui.org/ui"
	"gioui.org/ui/app/internal/gpu"
	"gioui.org/ui/input"
	"gioui.org/ui/internal/ops"
	"gioui.org/ui/key"
)

type WindowOptions struct {
	Width  ui.Value
	Height ui.Value
	Title  string
}

type Window struct {
	Profiling bool

	driver     *window
	lastFrame  time.Time
	drawStart  time.Time
	gpu        *gpu.GPU
	timings    string
	inputState key.TextInputState
	err        error

	events chan Event

	eventLock sync.Mutex

	mu           sync.Mutex
	stage        Stage
	size         image.Point
	syncGPU      bool
	animating    bool
	hasNextFrame bool
	nextFrame    time.Time
	delayedDraw  *time.Timer

	reader ui.OpsReader
}

// driver is the interface for the platform implementation
// of a Window.
var _ interface {
	// setAnimating sets the animation flag. When the window is animating,
	// Draw events are delivered as fast as the display can handle them.
	setAnimating(anim bool)
	// setTextInput updates the virtual keyboard state.
	setTextInput(s key.TextInputState)
} = (*window)(nil)

var ackEvent Event

func newWindow(nw *window) *Window {
	w := &Window{
		driver: nw,
		events: make(chan Event),
		stage:  StagePaused,
	}
	return w
}

func (w *Window) Events() <-chan Event {
	return w.events
}

func (w *Window) Timings() string {
	return w.timings
}

func (w *Window) SetTextInput(s key.TextInputState) {
	if !w.IsAlive() {
		return
	}
	if s != w.inputState && (s == key.TextInputClosed || s == key.TextInputOpen) {
		w.driver.setTextInput(s)
	}
	if s == key.TextInputFocus {
		w.Redraw()
	}
	w.inputState = s
}

func (w *Window) Err() error {
	return w.err
}

func (w *Window) Draw(root *ui.Ops) {
	if !w.IsAlive() {
		return
	}
	w.mu.Lock()
	var drawDur time.Duration
	if !w.drawStart.IsZero() {
		drawDur = time.Since(w.drawStart)
		w.drawStart = time.Time{}
	}
	stage := w.stage
	sync := w.syncGPU
	size := w.size
	w.hasNextFrame = false
	w.syncGPU = false
	w.mu.Unlock()
	if stage < StageRunning {
		return
	}
	if w.gpu != nil {
		if sync {
			w.gpu.Refresh()
		}
		if err := w.gpu.Flush(); err != nil {
			w.gpu.Release()
			w.gpu = nil
		}
	}
	if w.gpu == nil {
		ctx, err := newContext(w.driver)
		if err != nil {
			w.err = err
			return
		}
		w.gpu, err = gpu.NewGPU(ctx)
		if err != nil {
			w.err = err
			return
		}
	}
	now := time.Now()
	frameDur := now.Sub(w.lastFrame)
	frameDur = frameDur.Truncate(100 * time.Microsecond)
	w.lastFrame = now
	if w.Profiling {
		q := 100 * time.Microsecond
		w.timings = fmt.Sprintf("tot:%7s cpu:%7s %s", frameDur.Round(q), drawDur.Round(q), w.gpu.Timings())
		w.setNextFrame(time.Time{})
	}
	w.reader.Reset(root)
	if t, ok := collectRedraws(&w.reader); ok {
		w.setNextFrame(t)
	}
	w.updateAnimation()
	w.gpu.Draw(w.Profiling, size, root)
}

func collectRedraws(r *ui.OpsReader) (time.Time, bool) {
	var t time.Time
	redraw := false
	for {
		encOp, ok := r.Decode()
		if !ok {
			break
		}
		switch ops.OpType(encOp.Data[0]) {
		case ops.TypeInvalidate:
			var op ui.InvalidateOp
			op.Decode(encOp.Data)
			if !redraw || op.At.Before(t) {
				redraw = true
				t = op.At
			}
		}
	}
	return t, redraw
}

func (w *Window) Redraw() {
	if !w.IsAlive() {
		return
	}
	w.setNextFrame(time.Time{})
	w.updateAnimation()
}

func (w *Window) updateAnimation() {
	w.mu.Lock()
	defer w.mu.Unlock()
	animate := false
	if w.stage >= StageRunning && w.hasNextFrame {
		if dt := time.Until(w.nextFrame); dt <= 0 {
			animate = true
		} else {
			w.delayedDraw = time.AfterFunc(dt, w.Redraw)
		}
	}
	if animate != w.animating {
		w.animating = animate
		w.driver.setAnimating(animate)
	}
}

func (w *Window) setNextFrame(at time.Time) {
	w.mu.Lock()
	defer w.mu.Unlock()
	if !w.hasNextFrame || at.Before(w.nextFrame) {
		if w.delayedDraw != nil {
			w.delayedDraw.Stop()
			w.delayedDraw = nil
		}
		w.hasNextFrame = true
		w.nextFrame = at
	}
}

func (w *Window) Size() image.Point {
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.size
}

func (w *Window) Stage() Stage {
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.stage
}

func (w *Window) IsAlive() bool {
	return w.Stage() != StageDead && w.err == nil
}

func (w *Window) contextDriver() interface{} {
	return w.driver
}

func (w *Window) event(e Event) {
	w.eventLock.Lock()
	defer w.eventLock.Unlock()
	w.mu.Lock()
	needAck := false
	needRedraw := false
	switch e := e.(type) {
	case input.Event:
		needRedraw = true
	case *Command:
		needAck = true
		needRedraw = true
	case ChangeStage:
		w.stage = e.Stage
		if w.stage > StageDead {
			needAck = true
			w.syncGPU = true
		}
	case Draw:
		if e.Size == (image.Point{}) {
			panic(errors.New("internal error: zero-sized Draw"))
		}
		if w.stage < StageRunning {
			// No drawing if not visible.
			break
		}
		w.drawStart = time.Now()
		needAck = true
		w.syncGPU = e.sync
		w.size = e.Size
	}
	stage := w.stage
	w.mu.Unlock()
	if needRedraw {
		w.setNextFrame(time.Time{})
	}
	w.updateAnimation()
	w.events <- e
	if needAck {
		// Send a dummy event; when it gets through we
		// know the application has processed the actual event.
		w.events <- ackEvent
	}
	if w.gpu != nil {
		w.mu.Lock()
		sync := w.syncGPU
		w.syncGPU = false
		w.mu.Unlock()
		switch {
		case stage < StageRunning:
			w.gpu.Release()
			w.gpu = nil
		case sync:
			w.gpu.Refresh()
		}
	}
	if stage == StageDead {
		close(w.events)
	}
}