compose-rust 0.0.11

Declarative UI in Rust, rendered by an AOT-compiled Compose Multiplatform engine.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
package dev.darkpyonix.composerust.runtime

import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.rememberUpdatedState
import kotlinx.coroutines.launch
import dev.darkpyonix.composerust.protocol.ReducedMotion
import dev.darkpyonix.composerust.protocol.SystemColorScheme
import dev.darkpyonix.composerust.ui.node.platformReducedMotionSetting
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.exclude
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.safeDrawing
import dev.darkpyonix.composerust.design.NavigationPresentation
import androidx.compose.foundation.layout.height
import androidx.compose.ui.Alignment
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalFontFamilyResolver
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import dev.darkpyonix.composerust.foundation.HostMessages
import dev.darkpyonix.composerust.foundation.navigationFor
import dev.darkpyonix.composerust.foundation.systemChrome
import androidx.compose.ui.graphics.Color
import dev.darkpyonix.composerust.protocol.ColorRole
import dev.darkpyonix.composerust.protocol.Modifier as ProtocolModifier
import dev.darkpyonix.composerust.protocol.WindowSizeClass
import dev.darkpyonix.composerust.ui.platform.FrameRequestSource
import dev.darkpyonix.composerust.ui.platform.FrameRequests
import dev.darkpyonix.composerust.ui.platform.LocalFrameRequests
import dev.darkpyonix.composerust.ui.platform.serveFrameRequests
import androidx.compose.ui.platform.LocalWindowInfo
import dev.darkpyonix.composerust.protocol.HostEvent
import dev.darkpyonix.composerust.protocol.Mutation
import androidx.compose.runtime.SideEffect
import dev.darkpyonix.composerust.protocol.DesignSystem
import dev.darkpyonix.composerust.protocol.Paint
import dev.darkpyonix.composerust.protocol.PropertyKind
import dev.darkpyonix.composerust.protocol.PropertyValue
import dev.darkpyonix.composerust.protocol.SlotRole
import dev.darkpyonix.composerust.protocol.WidgetKind
import dev.darkpyonix.composerust.design.CaptionSide
import dev.darkpyonix.composerust.design.LocalDesignTheme
import dev.darkpyonix.composerust.design.LocalReduceTransparency
import dev.darkpyonix.composerust.design.detectHostPlatform
import dev.darkpyonix.composerust.design.platformCaption
import dev.darkpyonix.composerust.design.ResolvedTheme
import dev.darkpyonix.composerust.design.themeFontChains
import dev.darkpyonix.composerust.design.themeFonts
import dev.darkpyonix.composerust.design.themeOf
import dev.darkpyonix.composerust.protocol.MaterialRole
import dev.darkpyonix.composerust.ui.node.Asset
import dev.darkpyonix.composerust.ui.node.Node
import dev.darkpyonix.composerust.ui.node.NodeTable
import dev.darkpyonix.composerust.ui.node.RenderNode
import dev.darkpyonix.composerust.ui.node.platformFallbackFamilies
import dev.darkpyonix.composerust.ui.node.platformWindowMaterial
import dev.darkpyonix.composerust.ui.node.TableError
import java.lang.InterruptedException
import java.lang.System
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.getValue
import androidx.compose.foundation.isSystemInDarkTheme
import dev.darkpyonix.composerust.design.HostPlatform

/**
 * The press a `WindowDrag(false)` node saw, as pointer id and uptime. Two fields rather than
 * a pair, so marking a press allocates nothing.
 */
internal class WindowDragExclusion {
    var downId: Long = -1L
    var downUptime: Long = -1L
    fun mark(id: Long, uptime: Long) { downId = id; downUptime = uptime }
    fun clear() { downId = -1L; downUptime = -1L }
    fun isMarked(id: Long, uptime: Long): Boolean = downId == id && downUptime == uptime
}
internal val LocalWindowDragExclusion = staticCompositionLocalOf<WindowDragExclusion?> { null }

/**
 * Sends one event to the Host and reports whether the Host consumed it.
 *
 * Consumption is the same model as the web's `preventDefault()` and Compose's
 * `PointerInputChange.consume()`: the handler marks the event, and the boundary returns that
 * mark in `MutationBatch.result`. The Renderer treats a non-zero result as "consumed", so a
 * Host that always returns 0 simply never consumes. It is what lets Enter in a multiline
 * field submit without also inserting a newline.
 */
fun interface EventDispatcher {
    fun dispatch(event: HostEvent): Boolean
}

/**
 * Owns the interpreted tree and the boundary calls for one Host.
 *
 * The calls are synchronous and on this thread: there is no queue between the two sides, and
 * a batch is consumed inside the call that produced it.
 *
 * Every batch is applied inside a single `Snapshot.withMutableSnapshot` transaction, so the
 * intermediate states of a batch are never drawn.
 */
class ComposeRustHost(private val connection: HostConnection) : EventDispatcher {
    val table: NodeTable = NodeTable()

    val roots: List<Int> get() = table.roots

    /**
     * The frame source this Host was started against, and how many requests it had counted
     * just before. The frame loop counts from here rather than from when it began listening.
     */
    internal var startedWith: FrameRequestSource? = null
        private set
    internal var requestsBeforeStart: Long = 0L
        private set

    /**
     * Called once a batch has been applied and its errors reported, on the thread the Host
     * runs on. The window manager of a multi-window application hangs here to open,
     * close and update platform windows from the nodes the batch changed. Null for every
     * other application, which is what keeps a single window's path as it was.
     */
    internal var afterBatch: (() -> Unit)? = null

    fun start() = start(FrameRequests.global)

    internal fun start(frames: FrameRequestSource) {
        startedWith = frames
        requestsBeforeStart = frames.counter.value
        applyTransaction { apply -> connection.init(apply) }
        // After the first batch, so the first thing the Host hears is a press that started
        // the application, if one did, and then what the platform says about permission.
        table.notifications.attach(this)
        table.fileDialogs.attach(this)
        table.clipboardReads.attach(this)
        table.fileCalls.attach(this)
        table.storage.attach(this)
    }

    /** Dispatches synchronously and returns the Host's consumption result. */
    override fun dispatch(event: HostEvent): Boolean {
        // A report goes the way the errors found in a batch go, best effort, so a Host that
        // refuses it leaves the report itself to be printed. Sent like any other event, a
        // refused report became a second, empty error: "dispatch_event returned -1", with
        // the missing picture or the font it was about lost. The Rust Host refuses every
        // report, so each picture Android could not decode cost its real message.
        if (event is HostEvent.ProtocolError) {
            report(event)
            return false
        }
        var result = 0L
        applyTransaction { apply -> result = connection.dispatchEvent(event, apply) }
        return result != 0L
    }

    /**
     * Throws the interpreted tree away and asks the Host for the whole of it again.
     *
     * For a Renderer that cannot keep its node table across whatever just happened to it.
     * It costs the application's state, because the Host keeps no shadow of the tree it
     * has already sent and answers by building the application from nothing, so a Renderer
     * that can keep its table should keep it instead. The Android host does.
     */
    fun resync() {
        table.clear()
        applyTransaction { apply ->
            connection.dispatchEvent(
                HostEvent.Resync(nodeId = NodeTable.ROOT_ID, handlerId = 0),
                apply,
            )
        }
    }

    /** Called once per frame after a Host worker asked for one. */
    fun renderFrame(frameTimeNanos: Long) {
        // What the notification centre heard since the last frame goes first. A press or an
        // answer from the platform asks for a frame for exactly this, because the frame is
        // where the UI thread, and so the Host, can be reached from any other thread.
        table.notifications.drain()
        table.fileDialogs.drain()
        table.clipboardReads.drain()
        table.fileCalls.drain()
        table.storage.drain()
        applyTransaction { apply -> connection.renderFrame(frameTimeNanos, apply) }
    }

