Repository navigation
Expand file tree
/
Copy pathglass_host.dart
More file actions
1859 lines (1727 loc) · 78.5 KB
/
Copy pathglass_host.dart
File metadata and controls
1859 lines (1727 loc) · 78.5 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
// The thing that runs the pipeline on a real screen.
//
// A host owns the register, the pipeline and the retake oracle, records after
// the frame that has just been painted, and publishes the result to the
// surfaces, which draw it on the frame after that.
//
// **The one-frame delay is structural, not a bug to be fixed later.** A capture
// reads the tree that was just painted, so the earliest a surface can show it
// is the following frame; that is the staleness the retake budget prices, and
// it is why the first frame of any screen paints without a proxy. Both facts
// are counted rather than hoped for — a surface that never gets a proxy and one
// that gets a stale one look identical on a screenshot.
//
// What this deliberately does not do is choose *when* the frame happens. It
// records in a post-frame callback, because that is the only place the tree is
// both laid out and painted; the oracle decides whether to record at all.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import '../hardware.dart';
import '../thermal.dart';
import '../proxy/occlusion.dart';
import '../proxy/proxy_blur.dart';
import '../proxy/proxy_layer_watch.dart';
import '../proxy/proxy_pipeline.dart';
import '../proxy/proxy_resolution.dart';
import '../proxy/proxy_retake.dart';
import '../proxy/proxy_walk.dart';
import '../proxy/shadow_filter.dart';
import 'glass_above.dart';
import 'glass_adaptive.dart';
import 'glass_drop_motion.dart';
import 'glass_finish.dart';
import 'glass_group.dart';
import 'glass_ledger.dart';
import 'glass_press.dart';
import 'glass_ripple.dart';
import 'glass_surface.dart';
import 'glass_theme.dart';
import 'glass_tier.dart';
/// Where the package's own shader lives.
///
/// One key in every bundle: the pubspec declares it through `packages/g1455/`
/// and keeps the file under `lib/`, which the tool keys identically whether
/// this package is the root or a dependency (see `pubspec.yaml`).
///
/// {@category Diagnostics}
const String kGlassShaderAsset = 'packages/g1455/shaders/glass_surface.frag';
/// The surface's shader with the ripple compiled in.
///
/// Loaded the first time a surface under a host declares a [GlassRipple], or
/// by [GlassHost.precache].
///
/// {@category Diagnostics}
const String kGlassRippleShaderAsset = 'packages/g1455/shaders/glass_surface_ripple.frag';
/// The current proxy, as something a surface can listen to.
///
/// A [Listenable] holding one frame, so a surface repaints when the proxy is
/// re-recorded and not when anything else happens. The frame's ownership stays
/// with the pipeline; this only points at it.
///
/// Every [GlassHost] owns one and hands it down through [GlassProxyScope].
/// What a report reads off it is the counters — [generation], [snapshots],
/// [repacks], [readBacks] and the rest — which say whether a frame captured.
///
/// ```dart
/// final GlassProxyHandle? handle = GlassProxyScope.maybeOf(context);
/// debugPrint('published ${handle?.generation} frames, '
/// '${handle?.snapshots} snapshots');
/// ```
///
/// {@category Diagnostics}
class GlassProxyHandle extends ChangeNotifier {
GlassProxyFrame? _frame;
/// The proxy last published at the base level, or null before the first
/// capture and on a screen with nothing to capture.
GlassProxyFrame? get frame => _frame;
/// The compiled shader, once it has arrived.
///
/// Null until then, and a surface with a proxy and no program draws the
/// **unrefracted** proxy rather than nothing — which is better than a flat
/// tint and worse than glass, so it is counted separately
/// (`RenderGlassSurface.paintsWithOptics`) rather than left to look like
/// success on a screenshot.
ui.FragmentProgram? get program => _program;
ui.FragmentProgram? _program;
set program(ui.FragmentProgram? value) {
if (identical(value, _program)) {
return;
}
_program = value;
notifyListeners();
}
/// The compiled *group* shader, once it has arrived.
///
/// A second program rather than a mode of the first, because adding a path to
/// a runtime effect reprices every mode already in it by 52-62% and the lone
/// surface is the common case. Loaded whether or not the screen has a
/// group: a host that compiled it lazily would put the first frame of a
/// fused toolbar on a different code path from every frame after it.
ui.FragmentProgram? get groupProgram => _groupProgram;
ui.FragmentProgram? _groupProgram;
set groupProgram(ui.FragmentProgram? value) {
if (identical(value, _groupProgram)) {
return;
}
_groupProgram = value;
notifyListeners();
}
/// The surface's program with the ripple compiled in, once something asked
/// for it ([wantRippleProgram]) and it arrived.
///
/// A third program for the same reason, and loaded on demand rather than
/// with the other two: a ripple is opt-in, and a screen that never declares one
/// should not compile it. Until it arrives a touched surface draws the base
/// program, which is the picture without the wave.
ui.FragmentProgram? get rippleProgram => _rippleProgram ??= _cachedRippleProgram;
ui.FragmentProgram? _rippleProgram;
static ui.FragmentProgram? _cachedRippleProgram;
static Future<ui.FragmentProgram>? _loadingRipple;
/// The one load of the ripple program per process, which fills the cache
/// before anything waiting on it runs — shared by [wantRippleProgram] and
/// [GlassHost.precache].
static Future<ui.FragmentProgram> _loadRipple() => _loadingRipple ??= _loadShader(
kGlassRippleShaderAsset,
(ui.FragmentProgram program) => _cachedRippleProgram = program,
() => _loadingRipple = null,
);
/// Loads [rippleProgram], once per process, and notifies when it lands.
void wantRippleProgram() {
if (rippleProgram != null) {
return;
}
_loadRipple().then((ui.FragmentProgram program) {
if (_rippleProgram == null && !_disposed) {
_rippleProgram = program;
notifyListeners();
}
}, onError: _reportShaderLoadError);
}
bool _disposed = false;
/// What the host declared its hardware to be.
///
/// Carried here for the one choice a group makes at paint time that the host
/// cannot make for it: whether the fused draw is split. Splitting is cheaper
/// on some GPU families and dearer on others, so a group has to be told
/// which one it is on, and the handle is what every group below a host holds.
GlassHardware get hardware => _hardware;
GlassHardware _hardware = GlassHardware.detect();
set hardware(GlassHardware value) {
if (value == _hardware) {
return;
}
_hardware = value;
notifyListeners();
}
/// How many frames have been published. The counter that tells a surface with
/// no proxy apart from a surface whose proxy never updates.
int get generation => _generation;
int _generation = 0;
/// How many rasterizations the pipeline has asked the engine for.
///
/// Set by the host from `GlassProxyPipeline.snapshots`, because that is where
/// they are taken. It is what gives [GlassHost.blurPass] an observable trace:
/// `split` and `folded` publish the same picture from the same divisor at the
/// same sigma, and a report carrying only the label would be recording what
/// was asked for rather than what ran.
int snapshots = 0;
/// How many times the atlas layout has been repacked.
///
/// Set from `GlassProxyPipeline.repacks` for the same reason [snapshots] is:
/// without it, the one thing a retained layout is *for* would be
/// unobservable from outside. Repacking every frame is the dominant cost of
/// the whole route, and the ratio to [generation] is the reading — 1.0 means
/// nothing is retained.
int repacks = 0;
/// How many entries the layer watch's last signature had, or 0 if it never
/// ran.
///
/// The trace the watch would otherwise not have: without it a run that never
/// walked would report as a walk that costs nothing. Non-zero says the
/// composited subtree was described; its size says how much of one.
int watchedLayers = 0;
/// How many frames the watch saw a change that missed every slot of the atlas.
///
/// A counter rather than a flag because "a shared texture is a shared dirty
/// flag" is an argument about a *rate*: a mechanism that pays on 3% of
/// frames and one that pays on 90% call for different designs. It is
/// separately readable from [generation] on purpose — a report that only
/// counted publishes could not tell a screen where nothing moved from one
/// where everything moved away from the glass.
int changesOutsideCapture = 0;
/// Frames on which the GPU's texture limit moved the divisor.
///
/// Set from `GlassProxyPipeline.ceilingDeepenings` and `ceilingRefusals`, and
/// here for the reason every other counter on this handle is: the ceiling
/// fires on a geometry nobody arranges on purpose — one oversized sheet on a
/// desktop-sized window — so a report that did not carry it could not tell a
/// run where it never fired from a run where it fired on every frame, and
/// those look identical in every timing.
///
/// [ceilingOverruns] is the third and it is the one that should never move:
/// the search reasons about the layout before packing it, the check after the
/// pack only refuses, and both can drop a frame. Non-zero means the reasoning
/// was wrong, which is a bug report and not a measurement.
int ceilingDeepenings = 0;
/// Frames on which nothing fit under the texture limit and no proxy was
/// produced. See [ceilingDeepenings].
int ceilingRefusals = 0;
/// Frames the pack overran a limit the search had reasoned it would fit
/// under. Should stay at zero; see [ceilingDeepenings].
int ceilingOverruns = 0;
/// Frames held across a change because thermal pressure bought the lag,
/// mirrored from the host so a report can read it beside
/// [generation]: the two reset together, with the tree, and a throttle that
/// never fired and one that fired every frame are otherwise the same run.
int throttled = 0;
/// How many times the host has read the backdrop back for glass that reads
/// it (`GlassHost.adaptive`) — zero for ever on a host without it, which is
/// the observable that says the feature costs nothing when off.
///
/// Counted when a read is started rather than when it lands, because the
/// start is what was paid for: a read-back still in flight when the host goes
/// away cost its copy all the same.
int readBacks = 0;
/// The verdicts of the glass under this host, when it reads its backdrop;
/// null when it does not. What a component listens to — apart from this
/// handle, whose own notifications repaint every surface.
GlassBackdropReadings? get readings => _readings;
GlassBackdropReadings? _readings;
/// Declares a change nothing above the content is painted for.
///
/// The last resort under [GlassContentDeclaration.declared]: the host
/// observes a scroll, its own repaint and the composited layers on its own.
/// What is left is a change none of those can see.
///
/// Reach it with `GlassProxyScope.maybeOf(context)?.noteChange()`.
///
/// Free under [GlassContentDeclaration.undeclared], where the proxy is
/// re-recorded anyway, and the difference between a working screen and a
/// frozen one under the default.
void noteChange() => _changes.notify();
/// Fires when [noteChange] is called. The host listens; nothing else should.
Listenable get changes => _changes;
final _HandleChanges _changes = _HandleChanges();
@override
void dispose() {
_disposed = true;
_changes.dispose();
super.dispose();
}
/// Publishes [frame] as the base level and starts a new [generation].
///
/// Called by the host; silent when [frame] is the one already published.
void publish(GlassProxyFrame? frame) {
if (identical(frame, _frame)) {
return;
}
_frame = frame;
_generation++;
notifyListeners();
}
/// The proxies of glass that stands on glass, by level: `upper[0]` is what
/// the surfaces one glass deep sample, and so on up.
///
/// A level apart from [frame] rather than more slots in it, because what a
/// level captures *contains* the level below it drawn — the lens over a tab
/// bar has to see the bar's glass and its icons — so it can only be recorded
/// once the level below has been published. See `GlassHost` for the walk.
List<GlassProxyFrame?> get upper => _upper;
List<GlassProxyFrame?> _upper = const <GlassProxyFrame?>[];
/// Publishes the levels above [frame]. Not a new generation: they are the
/// same capture, finished.
///
/// Silent when nothing changed, as [publish] is: the host publishes the
/// levels on every frame that has nothing to capture, and a notification
/// there repaints every surface at presence zero, whose repaint is the next
/// frame — a screen whose only glass was a resting drop (a segmented
/// control, a switch) never settled.
void publishUpper(List<GlassProxyFrame?> frames) {
if (listEquals(frames, _upper)) {
return;
}
_upper = List<GlassProxyFrame?>.unmodifiable(frames);
notifyListeners();
}
/// The frame that holds [key]'s slot: the base one, or the level it stands
/// at. The base one when none does, so that the caller's `slotForKey` says
/// "not in this frame" exactly as it did before there were levels.
GlassProxyFrame? frameFor(Object key) {
final GlassProxyFrame? base = _frame;
if (_upper.isEmpty || (base != null && base.keys.contains(key))) {
return base;
}
for (final GlassProxyFrame? frame in _upper) {
if (frame != null && frame.keys.contains(key)) {
return frame;
}
}
return base;
}
}
/// The application's own change declarations, as something the host can watch.
///
/// Shaped like `RenderGlassProxy.proxyChanges` on purpose: the oracle already
/// subscribes to that, so a second input to the same decision is the same kind
/// of thing rather than a second mechanism.
class _HandleChanges extends ChangeNotifier {
void notify() => notifyListeners();
}
/// Carries the current proxy down the tree.
///
/// Installed by [GlassHost] around its child; an application does not build
/// one. [maybeOf] is how a test, a benchmark or a custom component reaches the
/// host's [GlassProxyHandle].
///
/// {@category Diagnostics}
class GlassProxyScope extends InheritedWidget {
/// Hands [handle] to [child] and everything below it.
const GlassProxyScope({required this.handle, required super.child, super.key});
/// The host's handle.
final GlassProxyHandle handle;
/// The handle of the nearest [GlassHost] above [context], or null when there
/// is none. Registers [context] for a rebuild when the handle is replaced.
static GlassProxyHandle? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<GlassProxyScope>()?.handle;
@override
bool updateShouldNotify(GlassProxyScope oldWidget) => oldWidget.handle != handle;
}
/// Owns the whole proxy pipeline for one screen: it captures what is painted
/// under the glass and hands it to every [GlassSurface] below it.
///
/// Put it above everything the glass is meant to show — in an application,
/// once, above the navigator.
///
/// ## How it captures
///
/// Its child is the screen: the register finds the surfaces inside it, the
/// pass reads it, and the surfaces sample the result. After each frame is
/// painted the host records what is under the glass into one atlas, at a
/// resolution chosen against a measured quality budget ([budgetDeltaE]), and
/// publishes it; the surfaces draw it through their finish on the frame after.
///
/// **The one-frame delay is structural.** A capture reads the tree that was
/// just painted, so the earliest a surface can show it is the following frame,
/// and the first frame of any screen paints its glass without a proxy. The
/// shaders arrive asynchronously too, which [precache] moves to before the
/// first frame.
///
/// It records only when something under the glass changed ([content]): a
/// still screen captures nothing, and glass moving over still content inside a
/// [GlassTravel] captures nothing either. Below the top rung ([tier]) nothing
/// is captured at all.
///
/// ## What the application declares
///
/// What the render tree does not carry, the host is told:
///
/// * what is behind the glass: [backdrop], and whether it is an image,
/// [richBackdrop];
/// * the accessibility the platform does not relay everywhere:
/// [highContrast], and a floor for the labels, [minLabelContrast];
/// * the device: [hardware], and its [thermal] state;
/// * the look: [finish], [tier], [ripple], [dropMotion], [press], and whether the
/// glass reads its own backdrop, [adaptive].
///
/// Each is installed into a [GlassThemeData] for the screen, which an inner
/// [GlassTheme] can change for a subtree. The rest — [maxCaptures], [blurPass],
/// [resolution], [maxTextureSide], [shadowFilter], [occlusion] — are
/// diagnostic seams and overrides that a shipping application leaves alone.
///
/// ## Where it goes
///
/// Above the navigator, in `MaterialApp.builder` (or the `builder` of
/// `CupertinoApp` or `WidgetsApp`), so that a dialog, a sheet or a menu — all
/// built in the navigator's overlay — is under it and captured like any other
/// glass. A host inside a route would not see them.
///
/// ```dart
/// Future<void> main() async {
/// WidgetsFlutterBinding.ensureInitialized();
/// await GlassHost.precache();
/// runApp(const MyApp());
/// }
///
/// class MyApp extends StatelessWidget {
/// const MyApp({super.key});
///
/// @override
/// Widget build(BuildContext context) => MaterialApp(
/// builder: (BuildContext context, Widget? child) => GlassHost(
/// backdrop: const Color(0xFF101014),
/// richBackdrop: true,
/// minLabelContrast: kTextContrastAA,
/// child: child!,
/// ),
/// home: const HomePage(),
/// );
/// }
/// ```
///
/// See also:
///
/// * [GlassSurface], the glass that samples what the host captures.
/// * [GlassTheme] and [GlassThemeData], what the host installs for its
/// subtree.
/// * [GlassFinish], the material named by [finish].
/// * [GlassTravel] and [GlassProxy], which tell the host where glass moves
/// and how a subtree is captured.
/// * [The host](https://g1455.plugfox.dev/foundations/host) and
/// [Installation](https://g1455.plugfox.dev/start/installation) on the site.
///
/// {@category Foundations}
class GlassHost extends StatefulWidget {
/// A host over [child]. Every other argument is optional, and its default is
/// the shipping behaviour.
const GlassHost({
required this.child,
this.hardware,
this.finish,
this.appearance,
this.tier = GlassTierChoice.byDefault,
this.backdrop,
this.highContrast,
this.richBackdrop = false,
this.minLabelContrast,
this.ripple,
this.dropMotion = const GlassDropMotion(),
this.press = const GlassPress(),
this.thermal,
this.thermalPolicy = const GlassThermalPolicy(),
this.budgetDeltaE = ProxyResolutionPolicy.defaultDamageBudgetDeltaE,
this.shadowFilter,
this.occlusion,
this.resolution,
this.maxCaptures,
this.maxTextureSide,
this.blurPass,
this.content = GlassContentDeclaration.byDefault,
this.adaptive,
super.key,
});
/// The screen: everything the glass under this host may show, and the
/// glass itself. In an application, the navigator `MaterialApp.builder`
/// hands over.
final Widget child;
/// Whose measurements apply. Defaults to what the platform can be asked —
/// Apple platforms answer, everything else is [GlassHardware.unmeasured],
/// which gets the same divisor and the same merging as a declared family and
/// a null where the price would be.
final GlassHardware? hardware;
/// The optics every surface under this host wears unless it names its own.
///
/// Its `name` is the key into the measured damage tables and its sigma
/// decides the bleed, the residual blur and — through the budget — the retake
/// ceiling. So a finish nobody has graded gets refusals rather than numbers,
/// which is the intended behaviour.
///
/// Null is Apple's `.regular`, which is two materials:
/// [GlassFinish.regular] picks [GlassFinish.regularDark] or
/// [GlassFinish.regularLight] from [backdrop] and the platform's appearance,
/// and the host follows the appearance as it changes. Name either branch to
/// hold it — a dark glass on a light screen is a choice Apple's material
/// does not make, and this is where an application makes it.
final GlassFinish? finish;
/// The appearance `.regular` picks its branch in when [finish] is null, or
/// null to follow the platform's (`MediaQuery.platformBrightnessOf`).
///
/// Declare it when the application's theme does not follow the phone's. A
/// dark-themed application on a phone in the light appearance otherwise
/// gets light glass over its dark content: in the light appearance
/// `.regular` takes its light branch over anything above a luma of 54
/// ([GlassFinish.kRegularSwitchLight]), and an ordinary dark grey page is above that.
///
/// ```dart
/// MaterialApp(
/// themeMode: mode,
/// builder: (context, child) => GlassHost(
/// appearance: mode == ThemeMode.system ? null : (mode == ThemeMode.dark ? Brightness.dark : Brightness.light),
/// child: child!,
/// ),
/// )
/// ```
///
/// Unlike naming a branch in [finish], this keeps `.regular` a choice:
/// [backdrop] and [adaptive] still move the glass between its branches, in
/// the appearance declared here. Ignored when [finish] is named.
final Brightness? appearance;
/// Which rung of the finish ladder every surface under this host draws.
///
/// [GlassTier.full] and its reasons are in `glass_tier.dart`; the short
/// version is that the ladder has no automatic input, so this is a
/// declaration and the package supplies no default but the top rung.
///
/// Below the top rung the whole pipeline goes quiet: nothing under this host
/// reads a proxy, so nothing is captured, no atlas is packed and no shader is
/// sampled. The host still mounts — its register still counts the glass,
/// because the translucency tax does not care which rung drew it — and
/// `recorded` stays at zero, which is the observable that says the lower
/// rungs read no backdrop at all.
final GlassTierChoice tier;
/// What is behind the glass on this screen, on average.
///
/// Installed into the theme, and read by [GlassTier.opaque] alone — see
/// [GlassThemeData.backdrop] for why the bottom rung is the only one that
/// cannot work it out for itself.
final Color? backdrop;
/// The platform's increase-contrast switch, or null to read it from
/// `MediaQuery.highContrastOf` — which the engine sets on iOS and on Android
/// 34+, and **never on macOS**, where the application has to read
/// `NSWorkspace.accessibilityDisplayShouldIncreaseContrast` itself and pass
/// it. See [GlassThemeData.highContrast] for what it draws.
final bool? highContrast;
/// Whether the screen under the glass is an image rather than a colour. See
/// [GlassThemeData.richBackdrop].
final bool richBackdrop;
/// The least contrast a component label must reach, met by dimming the glass
/// when the finish cannot reach it. See [GlassThemeData.minLabelContrast].
final double? minLabelContrast;
/// Whether the glass reads its own backdrop, and how; null — the default —
/// for glass that goes by what is declared ([backdrop], [richBackdrop], the
/// platform's appearance).
///
/// Set, each component under this host ([GlassBar], [GlassCard],
/// [GlassButton]) is told the mean level of the captured backdrop inside its
/// own box, and picks the branch of `.regular` and its label colour from it —
/// so a bar over a photograph's sky and a button over its shadow each wear
/// the branch Apple's material would. The precedence against what is
/// declared, and the band and hold that keep it from flickering, are in
/// [GlassAdaptive] and `glass_adaptive.dart`.
///
/// **What it costs** is one small asynchronous read-back per capture at most,
/// never per frame, and nothing on a frame that keeps its capture unless a
/// glass moved inside its [GlassTravel]; at most one per
/// [GlassAdaptive.interval], which is longer on the web, where a read-back
/// stalls CanvasKit. A screen whose glass reads both branches of `.regular`
/// is priced by the stricter one, which can lower the capture's divisor.
/// Off, nothing is read, recorded or scheduled, and
/// [GlassProxyHandle.readBacks] stays at zero.
///
/// A raw [GlassSurface] does not adapt on its own: the label is the
/// component's, and so is the move between branches.
/// [GlassThemeData.adaptedTo] is what a custom component calls to do the
/// same, with a reading it gets from `GlassProxyHandle.readings` — which,
/// with [GlassProxyScope] and [GlassBackdropReadings], is exported by
/// `package:g1455/glass_diagnostics.dart`, not by this library.
final GlassAdaptive? adaptive;
/// The wave every surface below makes when touched, or null for none — the
/// platform's behaviour. See [GlassThemeData.ripple] and [GlassRipple].
final GlassRipple? ripple;
/// How the held drop of the switch, the slider, the segmented control and
/// the tab bar deforms as it launches and brakes, unless a control declares
/// its own. [GlassDropMotion.none] keeps every drop round. It costs no
/// capture; see [GlassThemeData.dropMotion] and [GlassDropMotion].
final GlassDropMotion dropMotion;
/// How a pressed [GlassButton] swells and leans toward a dragging finger,
/// unless it declares its own. [GlassPress.none] keeps every button its
/// size. It costs two captures a press and nothing at rest; see
/// [GlassThemeData.press] and [GlassPress].
final GlassPress press;
/// The device's thermal state, as the application read it — the package
/// ships no platform code to read it. Null is nominal.
///
/// Spent by [thermalPolicy] on the retake, never on the ladder: under
/// pressure a changing screen may be captured less often, by as many frames
/// as the finish's own staleness price allows.
final GlassThermalState? thermal;
/// What each thermal state may spend on staleness. [GlassThermalPolicy.never]
/// keeps every frame fresh whatever the device says.
final GlassThermalPolicy thermalPolicy;
/// The whole quality allowance, in ΔE against the same finish at full
/// quality. 1% of the distance between two of Apple's own materials.
///
/// One number for both axes, because the resolution's error and the
/// staleness's compose rather than add: the divisor is chosen against it and
/// the retake ceiling is what is left afterwards.
final double budgetDeltaE;
/// Whether this screen may hold a proxy nothing under it has changed.
///
/// **The default holds.** That is the largest lever this package has: holding
/// a still screen saves 66…79% of the glass's added cost on Adreno and 98% on
/// Metal, because the capture is most of what the route adds.
///
/// Holding is safe without any promise from the application: the host walks
/// the composited subtree each frame (under 3 µs) and retakes on any change
/// it sees. What is left of the risk lives in one table of layer types, and a
/// test checks that table against the SDK's `layer.dart`.
///
/// Pass [GlassContentDeclaration.undeclared] to go back to re-recording every
/// frame — for a host compositing through something it thinks this package
/// misreads, or for a benchmark that wants the capture on every frame.
final GlassContentDeclaration content;
/// Which shadows the capture may skip. Of the quality degradations measured,
/// this is the cheapest by a wide margin: under 0.2 ΔE behind the glass.
///
/// Null means "draw them", which is the conservative default rather than the
/// cheap one — half of `ShadowFilter` is a heuristic (a shape, line, point
/// or image painted through a `MaskFilter` is *usually* a shadow), and a
/// design that blurs a highlight on purpose would lose it silently.
final ShadowFilter? shadowFilter;
/// Where the descent may stop, if the application has worked it out.
final OcclusionPolicy? occlusion;
/// The proxy divisor, named by the host instead of chosen from the tables.
///
/// Null is the normal case and the one every application should use: the
/// policy trades measured quality against measured price and says which of
/// the four things stopped it. This overrides that, and it exists because the
/// tables cannot be checked without it — see
/// [ProxyDivisorReason.pinnedByHost]. It is the same shape as [hardware]:
/// something the package cannot work out, declared by whoever can.
final ProxyResolution? resolution;
/// Stops recording after this many captures. Null records for ever, which is
/// the only shipping behaviour.
///
/// **A diagnostic seam.** It separates the capture's own cost from the cost
/// of sampling its result: a held proxy is still sampled every frame at
/// exactly the same size, so the shader's work does not change and only the
/// recording stops — which is how a frame on Xclipse that spent 28.5 ms
/// waiting with the GPU 54% busy can be traced to its cause.
///
/// Setting it makes the picture wrong on purpose: the proxy goes stale for
/// ever, which is a cost experiment and never a mode. `held` and `recorded`
/// are what say which happened.
final int? maxCaptures;
/// How the residual blur reaches the atlas — and, at [ProxyBlurPass.none],
/// whether it reaches it at all. The second diagnostic on this widget, and at
/// that value the same shape as [maxCaptures]: it makes the picture wrong on
/// purpose, so it is a cost experiment and never a mode.
///
/// [ProxyBlurPass.folded] is the exception — it draws the same picture to
/// within a code value. Its price differs in sign between GPU families, so
/// null here takes [ProxyBlurPass.defaultFor], which reads the hardware
/// declaration. Naming one overrides that.
///
/// [ProxyBlurPass.none] exists to explain why the cost stops falling with the
/// divisor (on the M2 iPad Pro, 0.94 and 0.65 ms saved across the first two
/// steps, then 0.05): at a divisor of 8 this pass's sigma in texels falls to 0.58, where
/// Impeller's truncation radius `(σ − 0.5)·√3` is 0.13 of a texel. Turning it
/// off splits "the blur ran out" from "the bandwidth ran out"; nothing else
/// does, because both follow the proxy and neither has a counter.
///
/// Not a finish of sigma 0, which would be a different material and would
/// change the shader as well as the pass.
final ProxyBlurPass? blurPass;
/// The largest texture this GPU will actually allocate, in device pixels a
/// side. Null takes [GlassHardware.maxTextureSide], which is a specification
/// floor rather than a reading of the device.
///
/// Worth declaring on a large screen and pointless on a phone: it is what
/// stops the atlas from being handed to a `toImageSync` that would silently
/// rescale it (`AtlasLayout.fitsTexture`), and the package's only answer to
/// hitting it is a coarser proxy. A host that knows its device reports 16384
/// and says so keeps the quality the floor of 4096 would have spent.
final int? maxTextureSide;
/// Compiles the package's shaders now, so that the first glass on screen is
/// drawn through its optics rather than without them.
///
/// ```dart
/// Future<void> main() async {
/// WidgetsFlutterBinding.ensureInitialized();
/// await GlassHost.precache();
/// runApp(const MyApp());
/// }
/// ```
///
/// **What it changes.** A host otherwise starts compiling in its
/// `initState` — `FragmentProgram.fromAsset` is a future — and until a
/// program lands, the glass that needs it draws a stand-in:
///
/// - a surface with a proxy and no surface program draws the captured,
/// blurred backdrop clipped to its shape: no tint, no rim, no bend
/// (`RenderGlassSurface.paintsWithOptics` counts the difference). A faded
/// surface, such as a soft `GlassScrollEdge`, draws nothing;
/// - a fused [GlassGroup] with no group program draws nothing at all, and
/// its members leave their glass to it;
/// - a touched surface under a [GlassRipple] with no ripple program draws
/// the surface program, which is the picture without the wave;
/// - on Impeller, a proxy captured before the atlas's Gaussian arrives is
/// blurred by the engine's `ImageFilter.blur`, whose kernel is cut short,
/// and is captured again on the frame after it does.
///
/// The content on the glass — a bar's title, a button's icon — is drawn in
/// every case. Once this future completes, every host mounted afterwards
/// finds the programs in the cache and hands them to its surfaces in its
/// `initState`, before its first frame.
///
/// **What it does not change.** A capture reads the frame that was just
/// painted, so the very first frame of a host has no proxy and its glass
/// draws only its content, precached or not; the first frame that *has* a
/// proxy is the one this makes glass. The lower rungs ([GlassTier.cheap],
/// [GlassTier.opaque]) read no program and do not need it.
///
/// Shares the loads a host starts on its own, so it is idempotent, costs
/// nothing once the programs are in, and never compiles one twice — called
/// after a host has mounted, it waits for the load already in flight.
/// [group] and [ripple] leave out the blend group's program and the
/// ripple's, for an application that uses neither; every host still loads
/// the group program itself when it mounts. Completes with a load's error
/// if one fails.
///
/// > **Note:** the shaders are declared in this package's own pubspec, so an
/// > application adds nothing to its `flutter: shaders:` for them.
///
/// See also:
///
/// * [GlassRipple], whose program `ripple: false` leaves out.
/// * [GlassGroup], whose program `group: false` leaves out.
/// * [Installation](https://g1455.plugfox.dev/start/installation) on the
/// site.
static Future<void> precache({bool group = true, bool ripple = true}) async {
// What is cached is not waited on: the load that filled it is done, and
// its future belongs to the zone that started it — in a widget test, the
// fake clock of a test that may have ended, which nothing flushes again.
await Future.wait(<Future<ui.FragmentProgram>>[
if (_GlassHostState._cachedProgram == null) _GlassHostState._loadBase(),
if (group && _GlassHostState._cachedGroupProgram == null) _GlassHostState._loadGroup(),
if (ripple && GlassProxyHandle._cachedRippleProgram == null) GlassProxyHandle._loadRipple(),
if (ui.ImageFilter.isShaderFilterSupported && glassBlurProgram == null) _GlassHostState._loadBlur(),
]);
}
@override
State<GlassHost> createState() => _GlassHostState();
}
class _GlassHostState extends State<GlassHost> {
final GlassLedger _ledger = GlassLedger();
/// What actually establishes that nothing changed, when the host is allowed
/// to hold at all.
///
/// The observations above it — a scroll, this host's own repaint, a marker —
/// are cheap and correct and *incomplete*: each of them stops at a nested
/// repaint boundary, and a realistic screen crosses 8 to 15 of those. This
/// one cannot be hidden from, because a repaint mints new pictures in
/// whichever layer owns it, and a change that repaints nothing (a moved
/// retained layer) is a property of that layer. It runs only where
/// holding is possible: under the default declaration the proxy is re-recorded
/// anyway and the walk would be pure cost.
final ProxyLayerWatch _watch = ProxyLayerWatch();
/// The same walk with only the glass *draws* excluded, advanced only inside
/// the watch's assertion and so only in debug.
///
/// The assertion is about the table, and the table is what both walks share;
/// what excluding a whole surface adds is a second reason for "no change"
/// that is not a hole. A repaint of the host's boundary mints its new
/// pictures wherever its dirty children paint, and when every one of them is
/// inside glass — a label in a bar changing, with nothing of the boundary's
/// own painted outside the glass — the oracle's walk is right to see nothing:
/// none of it is in the proxy. A label changing on a tap is exactly that.
///
/// Not a walk with nothing excluded, which is the obvious version and has no
/// teeth: a draw layer is a type the table does not read, so it reports a
/// change on every frame and the assertion could never fire while any glass
/// was on the screen. This one is weaker than the oracle's walk on one kind
/// of frame: a publish repaints a surface, and with it the content inside, so
/// right after one the content walk changes and a hole elsewhere would pass.
/// On every frame without a publish it is as quiet as the oracle's — the
/// steady state, where a held proxy is what is at stake.
final ProxyLayerWatch _debugWatchContent = ProxyLayerWatch();
/// Whether the framework painted this host's subtree during the frame just
/// ended. Read by the watch's own assertion and cleared with every capture.
bool _framePainted = false;
final GlassProxyHandle _handle = GlassProxyHandle();
final GlobalKey _rootKey = GlobalKey();
late GlassProxyPipeline _pipeline;
late RetakeOracle _oracle;
bool _scheduled = false;
/// Frames that were recorded, and frames that were held. Counted because a
/// policy that quietly records every frame looks exactly like one that works.
int recorded = 0;
int held = 0;
/// Of [held], the frames held across a change because thermal pressure bought
/// the staleness. Counted apart because it is the one hold that knows
/// its picture is out of date.
int throttled = 0;
/// How many [GlassProxy] markers the oracle is subscribed to.
///
/// Exposed for the same reason [recorded] and [held] are: a subscription that
/// never happened and one that found nothing to subscribe to look identical
/// from outside.
int get watchedMarkers => _oracle.watchedMarkers;
/// Whether the marker subscription has to be rebuilt before the next capture.
///
/// The walk is `visitChildren` over the whole subtree — about 24 µs per pass
/// on a typical screen — so it runs when the tree's *structure* changes rather than
/// every frame. The ledger is the signal: it notifies exactly when a surface
/// arrives or leaves and never on geometry, because it stores surfaces rather
/// than their rects.
///
/// It is a proxy for the real event and not the event: a subtree can gain a
/// marker without a surface arriving, and that marker stays unwatched until
/// something else moves. What that costs is bounded rather than unbounded —
/// the oracle falls back to its ceiling — and the honest fix is for markers to
/// register themselves the way surfaces do, which is API this package does not
/// have yet.
bool _markersStale = true;
GlassHardware get _hardware => widget.hardware ?? GlassHardware.detect();
/// [GlassHost.finish], or the branch of `.regular` the screen is on. Set
/// before the first [_build], from [didChangeDependencies]: the appearance
/// is inherited, and `initState` may not read it.
late GlassFinish _finish;
/// The appearance `.regular` was picked in, or null when a finish was named —
/// what lets a reading pick the branch again for one glass.
Brightness? get _regularAppearance => widget.finish != null ? null : _appearance;
/// [GlassHost.appearance], or the platform's. Read only when it is not
/// declared, so a declared one does not depend on the platform's.
Brightness get _appearance => widget.appearance ?? MediaQuery.maybePlatformBrightnessOf(context) ?? Brightness.light;
/// Reads the backdrop back for [GlassHost.adaptive]; null — and nothing at
/// all — without it.
GlassBackdropReader? _reader;
void _adapt() {
final GlassAdaptive? adaptive = widget.adaptive;
final GlassBackdropReader? reader = _reader;
if (adaptive == null) {
if (reader != null) {
_handle._readings = null;
reader.dispose();
_reader = null;
}
} else if (reader == null) {
_reader = GlassBackdropReader(adaptive, _handle);
_handle._readings = _reader!.readings;
} else {
reader.adaptive = adaptive;
}
}
GlassFinish _resolveFinish() =>
widget.finish ?? GlassFinish.regular(appearance: _appearance, backdrop: widget.backdrop);
static ui.FragmentProgram? _cachedProgram;
static Future<ui.FragmentProgram>? _loading;
static ui.FragmentProgram? _cachedGroupProgram;
static Future<ui.FragmentProgram>? _loadingGroup;
/// The one load of each program per process, which fills the cache before
/// anything waiting on it runs — shared by every host's `initState` and by
/// [GlassHost.precache], so neither path compiles a program twice.
static Future<ui.FragmentProgram> _loadBase() => _loading ??= _loadShader(
kGlassShaderAsset,
(ui.FragmentProgram program) => _cachedProgram = program,
() => _loading = null,
);
static Future<ui.FragmentProgram> _loadGroup() => _loadingGroup ??= _loadShader(
kGlassGroupShaderAsset,
(ui.FragmentProgram program) => _cachedGroupProgram = program,
() => _loadingGroup = null,
);
static Future<ui.FragmentProgram>? _loadingBlur;
/// The Gaussian the pipeline blurs with on Impeller (`proxy_blur.dart`).
static Future<ui.FragmentProgram> _loadBlur() => _loadingBlur ??= _loadShader(
kGlassBlurShaderAsset,
(ui.FragmentProgram program) => glassBlurProgram = program,
() => _loadingBlur = null,
);
@override
void initState() {
super.initState();
_ledger.addListener(_markersChanged);
// Through a closure rather than `_oracle.noteChange` directly: the oracle is
// rebuilt whenever the finish, the budget or the declaration changes, and a
// listener bound to the old one would declare changes to a dead object.
_handle.changes.addListener(_noteDeclaredChange);
_adapt();
_loadProgram();
_loadGroupProgram();
_loadBlurProgram();
}
void _noteDeclaredChange() => _oracle.noteChange();
/// A surface arrived or left, so the subtree is a different subtree.
void _markersChanged() => _markersStale = true;
/// Compiles the shader once per process.
///
/// `FragmentProgram.fromAsset` is a future, and it is the one engine future a
/// widget test's fake clock does complete — it comes over the asset channel,
/// which the binding pumps. Everything else on that list hangs until the
/// ten-minute timeout.
void _loadProgram() {
final ui.FragmentProgram? cached = _cachedProgram;
if (cached != null) {
_handle.program = cached;
return;
}
_loadBase().then((ui.FragmentProgram program) {
if (mounted) {
_handle.program = program;
}
}, onError: _reportShaderLoadError);
}
/// The same, for the fused draw.
///
/// Loaded unconditionally rather than when a group appears: a program
/// compiled on the frame a toolbar first fuses would put that frame on a
/// different path from every frame after it, and the first frame of an
/// animation is the one somebody screenshots.
void _loadGroupProgram() {
final ui.FragmentProgram? cached = _cachedGroupProgram;
if (cached != null) {
_handle.groupProgram = cached;
return;
}
_loadGroup().then((ui.FragmentProgram program) {
if (mounted) {
_handle.groupProgram = program;
}
}, onError: _reportShaderLoadError);
}
/// The same, for the Gaussian the atlas is blurred with on Impeller, which
/// the pipeline reads from `proxy_blur.dart` rather than from the handle.
///
/// Until it arrives the atlas is blurred by `ImageFilter.blur`, corrected,
/// and a proxy captured so is held like any other; so its arrival is
/// declared as a change, and a frame is asked for to capture through it —