summaryrefslogtreecommitdiff
path: root/examples/notepad.c
blob: 0b331e8797c9c463ebbed02b9076fcfa13e54f53 (plain)
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
/**
 * @file notepad.c
 * A full-featured desktop text editor built on YASL Approach A.
 *
 * Features:
 * - New (Ctrl+N), Open (Ctrl+O, CLI arg, drag-and-drop), Save (Ctrl+S), Save As (Ctrl+Shift+S)
 * - Tab key with 4-space tab stops; Shift+Tab unindent
 * - Clipboard Copy (Ctrl+C), Cut (Ctrl+X), Paste (Ctrl+V) via YASL native clipboard
 * - Undo (Ctrl+Z) & Redo (Ctrl+Y / Ctrl+Shift+Z)
 * - Find (Ctrl+F), Find Next (F3), Find Prev (Shift+F3), Replace (Ctrl+H), Goto Line (Ctrl+G)
 * - Insert Date/Time (F5)
 * - Word navigation (Ctrl+Left/Right) & Word deletion (Ctrl+Backspace/Delete)
 * - Word Wrap toggle (Ctrl+W) & Horizontal Scrolling
 * - Zoom In / Out / Reset (Ctrl+=, Ctrl+-, Ctrl+0)
 * - Mouse selection with click, drag, double-click (word), triple-click (line)
 * - Unsaved changes confirmation on exit
 * - Real-time asynchronous background stats via yasl_display_post()
 * - 0% CPU consumption when idle (YASL_PACING_ON_DEMAND)
 */

#define _DEFAULT_SOURCE
#include <yasl/app.h>

#include <ctype.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define MAX_LINES 4096
#define MAX_LINE_LEN 1024
#define MAX_UNDO 32