    /**
     * Plays one frame of the animations the Host handed over, and hands the Host the events
     * they asked for. Called inside a frame, on the thread the Host was started on.
     */
    internal fun tickAnimations(frameTimeNanos: Long, theme: dev.darkpyonix.composerust.design.ResolvedTheme) {
        table.animations.tick(frameTimeNanos, theme) { event -> dispatch(event) }
    }

    /** The last system appearance told to the Host, or null before the first report. */
    private var reportedScheme: SystemColorScheme? = null

    /**
     * Tells the Host whether the system appearance is dark, the first time and then only
     * when it changes.
     *
     * The value is kept here, on the Host, rather than in a window's composition: every
     * window of an application reads the same system setting, and each one reporting it
     * would tell the Host the same thing once per window. Kept per window, it would also
     * be told again whenever a window's content was composed afresh.
     */
    internal fun reportSystemScheme(dark: Boolean) {
        val scheme = if (dark) SystemColorScheme.Dark else SystemColorScheme.Light
        if (reportedScheme == scheme) return
        reportedScheme = scheme
        dispatch(HostEvent.ColorSchemeChanged(nodeId = 0, handlerId = 0, scheme = scheme))
    }

    fun shutdown() {
        table.notifications.shutdown()
        table.fileDialogs.shutdown()
        table.clipboardReads.shutdown()
        table.fileCalls.shutdown()
        table.storage.shutdown()
        connection.shutdown()
    }

    private fun applyTransaction(call: ((Mutation) -> Unit) -> Unit) {
        val protocolErrors = mutableListOf<TableError>()
        var editorEvents: List<HostEvent> = emptyList()
        Snapshot.withMutableSnapshot {
            try {
                call { mutation -> table.apply(mutation) }
            } catch (error: Throwable) {
                // A malformed batch must not take the process down: it becomes a reported
                // protocol error instead.
                if (error is InterruptedException) throw error
                protocolErrors += TableError(PROTOCOL_DECODE_ERROR, error.describe())
            }
            protocolErrors += table.drainErrors()
            editorEvents = table.drainEvents()
        }
        // Reported after the transaction so the Host is never re-entered mid-batch.
        //
        // A Host is free to reject the report itself: nothing promises that reporting an
        // error succeeds, and the Rust Host answers a `ProtocolError` event with a
        // protocol-error status because no handler owns it. Letting that failure out of here
        // would turn a reported error into a crashed composition, which is the outcome the
        // report exists to prevent, so the report is best effort and the original error is
        // what gets printed.
        protocolErrors.forEach { error ->
            report(
                HostEvent.ProtocolError(
                    nodeId = NodeTable.ROOT_ID,
                    handlerId = 0,
                    code = error.code,
                    message = error.message,
                ),
            )
        }
        // What a code editor did with an edit the batch asked of it: the change it made, or
        // the refusal. After the batch for the same reason as the errors above, and each in
        // its own call, because the Host answers each one with a batch of its own.
        editorEvents.forEach { event -> dispatch(event) }
        afterBatch?.invoke()
    }

    /**
     * Hands one protocol error to the Host, and prints it when the Host will not take it.
     *
     * Never inside a batch's transaction, so the Host is never re-entered mid-batch.
     */
    private fun report(event: HostEvent.ProtocolError) {
        try {
            connection.dispatchEvent(event) { mutation -> Snapshot.withMutableSnapshot { table.apply(mutation) } }
        } catch (refused: Throwable) {
            if (refused is InterruptedException) throw refused
            onProtocolError(TableError(event.code, event.message))
        }
    }

    private companion object {
        const val PROTOCOL_DECODE_ERROR = 100
    }
}

/**
 * Where a protocol error goes when the Host will not take the report.
 *
 * Tests replace it to assert on what was reported; production leaves it printing.
 */
internal var onProtocolError: (TableError) -> Unit = { error ->
    System.err.println("compose-rust protocol error ${error.code}: ${error.message}")
}

/**
 * What to say about a failure, all the way down.
 *
 * The cause as well as the throwable, because some of them say nothing on their own. A
 * class whose initialiser failed reports "There was an error during file or class
 * initialization" and keeps which class and why in its cause, and a reader given only the
 * first line has been told that something went wrong and nothing else. That message was
 * printed twice a second by a window that came up black, and finding what it meant took
 * a debugger and an address arithmetic.
 */
private fun Throwable.describe(): String {
    val parts = mutableListOf<String>()
    var current: Throwable? = this
    var depth = 0
    while (current != null && depth < CAUSE_DEPTH) {
        val name = current::class.qualifiedName ?: current::class.simpleName ?: "error"
        val said = current.message
        parts += if (said.isNullOrBlank()) name else "$name: $said"
        current = current.cause
        depth++
    }
    return parts.joinToString(", caused by ")
}

/** How far down a cause chain is worth printing before it is noise. */
private const val CAUSE_DEPTH = 6

/** Creates a Host bound to the composition's lifetime. */
@Composable
fun rememberComposeRustHost(connection: HostConnection): ComposeRustHost {
    val host = remember(connection) { ComposeRustHost(connection) }
    DisposableEffect(host) {
        host.start()
        onDispose { host.shutdown() }
    }
    return host
}

/**
 * The same, for a Host that was already started outside composition.
 *
 * The platform layer starts one before it builds the window, because what the window
 * should look like is in the first batch and a window cannot be told after it exists: its
 * decoration is fixed when it is created. Starting it again here would be the Host's
 * second init, which the boundary answers with an error rather than a tree.
 */
@Composable
fun rememberStartedComposeRustHost(host: ComposeRustHost): ComposeRustHost {
    DisposableEffect(host) { onDispose { host.shutdown() } }
    return host
}

/**
 * The content of one real window: [ComposeRustContent] filling the whole window.
 *
 * What [ComposeRustContent] measures is what the Host is told the window's size is, and a
 * Compose root wraps its content unless asked to fill. A window whose tree is one line of
 * text would then report one line of text. Every platform window draws through this, so
 * none of them can forget the fill; a caller embedding the content in a larger Compose
 * layout calls [ComposeRustContent] and sizes it itself.
 */
@Composable
fun WindowContent(
    host: ComposeRustHost,
    modifier: Modifier = Modifier,
    caption: WindowCaption = WindowCaption.None,
    windowNodeId: Int = 0,
) {
    ComposeRustContent(host, Modifier.fillMaxSize().then(modifier), caption, windowNodeId)
}

/**
 * Draws the Host's tree and runs the frame loop.
 *
 * Frame requests coming from Host worker threads coalesce into at most one `render_frame`
 * per frame, inside `withFrameNanos`.
 *
 * Drawn at the window's zoom. A desktop window holds its [Zoom] and has already given its
 * scene the Density it makes; inside a platform's own Compose host there is none, so one is
 * made here, takes the system's text size from the font scale the host already carries, and
 * is applied around the content.
 */
