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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
//! Desktop shell for Fission applications.
//!
//! Provides the native window, GPU-accelerated rendering pipeline (via Vello + wgpu),
//! input handling, clipboard, IME, and platform video integration needed to run a
//! Fission UI on macOS, Windows, and Linux.
//!
//! The main entry point is [`DesktopApp::new(root_widget)`](DesktopApp::new), which
//! creates a winit event loop and runs the full build-layout-paint-present cycle.
use anyhow::Result;
use std::collections::{HashMap, VecDeque};
use std::num::NonZeroU32;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use winit::{
dpi::PhysicalPosition,
event::{ElementState, Event, Ime, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent},
event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
keyboard::PhysicalKey,
window::{Window, WindowBuilder},
};
use fission_core::env::{VideoState, VideoStateMap, VideoStatus};
use fission_core::lowering::{build_layout_tree, LoweringContext};
use fission_core::{
Action, ActionId, AppState, BuildCtx, Clock, Env, ImeHandler, InputEvent, KeyCode,
KeyEvent as FissionKeyEvent, Lower, Node, PointerButton, PointerEvent, Runtime, ScrollStateMap,
View, Widget,
};
use fission_core::{ActionInput, Effect, EffectPayload, SystemEffect};
use fission_diagnostics::prelude as diag;
use fission_ir::{op::Color as IrColor, CoreIR, FlexDirection, NodeId, Op, PaintOp, WidgetNodeId};
use fission_layout::{LayoutEngine, LayoutSize};
use fission_render::{
Color as RenderColor, DisplayList, LayoutPoint, LayoutRect, LayoutUnit, Renderer,
};
use fission_render_vello::parley::FontContext;
use fission_render_vello::{VelloRenderer, VelloTextMeasurer};
use fission_shell::{Platform, VideoBackend, VideoEvent, VideoPlayer};
use fission_theme::fonts;
use fontique::{Blob, Collection, CollectionOptions, FontInfoOverride, SourceCache};
// Vello / WGPU
use pollster::block_on;
use vello::util::{RenderContext, RenderSurface};
use vello::wgpu;
use vello::{AaConfig, AaSupport, Renderer as VelloSceneRenderer, RendererOptions, Scene};
mod pipeline;
pub use pipeline::Pipeline;
mod video_backend;
#[cfg(target_os = "macos")]
use video_backend::MacVideoBackend;
#[cfg(not(target_os = "macos"))]
use video_backend::MockVideoBackend;
mod clipboard;
use clipboard::DesktopClipboard;
mod ime;
use ime::DesktopImeHandler;
pub mod test_control;
use fission_core::action::ActionEnvelope;
/// A single completed background effect result, ready to be dispatched on the main thread.
///
/// Fields: `(req_id, result_payload_or_error, on_ok_continuation, on_err_continuation)`
type EffectResult = (
u64,
std::result::Result<EffectPayload, String>,
Option<ActionEnvelope>,
Option<ActionEnvelope>,
);
/// Callback signature for application-specific effect handlers.
///
/// The handler receives the opaque `Vec<u8>` payload from `Effect::App(...)`,
/// plus the envelope metadata needed to send a result back on the channel.
pub type AppEffectHandler = Box<
dyn Fn(Vec<u8>, u64, Option<ActionEnvelope>, Option<ActionEnvelope>, mpsc::Sender<EffectResult>)
+ Send
+ Sync,
>;
struct ActivePlayer {
player: Box<dyn VideoPlayer>,
last_status: Option<VideoStatus>,
last_rate: Option<f32>,
last_volume: Option<f32>,
last_muted: Option<bool>,
}
fn request_redraw_throttled(
window: &Window,
elwt: &EventLoopWindowTarget<()>,
last_redraw_at: &mut Instant,
min_frame: Duration,
redraw_pending: &mut bool,
) {
let now = Instant::now();
let next = *last_redraw_at + min_frame;
if now >= next {
*last_redraw_at = now;
*redraw_pending = false;
window.request_redraw();
} else {
*redraw_pending = true;
elwt.set_control_flow(ControlFlow::WaitUntil(next));
}
}
/// Drain pending effects from the runtime and either execute them synchronously
/// (fire-and-forget effects like `OpenUrl`) or spawn background threads for I/O
/// effects (`FileRead`, `HttpGet`) and send results back through `effect_tx`.
///
/// Returns `true` if any synchronous callback was dispatched (caller should redraw).
fn process_pending_effects(
runtime: &mut Runtime,
effect_tx: &mpsc::Sender<EffectResult>,
app_effect_handler: Option<&AppEffectHandler>,
) -> bool {
use std::process::Command;
let pending = std::mem::take(&mut runtime.pending_effects);
if pending.is_empty() {
return false;
}
let mut dispatched_callback = false;
for env in pending {
match env.effect {
Effect::System(ref system) => {
match system {
// ── Fire-and-forget: OpenUrl ─────────────────────────────
SystemEffect::OpenUrl { url, in_app } => {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Info,
diag::DiagEventKind::InputEvent {
kind: format!("system_effect:OpenUrl in_app={}", in_app),
target: None,
position: None,
},
);
let result = if cfg!(target_os = "macos") {
Command::new("open").arg(url).spawn().map(|_| ())
} else if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", "start", url])
.spawn()
.map(|_| ())
} else {
Command::new("xdg-open").arg(url).spawn().map(|_| ())
};
if let Err(e) = result {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Error,
diag::DiagEventKind::InputEvent {
kind: format!("system_effect:OpenUrl failed: {}", e),
target: None,
position: None,
},
);
}
// Dispatch immediate callback (fire-and-forget success).
if let Some(on_ok) = env.on_ok {
let _ = runtime.dispatch_with_input(
on_ok,
NodeId::derived(0, &[0]),
&ActionInput::EffectOk {
req_id: env.req_id,
payload: EffectPayload::Empty,
},
);
dispatched_callback = true;
}
}
// ── Fire-and-forget: Authenticate ────────────────────────
SystemEffect::Authenticate { url, .. } => {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Info,
diag::DiagEventKind::InputEvent {
kind: "system_effect:Authenticate".into(),
target: None,
position: None,
},
);
let _ = if cfg!(target_os = "macos") {
Command::new("open").arg(url).spawn()
} else if cfg!(target_os = "windows") {
Command::new("cmd").args(["/C", "start", url]).spawn()
} else {
Command::new("xdg-open").arg(url).spawn()
};
if let Some(on_ok) = env.on_ok {
let _ = runtime.dispatch_with_input(
on_ok,
NodeId::derived(0, &[0]),
&ActionInput::EffectOk {
req_id: env.req_id,
payload: EffectPayload::Empty,
},
);
dispatched_callback = true;
}
}
// ── Fire-and-forget: Alert (log only) ────────────────────
SystemEffect::Alert { title, message } => {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Info,
diag::DiagEventKind::InputEvent {
kind: format!("system_effect:Alert title={}", title),
target: None,
position: None,
},
);
eprintln!("[alert] {}: {}", title, message);
if let Some(on_ok) = env.on_ok {
let _ = runtime.dispatch_with_input(
on_ok,
NodeId::derived(0, &[0]),
&ActionInput::EffectOk {
req_id: env.req_id,
payload: EffectPayload::Empty,
},
);
dispatched_callback = true;
}
}
// ── Background: FileRead ─────────────────────────────────
SystemEffect::FileRead { path } => {
let tx = effect_tx.clone();
let on_ok = env.on_ok.clone();
let on_err = env.on_err.clone();
let req_id = env.req_id;
let path = path.clone();
std::thread::spawn(move || {
match std::fs::read_to_string(&path) {
Ok(content) => {
let payload = EffectPayload::InlineBytes(content.into_bytes());
let _ = tx.send((req_id, Ok(payload), on_ok, on_err));
}
Err(e) => {
let _ = tx.send((req_id, Err(e.to_string()), on_ok, on_err));
}
}
});
}
// ── Background: HttpGet ───────────────────────────────────
SystemEffect::HttpGet { url, headers } => {
let tx = effect_tx.clone();
let on_ok = env.on_ok.clone();
let on_err = env.on_err.clone();
let req_id = env.req_id;
let url = url.clone();
let headers = headers.clone();
std::thread::spawn(move || {
// Minimal blocking HTTP GET using std only (no external crate).
// This parses the URL, opens a TCP stream, and reads the response.
let result = (|| -> std::result::Result<Vec<u8>, String> {
use std::io::{Read, Write};
use std::net::TcpStream;
// Parse URL (very basic: http://host[:port]/path)
let url_trimmed = url.trim();
let (scheme, rest) = if let Some(r) = url_trimmed.strip_prefix("https://") {
("https", r)
} else if let Some(r) = url_trimmed.strip_prefix("http://") {
("http", r)
} else {
return Err(format!("unsupported URL scheme: {}", url_trimmed));
};
let (host_port, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/"),
};
let default_port: u16 = if scheme == "https" { 443 } else { 80 };
let (host, port) = match host_port.rfind(':') {
Some(i) => {
let p = host_port[i + 1..].parse::<u16>().unwrap_or(default_port);
(&host_port[..i], p)
}
None => (host_port, default_port),
};
if scheme == "https" {
return Err("HTTPS not supported in minimal HttpGet executor; use a custom app effect handler for TLS".into());
}
let addr = format!("{}:{}", host, port);
let mut stream = TcpStream::connect(&addr)
.map_err(|e| format!("connect {}: {}", addr, e))?;
stream
.set_read_timeout(Some(std::time::Duration::from_secs(30)))
.ok();
let mut request = format!(
"GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n",
path, host
);
for (k, v) in &headers {
request.push_str(&format!("{}: {}\r\n", k, v));
}
request.push_str("\r\n");
stream
.write_all(request.as_bytes())
.map_err(|e| format!("write: {}", e))?;
let mut buf = Vec::new();
stream
.read_to_end(&mut buf)
.map_err(|e| format!("read: {}", e))?;
// Strip HTTP headers (find \r\n\r\n)
let body_start = buf
.windows(4)
.position(|w| w == b"\r\n\r\n")
.map(|i| i + 4)
.unwrap_or(0);
Ok(buf[body_start..].to_vec())
})();
match result {
Ok(bytes) => {
let payload = EffectPayload::InlineBytes(bytes);
let _ = tx.send((req_id, Ok(payload), on_ok, on_err));
}
Err(msg) => {
let _ = tx.send((req_id, Err(msg), on_ok, on_err));
}
}
});
}
// ── Cancel / ReleaseResource: no-op at shell level ───────
SystemEffect::Cancel { .. } | SystemEffect::ReleaseResource { .. } => {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Debug,
diag::DiagEventKind::InputEvent {
kind: format!("system_effect:{:?} (no-op)", system),
target: None,
position: None,
},
);
}
}
}
// ── App-specific effects ─────────────────────────────────────
Effect::App(payload) => {
if let Some(handler) = app_effect_handler {
handler(
payload,
env.req_id,
env.on_ok.clone(),
env.on_err.clone(),
effect_tx.clone(),
);
} else {
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Warn,
diag::DiagEventKind::InputEvent {
kind: "app_effect:unhandled (no handler registered)".into(),
target: None,
position: None,
},
);
}
}
}
}
dispatched_callback
}
/// Drain completed background effect results from the channel and dispatch
/// their continuations on the main thread.
///
/// Returns `true` if any continuation was dispatched (caller should redraw).
fn drain_effect_results(
runtime: &mut Runtime,
effect_rx: &mpsc::Receiver<EffectResult>,
) -> bool {
let mut dispatched = false;
while let Ok((req_id, result, on_ok, on_err)) = effect_rx.try_recv() {
match result {
Ok(payload) => {
if let Some(action) = on_ok {
let _ = runtime.dispatch_with_input(
action,
NodeId::derived(0, &[0]),
&ActionInput::EffectOk { req_id, payload },
);
dispatched = true;
}
}
Err(msg) => {
if let Some(action) = on_err {
let _ = runtime.dispatch_with_input(
action,
NodeId::derived(0, &[0]),
&ActionInput::EffectErr {
req_id,
message: msg,
},
);
dispatched = true;
}
}
}
}
dispatched
}
fn focused_text_input_id(runtime: &Runtime, ir: Option<&CoreIR>) -> Option<NodeId> {
let focused = runtime.runtime_state.interaction.focused?;
let ir = ir?;
let mut current = Some(focused);
while let Some(id) = current {
let node = ir.nodes.get(&id)?;
if let Op::Semantics(sem) = &node.op {
if sem.role == fission_ir::Role::TextInput {
return Some(id);
}
}
current = node.parent;
}
None
}
fn reset_text_input_caret(
runtime: &mut Runtime,
ir: Option<&CoreIR>,
last_blink_toggle: &mut Instant,
) {
if let Some(id) = focused_text_input_id(runtime, ir) {
runtime.runtime_state.caret_visible.insert(id, true);
*last_blink_toggle = Instant::now();
}
}
#[derive(Debug, Clone)]
struct PendingTextTrace {
seq: u64,
source: String,
target: Option<NodeId>,
started_at: Instant,
handled_at: Option<Instant>,
effects_at: Option<Instant>,
present_after_frame: u64,
}
fn start_text_trace(
enabled: bool,
traces: &mut VecDeque<PendingTextTrace>,
next_seq: &mut u64,
source: String,
target: Option<NodeId>,
presented_frames: u64,
) -> Option<u64> {
if !enabled {
return None;
}
*next_seq += 1;
let seq = *next_seq;
traces.push_back(PendingTextTrace {
seq,
source,
target,
started_at: Instant::now(),
handled_at: None,
effects_at: None,
present_after_frame: presented_frames + 1,
});
Some(seq)
}
fn mark_text_trace_handled(traces: &mut VecDeque<PendingTextTrace>, seq: Option<u64>) {
if let Some(seq) = seq {
if let Some(trace) = traces.iter_mut().rev().find(|trace| trace.seq == seq) {
trace.handled_at = Some(Instant::now());
}
}
}
fn mark_text_trace_effects(traces: &mut VecDeque<PendingTextTrace>, seq: Option<u64>) {
if let Some(seq) = seq {
if let Some(trace) = traces.iter_mut().rev().find(|trace| trace.seq == seq) {
trace.effects_at = Some(Instant::now());
}
}
}
fn set_text_trace_target(
traces: &mut VecDeque<PendingTextTrace>,
seq: Option<u64>,
target: Option<NodeId>,
) {
if let Some(seq) = seq {
if let Some(trace) = traces.iter_mut().rev().find(|trace| trace.seq == seq) {
trace.target = target;
}
}
}
fn cancel_text_trace(traces: &mut VecDeque<PendingTextTrace>, seq: Option<u64>) {
if let Some(seq) = seq {
traces.retain(|trace| trace.seq != seq);
}
}
fn flush_text_traces(
enabled: bool,
traces: &mut VecDeque<PendingTextTrace>,
presented_frames: u64,
) {
if !enabled {
traces.clear();
return;
}
loop {
let should_flush = traces
.front()
.map(|trace| trace.present_after_frame <= presented_frames)
.unwrap_or(false);
if !should_flush {
break;
}
let Some(trace) = traces.pop_front() else {
break;
};
let now = Instant::now();
let handled_at = trace.handled_at.unwrap_or(now);
let effects_at = trace.effects_at.unwrap_or(handled_at);
let total_ms = now.duration_since(trace.started_at).as_secs_f64() * 1000.0;
let handle_ms = handled_at
.duration_since(trace.started_at)
.as_secs_f64()
* 1000.0;
let effects_ms = effects_at
.duration_since(handled_at)
.as_secs_f64()
* 1000.0;
let queue_ms = now.duration_since(effects_at).as_secs_f64() * 1000.0;
let target_u128 = trace.target.map(|id| id.as_u128());
let msg = format!(
"text_input_latency seq={} src={} handle_ms={:.2} effects_ms={:.2} queue_ms={:.2} total_ms={:.2} frame={}",
trace.seq, trace.source, handle_ms, effects_ms, queue_ms, total_ms, presented_frames
);
eprintln!("[text-trace] {}", msg);
diag::emit(
diag::DiagCategory::Input,
diag::DiagLevel::Info,
diag::DiagEventKind::InputEvent {
kind: msg,
target: target_u128,
position: None,
},
);
}
}
/// Type alias for an application-level key handler.
///
/// Receives `(&mut S, &KeyCode, modifiers)` and returns `true` if the key was consumed.
pub type KeyHandler<S> = Arc<dyn Fn(&mut S, &fission_core::KeyCode, u8) -> bool + Send + Sync>;
/// Type alias for a per-frame hook callback.
///
/// Receives `(&mut S)` and returns `true` to request a redraw.
pub type FrameHook<S> = Arc<dyn Fn(&mut S) -> bool + Send + Sync>;
/// The desktop application shell that owns the window, event loop, and rendering pipeline.
///
/// Generic over `S` (the application state type) and `W` (the root widget type).
/// Construct via [`DesktopApp::new()`] and configure with builder methods
/// (`with_title`, `with_state_init`, `with_key_handler`, etc.) before calling
/// [`run()`](DesktopApp::run) to start the event loop.
pub struct DesktopApp<S: AppState, W: Widget<S>> {
runtime: Runtime,
layout_engine: LayoutEngine,
root_widget: W,
env: Env,
pipeline: Pipeline,
measurer: Arc<VelloTextMeasurer>,
sync_env: Option<Arc<dyn Fn(&S, &mut Env) + Send + Sync>>,
key_handler: Option<KeyHandler<S>>,
frame_hook: Option<FrameHook<S>>,
title: String,
/// Channel pair for receiving completed background effect results.
effect_result_tx: mpsc::Sender<EffectResult>,
effect_result_rx: mpsc::Receiver<EffectResult>,
/// Optional handler for `Effect::App(...)` payloads.
app_effect_handler: Option<AppEffectHandler>,
_phantom: std::marker::PhantomData<S>,
}
impl<S: AppState + Default, W: Widget<S> + 'static> DesktopApp<S, W> {
pub fn new(root_widget: W) -> Self {
let mut runtime = Runtime::default();
runtime.add_app_state(Box::new(S::default())).unwrap();
const DEFAULT_FONT_FAMILY: &str = "Fission Default";
let font_cx = Arc::new(Mutex::new(build_font_context()));
{
let mut font_cx = font_cx.lock().unwrap();
let font_data = fonts::default_font_bytes().to_vec();
let info_override = FontInfoOverride {
family_name: Some(DEFAULT_FONT_FAMILY),
..Default::default()
};
font_cx
.collection
.register_fonts(Blob::from(font_data), Some(info_override));
}
let measurer = Arc::new(VelloTextMeasurer::new_with_default_family(
font_cx.clone(),
DEFAULT_FONT_FAMILY,
));
let env = Env::new(measurer.clone() as Arc<dyn fission_layout::TextMeasurer>);
let clipboard: Arc<dyn fission_core::env::Clipboard> = Arc::new(DesktopClipboard::new());
let layout_engine = LayoutEngine::new().with_measurer(measurer.clone());
let runtime = runtime
.with_measurer(measurer.clone())
.with_clipboard(clipboard);
let (effect_result_tx, effect_result_rx) = mpsc::channel();
Self {
runtime,
layout_engine,
root_widget,
env,
pipeline: Pipeline::new(),
measurer,
sync_env: None,
key_handler: None,
frame_hook: None,
title: "Fission".into(),
effect_result_tx,
effect_result_rx,
app_effect_handler: None,
_phantom: std::marker::PhantomData,
}
}
pub fn with_key_handler<F>(mut self, handler: F) -> Self
where
F: Fn(&mut S, &fission_core::KeyCode, u8) -> bool + Send + Sync + 'static,
{
self.key_handler = Some(Arc::new(handler));
self
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
/// Mutate the initial application state before the first frame.
pub fn with_state_init<F>(mut self, init: F) -> Self
where
F: FnOnce(&mut S),
{
if let Some(state) = self.runtime.get_app_state_mut::<S>() {
init(state);
}
self
}
pub fn with_env(mut self, env: Env) -> Self {
self.env = env;
self
}
pub fn with_sync_env<F>(mut self, f: F) -> Self
where
F: Fn(&S, &mut Env) + Send + Sync + 'static,
{
self.sync_env = Some(Arc::new(f));
self
}
/// Register a hook that runs on every `AboutToWait` event with mutable
/// access to the application state. Return `true` to request a redraw.
/// Useful for polling background services (e.g. LSP) between key events.
pub fn with_frame_hook<F>(mut self, f: F) -> Self
where
F: Fn(&mut S) -> bool + Send + Sync + 'static,
{
self.frame_hook = Some(Arc::new(f));
self
}
/// Register a handler for `Effect::App(payload)` effects.
///
/// The handler runs on the calling thread and should spawn its own
/// background work if needed, sending results through the provided
/// `mpsc::Sender<EffectResult>`.
pub fn with_app_effect_handler<F>(mut self, handler: F) -> Self
where
F: Fn(Vec<u8>, u64, Option<ActionEnvelope>, Option<ActionEnvelope>, mpsc::Sender<EffectResult>)
+ Send
+ Sync
+ 'static,
{
self.app_effect_handler = Some(Box::new(handler));
self
}
pub fn register_reducer(
&mut self,
action_id: ActionId,
reducer: fn(&mut S, &fission_core::ActionEnvelope, NodeId) -> Result<()>,
) -> Result<()> {
self.runtime.register_reducer::<S>(action_id, reducer)
}
pub fn absorb_registry(&mut self, registry: fission_core::ActionRegistry<S>) {
self.runtime.absorb_persistent_registry(registry);
}
pub fn run(mut self) -> Result<()> {
diag::emit(
diag::DiagCategory::Frame,
diag::DiagLevel::Info,
diag::DiagEventKind::FrameStart { root: None },
);
diag::init_from_env();
let event_loop =
EventLoop::new().map_err(|e| anyhow::anyhow!("Event loop error: {}", e))?;
let window = Arc::new(
WindowBuilder::new()
.with_title(&self.title)
.build(&event_loop)
.map_err(|e| anyhow::anyhow!("Window build error: {}", e))?,
);
let ime_handler: Arc<dyn ImeHandler> = Arc::new(DesktopImeHandler::new(window.clone()));
self.runtime = self.runtime.with_ime_handler(ime_handler);
// Vello Context
let mut render_cx = RenderContext::new();
let mut surface = block_on(render_cx.create_surface(
window.clone(),
window.inner_size().width,
window.inner_size().height,
wgpu::PresentMode::AutoVsync,
))
.unwrap();
// Enable Alpha for video hole punching
let device_handle = &render_cx.devices[surface.dev_id];
surface.config.alpha_mode = wgpu::CompositeAlphaMode::PostMultiplied;
surface
.surface
.configure(&device_handle.device, &surface.config);
// Recreate target texture with COPY_SRC so GPU screenshots work
recreate_target_texture(&mut surface, &render_cx);
let mut vello_renderer = VelloSceneRenderer::new(
&device_handle.device,
RendererOptions {
use_cpu: false,
antialiasing_support: AaSupport::all(),
num_init_threads: None,
pipeline_cache: None,
},
)
.unwrap();
let mut scene = Scene::new();
window.request_redraw();
let mut runtime = self.runtime;
let mut layout_engine = self.layout_engine;
let root_widget = self.root_widget;
let mut env = self.env;
let mut pipeline = self.pipeline;
let measurer = self.measurer;
let effect_result_tx = self.effect_result_tx;
let effect_result_rx = self.effect_result_rx;
let app_effect_handler = self.app_effect_handler;
#[cfg(target_os = "macos")]
let video_backend: Arc<dyn VideoBackend> = Arc::new(MacVideoBackend::new(&window));
#[cfg(not(target_os = "macos"))]
let video_backend: Arc<dyn VideoBackend> = Arc::new(MockVideoBackend::new());
let mut players: HashMap<WidgetNodeId, ActivePlayer> = HashMap::new();
let mut last_cursor_position: Option<PhysicalPosition<f64>> = None;
let max_fps = std::env::var("FISSION_MAX_FPS")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|v| *v > 0)
.unwrap_or(60);
let min_frame = Duration::from_secs_f32(1.0 / max_fps as f32);
let mut last_redraw_at = Instant::now()
.checked_sub(min_frame)
.unwrap_or_else(Instant::now);
let mut redraw_pending = false;
let mut last_frame_time = Instant::now();
let blink_enabled = std::env::var("FISSION_TEXTINPUT_BLINK")
.map(|v| !matches!(v.to_ascii_lowercase().as_str(), "0" | "false" | "no"))
.unwrap_or(true);
let blink_period = Duration::from_millis(
std::env::var("FISSION_TEXTINPUT_BLINK_MS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.filter(|v| *v > 0)
.unwrap_or(530),
);
let mut last_blink_toggle = Instant::now();
let mut blink_focus_id: Option<NodeId> = None;
let text_trace_enabled = std::env::var("FISSION_TEXT_TRACE")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
.unwrap_or(false);
let mut presented_frames: u64 = 0;
let mut next_text_trace_seq: u64 = 0;
let mut pending_text_traces: VecDeque<PendingTextTrace> = VecDeque::new();
let mut current_mods: u8 = 0;
// Test control channel (enabled via FISSION_TEST_CONTROL_PORT env var)
let test_control_rx: Option<test_control::CommandReceiver> = std::env::var("FISSION_TEST_CONTROL_PORT")
.ok()
.and_then(|v| v.parse::<u16>().ok())
.map(|port| {
let (tx, rx) = test_control::create_channel();
test_control::spawn_server(port, tx);
rx
});
let mut pending_screenshot: Option<(String, test_control::ResponseSender)> = None;
event_loop
.run(move |event, elwt| {
elwt.set_control_flow(ControlFlow::Wait);
match event {
Event::AboutToWait => {
let now = Instant::now();
let dt = now.duration_since(last_frame_time);
last_frame_time = now;
// Tick Runtime (Animations)
let dt_ms = dt.as_millis() as u64;
if let Err(e) = runtime.tick(dt_ms) {
eprintln!("Runtime tick error: {:?}", e);
}
// Video Logic
let surfaces = pipeline.take_video_surfaces();
let mut active_nodes = std::collections::HashSet::new();
for surface in &surfaces {
active_nodes.insert(surface.widget_id);
// Create player if missing
if !players.contains_key(&surface.widget_id) {
if let Some(state) = runtime.runtime_state.video.states.get(&surface.widget_id) {
let source = &state.asset_source;
if !source.is_empty() {
let player = video_backend.create_player(source);
if let Some(state) = runtime.runtime_state.video.states.get_mut(&surface.widget_id) {
state.surface_id = Some(player.surface_id());
}
players.insert(surface.widget_id, ActivePlayer {
player,
last_status: None,
last_rate: None,
last_volume: None,
last_muted: None,
});
}
}
}
}
// Cleanup inactive players
players.retain(|id, _| active_nodes.contains(id));
// Update backend
video_backend.present_surfaces(&surfaces);
// Video Logic - Process Player Events and Sync State
for (widget_id, active_player) in players.iter_mut() {
if let Some(video_state) = runtime.runtime_state.video.states.get_mut(widget_id) {
let player = &mut active_player.player;
// Sync player controls from runtime state
if active_player.last_status != Some(video_state.status) {
match video_state.status {
VideoStatus::Playing => player.play(),
VideoStatus::Paused => player.pause(),
VideoStatus::Stopped => player.stop(),
_ => {}
}
active_player.last_status = Some(video_state.status);
}
// Update runtime state from player events
for event in player.poll_events() {
match event {
VideoEvent::Ready { duration } => {
video_state.duration_ms = Some(duration);
if video_state.status == VideoStatus::Playing {
player.play();
}
},
VideoEvent::Ended => {
video_state.status = VideoStatus::Ended;
active_player.last_status = Some(VideoStatus::Ended);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
},
VideoEvent::Error(e) => {
eprintln!("Video playback error for {:?}: {:?}", widget_id, e);
video_state.status = VideoStatus::Error;
active_player.last_status = Some(VideoStatus::Error);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
},
}
}
// Sync other properties
video_state.position_ms = player.position();
if active_player.last_rate != Some(video_state.rate) {
player.set_rate(video_state.rate);
active_player.last_rate = Some(video_state.rate);
}
if active_player.last_volume != Some(video_state.volume) {
player.set_volume(video_state.volume);
active_player.last_volume = Some(video_state.volume);
}
if active_player.last_muted != Some(video_state.muted) {
player.set_muted(video_state.muted);
active_player.last_muted = Some(video_state.muted);
}
if let Some(seek_pos) = video_state.pending_seek.take() {
player.seek_to(seek_pos);
}
}
}
// Check if we need a redraw (Animation or Video playing)
// Only force continuous redraws for non-repeating animations
// or active video players. Repeating animations (spinners, skeleton
// shimmer) should not burn CPU when idle.
let has_finite_animation = runtime.runtime_state.animation.active.values()
.any(|a| !a.repeat);
let has_repeating_animation = runtime.runtime_state.animation.active.values()
.any(|a| a.repeat);
let needs_redraw = has_finite_animation || !players.is_empty();
let focused_text_input = focused_text_input_id(&runtime, pipeline.prev_ir.as_ref());
if focused_text_input != blink_focus_id {
if let Some(prev) = blink_focus_id {
runtime.runtime_state.caret_visible.remove(&prev);
}
blink_focus_id = focused_text_input;
if let Some(id) = blink_focus_id {
runtime.runtime_state.caret_visible.insert(id, true);
last_blink_toggle = now;
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
// Cursor blink: toggle visibility but DON'T request a full
// rebuild. A full build/layout/paint cycle is too expensive
// for the editor (tree-sitter, minimap, etc.). Instead, we
// just note the flag change and let the NEXT user-triggered
// redraw pick it up. The cursor will appear steady but
// that's how VS Code / Zed work too.
if blink_enabled {
if let Some(id) = blink_focus_id {
if now.duration_since(last_blink_toggle) >= blink_period {
let visible = runtime.runtime_state.caret_visible.get(&id).copied().unwrap_or(true);
runtime.runtime_state.caret_visible.insert(id, !visible);
last_blink_toggle = now;
// NOTE: intentionally NOT requesting redraw here.
// The caret state will be picked up on the next
// user-triggered frame (typing, scrolling, etc.)
}
}
}
let blink_wake_at = if blink_enabled && blink_focus_id.is_some() {
Some(last_blink_toggle + blink_period)
} else {
None
};
// Poll test control channel
if let Some(ref rx) = test_control_rx {
while let Ok((cmd, responder)) = rx.try_recv() {
use fission_test_driver::{TestCommand, TestResponse, TextItem, SemanticNode};
let resp = match cmd {
TestCommand::Tap { x, y } => {
let point = LayoutPoint::new(x, y);
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
let _ = runtime.handle_input(InputEvent::Pointer(PointerEvent::Down { point, button: PointerButton::Primary }), ir, snap);
let _ = runtime.handle_input(InputEvent::Pointer(PointerEvent::Up { point, button: PointerButton::Primary }), ir, snap);
}
TestResponse::Ok {}
}
TestCommand::TapText { text } => {
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
let mut found = None;
for (id, node) in &ir.nodes {
let txt = match &node.op {
fission_ir::Op::Paint(fission_ir::PaintOp::DrawText { text: t, .. }) => Some(t.as_str()),
fission_ir::Op::Paint(fission_ir::PaintOp::DrawRichText { runs, .. }) => {
// Check concatenated text
let combined: String = runs.iter().map(|r| r.text.clone()).collect();
if combined.contains(&text) { Some("") } else { None }
}
_ => None,
};
if let Some(t) = txt {
if t.contains(&text) || t.is_empty() {
// Find parent layout node for position
let check_id = node.parent.unwrap_or(*id);
if let Some(rect) = snap.get_node_rect(check_id).or_else(|| snap.get_node_rect(*id)) {
found = Some((rect.x() + rect.width() / 2.0, rect.y() + rect.height() / 2.0));
break;
}
}
}
}
if let Some((cx, cy)) = found {
let point = LayoutPoint::new(cx, cy);
let _ = runtime.handle_input(InputEvent::Pointer(PointerEvent::Down { point, button: PointerButton::Primary }), ir, snap);
let _ = runtime.handle_input(InputEvent::Pointer(PointerEvent::Up { point, button: PointerButton::Primary }), ir, snap);
TestResponse::Ok {}
} else {
TestResponse::Error { message: format!("text '{}' not found", text) }
}
} else {
TestResponse::Error { message: "no frame rendered yet".into() }
}
}
TestCommand::Scroll { x, y, dx, dy } => {
let point = LayoutPoint::new(x, y);
let delta = LayoutPoint::new(dx, dy);
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
let _ = runtime.handle_input(InputEvent::Pointer(PointerEvent::Scroll { point, delta }), ir, snap);
}
TestResponse::Ok {}
}
TestCommand::TypeText { text } => {
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
for ch in text.chars() {
let key = if ch == ' ' { KeyCode::Space } else if ch == '\n' { KeyCode::Enter } else { KeyCode::Char(ch) };
let _ = runtime.handle_input(InputEvent::Keyboard(FissionKeyEvent::Down { key_code: key, modifiers: 0 }), ir, snap);
}
}
TestResponse::Ok {}
}
TestCommand::PressKey { key, modifiers } => {
let kc = match key.as_str() {
"Enter" => KeyCode::Enter,
"Escape" => KeyCode::Escape,
"Tab" => KeyCode::Tab,
"Backspace" => KeyCode::Backspace,
"Left" => KeyCode::Left,
"Right" => KeyCode::Right,
"Up" => KeyCode::Up,
"Down" => KeyCode::Down,
"Home" => KeyCode::Home,
"End" => KeyCode::End,
"Space" => KeyCode::Space,
s if s.len() == 1 => KeyCode::Char(s.chars().next().unwrap()),
_ => KeyCode::Space,
};
// Check app key handler first
let mut handled = false;
if let Some(handler) = &self.key_handler {
let handler = handler.clone();
if let Some(state) = runtime.get_app_state_mut::<S>() {
handled = handler(state, &kc, modifiers);
}
}
if !handled {
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
let _ = runtime.handle_input(InputEvent::Keyboard(FissionKeyEvent::Down { key_code: kc, modifiers }), ir, snap);
}
}
TestResponse::Ok {}
}
TestCommand::Screenshot { path } => {
pending_screenshot = Some((path, responder));
window.request_redraw();
continue; // Don't respond yet, respond after render
}
TestCommand::GetText {} => {
let mut items = Vec::new();
if let (Some(ir), Some(snap)) = (pipeline.prev_ir.as_ref(), pipeline.last_snapshot.as_ref()) {
for (id, node) in &ir.nodes {
let text_content = match &node.op {
fission_ir::Op::Paint(fission_ir::PaintOp::DrawText { text, .. }) => Some(text.clone()),
fission_ir::Op::Paint(fission_ir::PaintOp::DrawRichText { runs, .. }) => {
Some(runs.iter().map(|r| r.text.clone()).collect::<String>())
}
_ => None,
};
if let Some(text) = text_content {
if text.is_empty() { continue; }
let check_id = node.parent.unwrap_or(*id);
let rect = snap.get_node_rect(check_id).or_else(|| snap.get_node_rect(*id));
let (x, y, w, h) = rect.map(|r| (r.x(), r.y(), r.width(), r.height())).unwrap_or((0.0, 0.0, 0.0, 0.0));
items.push(TextItem { text, x, y, width: w, height: h });
}
}
}
TestResponse::Text { items }
}
TestCommand::GetTree {} => {
let mut nodes = Vec::new();
if let Some(ir) = &pipeline.prev_ir {
for (id, node) in &ir.nodes {
if let fission_ir::Op::Semantics(sem) = &node.op {
let rect = pipeline.last_snapshot.as_ref()
.and_then(|s| s.get_node_rect(*id));
let (x, y, w, h) = rect.map(|r| (r.x(), r.y(), r.width(), r.height())).unwrap_or((0.0, 0.0, 0.0, 0.0));
nodes.push(SemanticNode {
role: format!("{:?}", sem.role),
label: sem.label.clone(),
value: sem.value.clone(),
focusable: sem.focusable,
x, y, width: w, height: h,
});
}
}
}
TestResponse::Tree { nodes }
}
TestCommand::Wait { ms } => {
std::thread::sleep(std::time::Duration::from_millis(ms));
TestResponse::Ok {}
}
TestCommand::Pump {} => {
// Defer response until after the next frame renders
pending_screenshot = Some(("__pump__".into(), responder));
window.request_redraw();
continue; // Don't respond yet
}
TestCommand::Quit {} => {
elwt.exit();
TestResponse::Ok {}
}
};
let _ = responder.send(resp);
window.request_redraw();
}
}
// Drain completed background effect results and dispatch
// their continuations back into the runtime on the main thread.
let effect_results_dispatched = drain_effect_results(&mut runtime, &effect_result_rx);
if effect_results_dispatched {
// Background work completed — process any new effects
// the continuation reducers may have emitted.
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
window.request_redraw();
}
// Application frame hook (e.g. LSP polling).
let frame_hook_wants_redraw = if let Some(ref hook) = self.frame_hook {
let hook = hook.clone();
if let Some(state) = runtime.get_app_state_mut::<S>() {
hook(state)
} else {
false
}
} else {
false
};
if frame_hook_wants_redraw {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
// When a frame_hook is registered, ensure the event loop
// wakes at least every 2 seconds so the hook fires even
// when no user input or animation is happening (e.g. for
// asynchronous LSP diagnostics).
let frame_hook_wake_at = if self.frame_hook.is_some() {
Some(now + Duration::from_secs(2))
} else {
None
};
if needs_redraw || redraw_pending || effect_results_dispatched || frame_hook_wants_redraw {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
let mut wake_at = last_redraw_at + min_frame;
if let Some(blink_at) = blink_wake_at {
if blink_at < wake_at {
wake_at = blink_at;
}
}
if let Some(hook_at) = frame_hook_wake_at {
if hook_at < wake_at {
wake_at = hook_at;
}
}
elwt.set_control_flow(ControlFlow::WaitUntil(wake_at));
} else if let Some(blink_at) = blink_wake_at {
let mut wake_at = blink_at;
if let Some(hook_at) = frame_hook_wake_at {
if hook_at < wake_at {
wake_at = hook_at;
}
}
elwt.set_control_flow(ControlFlow::WaitUntil(wake_at));
} else if let Some(hook_at) = frame_hook_wake_at {
elwt.set_control_flow(ControlFlow::WaitUntil(hook_at));
} else if has_repeating_animation {
// Wake at 200ms for repeating animations (spinners, shimmer)
let anim_at = now + Duration::from_millis(200);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
elwt.set_control_flow(ControlFlow::WaitUntil(anim_at));
} else {
elwt.set_control_flow(ControlFlow::Wait);
}
}
Event::WindowEvent { window_id, event } if window_id == window.id() => {
match event {
WindowEvent::Resized(size) => {
if size.width > 0 && size.height > 0 {
// Invalidate viewport to force full layout rebuild
pipeline.last_viewport = None;
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
WindowEvent::ScaleFactorChanged { .. } => {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
WindowEvent::RedrawRequested => {
redraw_pending = false;
diag::begin_frame(None);
// Drain pending effects before building the next frame.
// This prevents the effect queue from growing unbounded.
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
let size = window.inner_size();
if size.width > 0 && size.height > 0 {
if size.width != surface.config.width || size.height != surface.config.height {
render_cx.resize_surface(&mut surface, size.width, size.height);
// Re-apply alpha mode after resize
let device_handle = &render_cx.devices[surface.dev_id];
surface.config.alpha_mode = wgpu::CompositeAlphaMode::PostMultiplied;
surface.surface.configure(&device_handle.device, &surface.config);
// Recreate target texture with COPY_SRC for screenshots
recreate_target_texture(&mut surface, &render_cx);
}
let scale_factor = window.scale_factor();
let layout_width = (size.width as f64 / scale_factor) as f32;
let layout_height = (size.height as f64 / scale_factor) as f32;
env.viewport_size = LayoutSize {
width: layout_width,
height: layout_height,
};
if let Some(sync) = &self.sync_env {
let state = runtime.get_app_state::<S>().unwrap();
sync(state, &mut env);
}
let (node_tree, registry, anims, videos, web_views, portals) = {
let state = runtime.get_app_state::<S>().unwrap();
let view = View::new(state, &runtime.runtime_state, &env, pipeline.last_snapshot.as_ref());
let mut ctx = BuildCtx::new();
let node = root_widget.build(&mut ctx, &view);
let anims = ctx.take_animation_requests();
let videos = ctx.take_video_registrations();
let web_views = ctx.take_web_registrations();
let portals_with_ids = ctx.take_portals();
let portals = portals_with_ids.into_iter().map(|(id, node)| {
if let Some(id) = id {
// Use a derived ID for the wrapper to avoid conflict with the widget's own node
let wrapper_id = fission_core::NodeId::derived(id.as_u128(), &[0x0000_F001]);
fission_core::ui::Container::new(node)
.id(wrapper_id)
.width(env.viewport_size.width)
.height(env.viewport_size.height)
.into_node()
} else {
node
}
}).collect::<Vec<_>>();
// Emit portal summary to diagnostics
{
use fission_diagnostics::prelude as diag;
diag::emit(
diag::DiagCategory::Layout,
diag::DiagLevel::Debug,
diag::DiagEventKind::PortalsComposed { portal_count: portals.len() as u32 },
);
}
(node, ctx.registry, anims, videos, web_views, portals)
};
runtime.clear_reducers();
runtime.absorb_registry(registry);
for (target, req) in anims {
runtime.enqueue_animation(target, req);
}
runtime.sync_video_nodes(&videos);
runtime.sync_web_nodes(&web_views);
// Always compose an overlay layer above content.
// Portals are injected into that layer and never
// participate in normal layout.
let final_root = fission_core::Node::Overlay(
fission_core::ui::Overlay {
id: None,
content: Box::new(node_tree),
overlay: Box::new(fission_core::Node::ZStack(
fission_core::ui::ZStack {
children: portals,
..Default::default()
},
)),
}
);
let mut lower_cx = LoweringContext::new(&env, &runtime.runtime_state, runtime.measurer.as_ref(), pipeline.last_snapshot.as_ref());
let root_id = final_root.lower(&mut lower_cx);
lower_cx.ir.root = Some(root_id);
let cx_ir = lower_cx.ir;
let viewport = LayoutSize {
width: layout_width,
height: layout_height,
};
// Vello Rendering
scene.reset();
let mut renderer_wrapper = VelloRenderer::new(&mut scene, measurer.clone(), scale_factor);
match pipeline.render(
cx_ir,
viewport,
&mut layout_engine,
&runtime.runtime_state.scroll,
&mut renderer_wrapper,
&runtime.runtime_state.video,
&runtime.runtime_state.web,
&env,
) {
Ok(_stats) => {
let surface_texture = surface.surface.get_current_texture().expect("failed to get texture");
let device_handle = &render_cx.devices[surface.dev_id];
let render_params = vello::RenderParams {
base_color: vello::peniko::Color::from_rgb8(30, 30, 30),
width: size.width,
height: size.height,
antialiasing_method: vello::AaConfig::Area,
};
vello_renderer.render_to_texture(
&device_handle.device,
&device_handle.queue,
&scene,
&surface.target_view,
&render_params,
).expect("failed to render");
let surface_view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device_handle.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Surface Blit"),
});
surface.blitter.copy(
&device_handle.device,
&mut encoder,
&surface.target_view,
&surface_view,
);
device_handle.queue.submit(Some(encoder.finish()));
// GPU screenshot BEFORE present (target texture has content)
if let Some((path, responder)) = pending_screenshot.take() {
if path == "__pump__" {
let _ = responder.send(fission_test_driver::TestResponse::Ok {});
} else {
let resp = gpu_screenshot(
&device_handle.device,
&device_handle.queue,
&surface.target_texture,
size.width,
size.height,
&path,
);
let _ = responder.send(resp);
}
}
surface_texture.present();
presented_frames = presented_frames.saturating_add(1);
flush_text_traces(
text_trace_enabled,
&mut pending_text_traces,
presented_frames,
);
diag::end_frame(diag::FrameStats::default());
}
Err(e) => {
eprintln!("Pipeline error: {:?}", e);
}
}
}
}
WindowEvent::CloseRequested => {
elwt.exit();
}
// Input Handling
WindowEvent::CursorMoved { position, .. } => {
if let (Some(ir), Some(layout)) = (&pipeline.prev_ir, &pipeline.last_snapshot) {
last_cursor_position = Some(position);
let scale_factor = window.scale_factor();
let point = LayoutPoint {
x: (position.x / scale_factor) as f32,
y: (position.y / scale_factor) as f32,
};
let event = InputEvent::Pointer(PointerEvent::Move { point });
if let Err(e) = runtime.handle_input(event, ir, layout) {
eprintln!("Input handling error: {:?}", e);
}
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
WindowEvent::MouseInput { state, button, .. } => {
if let (Some(ir), Some(layout)) = (&pipeline.prev_ir, &pipeline.last_snapshot) {
if let Some(position) = last_cursor_position {
let scale_factor = window.scale_factor();
let point = LayoutPoint {
x: (position.x / scale_factor) as f32,
y: (position.y / scale_factor) as f32,
};
if let Some(btn) = map_mouse_button(button) {
if let Some(event) = build_pointer_event(state, btn, point) {
let trace_seq = if text_trace_enabled && state.is_pressed() {
start_text_trace(
text_trace_enabled,
&mut pending_text_traces,
&mut next_text_trace_seq,
"pointer_down".to_string(),
None,
presented_frames,
)
} else {
None
};
// println!("Dispatching input: {:?} at {:?}", event, point);
if let Err(e) = runtime.handle_input(event, ir, layout) {
eprintln!("Input handling error: {:?}", e);
} else {
// println!("Input dispatched successfully");
}
mark_text_trace_handled(&mut pending_text_traces, trace_seq);
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
mark_text_trace_effects(&mut pending_text_traces, trace_seq);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
if state.is_pressed() {
let target = focused_text_input_id(&runtime, pipeline.prev_ir.as_ref());
if target.is_some() {
set_text_trace_target(&mut pending_text_traces, trace_seq, target);
} else {
cancel_text_trace(&mut pending_text_traces, trace_seq);
}
reset_text_input_caret(&mut runtime, pipeline.prev_ir.as_ref(), &mut last_blink_toggle);
}
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
}
}
}
WindowEvent::MouseWheel { delta, .. } => {
if let (Some(ir), Some(layout)) = (&pipeline.prev_ir, &pipeline.last_snapshot) {
if let Some(position) = last_cursor_position {
let scale_factor = window.scale_factor();
let point = LayoutPoint {
x: (position.x / scale_factor) as f32,
y: (position.y / scale_factor) as f32,
};
let scroll_delta = match delta {
MouseScrollDelta::LineDelta(x, y) => LayoutPoint { x: -x * 50.0, y: -y * 50.0 },
MouseScrollDelta::PixelDelta(p) => LayoutPoint {
x: -(p.x / scale_factor) as f32,
y: -(p.y / scale_factor) as f32,
},
};
let event = InputEvent::Pointer(PointerEvent::Scroll { point, delta: scroll_delta });
if std::env::var("FISSION_SCROLL_TRACE").ok().as_deref() == Some("1") {
eprintln!(
"[scroll-trace] mousewheel raw={:?} point=({:.1},{:.1}) delta=({:.1},{:.1})",
delta,
point.x,
point.y,
scroll_delta.x,
scroll_delta.y
);
}
if let Err(e) = runtime.handle_input(event, ir, layout) {
eprintln!("Scroll error: {:?}", e);
}
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
}
WindowEvent::ModifiersChanged(modifiers) => {
current_mods = 0;
if modifiers.state().shift_key() { current_mods |= 1; }
if modifiers.state().alt_key() { current_mods |= 2; }
if modifiers.state().control_key() { current_mods |= 4; }
if modifiers.state().super_key() { current_mods |= 8; }
}
WindowEvent::KeyboardInput { event, .. } => {
if event.state.is_pressed() {
use winit::keyboard::{Key, NamedKey};
let key_code = match event.logical_key {
Key::Named(NamedKey::Space) => Some(KeyCode::Space),
Key::Named(NamedKey::Enter) => Some(KeyCode::Enter),
Key::Named(NamedKey::Escape) => Some(KeyCode::Escape),
Key::Named(NamedKey::Backspace) => Some(KeyCode::Backspace),
Key::Named(NamedKey::Tab) => Some(KeyCode::Tab),
Key::Named(NamedKey::ArrowLeft) => Some(KeyCode::Left),
Key::Named(NamedKey::ArrowRight) => Some(KeyCode::Right),
Key::Named(NamedKey::ArrowUp) => Some(KeyCode::Up),
Key::Named(NamedKey::ArrowDown) => Some(KeyCode::Down),
Key::Named(NamedKey::Home) => Some(KeyCode::Home),
Key::Named(NamedKey::End) => Some(KeyCode::End),
_ => {
if let Some(text) = &event.text {
text.chars().next().map(KeyCode::Char)
} else {
None
}
}
};
if let (Some(code), Some(ir), Some(layout)) = (key_code, &pipeline.prev_ir, &pipeline.last_snapshot) {
// App-level key handler intercepts before framework
let mut key_handled_by_app = false;
if let Some(handler) = &self.key_handler {
let handler = handler.clone();
if let Some(state) = runtime.get_app_state_mut::<S>() {
if handler(state, &code, current_mods) {
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
key_handled_by_app = true;
}
}
}
if key_handled_by_app {
// Skip normal key handling
} else {
let target = focused_text_input_id(&runtime, pipeline.prev_ir.as_ref());
let trace_seq = start_text_trace(
text_trace_enabled && target.is_some(),
&mut pending_text_traces,
&mut next_text_trace_seq,
format!("keyboard:{:?}", code),
target,
presented_frames,
);
let input_event = InputEvent::Keyboard(FissionKeyEvent::Down {
key_code: code,
modifiers: current_mods,
});
if let Err(e) = runtime.handle_input(input_event, ir, layout) {
eprintln!("Keyboard error: {:?}", e);
}
mark_text_trace_handled(&mut pending_text_traces, trace_seq);
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
mark_text_trace_effects(&mut pending_text_traces, trace_seq);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
reset_text_input_caret(&mut runtime, pipeline.prev_ir.as_ref(), &mut last_blink_toggle);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
} // else (not handled by app key handler)
}
}
}
WindowEvent::Ime(ime) => {
if let (Some(ir), Some(layout)) = (&pipeline.prev_ir, &pipeline.last_snapshot) {
let (input_event, source) = match ime {
Ime::Commit(text) => (
Some(InputEvent::Ime(fission_core::event::ImeEvent::Commit { text: text.clone() })),
Some(format!("ime_commit:{}", text.chars().count())),
),
Ime::Preedit(text, _) => (
Some(InputEvent::Ime(fission_core::event::ImeEvent::Preedit { text: text.clone() })),
Some(format!("ime_preedit:{}", text.chars().count())),
),
_ => (None, None),
};
if let Some(e) = input_event {
let target = focused_text_input_id(&runtime, pipeline.prev_ir.as_ref());
let trace_seq = start_text_trace(
text_trace_enabled && target.is_some(),
&mut pending_text_traces,
&mut next_text_trace_seq,
source.unwrap_or_else(|| "ime".to_string()),
target,
presented_frames,
);
runtime.handle_input(e, ir, layout).ok();
mark_text_trace_handled(&mut pending_text_traces, trace_seq);
if process_pending_effects(&mut runtime, &effect_result_tx, app_effect_handler.as_ref()) {
mark_text_trace_effects(&mut pending_text_traces, trace_seq);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
reset_text_input_caret(&mut runtime, pipeline.prev_ir.as_ref(), &mut last_blink_toggle);
request_redraw_throttled(&window, elwt, &mut last_redraw_at, min_frame, &mut redraw_pending);
}
}
}
_ => {}
}
}
_ => {}
}
})
.map_err(|e| anyhow::anyhow!("Event loop error: {}", e))
}
}
fn build_font_context() -> FontContext {
let use_system_fonts = std::env::var("FISSION_USE_SYSTEM_FONTS")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
.unwrap_or(false);
let options = CollectionOptions {
shared: false,
system_fonts: use_system_fonts,
};
FontContext {
collection: Collection::new(options),
source_cache: SourceCache::default(),
}
}
// Helpers...
fn map_mouse_button(button: MouseButton) -> Option<PointerButton> {
match button {
MouseButton::Left => Some(PointerButton::Primary),
MouseButton::Right => Some(PointerButton::Secondary),
MouseButton::Middle => Some(PointerButton::Middle),
MouseButton::Other(id) => Some(PointerButton::Other(id as u8)),
_ => None,
}
}
fn build_pointer_event(
state: ElementState,
button: PointerButton,
point: LayoutPoint,
) -> Option<InputEvent> {
let pointer_event = match state {
ElementState::Pressed => PointerEvent::Down { point, button },
ElementState::Released => PointerEvent::Up { point, button },
};
Some(InputEvent::Pointer(pointer_event))
}
fn gpu_screenshot(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
width: u32,
height: u32,
path: &str,
) -> fission_test_driver::TestResponse {
if width == 0 || height == 0 {
return fission_test_driver::TestResponse::Error {
message: "zero-size viewport".into(),
};
}
let bytes_per_pixel = 4u32;
let unpadded_bytes_per_row = width * bytes_per_pixel;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded_bytes_per_row = (unpadded_bytes_per_row + align - 1) / align * align;
let buffer_size = (padded_bytes_per_row * height) as u64;
let staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("screenshot staging"),
size: buffer_size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("screenshot copy"),
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &staging,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded_bytes_per_row),
rows_per_image: Some(height),
},
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
queue.submit(Some(encoder.finish()));
let (tx, rx) = std::sync::mpsc::channel();
staging.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = tx.send(result);
});
let _ = device.poll(wgpu::PollType::Wait);
match rx.recv() {
Ok(Ok(())) => {}
Ok(Err(e)) => {
return fission_test_driver::TestResponse::Error {
message: format!("buffer map failed: {:?}", e),
};
}
Err(e) => {
return fission_test_driver::TestResponse::Error {
message: format!("buffer map channel error: {}", e),
};
}
}
let data = staging.slice(..).get_mapped_range();
// Remove row padding (texture is Rgba8Unorm, no swizzle needed)
let mut rgba = Vec::with_capacity((width * height * 4) as usize);
for row in 0..height {
let start = (row * padded_bytes_per_row) as usize;
let end = start + (width * bytes_per_pixel) as usize;
rgba.extend_from_slice(&data[start..end]);
}
drop(data);
staging.unmap();
match image::save_buffer(path, &rgba, width, height, image::ColorType::Rgba8) {
Ok(()) => fission_test_driver::TestResponse::Ok {},
Err(e) => fission_test_driver::TestResponse::Error {
message: format!("PNG save failed: {}", e),
},
}
}
fn recreate_target_texture(
surface: &mut RenderSurface,
render_cx: &RenderContext,
) {
let device = &render_cx.devices[surface.dev_id].device;
let size = wgpu::Extent3d {
width: surface.config.width.max(1),
height: surface.config.height.max(1),
depth_or_array_layers: 1,
};
let new_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("fission_target_with_copy"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm, // Must match Vello's internal format
usage: wgpu::TextureUsages::STORAGE_BINDING
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let new_view = new_texture.create_view(&wgpu::TextureViewDescriptor::default());
surface.target_texture = new_texture;
surface.target_view = new_view;
}