/* Classic 8x8 font bitmap covering ASCII 32 (' ') to 126 ('~') */
static const uint8_t font8x8[95][8] = {
    {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /*   */
    {0x18,0x3C,0x3C,0x18,0x18,0x00,0x18,0x00}, /* ! */
    {0x66,0x66,0x24,0x00,0x00,0x00,0x00,0x00}, /* " */
    {0x6C,0x6C,0xFE,0x6C,0xFE,0x6C,0x6C,0x00}, /* # */
    {0x18,0x3E,0x60,0x3C,0x06,0x7C,0x18,0x00}, /* $ */
    {0x00,0x63,0x66,0x0C,0x18,0x33,0x63,0x00}, /* % */
    {0x38,0x6C,0x38,0x76,0xDC,0xCC,0x76,0x00}, /* & */
    {0x18,0x18,0x30,0x00,0x00,0x00,0x00,0x00}, /* ' */
    {0x0C,0x18,0x30,0x30,0x30,0x18,0x0C,0x00}, /* ( */
    {0x30,0x18,0x0C,0x0C,0x0C,0x18,0x30,0x00}, /* ) */
    {0x00,0x66,0x3C,0xFF,0x3C,0x66,0x00,0x00}, /* * */
    {0x00,0x18,0x18,0x7E,0x18,0x18,0x00,0x00}, /* + */
    {0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x30}, /* , */
    {0x00,0x00,0x00,0x7E,0x00,0x00,0x00,0x00}, /* - */
    {0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x00}, /* . */
    {0x06,0x0C,0x18,0x30,0x60,0xC0,0x80,0x00}, /* / */
    {0x3C,0x66,0x6E,0x76,0x66,0x66,0x3C,0x00}, /* 0 */
    {0x18,0x38,0x18,0x18,0x18,0x18,0x7E,0x00}, /* 1 */
    {0x3C,0x66,0x06,0x0C,0x18,0x30,0x7E,0x00}, /* 2 */
    {0x3C,0x66,0x06,0x1C,0x06,0x66,0x3C,0x00}, /* 3 */
    {0x0C,0x1C,0x34,0x64,0x7E,0x04,0x04,0x00}, /* 4 */
    {0x7E,0x60,0x7C,0x06,0x06,0x66,0x3C,0x00}, /* 5 */
    {0x1C,0x30,0x60,0x7C,0x66,0x66,0x3C,0x00}, /* 6 */
    {0x7E,0x06,0x0C,0x18,0x30,0x30,0x30,0x00}, /* 7 */
    {0x3C,0x66,0x66,0x3C,0x66,0x66,0x3C,0x00}, /* 8 */
    {0x3C,0x66,0x66,0x3E,0x06,0x0C,0x38,0x00}, /* 9 */
    {0x00,0x18,0x18,0x00,0x00,0x18,0x18,0x00}, /* : */
    {0x00,0x18,0x18,0x00,0x00,0x18,0x18,0x30}, /* ; */
    {0x0C,0x18,0x30,0x60,0x30,0x18,0x0C,0x00}, /* < */
    {0x00,0x00,0x7E,0x00,0x7E,0x00,0x00,0x00}, /* = */
    {0x30,0x18,0x0C,0x06,0x0C,0x18,0x30,0x00}, /* > */
    {0x3C,0x66,0x06,0x0C,0x18,0x00,0x18,0x00}, /* ? */
    {0x3C,0x66,0x6E,0x6A,0x6E,0x60,0x3C,0x00}, /* @ */
    {0x18,0x3C,0x66,0x7E,0x66,0x66,0x66,0x00}, /* A */
    {0x7C,0x66,0x66,0x7C,0x66,0x66,0x7C,0x00}, /* B */
    {0x3C,0x66,0x60,0x60,0x60,0x66,0x3C,0x00}, /* C */
    {0x78,0x6C,0x66,0x66,0x66,0x6C,0x78,0x00}, /* D */
    {0x7E,0x60,0x60,0x7C,0x60,0x60,0x7E,0x00}, /* E */
    {0x7E,0x60,0x60,0x7C,0x60,0x60,0x60,0x00}, /* F */
    {0x3C,0x66,0x60,0x6E,0x66,0x66,0x3C,0x00}, /* G */
    {0x66,0x66,0x66,0x7E,0x66,0x66,0x66,0x00}, /* H */
    {0x3C,0x18,0x18,0x18,0x18,0x18,0x3C,0x00}, /* I */
    {0x0E,0x06,0x06,0x06,0x66,0x66,0x3C,0x00}, /* J */
    {0x66,0x6C,0x78,0x70,0x78,0x6C,0x66,0x00}, /* K */
    {0x60,0x60,0x60,0x60,0x60,0x60,0x7E,0x00}, /* L */
    {0x63,0x77,0x7F,0x6B,0x63,0x63,0x63,0x00}, /* M */
    {0x66,0x76,0x7E,0x7E,0x6E,0x66,0x66,0x00}, /* N */
    {0x3C,0x66,0x66,0x66,0x66,0x66,0x3C,0x00}, /* O */
    {0x7C,0x66,0x66,0x7C,0x60,0x60,0x60,0x00}, /* P */
    {0x3C,0x66,0x66,0x66,0x6E,0x3C,0x0E,0x00}, /* Q */
    {0x7C,0x66,0x66,0x7C,0x6C,0x66,0x66,0x00}, /* R */
    {0x3C,0x66,0x30,0x18,0x0C,0x66,0x3C,0x00}, /* S */
    {0x7E,0x18,0x18,0x18,0x18,0x18,0x18,0x00}, /* T */
    {0x66,0x66,0x66,0x66,0x66,0x66,0x3C,0x00}, /* U */
    {0x66,0x66,0x66,0x66,0x66,0x3C,0x18,0x00}, /* V */
    {0x63,0x63,0x63,0x6B,0x7F,0x77,0x63,0x00}, /* W */
    {0x66,0x66,0x3C,0x18,0x3C,0x66,0x66,0x00}, /* X */
    {0x66,0x66,0x66,0x3C,0x18,0x18,0x18,0x00}, /* Y */
    {0x7E,0x06,0x0C,0x18,0x30,0x60,0x7E,0x00}, /* Z */
    {0x3C,0x30,0x30,0x30,0x30,0x30,0x3C,0x00}, /* [ */
    {0x80,0xC0,0x60,0x30,0x18,0x0C,0x06,0x00}, /* \ */
    {0x3C,0x0C,0x0C,0x0C,0x0C,0x0C,0x3C,0x00}, /* ] */
    {0x18,0x3C,0x66,0x00,0x00,0x00,0x00,0x00}, /* ^ */
    {0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00}, /* _ */
    {0x30,0x18,0x0C,0x00,0x00,0x00,0x00,0x00}, /* ` */
    {0x00,0x00,0x3C,0x06,0x3E,0x66,0x3B,0x00}, /* a */
    {0x60,0x60,0x7C,0x66,0x66,0x66,0x7C,0x00}, /* b */
    {0x00,0x00,0x3C,0x66,0x60,0x66,0x3C,0x00}, /* c */
    {0x06,0x06,0x3E,0x66,0x66,0x66,0x3E,0x00}, /* d */
    {0x00,0x00,0x3C,0x66,0x7E,0x60,0x3C,0x00}, /* e */
    {0x1C,0x30,0x30,0x78,0x30,0x30,0x30,0x00}, /* f */
    {0x00,0x00,0x3B,0x66,0x66,0x3E,0x06,0x3C}, /* g */
    {0x60,0x60,0x7C,0x66,0x66,0x66,0x66,0x00}, /* h */
    {0x18,0x00,0x38,0x18,0x18,0x18,0x3C,0x00}, /* i */
    {0x06,0x00,0x0E,0x06,0x06,0x66,0x66,0x3C}, /* j */
    {0x60,0x60,0x66,0x6C,0x78,0x6C,0x66,0x00}, /* k */
    {0x38,0x18,0x18,0x18,0x18,0x18,0x3C,0x00}, /* l */
    {0x00,0x00,0x66,0x7F,0x7F,0x6B,0x63,0x00}, /* m */
    {0x00,0x00,0x7C,0x66,0x66,0x66,0x66,0x00}, /* n */
    {0x00,0x00,0x3C,0x66,0x66,0x66,0x3C,0x00}, /* o */
    {0x00,0x00,0x7C,0x66,0x66,0x7C,0x60,0x60}, /* p */
    {0x00,0x00,0x3E,0x66,0x66,0x3E,0x06,0x06}, /* q */
    {0x00,0x00,0x7C,0x66,0x60,0x60,0x60,0x00}, /* r */
    {0x00,0x00,0x3E,0x60,0x3C,0x06,0x7C,0x00}, /* s */
    {0x18,0x18,0x7E,0x18,0x18,0x18,0x0E,0x00}, /* t */
    {0x00,0x00,0x66,0x66,0x66,0x66,0x3B,0x00}, /* u */
    {0x00,0x00,0x66,0x66,0x66,0x3C,0x18,0x00}, /* v */
    {0x00,0x00,0x63,0x6B,0x7F,0x3E,0x36,0x00}, /* w */
    {0x00,0x00,0x66,0x3C,0x18,0x3C,0x66,0x00}, /* x */
    {0x00,0x00,0x66,0x66,0x66,0x3E,0x06,0x3C}, /* y */
    {0x00,0x00,0x7E,0x0C,0x18,0x30,0x7E,0x00}, /* z */
    {0x0E,0x18,0x18,0x70,0x18,0x18,0x0E,0x00}, /* { */
    {0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x00}, /* | */
    {0x70,0x18,0x18,0x0E,0x18,0x18,0x70,0x00}, /* } */
    {0x76,0xDC,0x00,0x00,0x00,0x00,0x00,0x00}  /* ~ */
};

#define MSG_STATS_READY 100

typedef enum prompt_mode {
    PROMPT_NONE = 0,
    PROMPT_OPEN,
    PROMPT_SAVE,
    PROMPT_FIND,
    PROMPT_REPLACE_FIND,
    PROMPT_REPLACE_WITH,
    PROMPT_GOTO,
    PROMPT_CONFIRM_QUIT,
} prompt_mode;

struct doc_stats {
    int words;
    int chars;
};

struct undo_snapshot {
    char lines[MAX_LINES][MAX_LINE_LEN];
    int line_count;
    int cursor_row;
    int cursor_col;
};

struct editor {
    struct yasl_display *display;
    struct yasl_surface *surface;

    /* File tracking */
    char file_path[512];
    bool has_file;
    bool is_modified;

    /* Text buffer */
    char lines[MAX_LINES][MAX_LINE_LEN];
    int line_count;

    /* Cursor & Selection */
    int cursor_row;
    int cursor_col;
    int sel_anchor_row;
    int sel_anchor_col;
    bool has_selection;
    bool mouse_dragging;

    /* Double/Triple click tracking */
    uint64_t last_click_time;
    struct yasl_vector2i last_click_pos;
    int click_count;

    /* Viewport & Layout */
    int scroll_y;
    int scroll_x;
    bool word_wrap;
    int zoom_offset; /* -1, 0, 1, 2 */
    bool caret_visible;

    /* Interactive mini-buffer prompt */
    prompt_mode prompt;
    char prompt_buf[256];
    int prompt_len;
    char search_query[256];
    char replace_query[256];

    /* Notification message in status bar */
    char status_msg[128];
    uint64_t status_msg_time;

    /* Undo & Redo stacks */
    struct undo_snapshot undo_stack[MAX_UNDO];
    int undo_count;
    struct undo_snapshot redo_stack[MAX_UNDO];
    int redo_count;

    /* Background stats from async worker */
    struct doc_stats stats;
    _Atomic bool worker_running;
    bool worker_started, worker_mutex_ready, worker_cond_ready;
    uint64_t worker_surface_id;
    bool worker_dirty;
    pthread_t worker_tid;
    pthread_mutex_t worker_mutex;
    pthread_cond_t worker_cond;
};

static void editor_set_status(struct editor *ed, const char *msg)
{
    snprintf(ed->status_msg, sizeof(ed->status_msg), "%s", msg);
    ed->status_msg_time = yasl_loop_now_ns();
}

static void editor_update_title(struct editor *ed)
{
    if (!ed->surface) return;
    const char *name = ed->has_file ? ed->file_path : "Untitled";
    const char *slash = strrchr(name, '/');
    if (slash) name = slash + 1;

    char title[540];
    snprintf(title, sizeof(title), "%s%s - YASL Notepad", ed->is_modified ? "*" : "", name);
    yasl_surface_set_title(ed->surface, title);
}

static void editor_save_undo(struct editor *ed)
{
    if (ed->undo_count >= MAX_UNDO) {
        memmove(&ed->undo_stack[0], &ed->undo_stack[1], sizeof(struct undo_snapshot) * (MAX_UNDO - 1));
        ed->undo_count = MAX_UNDO - 1;
    }
    struct undo_snapshot *s = &ed->undo_stack[ed->undo_count++];
    s->line_count = ed->line_count;
    s->cursor_row = ed->cursor_row;
    s->cursor_col = ed->cursor_col;
    for (int i = 0; i < ed->line_count; i++) {
        memcpy(s->lines[i], ed->lines[i], MAX_LINE_LEN);
    }
    ed->redo_count = 0; /* New edit clears redo stack */
}

static void editor_undo(struct editor *ed)
{
    if (ed->undo_count <= 0) {
        editor_set_status(ed, "Already at oldest change");
        return;
    }
    /* Push current state to redo */
    if (ed->redo_count < MAX_UNDO) {
        struct undo_snapshot *rs = &ed->redo_stack[ed->redo_count++];
        rs->line_count = ed->line_count;
        rs->cursor_row = ed->cursor_row;
        rs->cursor_col = ed->cursor_col;
        for (int i = 0; i < ed->line_count; i++) {
            memcpy(rs->lines[i], ed->lines[i], MAX_LINE_LEN);
        }
    }

    struct undo_snapshot *s = &ed->undo_stack[--ed->undo_count];
    ed->line_count = s->line_count;
    ed->cursor_row = s->cursor_row;
    ed->cursor_col = s->cursor_col;
    for (int i = 0; i < ed->line_count; i++) {
        memcpy(ed->lines[i], s->lines[i], MAX_LINE_LEN);
    }
    ed->has_selection = false;
    ed->is_modified = true;
    editor_update_title(ed);
    editor_set_status(ed, "Undo");
}

static void editor_redo(struct editor *ed)
{
    if (ed->redo_count <= 0) {
        editor_set_status(ed, "Already at newest change");
        return;
    }
    /* Push current state to undo */
    if (ed->undo_count < MAX_UNDO) {
        struct undo_snapshot *us = &ed->undo_stack[ed->undo_count++];
        us->line_count = ed->line_count;
        us->cursor_row = ed->cursor_row;
        us->cursor_col = ed->cursor_col;
        for (int i = 0; i < ed->line_count; i++) {
            memcpy(us->lines[i], ed->lines[i], MAX_LINE_LEN);
        }
    }

    struct undo_snapshot *s = &ed->redo_stack[--ed->redo_count];
    ed->line_count = s->line_count;
    ed->cursor_row = s->cursor_row;
    ed->cursor_col = s->cursor_col;
    for (int i = 0; i < ed->line_count; i++) {
        memcpy(ed->lines[i], s->lines[i], MAX_LINE_LEN);
    }
    ed->has_selection = false;
    ed->is_modified = true;
    editor_update_title(ed);
    editor_set_status(ed, "Redo");
}

static void editor_notify_worker(struct editor *ed)
{
    pthread_mutex_lock(&ed->worker_mutex);
    ed->worker_dirty = true;
    pthread_cond_signal(&ed->worker_cond);
    pthread_mutex_unlock(&ed->worker_mutex);
}

static void *worker_thread(void *arg)
{
    struct editor *ed = arg;
    while (ed->worker_running) {
        pthread_mutex_lock(&ed->worker_mutex);
        while (!ed->worker_dirty && ed->worker_running) {
            pthread_cond_wait(&ed->worker_cond, &ed->worker_mutex);
        }
        if (!ed->worker_running) {
            pthread_mutex_unlock(&ed->worker_mutex);
            break;
        }
        ed->worker_dirty = false;
        pthread_mutex_unlock(&ed->worker_mutex);

        usleep(30000);

        int word_count = 0;
        int char_count = 0;
        for (int i = 0; i < ed->line_count; i++) {
            const char *p = ed->lines[i];
            bool in_word = false;
            while (*p) {
                char_count++;
                if (isspace((unsigned char)*p)) {
                    in_word = false;
                } else if (!in_word) {
                    in_word = true;
                    word_count++;
                }
                p++;
            }
        }

        if (!ed->worker_running)
            break;

        struct doc_stats *s = malloc(sizeof(*s));
        if (s) {
            s->words = word_count;
            s->chars = char_count;
            if (!yasl_display_post(ed->display, &(struct yasl_message){
                    .target_id = ed->worker_surface_id, .code = MSG_STATS_READY,
                    .payload = s, .size = sizeof(*s), .release = free}))
                free(s);
        }
    }
    return NULL;
}

static uint64_t on_blink_timer(void *ud, yasl_timer_id id, uint64_t interval_ns)
{
    (void)id;
    struct editor *ed = ud;
    ed->caret_visible = !ed->caret_visible;
    yasl_surface_request_frame(ed->surface);
    return interval_ns;
}

/* File I/O */
static bool editor_open_file(struct editor *ed, const char *path)
{
    FILE *f = fopen(path, "r");
    if (!f) {
        char err[128];
        snprintf(err, sizeof(err), "Could not open: %s", path);
        editor_set_status(ed, err);
        return false;
    }

    ed->line_count = 0;
    char buf[MAX_LINE_LEN];
    while (fgets(buf, sizeof(buf), f) && ed->line_count < MAX_LINES) {
        size_t len = strlen(buf);
        while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) {
            buf[--len] = '\0';
        }
        snprintf(ed->lines[ed->line_count++], MAX_LINE_LEN, "%s", buf);
    }
    fclose(f);

    if (ed->line_count == 0) {
        ed->lines[0][0] = '\0';
        ed->line_count = 1;
    }

    snprintf(ed->file_path, sizeof(ed->file_path), "%s", path);
    ed->has_file = true;
    ed->is_modified = false;
    ed->cursor_row = 0;
    ed->cursor_col = 0;
    ed->scroll_y = 0;
    ed->scroll_x = 0;
    ed->has_selection = false;
    ed->undo_count = 0;
    ed->redo_count = 0;

    editor_update_title(ed);
    char msg[128];
    snprintf(msg, sizeof(msg), "Opened %s (%d lines)", path, ed->line_count);
    editor_set_status(ed, msg);
    editor_notify_worker(ed);
    return true;
}

