forked from guigui-gui/guigui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1121 lines (983 loc) · 33.6 KB
/
Copy pathapp.go
File metadata and controls
1121 lines (983 loc) · 33.6 KB
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2024 The Guigui Authors
package guigui
import (
"cmp"
"fmt"
"image"
"image/color"
"log/slog"
"maps"
"math"
"os"
"slices"
"strconv"
"strings"
"sync"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/vector"
"github.com/zeebo/xxh3"
)
type debugMode struct {
showRenderingRegions bool
showBuildLogs bool
showInputLogs bool
deviceScale float64
}
var theDebugMode debugMode
func init() {
for token := range strings.SplitSeq(os.Getenv("GUIGUI_DEBUG"), ",") {
switch {
case token == "showrenderingregions":
theDebugMode.showRenderingRegions = true
case token == "showbuildlogs":
theDebugMode.showBuildLogs = true
case token == "showinputlogs":
theDebugMode.showInputLogs = true
case strings.HasPrefix(token, "devicescale="):
f, err := strconv.ParseFloat(token[len("devicescale="):], 64)
if err != nil {
slog.Error(err.Error())
}
theDebugMode.deviceScale = f
case token == "":
default:
slog.Warn("unknown debug option", "option", token)
}
}
}
type invalidatedRegionsForDebugItem struct {
region image.Rectangle
time int
}
func invalidatedRegionForDebugMaxTime() int {
return ebiten.TPS() / 5
}
type widgetAndLayer struct {
widget Widget
layer int64
}
type requiredPhases int
const (
requiredPhasesBuildAndLayout = iota
// TODO: Use this when appropriated.
requiredPhasesLayout
requiredPhasesNone
)
func (r requiredPhases) addBuild() requiredPhases {
return requiredPhasesBuildAndLayout
}
func (r requiredPhases) addLayout() requiredPhases {
switch r {
case requiredPhasesBuildAndLayout:
return requiredPhasesBuildAndLayout
case requiredPhasesLayout:
return requiredPhasesLayout
case requiredPhasesNone:
return requiredPhasesLayout
}
return r
}
func (r requiredPhases) requiresBuild() bool {
return r == requiredPhasesBuildAndLayout
}
func (r requiredPhases) requiresLayout() bool {
return r == requiredPhasesBuildAndLayout || r == requiredPhasesLayout
}
type app struct {
root Widget
context Context
visitedLayers map[int64]struct{}
layers []int64
buildCount int64
requiredPhases requiredPhases
// maybeHitWidgets are widgets and their layer values at the cursor position.
// maybeHitWidgets are ordered by descending layer values.
//
// Layer values are fixed values just after a tree construction, so they are not changed during buildWidgets.
//
// maybeHitWidgets includes all the widgets regardless of their Visibility and Passthrough states.
maybeHitWidgets []widgetAndLayer
redrawRequestedRegions redrawRequests
redrawAndRebuildRequestedRegions redrawRequests
regionsToDraw image.Rectangle
invalidatedRegionsForDebug []invalidatedRegionsForDebugItem
screenWidth float64
screenHeight float64
deviceScale float64
lastScreenWidth float64
lastScreenHeight float64
lastCursorPosition image.Point
lastColorMode ebiten.ColorMode
lastFocused bool
inputState inputState
focusedWidget Widget
// widgetList is a flat DFS-ordered list of all widgets, populated after each buildWidgets call.
// It is used to avoid re-traversing the tree for passes that don't modify the tree structure.
widgetList []Widget
// prevWidgetList is the previous frame's widgetList, retained across builds
// so the tree-exit sweep in buildWidgets can find widgets that were in tree
// last frame but are not this frame and reclaim their widgetsAndBounds slices.
prevWidgetList []Widget
// bounds3DsPool is a free-list of backing arrays for widgetsAndBounds.bounds3Ds
// and currentBounds3D. Slices are pushed in when a widget leaves the tree and
// popped in widgetsAndBounds.equals when a widget's currentBounds3D is nil,
// so a churning set of widgets (e.g. list items scrolled in and out) does not
// reallocate a fresh backing array every time.
bounds3DsPool sync.Pool
// hasDirtyWidgets is true when any widget has rebuildRequested, redrawRequested, or eventDispatched set.
// This allows settleRedrawAndRebuildState to skip iterating widgetList when nothing is dirty.
hasDirtyWidgets bool
// stateKeyCheckPending is true when widget state may have changed since the last
// [app.checkStateKeys] run. It is set by widget phases (Build, Layout, Tick, HandleInput)
// and [Context] setters that affect state tracked in [Widget.WriteStateKey] or internalStateKey.
// When false, [app.checkStateKeys] short-circuits without iterating widgetList.
// Input handling is counted as a phase — whether a handler actually mutated state is
// not detectable, so every input handler call is conservatively treated as dirtying.
stateKeyCheckPending bool
stateKeyWriter StateKeyWriter
offscreen *ebiten.Image
debugScreen *ebiten.Image
}
// widgetStateKey runs widget.WriteStateKey into the shared writer and returns
// the resulting 128-bit hash. The writer is reset before the call.
func (a *app) widgetStateKey(widget Widget) xxh3.Uint128 {
a.stateKeyWriter.reset()
widget.WriteStateKey(&a.stateKeyWriter)
return a.stateKeyWriter.sum128()
}
var theApp app
type RunOptions struct {
Title string
WindowSize image.Point
WindowMinSize image.Point
WindowMaxSize image.Point
WindowFloating bool
AppScale float64
RunGameOptions *ebiten.RunGameOptions
}
func Run(root Widget, options *RunOptions) error {
return RunWithCustomFunc(root, options, ebiten.RunGameWithOptions)
}
func RunWithCustomFunc(root Widget, options *RunOptions, f func(game ebiten.Game, options *ebiten.RunGameOptions) error) error {
if options == nil {
options = &RunOptions{}
}
ebiten.SetWindowTitle(options.Title)
ebiten.SetWindowResizingMode(ebiten.WindowResizingModeEnabled)
ebiten.SetScreenClearedEveryFrame(false)
if options.WindowSize.X > 0 && options.WindowSize.Y > 0 {
ebiten.SetWindowSize(options.WindowSize.X, options.WindowSize.Y)
}
minW := -1
minH := -1
maxW := -1
maxH := -1
if options.WindowMinSize.X > 0 {
minW = options.WindowMinSize.X
}
if options.WindowMinSize.Y > 0 {
minH = options.WindowMinSize.Y
}
if options.WindowMaxSize.X > 0 {
maxW = options.WindowMaxSize.X
}
if options.WindowMaxSize.Y > 0 {
maxH = options.WindowMaxSize.Y
}
ebiten.SetWindowSizeLimits(minW, minH, maxW, maxH)
ebiten.SetWindowFloating(options.WindowFloating)
a := &theApp
a.root = root
root.copyCheck()
a.deviceScale = deviceScaleFactor()
a.root.widgetState().root = true
a.context.app = a
if options.AppScale > 0 {
a.context.appScaleMinus1 = options.AppScale - 1
}
var eop ebiten.RunGameOptions
if options.RunGameOptions != nil {
eop = *options.RunGameOptions
}
// Prefer SRGB for consistent result.
if eop.ColorSpace == ebiten.ColorSpaceDefault {
eop.ColorSpace = ebiten.ColorSpaceSRGB
}
return f(a, &eop)
}
func deviceScaleFactor() float64 {
if theDebugMode.deviceScale != 0 {
return theDebugMode.deviceScale
}
// Calling ebiten.Monitor() seems pretty expensive. Do not call this often.
// TODO: Ebitengine should be fixed.
return ebiten.Monitor().DeviceScaleFactor()
}
func (a *app) bounds() image.Rectangle {
return image.Rect(0, 0, int(math.Ceil(a.screenWidth)), int(math.Ceil(a.screenHeight)))
}
func (a *app) focusWidget(widget Widget) {
if areWidgetsSame(a.focusedWidget, widget) {
return
}
a.clearFocusAncestorFlags()
if a.focusedWidget != nil {
RequestRebuild(a.focusedWidget)
DispatchEvent(a.focusedWidget, widgetEventFocusChanged, false)
}
a.focusedWidget = widget
if a.focusedWidget != nil {
RequestRebuild(a.focusedWidget)
DispatchEvent(a.focusedWidget, widgetEventFocusChanged, true)
}
a.setFocusAncestorFlags()
// Redraw the entire screen, as any widgets can be affected by the focus change (#283).
// requestRedrawReasonWidgetFocus also requests rebuilding a tree.
a.requestRedraw(a.bounds(), requestRedrawReasonWidgetFocus, nil)
}
func (a *app) clearFocusAncestorFlags() {
for w := a.focusedWidget; w != nil; w = w.widgetState().parent {
w.widgetState().focusedOrHasFocusedChild = false
}
}
func (a *app) setFocusAncestorFlags() {
for w := a.focusedWidget; w != nil; w = w.widgetState().parent {
w.widgetState().focusedOrHasFocusedChild = true
}
}
func (a *app) setButtonInputReceptiveAncestorFlags() {
for _, widget := range a.widgetList {
if !widget.widgetState().buttonInputReceptive {
continue
}
for w := widget; w != nil; w = w.widgetState().parent {
ws := w.widgetState()
if ws.buttonInputReceptiveOrHasReceptiveChild {
break
}
ws.buttonInputReceptiveOrHasReceptiveChild = true
}
}
}
// settleRedrawAndRebuildState collects pending widget redraw/rebuild requests,
// determines which phases are required for the next buildAndLayoutWidgets call,
// accumulates draw regions into regionsToDraw, and resets the region buffers.
// It performs a single pass over the widget list to collect both redraw requests
// and event-dispatched widgets.
func (a *app) settleRedrawAndRebuildState(inputHandledWidget Widget) {
// Detect [Widget.WriteStateKey] changes since the last [Widget.Build] and flag rebuilds accordingly.
// This lets widgets skip explicit [RequestRebuild] calls for state they expose via [Widget.WriteStateKey].
a.checkStateKeys()
// Single pass: collect redraw requests and find the first event-dispatched widget.
// Skip the entire loop when no widget has set any dirty flag.
var dispatchedWidget Widget
if a.hasDirtyWidgets {
a.hasDirtyWidgets = false
for _, widget := range a.widgetList {
widgetState := widget.widgetState()
if widgetState.rebuildRequested || widgetState.redrawRequested {
if vb := a.context.visibleBounds(widgetState); !vb.Empty() {
var reason requestRedrawReason
if widgetState.rebuildRequested {
reason = widgetState.redrawReasonOnRebuild
} else {
reason = requestRedrawReasonRedrawWidget
}
a.requestRedrawWidget(widget, reason)
}
widgetState.rebuildRequested = false
widgetState.rebuildRequestedAt = ""
widgetState.redrawReasonOnRebuild = 0
widgetState.redrawRequested = false
widgetState.redrawRequestedAt = ""
}
if widgetState.eventDispatched {
if dispatchedWidget == nil {
dispatchedWidget = widget
}
widgetState.eventDispatched = false
}
}
}
// Determine which phases are required for the next build+layout cycle.
a.requiredPhases = requiredPhasesNone
if dispatchedWidget != nil {
a.requiredPhases = a.requiredPhases.addBuild()
if theDebugMode.showBuildLogs {
slog.Info("rebuilding tree next time: event dispatched", "widget", fmt.Sprintf("%T", dispatchedWidget))
}
}
if inputHandledWidget != nil {
a.requiredPhases = a.requiredPhases.addBuild()
if theDebugMode.showBuildLogs {
slog.Info("rebuilding tree next time: input handled", "widget", fmt.Sprintf("%T", inputHandledWidget))
}
}
if !a.redrawAndRebuildRequestedRegions.empty() {
a.requiredPhases = a.requiredPhases.addBuild()
if theDebugMode.showBuildLogs {
slog.Info("rebuilding tree next time: region redraw requested", "region", a.redrawAndRebuildRequestedRegions)
}
}
a.regionsToDraw = a.redrawRequestedRegions.union(a.regionsToDraw)
a.regionsToDraw = a.redrawAndRebuildRequestedRegions.union(a.regionsToDraw)
a.redrawRequestedRegions.reset()
a.redrawAndRebuildRequestedRegions.reset()
}
func (a *app) Update() error {
var layoutChangedInUpdate bool
if a.focusedWidget == nil {
a.focusWidget(a.root)
}
if s := deviceScaleFactor(); a.deviceScale != s {
a.deviceScale = s
a.requestRebuild(a.root.widgetState(), requestRedrawReasonScreenDeviceScale)
}
if a.context.ColorMode() != a.lastColorMode {
a.lastColorMode = a.context.ColorMode()
a.requestRebuild(a.root.widgetState(), requestRedrawReasonColorMode)
}
if focused := ebiten.IsFocused(); focused != a.lastFocused {
a.lastFocused = focused
// On regaining focus, redraw the entire screen: the screen is not cleared
// every frame, so regions changed while unfocused (e.g. a popup fading out
// off-screen) would otherwise never be repainted.
// requestRedrawReasonAppFocus also requests rebuilding a tree.
if focused {
a.requestRedraw(a.bounds(), requestRedrawReasonAppFocus, nil)
}
}
rootState := a.root.widgetState()
rootState.bounds = a.bounds()
// Call the first buildWidgets.
if layoutChanged, err := a.buildAndLayoutWidgets(); err != nil {
return err
} else if layoutChanged {
layoutChangedInUpdate = true
}
// Handle user inputs.
// TODO: Handle this in Ebitengine's HandleInput in the future (hajimehoshi/ebiten#1704)
a.inputState.update()
var inputHandledWidget Widget
if a.inputState.isPointingActive(layoutChangedInUpdate) {
if r := a.handleInputWidget(handleInputTypePointing); r.widget != nil {
if !r.aborted {
inputHandledWidget = r.widget
}
if theDebugMode.showInputLogs {
slog.Info("pointing input handled", "widget", fmt.Sprintf("%T", r.widget), "aborted", r.aborted)
}
}
}
// This gate covers only key handling, which depends on key input. A focused
// IME composer ([textinput.Composer]) is instead pumped every tick by its
// host widget (see basicwidget.Text's Tick), since an IME owning the
// keyboard reports composition updates with no key event.
//
// TODO: Run handleInputWidget on IME activity too (e.g. once Ebitengine
// exposes pending-IME-input state) so the composer is driven here uniformly
// and host widgets need no per-tick pump.
if a.inputState.isButtonActive() {
a.setButtonInputReceptiveAncestorFlags()
if r := a.handleInputWidget(handleInputTypeButton); r.widget != nil {
if !r.aborted {
inputHandledWidget = r.widget
}
if theDebugMode.showInputLogs {
slog.Info("keyboard input handled", "widget", fmt.Sprintf("%T", r.widget), "aborted", r.aborted)
}
}
}
a.settleRedrawAndRebuildState(inputHandledWidget)
// Call the second buildWidgets to construct the widget tree again to reflect the latest state.
if layoutChanged, err := a.buildAndLayoutWidgets(); err != nil {
return err
} else if layoutChanged {
layoutChangedInUpdate = true
}
if !a.cursorShape() {
ebiten.SetCursorShape(ebiten.CursorShapeDefault)
}
// Tick
if err := a.tickWidgets(); err != nil {
return err
}
// Invalidate the engire screen if the screen size is changed.
var screenInvalidated bool
if a.lastScreenWidth != a.screenWidth {
screenInvalidated = true
a.lastScreenWidth = a.screenWidth
}
if a.lastScreenHeight != a.screenHeight {
screenInvalidated = true
a.lastScreenHeight = a.screenHeight
}
if screenInvalidated {
a.requestRedraw(a.bounds(), requestRedrawReasonScreenSize, nil)
}
if layoutChangedInUpdate {
// Invalidate regions if a widget's children state is changed.
// A widget's bounds might be changed in Widget.Layout, so do this after building and layouting.
a.requestRedrawIfTreeChanged()
}
a.settleRedrawAndRebuildState(nil)
if theDebugMode.showRenderingRegions {
// Update the regions in the reversed order to remove items.
for idx := len(a.invalidatedRegionsForDebug) - 1; idx >= 0; idx-- {
if a.invalidatedRegionsForDebug[idx].time > 0 {
a.invalidatedRegionsForDebug[idx].time--
} else {
a.invalidatedRegionsForDebug = slices.Delete(a.invalidatedRegionsForDebug, idx, idx+1)
}
}
if !a.regionsToDraw.Empty() {
idx := slices.IndexFunc(a.invalidatedRegionsForDebug, func(i invalidatedRegionsForDebugItem) bool {
return i.region.Eq(a.regionsToDraw)
})
if idx < 0 {
a.invalidatedRegionsForDebug = append(a.invalidatedRegionsForDebug, invalidatedRegionsForDebugItem{
region: a.regionsToDraw,
time: invalidatedRegionForDebugMaxTime(),
})
} else {
a.invalidatedRegionsForDebug[idx].time = invalidatedRegionForDebugMaxTime()
}
}
}
return nil
}
func (a *app) Draw(screen *ebiten.Image) {
origScreen := screen
if theDebugMode.showRenderingRegions {
// As the screen is not cleered every frame, create offscreen here to keep the previous contents.
if a.offscreen != nil {
if a.offscreen.Bounds().Dx() != screen.Bounds().Dx() || a.offscreen.Bounds().Dy() != screen.Bounds().Dy() {
a.offscreen.Deallocate()
a.offscreen = nil
}
}
if a.offscreen == nil {
a.offscreen = ebiten.NewImage(screen.Bounds().Dx(), screen.Bounds().Dy())
}
screen = a.offscreen
}
a.drawWidget(screen)
if origScreen != screen {
op := &ebiten.DrawImageOptions{}
op.Blend = ebiten.BlendCopy
origScreen.DrawImage(a.offscreen, op)
a.drawDebugIfNeeded(origScreen)
}
a.regionsToDraw = image.Rectangle{}
}
func (a *app) Layout(outsideWidth, outsideHeight int) (int, int) {
panic("guigui: game.Layout should never be called")
}
func (a *app) LayoutF(outsideWidth, outsideHeight float64) (float64, float64) {
s := a.deviceScale
a.screenWidth = outsideWidth * s
a.screenHeight = outsideHeight * s
return a.screenWidth, a.screenHeight
}
func (a *app) requestRedraw(region image.Rectangle, reason requestRedrawReason, widget Widget) {
switch reason {
case requestRedrawReasonRedrawWidget, requestRedrawReasonLayout:
a.redrawRequestedRegions.add(region, reason, widget)
default:
a.redrawAndRebuildRequestedRegions.add(region, reason, widget)
}
}
func (a *app) requestRedrawWidget(widget Widget, reason requestRedrawReason) {
widgetState := widget.widgetState()
a.requestRedraw(a.context.visibleBounds(widgetState), reason, widget)
for _, child := range widgetState.children {
a.requestRedrawIfDifferentParentLayer(child, reason)
}
}
func (a *app) requestRedrawIfDifferentParentLayer(widget Widget, reason requestRedrawReason) {
widgetState := widget.widgetState()
if widgetState.inDifferentLayerFromParent() {
a.requestRedrawWidget(widget, reason)
return
}
for _, child := range widgetState.children {
a.requestRedrawIfDifferentParentLayer(child, reason)
}
}
// buildAndLayoutWidgets runs the build and layout phases based on requiredPhases,
// then updates the hit-test widget list. Build or layout may trigger further
// rebuild/relayout requests, so this method loops until no more phases are
// required or a maximum iteration count is reached. Between iterations,
// settleRedrawAndRebuildState collects pending requests and determines whether
// another pass is needed.
func (a *app) buildAndLayoutWidgets() (bool, error) {
const maxBuildLayoutIterations = 2
var layoutChanged bool
var counter int
for a.requiredPhases.requiresBuild() || a.requiredPhases.requiresLayout() {
if a.requiredPhases.requiresBuild() {
a.context.inBuild = true
if err := a.buildWidgets(); err != nil {
return false, err
}
a.context.inBuild = false
a.setFocusAncestorFlags()
}
if a.requiredPhases.requiresLayout() {
layoutChanged = true
a.layoutWidgets()
}
counter++
if counter >= maxBuildLayoutIterations {
break
}
a.settleRedrawAndRebuildState(nil)
}
a.updateHitWidgets(layoutChanged)
return layoutChanged, nil
}
// getBounds3Ds returns a reclaimed widgetStateAndBounds slice from the pool,
// or nil if the pool is empty. The returned slice has length 0 but may have
// non-zero capacity.
func (a *app) getBounds3Ds() []widgetStateAndBounds {
p, ok := a.bounds3DsPool.Get().(*[]widgetStateAndBounds)
if !ok {
return nil
}
return *p
}
// putBounds3Ds returns a widgetStateAndBounds slice to the pool for reuse. The
// slice's backing array is cleared so it does not keep widgetState values alive
// while sitting in the pool.
func (a *app) putBounds3Ds(s []widgetStateAndBounds) {
if cap(s) == 0 {
return
}
clear(s[:cap(s)])
s = s[:0]
a.bounds3DsPool.Put(&s)
}
func (a *app) buildWidgets() error {
a.buildCount++
a.stateKeyCheckPending = true
a.root.widgetState().builtAt = a.buildCount
// Clear event handlers to prevent unexpected handlings.
// An event handler is often a closure capturing variables, and this might cause unexpected behaviors.
for _, widget := range a.widgetList {
widgetState := widget.widgetState()
widgetState.eventHandlers = slices.Delete(widgetState.eventHandlers, 0, len(widgetState.eventHandlers))
widgetState.focusDelegate = nil
widgetState.actualLayerPlus1Cache = 0
widgetState.visibleCache = false
widgetState.visibleCacheValid = false
widgetState.enabledCache = false
widgetState.enabledCacheValid = false
widgetState.passthroughCacheValid = false
widgetState.passthroughCache = false
widgetState.focusedOrHasFocusedChild = false
widgetState.buttonInputReceptiveOrHasReceptiveChild = false
// Do not reset bounds an zs here, as they are used to determine whether redraw is needed.
}
// Swap widgetList and prevWidgetList so last frame's list is retained for the
// tree-exit sweep below, and reuse prevWidgetList's backing array as this
// frame's (empty) widgetList.
a.prevWidgetList, a.widgetList = a.widgetList, a.prevWidgetList
a.widgetList = slices.Delete(a.widgetList, 0, len(a.widgetList))
var adder ChildAdder
if err := traverseWidget(a.root, func(widget Widget) error {
widgetState := widget.widgetState()
widgetState.children = slices.Delete(widgetState.children, 0, len(widgetState.children))
adder.app = a
adder.widget = widget
if err := widget.Build(&a.context, &adder); err != nil {
return err
}
a.widgetList = append(a.widgetList, widget)
return nil
}); err != nil {
return err
}
// Reclaim widgetsAndBounds backing arrays from widgets that were in the tree
// last frame but are not this frame, so an incoming widget can pick them up
// from bounds3DsPool instead of allocating.
for _, widget := range a.prevWidgetList {
ws := widget.widgetState()
if ws.builtAt == a.buildCount {
continue
}
a.putBounds3Ds(ws.prev.bounds3Ds)
a.putBounds3Ds(ws.prev.currentBounds3D)
ws.prev.bounds3Ds = nil
ws.prev.currentBounds3D = nil
}
// Capture [Widget.WriteStateKey] snapshots so subsequent phases can detect state changes
// that would otherwise require an explicit [RequestRebuild] call. Also snapshot the
// framework-owned widgetState fields mutated via [Context] setters.
//
// If the key differs from the previous snapshot, the widget's state was mutated
// during this build cycle — typically by an ancestor's [Widget.Build] calling a
// setter on a descendant. Request a redraw so the Draw pass picks up the new
// state; without this, the widget would be Build-updated but never Draw-updated
// because its region would not be in regionsToDraw.
for _, widget := range a.widgetList {
ws := widget.widgetState()
newStateKey := a.widgetStateKey(widget)
newInternalStateKey := ws.internalStateKey()
if newStateKey != ws.capturedStateKey || newInternalStateKey != ws.capturedInternalStateKey {
requestRedraw(ws)
}
ws.capturedStateKey = newStateKey
ws.capturedInternalStateKey = newInternalStateKey
}
return nil
}
// checkStateKeys compares each widget's current [Widget.WriteStateKey] against the snapshot
// captured after the last [Widget.Build]. If the key has changed, it requests a rebuild.
// The snapshot is not refreshed here; it is only refreshed when [Widget.Build] runs again.
//
// The check is gated on stateKeyCheckPending: if no widget phase or [Context] setter has
// run since the last call, no state key could have changed and the iteration is skipped.
func (a *app) checkStateKeys() {
if !a.stateKeyCheckPending {
return
}
a.stateKeyCheckPending = false
for _, widget := range a.widgetList {
ws := widget.widgetState()
if ws.rebuildRequested {
continue
}
if ws.internalStateKey() != ws.capturedInternalStateKey {
a.requestRebuild(ws, requestRedrawReasonStateKeyChanged)
continue
}
if a.widgetStateKey(widget) == ws.capturedStateKey {
continue
}
a.requestRebuild(ws, requestRedrawReasonStateKeyChanged)
}
}
func (a *app) layoutWidgets() {
a.stateKeyCheckPending = true
clear(a.visitedLayers)
if a.visitedLayers == nil {
a.visitedLayers = map[int64]struct{}{}
}
var layouter ChildLayouter
for _, widget := range a.widgetList {
widgetState := widget.widgetState()
widgetState.hasVisibleBoundsCache = false
widgetState.visibleBoundsCache = image.Rectangle{}
widgetState.hasVisibleBoundsWithDescendantsCache = false
widgetState.visibleBoundsWithDescendantsCache = image.Rectangle{}
// Reset child layouts.
for _, child := range widgetState.children {
child.widgetState().bounds = image.Rectangle{}
}
// Call Layout.
// Even if widgetState.bounds.Empty(), call Layout to allow widgets to set up child states.
bounds := widgetBoundsFromWidget(&a.context, widget)
widget.Layout(&a.context, bounds, &layouter)
a.visitedLayers[widgetState.actualLayer()] = struct{}{}
}
a.layers = slices.Delete(a.layers, 0, len(a.layers))
a.layers = slices.AppendSeq(a.layers, maps.Keys(a.visitedLayers))
slices.Sort(a.layers)
}
func (a *app) updateHitWidgets(layoutChanged bool) {
pt := image.Pt(ebiten.CursorPosition())
if !layoutChanged && pt == a.lastCursorPosition {
return
}
a.lastCursorPosition = pt
a.maybeHitWidgets = slices.Delete(a.maybeHitWidgets, 0, len(a.maybeHitWidgets))
a.maybeHitWidgets = a.appendWidgetsAt(a.maybeHitWidgets, pt, a.root, true)
slices.SortStableFunc(a.maybeHitWidgets, func(a, b widgetAndLayer) int {
return cmp.Compare(b.layer, a.layer)
})
}
type handleInputType int
const (
handleInputTypePointing handleInputType = iota
handleInputTypeButton
)
func (a *app) handleInputWidget(typ handleInputType) HandleInputResult {
for i := len(a.layers) - 1; i >= 0; i-- {
layer := a.layers[i]
if r := a.doHandleInputWidget(typ, a.root, layer, a.context.IsFocused(a.root) || a.root.widgetState().buttonInputReceptive); r.IsHandled() {
return r
}
}
return HandleInputResult{}
}
func (a *app) doHandleInputWidget(typ handleInputType, widget Widget, layerToHandle int64, ancestorInputReceptive bool) HandleInputResult {
widgetState := widget.widgetState()
if widgetState.isPassthrough() {
return HandleInputResult{}
}
// Avoid (*Context).IsVisible and (*Context).IsEnabled for performance.
// These check parent widget states unnecessarily.
if widgetState.hidden {
return HandleInputResult{}
}
if widgetState.disabled {
return HandleInputResult{}
}
prunedForButtonInput := typ == handleInputTypeButton && !ancestorInputReceptive && !a.context.IsFocusedOrHasFocusedChild(widget) && !widgetState.buttonInputReceptive
// Even if this widget is pruned for button input, traverse children if a descendant is receptive.
if !prunedForButtonInput || widgetState.buttonInputReceptiveOrHasReceptiveChild {
// Iterate the children in the reverse order of rendering.
focused := a.context.IsFocused(widget)
for i := len(widgetState.children) - 1; i >= 0; i-- {
child := widgetState.children[i]
if r := a.doHandleInputWidget(typ, child, layerToHandle, ancestorInputReceptive || focused || widgetState.buttonInputReceptive); r.IsHandled() {
return r
}
}
}
if prunedForButtonInput {
return HandleInputResult{}
}
if layerToHandle != widgetState.actualLayer() {
return HandleInputResult{}
}
bounds := widgetBoundsFromWidget(&a.context, widget)
a.stateKeyCheckPending = true
switch typ {
case handleInputTypePointing:
return widget.HandlePointingInput(&a.context, bounds)
case handleInputTypeButton:
return widget.HandleButtonInput(&a.context, bounds)
default:
panic(fmt.Sprintf("guigui: unknown handleInputType: %d", typ))
}
}
func (a *app) cursorShape() bool {
var layer int64
for _, wl := range a.maybeHitWidgets {
if layer > wl.layer {
return false
}
widgetState := wl.widget.widgetState()
if !widgetState.isVisible() {
continue
}
if widgetState.isPassthrough() {
continue
}
if !widgetState.isEnabled() {
return false
}
bounds := widgetBoundsFromWidget(&a.context, wl.widget)
shape, ok := wl.widget.CursorShape(&a.context, bounds)
if !ok {
layer = wl.layer
continue
}
ebiten.SetCursorShape(shape)
return true
}
return false
}
func (a *app) tickWidgets() error {
for _, widget := range a.widgetList {
ws := widget.widgetState()
if ws.hasCustomTickChecked && !ws.hasCustomTick {
continue
}
bounds := widgetBoundsFromWidget(&a.context, widget)
if !ws.hasCustomTickChecked {
a.context.resetDefaultTickMethodCalled()
}
a.stateKeyCheckPending = true
if err := widget.Tick(&a.context, bounds); err != nil {
return err
}
if !ws.hasCustomTickChecked {
ws.hasCustomTickChecked = true
ws.hasCustomTick = !a.context.isDefaultTickMethodCalled()
}
}
return nil
}
func (a *app) requestRedrawIfTreeChanged() {
for _, widget := range a.widgetList {
widgetState := widget.widgetState()
// If the children and/or children's bounds are changed, request redraw.
if !widgetState.prev.equals(&a.context, widgetState.children) {
a.requestRedraw(a.context.visibleBounds(widgetState), requestRedrawReasonLayout, nil)
widgetState.prev.requestRedraw(a)
// If the widget is a clipping widget, all the children are included in the visible bounds.
if !widgetState.clipChildren {
for _, child := range widgetState.children {
a.requestRedraw(a.context.visibleBounds(child.widgetState()), requestRedrawReasonLayout, nil)
}
}
}
// Update prev to the current state for the next frame's comparison,
// reusing the currentBounds3D already computed by equals().
widgetState.prev.commitCurrent()
}
}
func (a *app) drawWidget(screen *ebiten.Image) {
if a.regionsToDraw.Empty() {
return
}
dst := screen
if dst.Bounds() != a.regionsToDraw {
dst = screen.RecyclableSubImage(a.regionsToDraw)
}
// Clear the redraw region so pixels no widget overdraws don't keep stale contents
// from the previous frame.
dst.Clear()
for _, layer := range a.layers {
a.doDrawWidget(dst, a.root, layer)
}
if dst != screen {
dst.Recycle()
dst = nil
}
}
func (a *app) doDrawWidget(dst *ebiten.Image, widget Widget, layerToRender int64) {
// Do not skip this even when visible bounds are empty.
// A child widget might have a different layer value and different visible bounds.
widgetState := widget.widgetState()
if widgetState.hidden {
return
}
if dst.Bounds().Empty() {
return
}
opacity := widgetState.opacity()
if opacity == 0 {
return
}
vb := a.context.visibleBounds(widgetState)
var copiedDst *ebiten.Image
var recyclable bool
renderCurrent := layerToRender == widgetState.actualLayer() && !dst.Bounds().Intersect(vb).Empty()
if renderCurrent {
if opacity < 1 {
// Keep the current destination image to draw it with the opacity later.
copiedDst, recyclable = widgetState.ensureOffscreen(dst.Bounds())
if recyclable {
defer copiedDst.Recycle()
}
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64(dst.Bounds().Min.X), float64(dst.Bounds().Min.Y))
op.Blend = ebiten.BlendCopy
copiedDst.DrawImage(dst, op)
}
widgetBounds := widgetBoundsFromWidget(&a.context, widget)
subDst := dst
if dst.Bounds() != vb {
subDst = dst.RecyclableSubImage(vb)
}