@Composable
fun ComposeRustContent(
    host: ComposeRustHost,
    modifier: Modifier = Modifier,
    caption: WindowCaption = WindowCaption.None,
    /**
     * The `Window` node whose content this draws, for one window of a multi-window application,
     * or 0 for the one window of a single window application. A window of the first
     * kind draws the children of its node, and the process serves the Host's frame requests once
     * for all of them (the window manager's `awaitFrame`), not once per window.
     */
    windowNodeId: Int = 0,
) {
    if (windowNodeId != 0) {
        CompositionLocalProvider(LocalWindowNodeId provides windowNodeId) {
            ComposeRustContent(host, modifier, caption, 0)
        }
        return
    }
    val provided = LocalZoom.current
    if (provided != null) {
        ZoomReporter(host, provided)
        DensityReporter(host)
        ComposeRustTree(host, modifier, caption)
        return
    }
    val base = LocalDensity.current
    val zoom = remember { Zoom(store = platformZoomLevelStore()) }
    SideEffect { zoom.followOs(base.fontScale) }
    val apple = remember {
        (hostPlatformOverride ?: detectHostPlatform()).let {
            it == HostPlatform.Ios || it == HostPlatform.MacOs
        }
    }
    CompositionLocalProvider(
        LocalDensity provides zoomedDensity(base.density, zoom.app, base.fontScale),
        LocalZoom provides zoom,
        LocalDisplayScale provides base.density,
    ) {
        ZoomReporter(host, zoom)
        DensityReporter(host)
        // `onKeyEvent` rather than the preview: it runs after everything inside has had the
        // key, so a key the application consumed never reaches it.
        ComposeRustTree(
            host,
            modifier.onKeyEvent { event ->
                zoom.takeShortcut(composeZoomShortcut(event, apple), consumedByApplication = false)
            },
            caption,
        )
    }
}

/**
 * How a theme reaches the assets the application registered, made once for a Host.
 *
 * Three lookups written where the theme is resolved were three new objects on every pass,
 * and the theme holding one of them was a new theme with them. Each still reads the cache
 * when it is called, so an asset registered later is found by whoever asks next.
 */
private class ThemeAssets(assets: dev.darkpyonix.composerust.ui.node.AssetCache) {
    val fontOf: (Int) -> androidx.compose.ui.text.font.FontFamily? =
        { asset -> (assets.asset(asset) as? Asset.Font)?.family }
    val chainOf: (Int) -> dev.darkpyonix.composerust.ui.node.FontChain? =
        // A single face is a chain of one only where the renderer carries fallback faces
        // of its own: that chain is what sends a letter the face lacks to them.
        { asset ->
            (assets.asset(asset) as? Asset.Font)?.let { font ->
                if (platformFallbackFamilies.isEmpty()) font.chain else font.letters
            }
        }
    val brushOf: (Int) -> androidx.compose.ui.graphics.Brush? =
        { asset -> (assets.asset(asset) as? Asset.Brush)?.brush }
}

/**
 * Whether the content below serves the Host's frame requests itself. True for a single window,
 * which has always done so; a multi-window renderer provides false and serves them once for
 * every window.
 */
internal val LocalServesFrames = staticCompositionLocalOf { true }

/** What a window's content draws: the roots of the tree for window 0, else the children of `Window` node [windowNodeId]. */
internal fun NodeTable.rootsOf(windowNodeId: Int): List<Int> =
    if (windowNodeId == 0) roots else node(windowNodeId)?.children ?: emptyList()