static bool editor_save_file(struct editor *ed, const char *path)
{
    FILE *f = fopen(path, "w");
    if (!f) {
        char err[128];
        snprintf(err, sizeof(err), "Could not save: %s", path);
        editor_set_status(ed, err);
        return false;
    }

    for (int i = 0; i < ed->line_count; i++) {
        fprintf(f, "%s\n", ed->lines[i]);
    }
    fclose(f);

    snprintf(ed->file_path, sizeof(ed->file_path), "%s", path);
    ed->has_file = true;
    ed->is_modified = false;
    editor_update_title(ed);

    char msg[128];
    snprintf(msg, sizeof(msg), "Saved to %s", path);
    editor_set_status(ed, msg);
    return true;
}

static void editor_new_file(struct editor *ed)
{
    ed->lines[0][0] = '\0';
    ed->line_count = 1;
    ed->has_file = false;
    ed->file_path[0] = '\0';
    ed->is_modified = false;
    ed->cursor_row = 0;
    ed->cursor_col = 0;
    ed->scroll_y = 0;
    ed->scroll_x = 0;
    ed->has_selection = false;
    ed->undo_count = 0;
    ed->redo_count = 0;
    editor_update_title(ed);
    editor_set_status(ed, "New file created");
    editor_notify_worker(ed);
}

static void decode_uri_path(const char *uri, char *out, size_t max_out)
{
    if (strncmp(uri, "file://", 7) == 0) {
        uri += 7;
        if (strncmp(uri, "localhost/", 10) == 0) {
            uri += 9;
        }
    }
    size_t out_len = 0;
    while (*uri && *uri != '\r' && *uri != '\n' && out_len < max_out - 1) {
        if (*uri == '%' && isxdigit((unsigned char)uri[1]) && isxdigit((unsigned char)uri[2])) {
            char hex[3] = {uri[1], uri[2], '\0'};
            out[out_len++] = (char)strtol(hex, NULL, 16);
            uri += 3;
        } else {
            out[out_len++] = *uri++;
        }
    }
    out[out_len] = '\0';
}

/* Selection helper */
static void get_selection_bounds(const struct editor *ed, int *r0, int *c0, int *r1, int *c1)
{
    if (!ed->has_selection) {
        *r0 = *r1 = ed->cursor_row;
        *c0 = *c1 = ed->cursor_col;
        return;
    }
    if (ed->sel_anchor_row < ed->cursor_row ||
        (ed->sel_anchor_row == ed->cursor_row && ed->sel_anchor_col <= ed->cursor_col)) {
        *r0 = ed->sel_anchor_row; *c0 = ed->sel_anchor_col;
        *r1 = ed->cursor_row;     *c1 = ed->cursor_col;
    } else {
        *r0 = ed->cursor_row;     *c0 = ed->cursor_col;
        *r1 = ed->sel_anchor_row; *c1 = ed->sel_anchor_col;
    }
}

static bool is_char_selected(const struct editor *ed, int r, int c)
{
    if (!ed->has_selection) return false;
    int r0, c0, r1, c1;
    get_selection_bounds(ed, &r0, &c0, &r1, &c1);
    if (r < r0 || r > r1) return false;
    if (r == r0 && r == r1) return c >= c0 && c < c1;
    if (r == r0) return c >= c0;
    if (r == r1) return c < c1;
    return true;
}