@Composable
private fun ComposeRustTree(
    host: ComposeRustHost,
    modifier: Modifier,
    caption: WindowCaption,
) {
    val frames = LocalFrameRequests.current
    val servesFrames = LocalServesFrames.current
    // The `Window` node this scene draws, or 0 for the one window of a single window
    // application. A window of a multi-window application draws its own node and nothing
    // else, and does not serve the Host's frame requests: the platform layer has one driver
    // for the whole process (`serveWindowFrames`), because the Host is asked once per frame
    // however many windows there are.
    val windowNodeId = LocalWindowNodeId.current
    val pageRoots = if (windowNodeId == 0) host.roots else host.table.node(windowNodeId)?.children?.toList().orEmpty()
    val focusManager = LocalFocusManager.current
    val clearFocusRevision = host.table.focusClearRevision
    LaunchedEffect(clearFocusRevision) {
        if (clearFocusRevision > 0L) focusManager.clearFocus()
    }
    LaunchedEffect(host, frames, windowNodeId, servesFrames) {
        if (windowNodeId != 0 || !servesFrames) return@LaunchedEffect
        // Counted from the Host's start, not from the moment this loop began listening. The
        // platform starts the Host before there is a window, and work the Host schedules in
        // its first render (an effect, a task spawned at startup) asks for a frame right then.
        // Counted from now, that request looked already served, and the work waited for some
        // unrelated event to be drawn; in a window where none came, it waited for ever.
        serveFrameRequests(
            frames.counter,
            awaitFrame = { onFrame -> withFrameNanos(onFrame) },
            serve = host::renderFrame,
            alreadyServed = if (host.startedWith === frames) host.requestsBeforeStart else frames.counter.value,
        )
    }
    // A notification centre answers on a thread of its own, and the way from any thread to
    // this one is a frame request. The centre asks through the same source this loop serves.
    SideEffect { host.table.notifications.wake = frames::request }
    // A file dialog's answer arrives the same way, from whichever thread the platform uses.
    SideEffect { host.table.fileDialogs.wake = frames::request }
    // A clipboard read is answered at the top of the frame it asks for.
    SideEffect { host.table.clipboardReads.wake = frames::request }
    // A file operation is answered at the top of the frame it asks for, like a clipboard read.
    SideEffect { host.table.fileCalls.wake = frames::request }
    // A storage answer from the browser is delivered at the top of the frame it asks for.
    SideEffect { host.table.storage.wake = frames::request }
    // The clipboard the Host's copies go to is the one this composition sees. Every window
    // shares it, so the root window's is enough.
    @Suppress("DEPRECATION")
    val clipboardManager = androidx.compose.ui.platform.LocalClipboardManager.current
    // The suspending clipboard, which is the only one a browser can read, and the scope its
    // reads run in: the composition's own, so they run on the UI thread.
    val composeClipboard = androidx.compose.ui.platform.LocalClipboard.current
    val clipboardScope = androidx.compose.runtime.rememberCoroutineScope()
    if (windowNodeId == 0) {
        DisposableEffect(host) { onDispose { host.table.clipboardReads.detach() } }
        DisposableEffect(host) { onDispose { host.table.fileCalls.detach() } }
        SideEffect {
            host.table.clipboard.sink = dev.darkpyonix.composerust.ui.platform.ClipboardSink { text ->
                @Suppress("DEPRECATION")
                clipboardManager.setText(androidx.compose.ui.text.AnnotatedString(text))
            }
            host.table.clipboardReads.launcher = { read ->
                clipboardScope.launch(block = { read() })
            }
            // File operations suspend on the same scope, on the UI thread.
            host.table.fileCalls.launcher = { operation ->
                clipboardScope.launch(block = { operation() })
            }
            host.table.clipboardReads.source = dev.darkpyonix.composerust.ui.platform.ClipboardSource {
                // A platform with a suspending read uses it. Elsewhere the clipboard manager
                // answers at once, which every other target supports.
                val platformRead = dev.darkpyonix.composerust.ui.platform.ClipboardReads.platform
                if (platformRead != null) {
                    platformRead(composeClipboard)
                } else {
                    @Suppress("DEPRECATION")
                    clipboardManager.getText()?.text
                }
            }
        }
    }
    // Whether the window is the one in use decides whether a notification that asked to be
    // shown only when it is not is shown at all, and coming back to the window is when a
    // permission changed in the system's settings is looked for.
    val windowFocused = LocalWindowInfo.current.isWindowFocused
    // One window of several does not report: its scene knows only itself, and the last to say
    // would win. The platform layer reports for the application, from the window that is key.
    if (windowNodeId == 0) SideEffect { host.table.notifications.windowFocusChanged(windowFocused) }
    // The theme is resolved once here, and every node reads it from the CompositionLocal. A `SetTheme` is therefore one record on the wire and one
    // invalidation in Compose, not a SetProp per node.
    val platform = remember { hostPlatformOverride ?: detectHostPlatform() }
    // Compose's isSystemInDarkTheme() reads the setting once on the desktop and never
    // notices it change, so a window there keeps its original colours while the rest of
    // the screen switches. The desktop installs an observer that does follow the system;
    // where nobody installs one, Compose's own answer is correct and is used.
    val observedDark = LocalSystemDarkObserver.current?.invoke() ?: isSystemInDarkTheme()
    val systemDark = systemDarkOverride ?: observedDark
    // The window's size is measured here, where the root content is, and reported to
    // the Host when either class changes, or for a window that asked for it, when the
    // size changes by a whole dp. onSizeChanged already fires only when the measured size
    // differs, and the reporter drops everything else, so a drag across one class costs
    // a window that did not ask no boundary calls.
    val reporter = remember(host, windowNodeId) { WindowSizeReporter(windowNodeId) }
    val density = LocalDensity.current
    val zoom = LocalZoom.current
    val fontFamilyResolver = LocalFontFamilyResolver.current
    val layoutDirection = LocalLayoutDirection.current
    // Where a node the Host already sent is measured when it asks. It composes nothing
    // until it is asked, and what it composes is never placed.
    val station = remember(host) { MeasuringStation { nodeId -> MeasuredNode(nodeId, host.table) } }
    DisposableEffect(host) { onDispose { RendererMeasure.uninstall(host.table) } }
    // The same measurement answers three questions. The Host is told when the class
    // changes so a component can choose what to put on the screen; the widgets that
    // change shape with the window read it from the CompositionLocal, because they are
    // drawn on this side and a round trip to ask would cost a boundary call, a
    // VirtualDom pass and a rebuilt subtree for a layout this side can already reach;
    // and the design system asks it, because a system is allowed to answer differently
    // in a desktop window than on a phone.
    val sizeClassState = remember(host) { mutableStateOf(WindowSizeClass.Compact) }
    var sizeClass by sizeClassState
    var measuredSize by remember(host, windowNodeId) { mutableStateOf<androidx.compose.ui.unit.IntSize?>(null) }
    // What the report carries besides the size, as the last composition left it. Read by
    // the layout callback below, which runs after that composition's effects.
    val reportInputs = remember(host, windowNodeId) { WindowReportInputs() }
    val measured = Modifier.onSizeChanged { size ->
        with(density) {
            val widthDp = size.width.toDp().value
            sizeClass = windowSizeClassOf(widthDp)
            measuredSize = size
            // The Host is told from the layout that measured the window, as it is told an
            // observed node's size. Waiting for the recomposition the write above schedules
            // means waiting for a second frame, and a window that draws only when asked
            // (macOS) can go a long time without one while the Host lays its page out for
            // a 0x0, compact window. The reporter drops a repeat, so the effect below,
            // which still reports a change of the safe area, sends nothing twice.
            reporter.report(widthDp, size.height.toDp().value, host, reportInputs.safeArea, reportInputs.everyDp)
        }
    }
    // Whether anything in the tree asked to be made of a material, and so whether the
    // window is stood up with the platform's own material behind it. The design system is
    // told the answer, because chrome that sits straight on the desktop is drawn
    // differently from chrome over the application's own page.
    val asked = host.table.asksForWindowMaterial(pageRoots)
    // The theme is the same object until something it is made from changes. Every node
    // reads it, so a theme made again on each pass through here composed the whole tree
    // again whenever this function ran: on every change of window class, which is one
    // frame of a drag of the window's edge, and that frame took several times the others.
    //
    // What it is made from is read on every pass and compared, not read inside the
    // remembered block: a font that arrives after the theme that names it has to be seen,
    // and a read that only happens when the block runs is forgotten the first time it
    // does not. The window's class is not one of the inputs. The theme asks for it where
    // an answer depends on it, and only what asked follows it.
    val themeAssets = remember(host) { ThemeAssets(host.table.assets) }
    val themeRecord = host.table.themeFor(windowNodeId)
    val themeFonts = themeFonts(themeRecord, themeAssets.fontOf)
    val themeFontChains = themeFontChains(themeRecord, themeAssets.chainOf)
    val windowBackdrop = asked && platformBacksWindowWithMaterial()
    // Asked only of an application that brought a palette, which is the only thing a high
    // contrast mode changes here.
    val highContrast = themeRecord?.palette?.isNotEmpty() == true &&
        dev.darkpyonix.composerust.ui.node.platformHighContrast()
    val overlayTokens = host.table.overlayTokens
    val theme = remember(
        themeAssets, themeRecord, platform, systemDark, sizeClassState, themeFonts,
        themeFontChains, windowBackdrop, highContrast, overlayTokens,
    ) {
        themeOf(
            themeRecord,
            platform,
            systemDark,
            sizeClass = { sizeClassState.value },
            fonts = themeFonts,
            chains = themeFontChains,
            brushOf = themeAssets.brushOf,
            windowBackdrop = windowBackdrop,
            highContrast = { highContrast },
            overlay = overlayTokens,
        )
    }
    // The animations the Host handed over are played here, on this side's frame clock, and
    // the Host is not called while they play unless one asked for events. The loop waits
    // for frames only while something is waiting to start or still running, so a screen
    // that has stopped moving asks for no frames at all.
    val currentTheme by rememberUpdatedState(theme)
    LaunchedEffect(host) {
        snapshotFlow { host.table.animations.generation.intValue }.collect {
            while (host.table.animations.needsFrames()) {
                withFrameNanos { frame -> host.tickAnimations(frame, currentTheme) }
            }
        }
    }
    // Moves and wheel travel are held between frames and sent once at the start of the next
    // one, so a pointer that reports faster than the screen draws runs the Host once a frame.
    // The loop waits for frames only while something is held.
    LaunchedEffect(host) {
        snapshotFlow { host.table.pointers.pendingGeneration.intValue }.collect {
            while (host.table.pointers.hasPending) {
                withFrameNanos { host.table.pointers.flush() }
            }
        }
    }
    // A scroll container the Host listens to reports where it is the same way: once at the
    // start of the frame after it moved, for the place it has reached by then.
    LaunchedEffect(host) {
        snapshotFlow { host.table.scrolls.pendingGeneration.intValue }.collect {
            while (host.table.scrolls.hasPending) {
                withFrameNanos { host.table.scrolls.flush { event -> host.dispatch(event) } }
            }
        }
    }
    // Whether the platform asks for reduced motion, told to the Host once and again when it
    // changes. Asked again when the window comes back into use, which is when a setting
    // changed in the system's preferences can have changed. The Host decides what to do
    // with it, as a page does with a media query; nothing here holds an animation still.
    val reducedMotion = remember(windowFocused) { platformReducedMotionSetting() }
    val reportedMotion = remember(host) { arrayOfNulls<ReducedMotion>(1) }
    SideEffect {
        if (reportedMotion[0] != reducedMotion) {
            reportedMotion[0] = reducedMotion
            host.dispatch(HostEvent.ReducedMotionChanged(nodeId = 0, handlerId = 0, state = reducedMotion))
        }
    }
    // Whether the system is light or dark, told to the Host before the first frame and then
    // on every change, whatever the theme asks for. The theme's own colours already follow
    // the system here without the Host; this is for what the Host draws itself, such as an
    // HTML page answering `prefers-color-scheme`. In a SideEffect, so it is sent on the
    // thread the Host runs on, after a composition that read the new value.
    SideEffect { host.reportSystemScheme(systemDark) }
    // The answer goes back to the Host, which asked a question it cannot answer itself:
    // an adaptive theme names no system, and the one that ends up running is worked out
    // here where the platform is. Only when it changes, the way a size class is reported.
    //
    // SideEffect rather than LaunchedEffect, and this is not a detail. A boundary call is
    // a direct call on the thread the Host was started on, and that thread is the one
    // composition is applied on. A coroutine effect runs on the toolkit's event thread
    // instead, where the Host has no state at all: the call came back refused, with the
    // status that means it was made in the wrong place.
    // What a measure call is answered with: this composition's density, fonts and design
    // system, made again whenever any of them changes. Installed here, on the thread the
    // composition runs on, which is the thread the Host calls back in on.
    SideEffect {
        RendererMeasure.install(
            MeasureContext(host.table, theme, density, layoutDirection, fontFamilyResolver, station, zoom),
        )
    }
    val reported = remember { arrayOfNulls<DesignSystem>(1) }
    SideEffect {
        if (reported[0] != theme.system) {
            reported[0] = theme.system
            host.dispatch(
                HostEvent.DesignSystemResolved(nodeId = 0, handlerId = 0, system = theme.system),
            )
        }
    }
    // A tree that opens with a bar, a picture or a colour of its own makes that the
    // window's caption, so the strip the window buttons sit in belongs to it rather than
    // to the page underneath it. Otherwise the page keeps it and the content starts below
    // the buttons.
    // The strips a phone's system draws in. Zero on a desktop, where a title bar is the
    // caption above instead. The keyboard is not one of them: it is reported on its own
    // below, because the page stops above it but nothing grows into it.
    val safeBars = with(LocalDensity.current) {
        val safe = WindowInsets.safeDrawing.exclude(WindowInsets.ime)
        SystemBars(top = safe.getTop(this).toDp(), bottom = safe.getBottom(this).toDp())
    }
    // How much of the window's bottom the on-screen keyboard covers. The window is not
    // panned for it (the platform layer asks for that), so this is where the page is
    // told: it ends above the keyboard, the bar at the top stays where it is, and the
    // focused field is brought into view inside the page that is left.
    val keyboard = platformKeyboardInset().coerceAtLeast(0.dp)
    // While the keyboard is up the gesture strip is under it, so nothing above the
    // keyboard leaves room for it.
    val bars = if (keyboard > 0.dp) safeBars.copy(bottom = 0.dp) else safeBars
    // A rail or a sidebar that runs to the top of the window takes the caption the same
    // way a bar does: the window buttons sit on its surface and the page beside it starts
    // its own content clear of them. Leaving the page to take the strip instead drew a band
    // of page colour across the whole window above the sidebar, which is the leftover
    // title bar this exists to avoid.
    // Asked of the navigation the page opens with, so a compact window gets what that
    // navigation chose rather than what its design system would have answered.
    val openingNavigation = host.table.openingNavigation(pageRoots)
    val navigation = theme.navigationFor(openingNavigation, sizeClass)
    // A navigation that is not on the screen at all has no strip to take the top with,
    // and the page under it starts below the window buttons like any other page.
    val stripTakesTheTop = navigation.carriesCaption &&
        navigation.presentation != NavigationPresentation.Bar &&
        navigation.presentation != NavigationPresentation.Hidden &&
        openingNavigation != null
    val barIsCaption = !caption.fullSize && (caption.height > 0.dp || bars.top > 0.dp) &&
        (host.table.opensWithABar(pageRoots) || stripTakesTheTop)
    // A navigation showing a bar along the bottom grows into the bottom strip, so the page
    // must not stop short of it as well. The same question the navigation itself asks,
    // asked here because the page is laid out before anything inside it.
    val navigationTakesTheBottom = bars.bottom > 0.dp &&
        navigation.presentation == NavigationPresentation.Bar &&
        openingNavigation != null
    val (pageTop, pageBottom) = pageInsets(caption, bars, barIsCaption, navigationTakesTheBottom, keyboard)
    // The clock and the gesture bar are drawn by the system over what this window drew, so
    // they follow the theme that was resolved rather than the device's setting. A light
    // application on a device in dark mode otherwise gets white icons on its own white
    // bar.
    LaunchedEffect(theme.dark) { systemChrome?.setDarkIcons(!theme.dark) }
    // The operating system's buttons in this theme's colours, never the design system's own
    // shape: the application lays its bar out around what is drawn here, and on Windows the
    // native hit test answers for the same three cells.
    val captionStyle = remember(theme) { platformCaption(theme) }
    val safeArea = if (caption.height <= 0.dp) WindowSafeArea() else {
        val width = if (LocalWindowActions.current == null) caption.buttonsWidth else
            captionStyle.buttonWidth * 3 + captionStyle.spacing * 2 + captionStyle.edgePadding * 2
        val atStart = if (LocalWindowActions.current == null) caption.buttonsAtStart else
            captionStyle.side == CaptionSide.Start
        WindowSafeArea(caption.height.value, if (atStart) width.value else 0f, if (atStart) 0f else width.value)
    }
    // Read through a derived state so a recomposition does not repeat the map lookup (which
    // boxes the node id) and the read only runs again when the property itself changes.
    // The implicit root window (id 0) opts in through its SetWindow settings and any other
    // window through its node property; the table answers for both.
    val reportEveryDp = remember(host, windowNodeId) {
        derivedStateOf { host.table.reportSizeFor(windowNodeId) }
    }.value
    // What decides whether the Host is told: both classes, and for a window that asked for
    // every whole-dp change, the size rounded to whole dp as well. It is read here, in the
    // composition, through a derived state, so a layout pass that changes it recomposes
    // this scope once and reaches the effect below, and a layout pass that does not change
    // it (a drag inside one class for a window that did not opt in) recomposes nothing.
    // Reading the size only inside the effect would subscribe to nothing, and a window
    // whose report depends on anything but the width class would never be told.
    // Recomposition runs at most once a frame, so several layout passes in one frame are
    // one report.
    @Suppress("UNUSED_VARIABLE")
    val reportKey = remember(host, windowNodeId, density, reportEveryDp) {
        derivedStateOf {
            val size = measuredSize ?: return@derivedStateOf -1L
            with(density) { windowReportKey(size.width.toDp().value, size.height.toDp().value, reportEveryDp) }
        }
    }.value
    SideEffect {
        reportInputs.safeArea = safeArea
        reportInputs.everyDp = reportEveryDp
        measuredSize?.let { size ->
            with(density) { reporter.report(size.width.toDp().value, size.height.toDp().value, host, safeArea, reportEveryDp) }
        }
    }
    // How much room the buttons take and at which end. The macOS system's own are at the
    // leading edge and the renderer's are at the trailing edge, as wide as the operating
    // system's buttons are, so the bar cannot assume either.
    // The bar is given the strip above it as well as the caption's own height. The two
    // are not the same shape: window buttons sit on the bar's row and a status bar sits
    // above it, so they are handed over separately.
    val strip = caption.copy(insetTop = bars.top)
    val barCaption = when {
        !barIsCaption -> WindowCaption.None
        LocalWindowActions.current == null -> strip
        else -> strip.copy(
            buttonsWidth = captionStyle.buttonWidth * 3 +
                captionStyle.spacing * 2 +
                captionStyle.edgePadding * 2,
            buttonsAtStart = captionStyle.side == CaptionSide.Start,
        )
    }
    // The window's collapsible split panes, so the platform's sidebar command reaches one
    // wherever focus is. Heard on the way back up from the focused node, so a text field
    // that wants the key keeps it.
    val sidebarShortcuts = remember(host) { dev.darkpyonix.composerust.foundation.SidebarShortcuts() }
    val overlayFocusStack = remember(host, windowNodeId) { dev.darkpyonix.composerust.foundation.OverlayFocusStack() }
    val dragWindow = LocalWindowDrag.current
    val dragExclusion = remember { WindowDragExclusion() }
    // The platform views of this window, and the surfaces drawn above them.
    val nativeViews = dev.darkpyonix.composerust.foundation.rememberNativeViews(host.table, windowNodeId, host)
    val dragStrip = if (caption.fullSize && caption.height > 0.dp) Modifier.pointerInput(caption.height, dragWindow) {
        awaitEachGesture {
            val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final)
            if (!down.isConsumed && !dragExclusion.isMarked(down.id.value, down.uptimeMillis) && down.position.y < caption.height.toPx()) {
                while (true) {
                    val change = awaitPointerEvent(PointerEventPass.Final).changes.firstOrNull { it.id == down.id } ?: break
                    if (change.isConsumed || !change.pressed) break
                    if ((change.position - down.position).getDistance() > viewConfiguration.touchSlop) {
                        change.consume()
                        dragWindow()
                        break
                    }
                }
            }
        }
    } else Modifier
    CompositionLocalProvider(
        dev.darkpyonix.composerust.foundation.LocalSidebarShortcuts provides sidebarShortcuts,
        dev.darkpyonix.composerust.foundation.LocalOverlayFocusStack provides overlayFocusStack,
        dev.darkpyonix.composerust.foundation.LocalNativeViews provides nativeViews,
        LocalWindowDragExclusion provides dragExclusion,
        LocalDesignTheme provides theme,
        LocalReduceTransparency provides reduceTransparency,
        LocalWindowCaption provides barCaption,
        LocalWindowCornerRadius provides caption.cornerRadius,
        LocalStripTakesTheTop provides (barIsCaption && stripTakesTheTop),
        LocalSystemBars provides bars,
    ) {
        // The background fills the whole window and the inset is applied inside it. Putting
        // the inset outside instead leaves the window's own background showing through the
        // strip the title bar used to occupy, which reads as a leftover title bar rather
        // than as content extending underneath one.
        // Told once, and again only when the answer changes. A window that never asks is
        // never told, and comes up on exactly the path it did before any of this existed.
        SideEffect { platformWindowMaterial(asked) }
        // Android's back closes the topmost overlay, as Escape does, and is left to the app
        // when none is open. Where no platform installs a back hook this does nothing.
        dev.darkpyonix.composerust.foundation.platformBackHandler(overlayFocusStack.hasOpen) {
            overlayFocusStack.handleBack()
        }
        CompositionLocalProvider(LocalWindowSizeClass provides sizeClass) {
            Box(
                modifier
                    .then(measured)
                    .then(dragStrip)
                    .onKeyEvent { event ->
                        overlayFocusStack.handleEscape(event) || sidebarShortcuts.handle(event, platform)
                    }
                    .background(host.table.windowFill(pageRoots, theme)),
            ) {
                Box(Modifier.padding(top = pageTop, bottom = pageBottom)) {
                    // Beside the roots, under the same locals, so a node measured here is
                    // measured as the page lays it out. It takes no room.
                    MeasuringStationLayout(station)
                    (if (windowNodeId == 0) host.roots else listOf(windowNodeId)).forEach { rootId ->
                        androidx.compose.runtime.key(rootId) {
                            RenderNode(rootId, host.table, host)
                        }
                    }
                }
                // The window's own buttons, over everything, because the caption strip is
                // the window's and whatever the Host drew runs underneath it. Nothing is
                // drawn where the platform draws its own: macOS keeps the system's
                // traffic lights, and the platform layer provides no actions there.
                if (caption.height > 0.dp) {
                    WindowButtons(
                        style = captionStyle,
                        modifier = Modifier
                            .align(
                                if (captionStyle.side == CaptionSide.Start) {
                                    Alignment.TopStart
                                } else {
                                    Alignment.TopEnd
                                },
                            )
                            .height(caption.height),
                    )
                }
                // Over the content rather than in it: a message is not part of the tree,
                // and it covers whatever it has to for as long as it is up.
                // A message the application placed stays out of the strips nothing should
                // be drawn under: the caption and a status bar along the top, a gesture
                // bar or the keyboard along the bottom.
                HostMessages(
                    host.table.messages,
                    host.table.insets,
                    host,
                    theme,
                    dev.darkpyonix.composerust.foundation.MessageSafeArea(
                        top = (caption.height + bars.top).coerceAtLeast(0.dp),
                        bottom = maxOf(keyboard, bars.bottom).coerceAtLeast(0.dp),
                        pageTop = pageTop,
                        topBar = host.table.openingTopBar(pageRoots) ?: 0,
                    ),
                )
            }
        }
    }
}

/**
 * Overrides the platform's dark mode reading, for tests and for the dev harness.
 *
 * `ColorScheme.FollowSystem` reads the platform; nothing else consults this.
 */
var systemDarkOverride: Boolean? = null

/**
 * Overrides which platform this is, for tests and for the dev harness.
 *
 * A design system is allowed to answer differently on two platforms that draw the same
 * language, so a test about one of those answers has to be able to say which platform it
 * means. Without this it gets the machine the test happens to be running on, which for a
 * test about a phone's tab bar is whatever laptop is in front of you.
 */
var hostPlatformOverride: HostPlatform? = null

/**
 * How to find out whether the system is in dark mode, when the platform knows better than
 * Compose does.
 *
 * Installed by the platform at startup. The desktop installs a poller, because Compose's
 * own reading there is taken once and never revisited. iOS and Android leave it null,
 * where Compose observes the change itself and a second mechanism would be noise.
 *
 * It lives here rather than in the desktop module because this file is compiled for every
 * target: the iOS renderer symlinks it, and Skiko, which the desktop observer reads, does
 * not exist on Kotlin/Native.
 *
 * It is a CompositionLocal rather than a global, and that is not a matter of taste. The
 * desktop observer polls in a loop that never finishes, which is correct in a window and
 * fatal under a test clock: a composition with a coroutine forever waiting on a delay never
 * goes idle, so waitForIdle spins until the test times out. As a global, one composition
 * installing it silently did that to every composition created afterwards in the same
 * process, including tests that had nothing to do with it.
 */