static void editor_delete_selection(struct editor *ed)
{
    if (!ed->has_selection) return;
    editor_save_undo(ed);

    int r0, c0, r1, c1;
    get_selection_bounds(ed, &r0, &c0, &r1, &c1);

    if (r0 == r1) {
        char *line = ed->lines[r0];
        int len = (int)strlen(line);
        memmove(line + c0, line + c1, (size_t)(len - c1 + 1));
    } else {
        char *first = ed->lines[r0];
        char *last = ed->lines[r1];
        char temp[MAX_LINE_LEN];
        snprintf(temp, sizeof(temp), "%s", last + c1);
        snprintf(first + c0, MAX_LINE_LEN - c0, "%s", temp);

        int lines_deleted = r1 - r0;
        memmove(ed->lines[r0 + 1], ed->lines[r1 + 1],
                (size_t)(ed->line_count - r1 - 1) * MAX_LINE_LEN);
        ed->line_count -= lines_deleted;
    }

    ed->cursor_row = r0;
    ed->cursor_col = c0;
    ed->has_selection = false;
    ed->is_modified = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

/* Clipboard operations */
static void editor_copy(struct editor *ed)
{
    char *buf = malloc((size_t)MAX_LINES * MAX_LINE_LEN);
    if (!buf) return;
    buf[0] = '\0';

    if (ed->has_selection) {
        int r0, c0, r1, c1;
        get_selection_bounds(ed, &r0, &c0, &r1, &c1);
        if (r0 == r1) {
            int len = c1 - c0;
            if (len > 0) {
                strncpy(buf, ed->lines[r0] + c0, (size_t)len);
                buf[len] = '\0';
            }
        } else {
            strcat(buf, ed->lines[r0] + c0);
            strcat(buf, "\n");
            for (int r = r0 + 1; r < r1; r++) {
                strcat(buf, ed->lines[r]);
                strcat(buf, "\n");
            }
            strncat(buf, ed->lines[r1], (size_t)c1);
        }
    } else {
        snprintf(buf, (size_t)MAX_LINES * MAX_LINE_LEN, "%s\n", ed->lines[ed->cursor_row]);
    }

    if (!yasl_clipboard_set(ed->display, YASL_CLIPBOARD, buf))
        editor_set_status(ed, "Clipboard copy failed");
    free(buf);
    editor_set_status(ed, "Copied to clipboard");
}

static void editor_cut(struct editor *ed)
{
    editor_copy(ed);
    if (ed->has_selection) {
        editor_delete_selection(ed);
    } else {
        editor_save_undo(ed);
        if (ed->line_count > 1) {
            memmove(ed->lines[ed->cursor_row], ed->lines[ed->cursor_row + 1],
                    (size_t)(ed->line_count - ed->cursor_row - 1) * MAX_LINE_LEN);
            ed->line_count--;
            if (ed->cursor_row >= ed->line_count) ed->cursor_row = ed->line_count - 1;
            ed->cursor_col = 0;
            ed->is_modified = true;
            editor_update_title(ed);
        } else {
            ed->lines[0][0] = '\0';
            ed->cursor_col = 0;
        }
    }
}

/* Search & Replace */
static void editor_find_next(struct editor *ed, const char *query, bool forward)
{
    if (!query || !*query) return;
    int qlen = (int)strlen(query);
    snprintf(ed->search_query, sizeof(ed->search_query), "%s", query);

    int start_r = ed->cursor_row;
    int dir = forward ? 1 : -1;

    for (int step = 0; step < ed->line_count; step++) {
        int r = (start_r + step * dir + ed->line_count) % ed->line_count;
        const char *line = ed->lines[r];
        int len = (int)strlen(line);

        if (forward) {
            int start_c = (r == ed->cursor_row && step == 0) ? ed->cursor_col : 0;
            if (start_c < len) {
                const char *match = strstr(line + start_c, query);
                if (match) {
                    int c = (int)(match - line);
                    ed->cursor_row = r;
                    ed->cursor_col = c + qlen;
                    ed->sel_anchor_row = r;
                    ed->sel_anchor_col = c;
                    ed->has_selection = true;
                    editor_set_status(ed, "Found match");
                    return;
                }
            }
        } else {
            /* Backward search on line */
            int limit = (r == ed->cursor_row && step == 0) ? ed->cursor_col - qlen : len - qlen;
            for (int c = limit; c >= 0; c--) {
                if (strncmp(line + c, query, (size_t)qlen) == 0) {
                    ed->cursor_row = r;
                    ed->cursor_col = c + qlen;
                    ed->sel_anchor_row = r;
                    ed->sel_anchor_col = c;
                    ed->has_selection = true;
                    editor_set_status(ed, "Found match");
                    return;
                }
            }
        }
    }
    editor_set_status(ed, "Not found");
}

static void editor_replace_current(struct editor *ed, const char *with)
{
    if (!ed->has_selection) return;
    editor_delete_selection(ed);
    size_t wlen = strlen(with);
    for (size_t i = 0; i < wlen; i++) {
        char *line = ed->lines[ed->cursor_row];
        int len = (int)strlen(line);
        if (len < MAX_LINE_LEN - 2) {
            memmove(line + ed->cursor_col + 1, line + ed->cursor_col, (size_t)(len - ed->cursor_col + 1));
            line[ed->cursor_col++] = with[i];
        }
    }
    ed->is_modified = true;
    editor_update_title(ed);
    editor_set_status(ed, "Replaced match");
}

/* Word navigation */
static int find_word_prev(const char *line, int col)
{
    while (col > 0 && isspace((unsigned char)line[col - 1])) col--;
    while (col > 0 && !isspace((unsigned char)line[col - 1])) col--;
    return col;
}

static int find_word_next(const char *line, int col)
{
    int len = (int)strlen(line);
    while (col < len && !isspace((unsigned char)line[col])) col++;
    while (col < len && isspace((unsigned char)line[col])) col++;
    return col;
}

/* Drawing primitives */
static void fill_rect(uint32_t *pixels, int w, int h, int rx, int ry, int rw, int rh, uint32_t col)
{
    int x0 = rx < 0 ? 0 : rx;
    int y0 = ry < 0 ? 0 : ry;
    int x1 = rx + rw > w ? w : rx + rw;
    int y1 = ry + rh > h ? h : ry + rh;

    for (int y = y0; y < y1; y++) {
        uint32_t *row = pixels + (size_t)y * w;
        for (int x = x0; x < x1; x++) {
            row[x] = col;
        }
    }
}

static void draw_char(uint32_t *pixels, int w, int h, int px, int py, char c, uint32_t col, int scale)
{
    if (c < 32 || c > 126) c = ' ';
    const uint8_t *glyph = font8x8[c - 32];

    for (int y = 0; y < 8; y++) {
        uint8_t row = glyph[y];
        for (int x = 0; x < 8; x++) {
            if (row & (0x80 >> x)) {
                fill_rect(pixels, w, h, px + x * scale, py + y * scale, scale, scale, col);
            }
        }
    }
}

static void draw_string(uint32_t *pixels, int w, int h, int px, int py, const char *str, uint32_t col, int scale)
{
    while (*str) {
        draw_char(pixels, w, h, px, py, *str, col, scale);
        px += 8 * scale;
        str++;
    }
}

/* Editing operations */
static void insert_char_at_cursor(struct editor *ed, char c)
{
    char *line = ed->lines[ed->cursor_row];
    int len = (int)strlen(line);
    if (len >= MAX_LINE_LEN - 2) return;

    memmove(line + ed->cursor_col + 1, line + ed->cursor_col, (size_t)(len - ed->cursor_col + 1));
    line[ed->cursor_col] = c;
    ed->cursor_col++;
    ed->is_modified = true;
    ed->caret_visible = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

static void insert_text(struct editor *ed, const char *text, size_t len)
{
    if (ed->has_selection) {
        editor_delete_selection(ed);
    }
    editor_save_undo(ed);

    for (size_t i = 0; i < len; i++) {
        if (text[i] == '\n') {
            if (ed->line_count >= MAX_LINES - 1) break;
            char *curr = ed->lines[ed->cursor_row];
            char remainder[MAX_LINE_LEN];
            snprintf(remainder, sizeof(remainder), "%s", curr + ed->cursor_col);
            curr[ed->cursor_col] = '\0';
            memmove(ed->lines[ed->cursor_row + 2], ed->lines[ed->cursor_row + 1],
                    (size_t)(ed->line_count - ed->cursor_row - 1) * MAX_LINE_LEN);
            ed->line_count++;
            snprintf(ed->lines[ed->cursor_row + 1], MAX_LINE_LEN, "%s", remainder);
            ed->cursor_row++;
            ed->cursor_col = 0;
        } else if (text[i] == '\t') {
            /* Tab stop: align to next multiple of 4 */
            int spaces = 4 - (ed->cursor_col % 4);
            if (spaces == 0) spaces = 4;
            for (int k = 0; k < spaces; k++) insert_char_at_cursor(ed, ' ');
        } else if (text[i] >= 32 && text[i] <= 126) {
            insert_char_at_cursor(ed, text[i]);
        }
    }
    ed->is_modified = true;
    ed->caret_visible = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

static void handle_tab(struct editor *ed, bool unindent)
{
    editor_save_undo(ed);
    if (!unindent) {
        if (!ed->has_selection) {
            int spaces = 4 - (ed->cursor_col % 4);
            if (spaces == 0) spaces = 4;
            for (int k = 0; k < spaces; k++) insert_char_at_cursor(ed, ' ');
        } else {
            int r0, c0, r1, c1;
            get_selection_bounds(ed, &r0, &c0, &r1, &c1);
            for (int r = r0; r <= r1; r++) {
                char *line = ed->lines[r];
                if (strlen(line) + 4 < MAX_LINE_LEN) {
                    memmove(line + 4, line, strlen(line) + 1);
                    memcpy(line, "    ", 4);
                }
            }
            ed->cursor_col += 4;
            ed->sel_anchor_col += 4;
            ed->is_modified = true;
            editor_update_title(ed);
        }
    } else {
        int r0 = ed->cursor_row, r1 = ed->cursor_row;
        if (ed->has_selection) {
            int c0, c1;
            get_selection_bounds(ed, &r0, &c0, &r1, &c1);
        }
        for (int r = r0; r <= r1; r++) {
            char *line = ed->lines[r];
            int spaces = 0;
            while (spaces < 4 && line[spaces] == ' ') spaces++;
            if (spaces > 0) {
                memmove(line, line + spaces, strlen(line) - spaces + 1);
                if (r == ed->cursor_row && ed->cursor_col >= spaces) ed->cursor_col -= spaces;
                ed->is_modified = true;
                editor_update_title(ed);
            }
        }
    }
}

static void handle_backspace(struct editor *ed, bool ctrl)
{
    if (ed->has_selection) {
        editor_delete_selection(ed);
        return;
    }
    editor_save_undo(ed);
    char *line = ed->lines[ed->cursor_row];
    if (ctrl) {
        /* Delete previous word */
        int prev_c = find_word_prev(line, ed->cursor_col);
        int deleted = ed->cursor_col - prev_c;
        if (deleted > 0) {
            int len = (int)strlen(line);
            memmove(line + prev_c, line + ed->cursor_col, (size_t)(len - ed->cursor_col + 1));
            ed->cursor_col = prev_c;
        }
    } else {
        if (ed->cursor_col > 0) {
            int len = (int)strlen(line);
            memmove(line + ed->cursor_col - 1, line + ed->cursor_col, (size_t)(len - ed->cursor_col + 1));
            ed->cursor_col--;
        } else if (ed->cursor_row > 0) {
            char *prev = ed->lines[ed->cursor_row - 1];
            int prev_len = (int)strlen(prev);
            int curr_len = (int)strlen(line);
            if (prev_len + curr_len < MAX_LINE_LEN - 1) {
                strncat(prev, line, (size_t)(MAX_LINE_LEN - prev_len - 1));
                memmove(ed->lines[ed->cursor_row], ed->lines[ed->cursor_row + 1],
                        (size_t)(ed->line_count - ed->cursor_row - 1) * MAX_LINE_LEN);
                ed->line_count--;
                ed->cursor_row--;
                ed->cursor_col = prev_len;
            }
        }
    }
    ed->is_modified = true;
    ed->caret_visible = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

static void handle_delete(struct editor *ed, bool ctrl)
{
    if (ed->has_selection) {
        editor_delete_selection(ed);
        return;
    }
    editor_save_undo(ed);
    char *line = ed->lines[ed->cursor_row];
    int len = (int)strlen(line);
    if (ctrl) {
        /* Delete next word */
        int next_c = find_word_next(line, ed->cursor_col);
        int deleted = next_c - ed->cursor_col;
        if (deleted > 0) {
            memmove(line + ed->cursor_col, line + next_c, (size_t)(len - next_c + 1));
        }
    } else {
        if (ed->cursor_col < len) {
            memmove(line + ed->cursor_col, line + ed->cursor_col + 1, (size_t)(len - ed->cursor_col));
        } else if (ed->cursor_row < ed->line_count - 1) {
            char *next = ed->lines[ed->cursor_row + 1];
            int next_len = (int)strlen(next);
            if (len + next_len < MAX_LINE_LEN - 1) {
                strncat(line, next, (size_t)(MAX_LINE_LEN - len - 1));
                memmove(ed->lines[ed->cursor_row + 1], ed->lines[ed->cursor_row + 2],
                        (size_t)(ed->line_count - ed->cursor_row - 2) * MAX_LINE_LEN);
                ed->line_count--;
            }
        }
    }
    ed->is_modified = true;
    ed->caret_visible = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

static void handle_enter(struct editor *ed)
{
    if (ed->has_selection) {
        editor_delete_selection(ed);
    }
    editor_save_undo(ed);
    if (ed->line_count >= MAX_LINES - 1) return;

    char *curr = ed->lines[ed->cursor_row];
    char remainder[MAX_LINE_LEN];
    snprintf(remainder, sizeof(remainder), "%s", curr + ed->cursor_col);
    curr[ed->cursor_col] = '\0';
    memmove(ed->lines[ed->cursor_row + 2], ed->lines[ed->cursor_row + 1],
            (size_t)(ed->line_count - ed->cursor_row - 1) * MAX_LINE_LEN);
    ed->line_count++;
    snprintf(ed->lines[ed->cursor_row + 1], MAX_LINE_LEN, "%s", remainder);
    ed->cursor_row++;
    ed->cursor_col = 0;
    ed->is_modified = true;
    ed->caret_visible = true;
    editor_update_title(ed);
    editor_notify_worker(ed);
}

static void insert_date_time(struct editor *ed)
{
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    char buf[64];
    strftime(buf, sizeof(buf), "%I:%M %p %m/%d/%Y", tm);
    insert_text(ed, buf, strlen(buf));
}

/* Prompt actions */
static void prompt_execute(struct editor *ed)
{
    switch (ed->prompt) {
    case PROMPT_OPEN:
        editor_open_file(ed, ed->prompt_buf);
        ed->prompt = PROMPT_NONE;
        break;
    case PROMPT_SAVE:
        editor_save_file(ed, ed->prompt_buf);
        ed->prompt = PROMPT_NONE;
        break;
    case PROMPT_FIND:
        editor_find_next(ed, ed->prompt_buf, true);
        ed->prompt = PROMPT_NONE;
        break;
    case PROMPT_REPLACE_FIND:
        snprintf(ed->search_query, sizeof(ed->search_query), "%s", ed->prompt_buf);
        ed->prompt = PROMPT_REPLACE_WITH;
        ed->prompt_len = 0;
        ed->prompt_buf[0] = '\0';
        return;
    case PROMPT_REPLACE_WITH:
        editor_find_next(ed, ed->search_query, true);
        editor_replace_current(ed, ed->prompt_buf);
        ed->prompt = PROMPT_NONE;
        break;
    case PROMPT_GOTO: {
        int target = atoi(ed->prompt_buf);
        if (target > 0) {
            if (target > ed->line_count) target = ed->line_count;
            ed->cursor_row = target - 1;
            ed->cursor_col = 0;
            char msg[64];
            snprintf(msg, sizeof(msg), "Jumped to line %d", target);
            editor_set_status(ed, msg);
        }
        ed->prompt = PROMPT_NONE;
        break;
    }
    case PROMPT_CONFIRM_QUIT:
        if (tolower((unsigned char)ed->prompt_buf[0]) == 'y') {
            if (ed->has_file) {
                editor_save_file(ed, ed->file_path);
            }
        }
        ed->prompt = PROMPT_NONE;
        break;
    default:
        ed->prompt = PROMPT_NONE;
        break;
    }
}

/* YASL App callbacks */
static enum yasl_app_result on_init(void *ud, struct yasl_display *d)
{
    struct editor *ed = ud;
    ed->display = d;

    struct yasl_window_spec spec = {
        .title = "Untitled - YASL Notepad",
        .size_logical = {960, 640},
    };
    ed->surface = yasl_surface_create_toplevel(d, &spec);
    if (!ed->surface) return YASL_APP_ERROR;
    ed->worker_surface_id = yasl_surface_id(ed->surface);

    yasl_surface_set_pacing(ed->surface, YASL_PACING_ON_DEMAND);
    if (!yasl_surface_add_timer(ed->surface, YASL_MS_TO_NS(500), on_blink_timer, ed))
        return YASL_APP_ERROR;

    ed->worker_running = true;
    if (pthread_mutex_init(&ed->worker_mutex, NULL)) return YASL_APP_ERROR;
    ed->worker_mutex_ready = true;
    if (pthread_cond_init(&ed->worker_cond, NULL)) return YASL_APP_ERROR;
    ed->worker_cond_ready = true;
    if (pthread_create(&ed->worker_tid, NULL, worker_thread, ed)) return YASL_APP_ERROR;
    ed->worker_started = true;

    if (ed->has_file) {
        editor_open_file(ed, ed->file_path);
    } else {
        editor_update_title(ed);
    }

    editor_notify_worker(ed);
    yasl_surface_request_frame(ed->surface);
    return YASL_APP_CONTINUE;
}

static enum yasl_app_result on_event(void *ud, const struct yasl_event *ev)
{
    struct editor *ed = ud;

    switch (ev->type) {
    case YASL_EVENT_TEXT:
        if (ed->prompt != PROMPT_NONE) {
            for (size_t i = 0; i < ev->text.len && ed->prompt_len < (int)sizeof(ed->prompt_buf) - 1; i++) {
                if (ev->text.data[i] >= 32 && ev->text.data[i] <= 126) {
                    ed->prompt_buf[ed->prompt_len++] = ev->text.data[i];
                    ed->prompt_buf[ed->prompt_len] = '\0';
                }
            }
        } else {
            insert_text(ed, ev->text.data, ev->text.len);
        }
        yasl_surface_request_frame(ed->surface);
        break;

    case YASL_EVENT_PASTE:
        if (ev->paste.status != YASL_TRANSFER_OK) {
            editor_set_status(ed, ev->paste.status == YASL_TRANSFER_UNAVAILABLE
                ? "Clipboard has no text" : "Clipboard transfer failed");
            yasl_surface_request_frame(ed->surface);
            break;
        }
        if (ev->text.data && ev->text.len > 0) {
            insert_text(ed, ev->text.data, ev->text.len);
            yasl_surface_request_frame(ed->surface);
        }
        break;

    case YASL_EVENT_DROP:
        if (ev->text.data && ev->text.len > 0) {
            char path[512];
            decode_uri_path(ev->text.data, path, sizeof(path));
            if (path[0]) {
                editor_open_file(ed, path);
                yasl_surface_request_frame(ed->surface);
            }
        }
        break;

    case YASL_EVENT_KEY:
        if (ev->key.action == YASL_KEY_PRESS || ev->key.action == YASL_KEY_REPEAT) {
            bool ctrl = (ev->key.mods & (YASL_MOD_CTRL | YASL_MOD_SUPER)) != 0;
            bool shift = (ev->key.mods & YASL_MOD_SHIFT) != 0;

            /* Interactive Prompt Mode */
            if (ed->prompt != PROMPT_NONE) {
                if (ev->key.key == YASL_KEY_ESCAPE) {
                    ed->prompt = PROMPT_NONE;
                } else if (ev->key.key == YASL_KEY_ENTER) {
                    prompt_execute(ed);
                } else if (ev->key.key == YASL_KEY_BACKSPACE && ed->prompt_len > 0) {
                    ed->prompt_buf[--ed->prompt_len] = '\0';
                }
                yasl_surface_request_frame(ed->surface);
                break;
            }

            /* Function Keys */
            if (ev->key.key == YASL_KEY_F3) {
                editor_find_next(ed, ed->search_query, !shift);
                yasl_surface_request_frame(ed->surface);
                return YASL_APP_CONTINUE;
            } else if (ev->key.key == YASL_KEY_F5) {
                insert_date_time(ed);
                yasl_surface_request_frame(ed->surface);
                return YASL_APP_CONTINUE;
            }

            /* Shortcuts */
            if (ctrl) {
                switch (ev->key.key) {
                case YASL_KEY_Q:
                    return YASL_APP_QUIT;
                case YASL_KEY_N:
                    editor_new_file(ed);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_S:
                    if (shift || !ed->has_file) {
                        ed->prompt = PROMPT_SAVE;
                        ed->prompt_len = 0;
                        ed->prompt_buf[0] = '\0';
                    } else {
                        editor_save_file(ed, ed->file_path);
                    }
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_O:
                    ed->prompt = PROMPT_OPEN;
                    ed->prompt_len = 0;
                    ed->prompt_buf[0] = '\0';
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_F:
                    ed->prompt = PROMPT_FIND;
                    ed->prompt_len = 0;
                    ed->prompt_buf[0] = '\0';
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_H:
                    ed->prompt = PROMPT_REPLACE_FIND;
                    ed->prompt_len = 0;
                    ed->prompt_buf[0] = '\0';
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_G:
                    ed->prompt = PROMPT_GOTO;
                    ed->prompt_len = 0;
                    ed->prompt_buf[0] = '\0';
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_W:
                    ed->word_wrap = !ed->word_wrap;
                    editor_set_status(ed, ed->word_wrap ? "Word Wrap: ON" : "Word Wrap: OFF");
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_EQUAL: /* Zoom In */
                    if (ed->zoom_offset < 2) ed->zoom_offset++;
                    editor_set_status(ed, "Zoom In");
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_MINUS: /* Zoom Out */
                    if (ed->zoom_offset > -1) ed->zoom_offset--;
                    editor_set_status(ed, "Zoom Out");
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_0: /* Zoom Reset */
                    ed->zoom_offset = 0;
                    editor_set_status(ed, "Zoom Reset");
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_A:
                    ed->sel_anchor_row = 0;
                    ed->sel_anchor_col = 0;
                    ed->cursor_row = ed->line_count - 1;
                    ed->cursor_col = (int)strlen(ed->lines[ed->line_count - 1]);
                    ed->has_selection = true;
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_C:
                    editor_copy(ed);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_X:
                    editor_cut(ed);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_V:
                    if (!yasl_clipboard_request(ed->surface, YASL_CLIPBOARD))
                        editor_set_status(ed, "Clipboard paste failed");
                    return YASL_APP_CONTINUE;
                case YASL_KEY_Z:
                    if (shift) editor_redo(ed);
                    else editor_undo(ed);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_Y:
                    editor_redo(ed);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_BACKSPACE:
                    handle_backspace(ed, true);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                case YASL_KEY_DELETE:
                    handle_delete(ed, true);
                    yasl_surface_request_frame(ed->surface);
                    return YASL_APP_CONTINUE;
                default:
                    break;
                }
            }

            /* Tab key */
            if (ev->key.key == YASL_KEY_TAB) {
                handle_tab(ed, shift);
                yasl_surface_request_frame(ed->surface);
                break;
            }

            /* Navigation with optional Shift selection */
            bool was_selecting = ed->has_selection;
            if (shift && !was_selecting) {
                ed->sel_anchor_row = ed->cursor_row;
                ed->sel_anchor_col = ed->cursor_col;
                ed->has_selection = true;
            }

            switch (ev->key.key) {
            case YASL_KEY_BACKSPACE:
                handle_backspace(ed, false);
                break;
            case YASL_KEY_DELETE:
                handle_delete(ed, false);
                break;
            case YASL_KEY_ENTER:
                handle_enter(ed);
                break;
            case YASL_KEY_LEFT:
                if (ctrl) {
                    ed->cursor_col = find_word_prev(ed->lines[ed->cursor_row], ed->cursor_col);
                } else if (ed->cursor_col > 0) {
                    ed->cursor_col--;
                } else if (ed->cursor_row > 0) {
                    ed->cursor_row--;
                    ed->cursor_col = (int)strlen(ed->lines[ed->cursor_row]);
                }
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_RIGHT: {
                int len = (int)strlen(ed->lines[ed->cursor_row]);
                if (ctrl) {
                    ed->cursor_col = find_word_next(ed->lines[ed->cursor_row], ed->cursor_col);
                } else if (ed->cursor_col < len) {
                    ed->cursor_col++;
                } else if (ed->cursor_row < ed->line_count - 1) {
                    ed->cursor_row++;
                    ed->cursor_col = 0;
                }
                if (!shift) ed->has_selection = false;
                break;
            }
            case YASL_KEY_UP:
                if (ed->cursor_row > 0) {
                    ed->cursor_row--;
                    int len = (int)strlen(ed->lines[ed->cursor_row]);
                    if (ed->cursor_col > len) ed->cursor_col = len;
                }
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_DOWN:
                if (ed->cursor_row < ed->line_count - 1) {
                    ed->cursor_row++;
                    int len = (int)strlen(ed->lines[ed->cursor_row]);
                    if (ed->cursor_col > len) ed->cursor_col = len;
                }
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_HOME:
                ed->cursor_col = 0;
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_END:
                ed->cursor_col = (int)strlen(ed->lines[ed->cursor_row]);
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_PAGE_UP:
                ed->scroll_y -= 15;
                if (ed->scroll_y < 0) ed->scroll_y = 0;
                ed->cursor_row = ed->scroll_y;
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_PAGE_DOWN:
                ed->scroll_y += 15;
                if (ed->scroll_y >= ed->line_count) ed->scroll_y = ed->line_count - 1;
                ed->cursor_row = ed->scroll_y;
                if (!shift) ed->has_selection = false;
                break;
            case YASL_KEY_ESCAPE:
                ed->has_selection = false;
                break;
            default:
                break;
            }
            ed->caret_visible = true;
            yasl_surface_request_frame(ed->surface);
        }
        break;

    case YASL_EVENT_POINTER_DOWN: {
        if (ev->pointer.button == YASL_BUTTON_PRIMARY) {
            struct yasl_geometry geom = yasl_surface_geometry(ed->surface);
            int scale = (geom.scale_120 >= 240 ? 2 : 1) + ed->zoom_offset;
            if (scale < 1) scale = 1;
            int char_w = 8 * scale;
            int line_h = 16 * scale;
            int gutter_w = 48 * scale;
            int header_h = 24 * scale;

            int row = (ev->pointer.pos.y - header_h) / line_h + ed->scroll_y;
            int col = (ev->pointer.pos.x - gutter_w) / char_w + (ed->word_wrap ? 0 : ed->scroll_x);
            if (row < 0) row = 0;
            if (row >= ed->line_count) row = ed->line_count - 1;
            int len = (int)strlen(ed->lines[row]);
            if (col < 0) col = 0;
            if (col > len) col = len;

            uint64_t now = yasl_loop_now_ns();
            if (now - ed->last_click_time < 350000000ull &&
                abs(ev->pointer.pos.x - ed->last_click_pos.x) < 8 &&
                abs(ev->pointer.pos.y - ed->last_click_pos.y) < 8) {
                ed->click_count++;
            } else {
                ed->click_count = 1;
            }
            ed->last_click_time = now;
            ed->last_click_pos = ev->pointer.pos;

            if (ed->click_count == 2) {
                /* Double click: select word */
                const char *line = ed->lines[row];
                int c0 = col, c1 = col;
                while (c0 > 0 && !isspace((unsigned char)line[c0 - 1])) c0--;
                while (line[c1] && !isspace((unsigned char)line[c1])) c1++;
                ed->sel_anchor_row = row; ed->sel_anchor_col = c0;
                ed->cursor_row = row; ed->cursor_col = c1;
                ed->has_selection = true;
            } else if (ed->click_count >= 3) {
                /* Triple click: select whole line */
                ed->sel_anchor_row = row; ed->sel_anchor_col = 0;
                ed->cursor_row = row; ed->cursor_col = (int)strlen(ed->lines[row]);
                ed->has_selection = true;
            } else {
                ed->cursor_row = row;
                ed->cursor_col = col;
                ed->sel_anchor_row = row;
                ed->sel_anchor_col = col;
                ed->has_selection = false;
                ed->mouse_dragging = true;
            }
            ed->caret_visible = true;
            yasl_surface_request_frame(ed->surface);
        }
        break;
    }

    case YASL_EVENT_POINTER_UP:
        if (ev->pointer.button == YASL_BUTTON_PRIMARY) {
            ed->mouse_dragging = false;
        }
        break;

    case YASL_EVENT_POINTER_MOTION:
        if (ed->mouse_dragging) {
            struct yasl_geometry geom = yasl_surface_geometry(ed->surface);
            int scale = (geom.scale_120 >= 240 ? 2 : 1) + ed->zoom_offset;
            if (scale < 1) scale = 1;
            int char_w = 8 * scale;
            int line_h = 16 * scale;
            int gutter_w = 48 * scale;
            int header_h = 24 * scale;

            int row = (ev->pointer.pos.y - header_h) / line_h + ed->scroll_y;
            int col = (ev->pointer.pos.x - gutter_w) / char_w + (ed->word_wrap ? 0 : ed->scroll_x);
            if (row < 0) row = 0;
            if (row >= ed->line_count) row = ed->line_count - 1;
            int len = (int)strlen(ed->lines[row]);
            if (col < 0) col = 0;
            if (col > len) col = len;

            ed->cursor_row = row;
            ed->cursor_col = col;
            ed->has_selection = (ed->cursor_row != ed->sel_anchor_row || ed->cursor_col != ed->sel_anchor_col);
            yasl_surface_request_frame(ed->surface);
        }
        break;

    case YASL_EVENT_POINTER_SCROLL:
        if (ev->pointer.mods & (YASL_MOD_CTRL | YASL_MOD_SUPER)) {
            /* Ctrl + Wheel = Zoom */
            if (ev->pointer.scroll.y > 0 && ed->zoom_offset < 2) ed->zoom_offset++;
            else if (ev->pointer.scroll.y < 0 && ed->zoom_offset > -1) ed->zoom_offset--;
        } else if (ev->pointer.mods & YASL_MOD_SHIFT) {
            /* Shift + Wheel = Horizontal scroll */
            ed->scroll_x -= (int)(ev->pointer.scroll.y * 3.0);
            if (ed->scroll_x < 0) ed->scroll_x = 0;
        } else {
            /* Normal vertical scroll */
            ed->scroll_y -= (int)(ev->pointer.scroll.y * 3.0);
            if (ed->scroll_y < 0) ed->scroll_y = 0;
            if (ed->scroll_y >= ed->line_count) ed->scroll_y = ed->line_count - 1;
        }
        yasl_surface_request_frame(ed->surface);
        break;

    case YASL_EVENT_USER:
        if (ev->user.code == MSG_STATS_READY && ev->user.payload) {
            struct doc_stats *s = (struct doc_stats *)ev->user.payload;
            ed->stats = *s;
            yasl_surface_request_frame(ed->surface);
        }
        break;

    case YASL_EVENT_WINDOW_CLOSE:
        return YASL_APP_QUIT;

    default:
        break;
    }

    return YASL_APP_CONTINUE;
}

static void on_frame(void *ud, struct yasl_surface *s, struct yasl_frame *ctx)
{
    (void)s;
    struct editor *ed = ud;
    int w = ctx->target.size.x;
    int h = ctx->target.size.y;
    uint32_t *pix = ctx->target.pixels;
    if (!pix || w <= 0 || h <= 0) return;

    int scale = (ctx->scale_120 >= 240 ? 2 : 1) + ed->zoom_offset;
    if (scale < 1) scale = 1;
    int char_w = 8 * scale;
    int line_h = 16 * scale;
    int gutter_w = 48 * scale;
    int header_h = 24 * scale;
    int status_h = 24 * scale;

    /* Theme colors */
    uint32_t bg_main = 0xff1e1e2e;
    uint32_t bg_header = 0xff181825;
    uint32_t bg_gutter = 0xff181825;
    uint32_t bg_active_line = 0xff252538;
    uint32_t bg_selection = 0xff3b4261;
    uint32_t bg_status = 0xff11111b;
    uint32_t bg_prompt = 0xff2a2b3d;
    uint32_t text_fg = 0xffcdd6f4;
    uint32_t text_gutter = 0xff6c7086;
    uint32_t text_header = 0xff89b4fa;
    uint32_t text_status = 0xffa6adc8;
    uint32_t caret_col = 0xfff38ba8;
    uint32_t status_accent = 0xffa6e3a1;

    /* 1. Clear background */
    fill_rect(pix, w, h, 0, 0, w, h, bg_main);

    /* 2. Top Header Menu bar */
    fill_rect(pix, w, h, 0, 0, w, header_h, bg_header);
    char header_str[256];
    snprintf(header_str, sizeof(header_str),
             "^N New  ^O Open  ^S Save  ^F Find  ^H Repl  ^G Goto  ^Z Undo  F5 Time  ^W Wrap");
    draw_string(pix, w, h, 12 * scale, 6 * scale, header_str, text_header, scale);

    /* 3. Gutter background */
    fill_rect(pix, w, h, 0, header_h, gutter_w, h - header_h - status_h, bg_gutter);

    /* 4. Ensure cursor is in visible vertical and horizontal bounds */
    int visible_lines = (h - header_h - status_h) / line_h;
    if (ed->cursor_row < ed->scroll_y) {
        ed->scroll_y = ed->cursor_row;
    } else if (ed->cursor_row >= ed->scroll_y + visible_lines) {
        ed->scroll_y = ed->cursor_row - visible_lines + 1;
    }

    int visible_cols = (w - gutter_w - 16 * scale) / char_w;
    if (visible_cols < 1) visible_cols = 1;
    if (!ed->word_wrap) {
        if (ed->cursor_col < ed->scroll_x) {
            ed->scroll_x = ed->cursor_col;
        } else if (ed->cursor_col >= ed->scroll_x + visible_cols) {
            ed->scroll_x = ed->cursor_col - visible_cols + 1;
        }
    } else {
        ed->scroll_x = 0;
    }

    /* 5. Active line highlight */
    int active_line_y = header_h + (ed->cursor_row - ed->scroll_y) * line_h;
    if (active_line_y >= header_h && active_line_y < h - status_h) {
        fill_rect(pix, w, h, gutter_w, active_line_y, w - gutter_w, line_h, bg_active_line);
    }

    /* 6. Render lines, gutter, and selection */
    for (int i = 0; i < visible_lines; i++) {
        int line_idx = ed->scroll_y + i;
        if (line_idx >= ed->line_count) break;

        int y = header_h + i * line_h + 4 * scale;

        /* Line number */
        char num_buf[16];
        snprintf(num_buf, sizeof(num_buf), "%3d", line_idx + 1);
        draw_string(pix, w, h, 8 * scale, y, num_buf, text_gutter, scale);

        /* Text and selection highlighting */
        const char *line_text = ed->lines[line_idx];
        int text_x = gutter_w + 8 * scale;
        int col = ed->scroll_x;

        while (line_text[col] && col - ed->scroll_x < visible_cols + 1) {
            int char_x = text_x + (col - ed->scroll_x) * char_w;
            if (is_char_selected(ed, line_idx, col)) {
                fill_rect(pix, w, h, char_x, header_h + i * line_h, char_w, line_h, bg_selection);
            }
            draw_char(pix, w, h, char_x, y, line_text[col], text_fg, scale);
            col++;
        }
    }

    /* 7. Caret */
    if (ed->caret_visible && active_line_y >= header_h && active_line_y < h - status_h) {
        int caret_x = gutter_w + 8 * scale + (ed->cursor_col - ed->scroll_x) * char_w;
        if (caret_x >= gutter_w && caret_x < w) {
            int caret_y = active_line_y + 3 * scale;
            fill_rect(pix, w, h, caret_x, caret_y, 2 * scale, 10 * scale, caret_col);
        }
    }

    /* 8. Bottom Status bar or Mini-buffer Prompt */
    int status_y = h - status_h;
    if (ed->prompt != PROMPT_NONE) {
        fill_rect(pix, w, h, 0, status_y, w, status_h, bg_prompt);
        const char *prompt_label = ed->prompt == PROMPT_OPEN ? "Open File: " :
                                   ed->prompt == PROMPT_SAVE ? "Save As: " :
                                   ed->prompt == PROMPT_FIND ? "Find: " :
                                   ed->prompt == PROMPT_REPLACE_FIND ? "Replace (Find): " :
                                   ed->prompt == PROMPT_REPLACE_WITH ? "Replace with: " :
                                   ed->prompt == PROMPT_GOTO ? "Go to Line: " :
                                   "Save changes before exit? (y/n/esc): ";
        char prompt_disp[350];
        snprintf(prompt_disp, sizeof(prompt_disp), "%s%s_", prompt_label, ed->prompt_buf);
        draw_string(pix, w, h, 12 * scale, status_y + 6 * scale, prompt_disp, 0xfffab387, scale);
    } else {
        fill_rect(pix, w, h, 0, status_y, w, status_h, bg_status);

        char status_left[160];
        if (ed->status_msg[0] && (yasl_loop_now_ns() - ed->status_msg_time < 3000000000ull)) {
            snprintf(status_left, sizeof(status_left), "%s", ed->status_msg);
        } else {
            snprintf(status_left, sizeof(status_left), "Ln %d, Col %d   Lines: %d   Words: %d   Chars: %d",
                     ed->cursor_row + 1, ed->cursor_col + 1, ed->line_count, ed->stats.words, ed->stats.chars);
        }
        draw_string(pix, w, h, 12 * scale, status_y + 6 * scale, status_left, text_status, scale);

        char status_right[96];
        snprintf(status_right, sizeof(status_right), "%s  [Wrap:%s]  [0%% CPU]",
                 ed->is_modified ? "[Modified]" : "[Saved]",
                 ed->word_wrap ? "ON" : "OFF");
        int right_w = (int)strlen(status_right) * char_w;
        draw_string(pix, w, h, w - right_w - 12 * scale, status_y + 6 * scale, status_right,
                    ed->is_modified ? 0xfffab387 : status_accent, scale);
    }

    if (!yasl_frame_present(ctx, NULL, 0))
        yasl_app_exit(yasl_surface_display(s), YASL_APP_ERROR);
}

static void on_quit(void *ud, struct yasl_display *d)
{
    (void)d;
    struct editor *ed = ud;
    ed->worker_running = false;
    if (ed->worker_started) {
        pthread_mutex_lock(&ed->worker_mutex);
        pthread_cond_broadcast(&ed->worker_cond);
        pthread_mutex_unlock(&ed->worker_mutex);
        pthread_join(ed->worker_tid, NULL);
    }
    if (ed->worker_cond_ready) pthread_cond_destroy(&ed->worker_cond);
    if (ed->worker_mutex_ready) pthread_mutex_destroy(&ed->worker_mutex);
}

int main(int argc, char **argv)
{
    static struct editor ed;

    /* Check command-line file argument */
    if (argc > 1) {
        snprintf(ed.file_path, sizeof(ed.file_path), "%s", argv[1]);
        ed.has_file = true;
    } else {
        const char *initial_content[] = {
            "// Welcome to YASL Notepad!",
            "// A full-featured desktop text editor built on YASL Approach A.",
            "",
            "#include <stdio.h>",
            "",
            "int main(int argc, char **argv) {",
            "    printf(\"Hello, modern YASL!\\n\");",
            "    return 0;",
            "}",
            "",
            "Comprehensive Features & Shortcuts:",
            "  - New Document:       Ctrl+N",
            "  - Open File:          Ctrl+O  (or drag-and-drop file onto window)",
            "  - Save / Save As:     Ctrl+S / Ctrl+Shift+S",
            "  - Find / Find Next:   Ctrl+F / F3 (Shift+F3 for prev)",
            "  - Replace:            Ctrl+H",
            "  - Go to Line:         Ctrl+G",
            "  - Insert Date/Time:   F5",
            "  - Word Wrap Toggle:   Ctrl+W",
            "  - Zoom In/Out/Reset:  Ctrl+= / Ctrl+- / Ctrl+0 (or Ctrl+Wheel)",
            "  - Copy / Cut / Paste: Ctrl+C / Ctrl+X / Ctrl+V",
            "  - Undo / Redo:        Ctrl+Z / Ctrl+Y (Ctrl+Shift+Z)",
            "  - Select All:         Ctrl+A",
            "  - Mouse Selection:    Click+Drag, Double-click (word), Triple-click (line)",
            "  - Word Navigation:    Ctrl+Left / Ctrl+Right",
            "  - Word Deletion:      Ctrl+Backspace / Ctrl+Delete",
            "  - Tab / Shift+Tab:    Align 4-space tab stops / unindent",
            "",
            "Try editing, typing, or opening files!"
        };
        ed.line_count = sizeof(initial_content) / sizeof(initial_content[0]);
        for (int i = 0; i < ed.line_count; i++) {
            snprintf(ed.lines[i], MAX_LINE_LEN, "%s", initial_content[i]);
        }
    }

    struct yasl_app_desc desc = {
        .app_id = "org.yasl.notepad",
        .backend = YASL_BACKEND_AUTO,
        .userdata = &ed,
        .init = on_init,
        .event = on_event,
        .frame = on_frame,
        .quit = on_quit,
    };

    return yasl_run(&desc);
}