val LocalSystemDarkObserver = staticCompositionLocalOf<(@Composable () -> Boolean)?> { null }

/**
 * The strip at the top of a window that belongs to the window rather than to the
 * application: on macOS the transparent title bar the close, minimise and zoom buttons
 * sit in, and on the platforms where the renderer draws the caption itself, the band it
 * draws it in.
 *
 * Content is allowed to run underneath it, which is the whole point of modern window
 * chrome, but a widget placed where the buttons are would leave both unusable. So
 * whatever owns the top of the window steps its own content clear of the strip while
 * still painting across it.
 *
 * The Host never sees these numbers and cannot set them. A safe area is a fact about the
 * window, not a decision the application makes.
 */
@androidx.compose.runtime.Immutable
data class WindowCaption(
    /** How tall the strip is. */
    val height: Dp = 0.dp,
    /** How much room the window buttons take at the end they sit at. */
    val buttonsWidth: Dp = 0.dp,
    /**
     * Which end that is.
     *
     * The platform's own buttons are at the leading edge, because the one platform that
     * keeps its own puts them there. Buttons the renderer draws sit wherever the running
     * design system puts them, which is the trailing edge for five of the seven, and a
     * bar that reserved room at the wrong end would push its title away from the buttons
     * and then draw them over its other end.
     */
    val buttonsAtStart: Boolean = true,
    /**
     * A strip directly above the bar that the bar's surface covers and its content starts
     * below.
     *
     * A phone's status bar, which is a different shape of problem from [height]: window
     * buttons share the bar's row and a clock does not, so a bar that treated the two the
     * same would draw its title through the time.
     */
    val insetTop: Dp = 0.dp,
    /**
     * How round the system made the window's corners, or zero where it does not say.
     *
     * Read from the window rather than written into a design system: macOS gives a window
     * with a toolbar a larger radius than one without, and changes both between releases.
     * A strip laid along the window's edge cuts its own corner concentric with this one.
     */
    val cornerRadius: Dp = 0.dp,
    val fullSize: Boolean = false,
) {
    companion object {
        /** No strip to avoid: a system title bar, or a platform without one. */
        val None = WindowCaption()
    }
}

/**
 * The caption the top app bar has to lay itself out around.
 *
 * Zero unless the Host's tree opens with a bar. Anything else keeps the caption on the
 * page, and a bar buried deeper in the tree is not at the top of the window, so stepping
 * its content down by the height of a strip it is nowhere near would only push it out of
 * line with everything beside it.
 */
val LocalWindowCaption = staticCompositionLocalOf { WindowCaption.None }

/**
 * How round the system made the window's corners, or zero where it does not say.
 *
 * Separate from [LocalWindowCaption], which only a bar opening the tree receives: a
 * sidebar beside that bar still stands inside the same window corner.
 */
val LocalWindowCornerRadius = staticCompositionLocalOf { 0.dp }

/**
 * Whether a rail or a sidebar at the root of the tree runs to the top of the window and
 * carries the caption on its own surface.
 *
 * Separate from [LocalWindowCaption], which a bar opening the tree also receives. A strip
 * that stepped its destinations down by the caption whenever one was handed out would
 * step them down under a bar that had already taken it, and leave a blank band beside it.
 */
val LocalStripTakesTheTop = staticCompositionLocalOf { false }

/** The child of a frame that fills [slot], if the application filled it. */
private fun NodeTable.slotChild(node: Node, slot: SlotRole): Int? =
    node.children.firstOrNull { childId ->
        val child = node(childId) ?: return@firstOrNull false
        child.widget == WidgetKind.ScaffoldSlot &&
            (child.property(PropertyKind.Slot) as? PropertyValue.Integer)?.value?.toInt() ==
            slot.ordinal + 1
    }

/**
 * The top app bar the page opens with, followed the way [opensWithABar] follows it, or null
 * when the first thing the tree draws is anything else.
 *
 * A message the application placed along the top keeps clear of this bar and of no other:
 * a bar further down the page is part of the page, not chrome across the top of it.
 */
internal fun NodeTable.openingTopBar(roots: List<Int>): Int? {
    var id = roots.firstOrNull() ?: return null
    repeat(BAR_SEARCH_DEPTH) {
        val node = node(id) ?: return null
        when (node.widget) {
            WidgetKind.TopAppBar -> return id
            WidgetKind.Column, WidgetKind.Box -> id = node.children.firstOrNull() ?: return null
            WidgetKind.Scaffold -> id = slotChild(node, SlotRole.TopBar) ?: return null
            WidgetKind.ScaffoldSlot -> id = node.children.firstOrNull() ?: return null
            else -> return null
        }
    }
    return null
}

/**
 * True when the first thing the tree draws is a top app bar.
 *
 * Only the leading edge is followed, and only through the layouts that are wrappers
 * rather than things on screen: an application writes `Column { TopAppBar { } ... }`, and
 * the column is not something the reader sees. A bar reached any other way is not the top
 * of the window.
 */
internal fun NodeTable.opensWithABar(roots: List<Int>): Boolean {
    var id = roots.firstOrNull() ?: return false
    repeat(BAR_SEARCH_DEPTH) {
        val node = node(id) ?: return false
        when (node.widget) {
            WidgetKind.TopAppBar -> return true
            // A picture at the top of the window is the same case as a bar: it is what
            // the reader sees across the top, and leaving a strip of page colour above it
            // reads as a title bar nobody asked for.
            WidgetKind.Image -> return true
            // A Column stacks its children, so its first child is the top of the window.
            // A Box stacks them front to back, and a bar drawn first is chrome the rest
            // of the screen scrolls under, which is the same thing here.
            //
            // A wrapper is passed through whether or not it paints a background. Its
            // colour is the page's, and the page is exactly what should start below the
            // window buttons rather than run under them; what it holds decides instead.
            WidgetKind.Column, WidgetKind.Box -> id = node.children.firstOrNull() ?: return false
            // A frame names its parts, so the top of the window is the slot that says it
            // is the top bar rather than whichever child happens to come first. Following
            // the order instead would hand the caption to the destinations on a screen
            // that filled the bottom slot and not the top one.
            WidgetKind.Scaffold -> id = slotChild(node, SlotRole.TopBar) ?: return false
            WidgetKind.ScaffoldSlot -> id = node.children.firstOrNull() ?: return false
            // Nothing else takes it. A shell that paints itself, a Navigation holding a
            // whole page for instance, is the page rather than a strip across the top of
            // it, and handing it the caption puts its first line of text under the window
            // buttons. What its colour should do is fill the window, which is a separate
            // question answered by windowFill below.
            else -> return false
        }
    }
    return false
}

/**
 * True when a navigation holding the whole page is what the tree opens with.
 *
 * The one that owns the window, rather than one nested inside part of a screen. Only that
 * one draws a bar along the bottom edge of the window, and only that bar should grow into
 * the strip the system's gesture bar sits in: a nested one has content below it and would
 * leave a gap in the middle of the screen.
 */
internal fun NodeTable.opensWithANavigation(roots: List<Int>): Boolean =
    openingNavigation(roots) != null

/** The navigation [opensWithANavigation] finds, or null where the page opens with none. */
internal fun NodeTable.openingNavigation(roots: List<Int>): Node? {
    var id = roots.firstOrNull() ?: return null
    repeat(BAR_SEARCH_DEPTH) {
        val node = node(id) ?: return null
        when (node.widget) {
            WidgetKind.Navigation -> return node
            // The same wrappers the search above passes through, for the same reason:
            // they are not things the reader sees.
            WidgetKind.Column, WidgetKind.Box -> id = node.children.firstOrNull() ?: return null
            // A frame's destinations are whatever fills its bottom slot, and the frame
            // owns the page around them, which is what this question is really asking.
            WidgetKind.Scaffold -> id = slotChild(node, SlotRole.BottomBar) ?: return null
            WidgetKind.ScaffoldSlot -> id = node.children.firstOrNull() ?: return null
            else -> return null
        }
    }
    return null
}

/**
 * The colour the whole window is painted, before the content is laid out inside it.
 *
 * The root's own fill where it named one, and the theme's background where it did not.
 * Painting the theme's background regardless leaves an application that holds its own
 * palette with a page in its colour and a strip along the top in the design system's,
 * which reads as a leftover title bar. This is the rule a container already follows, that
 * the fill the application named wins, applied to the window.
 */
internal fun NodeTable.windowFill(roots: List<Int>, theme: ResolvedTheme): Color {
    val named = paintAtTheTopOfTheWindow(roots)
    val fill = named?.let(theme::color) ?: theme.color(ColorRole.Background)
    return if (asksForWindowMaterial(roots)) fill.letTheWindowShowThrough() else fill
}

/**
 * The colour of whatever reaches the top of the window, or null where nothing named one.
 *
 * The root is asked first and then the leading edge below it, because the thing that fills
 * a window is not always the root: an application writes a frame and puts a page in it, so
 * what paints is a step or two down and nothing above it names a colour at all. Reading
 * only the root left the strip above the page in the design system's background while the
 * page under it was the application's own, which is the leftover title bar this section
 * exists to avoid.
 */
private fun NodeTable.paintAtTheTopOfTheWindow(roots: List<Int>): Paint? {
    var id = roots.firstOrNull() ?: return null
    var atTheRoot = true
    repeat(BAR_SEARCH_DEPTH) {
        val node = node(id) ?: return null
        val painted = node.modifiers.firstNotNullOfOrNull {
            (it as? ProtocolModifier.Background)?.paint
        }
        when (node.widget) {
            // Chrome, not the window. A bar or a picture takes the caption and paints that
            // strip itself, so lending the window its colour would paint every screen that
            // opens with one in the chrome's colour.
            WidgetKind.TopAppBar, WidgetKind.Image -> return null
            // A shell holds the whole page, so the colour it paints is the colour the
            // window is.
            WidgetKind.Navigation -> return painted
            // A frame paints nothing itself and names its parts, so the window's colour is
            // the content's rather than the bar's.
            WidgetKind.Scaffold -> {
                painted?.let { return it }
                atTheRoot = false
                id = slotChild(node, SlotRole.Content) ?: return null
            }
            WidgetKind.ScaffoldSlot -> {
                painted?.let { return it }
                atTheRoot = false
                id = node.children.firstOrNull() ?: return null
            }
            // The same wrappers the caption search passes through, and for the same
            // reason: they are not things the reader sees. Their own colour counts only at
            // the root, where it is the page's; deeper down a painted Column is a card or
            // a bubble, and painting the window in a bubble's colour hides the rounding
            // that makes it one.
            WidgetKind.Column, WidgetKind.Box -> {
                if (atTheRoot && painted != null) return painted
                atTheRoot = false
                id = node.children.firstOrNull() ?: return null
            }
            else -> return if (atTheRoot) painted else null
        }
    }
    return null
}

/**
 * Whether anything in this tree asked to be made of a material.
 *
 * Anything, not the page. A window that shows what is behind it is not a window that is
 * see-through all over: no application on this platform is. A sidebar is vibrant and the
 * page beside it is not, and that is decided where the material is drawn rather than
 * here. What is decided here is only whether the window is stood up in a form that has
 * anything behind it to show, which is a property of the window and has to be settled
 * before it opens.
 *
 * A page that paints itself still covers what is behind it, exactly as it always did.
 */
internal fun NodeTable.asksForWindowMaterial(roots: List<Int>): Boolean {
    // The roots are taken so that the question is asked of a tree rather than of the
    // table in the abstract, and so a caller cannot forget to check that one exists.
    if (roots.isEmpty()) return false
    return asksForMaterial
}

/**
 * The page of a window that is backed by a material: none of it.
 *
 * The material behind the window is the page. Painting one over it is painting over the
 * thing that was asked for, and it does not take much: a page at three quarters opacity
 * left four percent of the backdrop showing, which measures as a couple of levels and
 * reads as a flat dark rectangle.
 *
 * What the screen declared is still drawn. The root carries the material role, and the
 * design system's own glass is drawn for it in the ordinary way, over a window that now
 * has something real behind it to be glass over.
 */
private fun Color.letTheWindowShowThrough(): Color =
    if (platformBacksWindowWithMaterial()) Color.Transparent else this

/**
 * True where the window really has a material behind it for a translucent page to reveal.
 *
 * A hook with `false` for its default, because only the build that puts the material there
 * can answer and the others have to be safe. It used to be read off the operating system's
 * name, which is true of every macOS build and describes only one of them: the native
 * image, whose C entry puts an `NSVisualEffectView` under the window. The Kotlin/Native
 * renderer opens its own window and puts nothing behind it, and it was answering yes.
 *
 * What a wrong yes costs is the whole look of the window. Chrome becomes the recipe meant
 * to sit on the desktop, a tint at 0.18 with a rim, and the page gradient is made
 * translucent so the desktop can reach it. With nothing behind either, a window in light
 * mode comes up with a grey page and a grey sidebar: nothing transparent, everything drawn
 * as though it were.
 *
 * Everywhere else a page with alpha would show whatever the toolkit leaves behind a
 * window, which is nothing to look at and on some systems is black.
 */
var platformBacksWindowWithMaterial: () -> Boolean = { false }

/**
 * How many wrappers deep the search for that bar goes.
 *
 * Deep enough for the layouts an application really writes around a bar, shallow enough
 * that a tree which simply does not have one costs a handful of lookups per frame rather
 * than a walk.
 */
private const val BAR_SEARCH_DEPTH = 4

/**
 * Whether the reader has asked the system for reduced transparency.
 *
 * Every glass surface draws its opaque fallback instead when this is true, and the blur
 * pass that fed it disappears with it, so the setting removes the cost as well as the
 * look.
 *
 * It is read once, from `DXC_REDUCE_TRANSPARENCY` in the environment or the
 * `dev.darkpyonix.composerust.reduceTransparency` system property, either of which counts as set when
 * it is anything other than "0" or "false". A platform that can query the accessibility
 * setting directly assigns to this at startup instead; a platform that cannot leaves the
 * reader with a way to say so, which is better than no way at all.
 */
var reduceTransparency: Boolean = run {
    val raw = System.getenv("DXC_REDUCE_TRANSPARENCY")
        ?: System.getProperty("dev.darkpyonix.composerust.reduceTransparency")
        ?: return@run false
    !raw.equals("0", ignoreCase = true) && !raw.equals("false", ignoreCase = true)
}

/**
 * The strips of the window the system draws its own things in.
 *
 * A phone's status bar and its navigation bar, and the home indicator on the platforms
 * that have one. Zero on a desktop, where the window is the whole of what the application
 * draws in and a title bar is the [WindowCaption] above instead.
 *
 * This is deliberately not applied as padding around everything. An application that stops
 * short of both strips leaves the system's own background showing through them, which is
 * the grey band under a phone's gesture bar that no other application on the device has.
 * The window's fill is drawn edge to edge and then these are handed to whichever part of
 * the tree should grow into them.
 */
data class SystemBars(val top: Dp = 0.dp, val bottom: Dp = 0.dp) {
    companion object {
        /** A window with nothing over it. */
        val None = SystemBars()
    }
}

/** What the bottom strip is, for the part of the tree that grows into it. */
val LocalSystemBars = staticCompositionLocalOf { SystemBars.None }

/**
 * How far the page has to start and stop short of the edges of the window.
 *
 * Whatever a strip is given to is not the page's concern, which is what the two booleans
 * say. A bar that opens the tree takes the top strip and paints its own surface behind the
 * status bar, the way every application on a phone does. A navigation showing a bar along
 * the bottom takes the bottom strip for the same reason. What is left over is the page's,
 * because content running under a clock or a gesture bar is unreadable.
 *
 * The keyboard is the one thing nothing grows into. While it is up the page ends at its top
 * edge, whatever took the bottom strip before, so the field being typed into and everything
 * below it on the page are above the keyboard rather than under it. The top is not touched:
 * the bar there stays where it was.
 */
internal fun pageInsets(
    caption: WindowCaption,
    bars: SystemBars,
    barTakesTheTop: Boolean,
    navigationTakesTheBottom: Boolean,
    keyboard: Dp = 0.dp,
): Pair<Dp, Dp> {
    // Never below nothing, whatever a platform measured. This is a padding, and a negative
    // one does not draw oddly: it throws, from inside composition, and takes the window
    // with it.
    val top = if (caption.fullSize || barTakesTheTop) 0.dp else (caption.height + bars.top).coerceAtLeast(0.dp)
    val bottom = when {
        keyboard > 0.dp -> maxOf(keyboard, bars.bottom)
        navigationTakesTheBottom -> 0.dp
        else -> bars.bottom
    }
    return top to bottom
}

/**
 * How much of the window's bottom edge the on-screen keyboard covers, as the platform
 * reports it. Zero where there is no on-screen keyboard.
 *
 * The window is the one it is read in: the page reads it for the application's window, and
 * a sheet or a dialog reads it again inside its own (see `overlayKeyboardInset`).
 *
 * A hook so a test can put a keyboard on a desktop window, which has none.
 */
var platformKeyboardInset: @Composable () -> Dp = {
    with(LocalDensity.current) { WindowInsets.ime.getBottom(this).toDp() }
}