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
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
|
/* Copyright 2020 Jaakko Keränen <jaakko.keranen@iki.fi>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* TODO: Move DocumentView into a source file of its own. Consider cleaning up the network
request handling. */
#include "documentwidget.h"
#include "app.h"
#include "audio/player.h"
#include "banner.h"
#include "bookmarks.h"
#include "command.h"
#include "defs.h"
#include "gempub.h"
#include "gmcerts.h"
#include "gmdocument.h"
#include "gmrequest.h"
#include "gmutil.h"
#include "gopher.h"
#include "history.h"
#include "indicatorwidget.h"
#include "inputwidget.h"
#include "keys.h"
#include "labelwidget.h"
#include "linkinfo.h"
#include "media.h"
#include "paint.h"
#include "periodic.h"
#include "root.h"
#include "mediaui.h"
#include "scrollwidget.h"
#include "sitespec.h"
#include "touch.h"
#include "translation.h"
#include "uploadwidget.h"
#include "util.h"
#include "visbuf.h"
#include "visited.h"
#if defined (iPlatformAppleDesktop)
# include "macos.h"
#endif
#if defined (iPlatformAppleMobile)
# include "ios.h"
#endif
#include <the_Foundation/archive.h>
#include <the_Foundation/file.h>
#include <the_Foundation/fileinfo.h>
#include <the_Foundation/objectlist.h>
#include <the_Foundation/path.h>
#include <the_Foundation/ptrarray.h>
#include <the_Foundation/ptrset.h>
#include <the_Foundation/regexp.h>
#include <the_Foundation/stringarray.h>
#include <SDL_clipboard.h>
#include <SDL_timer.h>
#include <SDL_render.h>
#include <ctype.h>
#include <errno.h>
/*----------------------------------------------------------------------------------------------*/
iDeclareType(PersistentDocumentState)
iDeclareTypeConstruction(PersistentDocumentState)
iDeclareTypeSerialization(PersistentDocumentState)
enum iReloadInterval {
never_RelodPeriod,
minute_ReloadInterval,
fiveMinutes_ReloadInterval,
fifteenMinutes_ReloadInterval,
hour_ReloadInterval,
fourHours_ReloadInterval,
twicePerDay_ReloadInterval,
day_ReloadInterval,
max_ReloadInterval
};
static int seconds_ReloadInterval_(enum iReloadInterval d) {
static const int mins[] = { 0, 1, 5, 15, 60, 4 * 60, 12 * 60, 24 * 60 };
if (d < 0 || d >= max_ReloadInterval) return 0;
return mins[d] * 60;
}
static const char *label_ReloadInterval_(enum iReloadInterval d) {
switch (d) {
case never_RelodPeriod:
return cstr_Lang("reload.never");
case day_ReloadInterval:
return cstr_Lang("reload.onceperday");
case minute_ReloadInterval:
case fiveMinutes_ReloadInterval:
case fifteenMinutes_ReloadInterval:
return formatCStr_Lang("num.minutes.n", seconds_ReloadInterval_(d) / 60);
default:
return formatCStr_Lang("num.hours.n", seconds_ReloadInterval_(d) / 3600);
}
return "";
}
struct Impl_PersistentDocumentState {
iHistory *history;
iString * url;
enum iReloadInterval reloadInterval;
};
void init_PersistentDocumentState(iPersistentDocumentState *d) {
d->history = new_History();
d->url = new_String();
d->reloadInterval = 0;
}
void deinit_PersistentDocumentState(iPersistentDocumentState *d) {
delete_String(d->url);
delete_History(d->history);
}
void serialize_PersistentDocumentState(const iPersistentDocumentState *d, iStream *outs) {
serialize_String(d->url, outs);
uint16_t params = d->reloadInterval & 7;
writeU16_Stream(outs, params);
serialize_History(d->history, outs);
}
void deserialize_PersistentDocumentState(iPersistentDocumentState *d, iStream *ins) {
deserialize_String(d->url, ins);
if (indexOfCStr_String(d->url, " ptr:0x") != iInvalidPos) {
/* Oopsie, this should not have been written; invalid URL. */
clear_String(d->url);
}
const uint16_t params = readU16_Stream(ins);
d->reloadInterval = params & 7;
deserialize_History(d->history, ins);
}
iDefineTypeConstruction(PersistentDocumentState)
/*----------------------------------------------------------------------------------------------*/
iDeclareType(DrawBufs)
enum iDrawBufsFlag {
updateSideBuf_DrawBufsFlag = iBit(1),
updateTimestampBuf_DrawBufsFlag = iBit(2),
};
struct Impl_DrawBufs {
int flags;
SDL_Texture *sideIconBuf;
iTextBuf *timestampBuf;
uint32_t lastRenderTime;
};
static void init_DrawBufs(iDrawBufs *d) {
d->flags = 0;
d->sideIconBuf = NULL;
d->timestampBuf = NULL;
d->lastRenderTime = 0;
}
static void deinit_DrawBufs(iDrawBufs *d) {
delete_TextBuf(d->timestampBuf);
if (d->sideIconBuf) {
SDL_DestroyTexture(d->sideIconBuf);
}
}
iDefineTypeConstruction(DrawBufs)
/*----------------------------------------------------------------------------------------------*/
iDeclareType(VisBufMeta)
struct Impl_VisBufMeta {
iGmRunRange runsDrawn;
};
static void visBufInvalidated_(iVisBuf *d, size_t index) {
iVisBufMeta *meta = d->buffers[index].user;
iZap(meta->runsDrawn);
}
/*----------------------------------------------------------------------------------------------*/
enum iRequestState {
blank_RequestState,
fetching_RequestState,
receivedPartialResponse_RequestState,
ready_RequestState,
};
enum iDocumentWidgetFlag {
selecting_DocumentWidgetFlag = iBit(1),
noHoverWhileScrolling_DocumentWidgetFlag = iBit(2),
showLinkNumbers_DocumentWidgetFlag = iBit(3),
setHoverViaKeys_DocumentWidgetFlag = iBit(4),
newTabViaHomeKeys_DocumentWidgetFlag = iBit(5),
centerVertically_DocumentWidgetFlag = iBit(6),
selectWords_DocumentWidgetFlag = iBit(7),
selectLines_DocumentWidgetFlag = iBit(8),
pinchZoom_DocumentWidgetFlag = iBit(9),
movingSelectMarkStart_DocumentWidgetFlag = iBit(10),
movingSelectMarkEnd_DocumentWidgetFlag = iBit(11),
otherRootByDefault_DocumentWidgetFlag = iBit(12), /* links open to other root by default */
urlChanged_DocumentWidgetFlag = iBit(13),
drawDownloadCounter_DocumentWidgetFlag = iBit(14),
fromCache_DocumentWidgetFlag = iBit(15), /* don't write anything to cache */
animationPlaceholder_DocumentWidgetFlag = iBit(16), /* avoid slow operations */
invalidationPending_DocumentWidgetFlag = iBit(17), /* invalidate as soon as convenient */
leftWheelSwipe_DocumentWidgetFlag = iBit(18), /* swipe state flags are used on desktop */
rightWheelSwipe_DocumentWidgetFlag = iBit(19),
eitherWheelSwipe_DocumentWidgetFlag = leftWheelSwipe_DocumentWidgetFlag |
rightWheelSwipe_DocumentWidgetFlag,
};
enum iDocumentLinkOrdinalMode {
numbersAndAlphabet_DocumentLinkOrdinalMode,
homeRow_DocumentLinkOrdinalMode,
};
enum iWheelSwipeState {
none_WheelSwipeState,
direct_WheelSwipeState,
};
/* TODO: DocumentView is supposed to be useful on its own; move to a separate source file. */
iDeclareType(DocumentView)
struct Impl_DocumentView {
iDocumentWidget *owner; /* TODO: Convert to an abstract provider of metrics? */
iGmDocument * doc;
int pageMargin;
iSmoothScroll scrollY;
iAnim sideOpacity;
iAnim altTextOpacity;
iGmRunRange visibleRuns;
iPtrArray visibleLinks;
iPtrArray visiblePre;
iPtrArray visibleMedia; /* currently playing audio / ongoing downloads */
iPtrArray visibleWideRuns; /* scrollable blocks; TODO: merge into `visiblePre` */
const iGmRun * hoverPre; /* for clicking */
const iGmRun * hoverAltPre; /* for drawing alt text */
const iGmRun * hoverLink;
iArray wideRunOffsets;
iAnim animWideRunOffset;
uint16_t animWideRunId;
iGmRunRange animWideRunRange;
iDrawBufs * drawBufs; /* dynamic state for drawing */
iVisBuf * visBuf;
iVisBufMeta * visBufMeta;
iGmRunRange renderRuns;
iPtrSet * invalidRuns;
};
struct Impl_DocumentWidget {
iWidget widget;
int flags; /* internal behavior, see enum iDocumentWidgetFlag */
/* User interface: */
enum iDocumentLinkOrdinalMode ordinalMode;
size_t ordinalBase;
iRangecc selectMark;
iRangecc initialSelectMark; /* for word/line selection */
iRangecc foundMark;
const iGmRun * grabbedPlayer; /* currently adjusting volume in a player */
float grabbedStartVolume;
int mediaTimer;
const iGmRun * contextLink;
iClick click;
iInt2 contextPos; /* coordinates of latest right click */
int pinchZoomInitial;
int pinchZoomPosted;
float swipeSpeed; /* points/sec */
uint32_t lastSwipeTime;
int wheelSwipeDistance;
enum iWheelSwipeState wheelSwipeState;
iString pendingGotoHeading;
iString linePrecedingLink;
/* Network request: */
enum iRequestState state;
iGmRequest * request;
iGmLinkId requestLinkId; /* ID of the link that initiated the current request */
iAtomicInt isRequestUpdated; /* request has new content, need to parse it */
int certFlags;
iBlock * certFingerprint;
iDate certExpiry;
iString * certSubject;
int redirectCount;
iObjectList * media; /* inline media requests */
/* Document: */
iPersistentDocumentState mod;
iString * titleUser;
enum iGmStatusCode sourceStatus;
iString sourceHeader;
iString sourceMime;
iBlock sourceContent; /* original content as received, for saving; set on request finish */
iTime sourceTime;
iGempub * sourceGempub; /* NULL unless the page is Gempub content */
iBanner * banner;
float initNormScrollY;
/* Rendering: */
iDocumentView view;
iLinkInfo * linkInfo;
/* Widget structure: */
iScrollWidget *scroll;
iWidget * footerButtons;
iWidget * menu;
iWidget * playerMenu;
iWidget * copyMenu;
iTranslation * translation;
iWidget * phoneToolbar;
};
iDefineObjectConstruction(DocumentWidget)
/* Sorted by proximity to F and J. */
static const int homeRowKeys_[] = {
'f', 'd', 's', 'a',
'j', 'k', 'l',
'r', 'e', 'w', 'q',
'u', 'i', 'o', 'p',
'v', 'c', 'x', 'z',
'm', 'n',
'g', 'h',
'b',
't', 'y',
};
static int docEnum_ = 0;
static void animate_DocumentWidget_ (void *ticker);
static void animateMedia_DocumentWidget_ (iDocumentWidget *d);
static void updateSideIconBuf_DocumentWidget_ (const iDocumentWidget *d);
static void prerender_DocumentWidget_ (iAny *);
static void scrollBegan_DocumentWidget_ (iAnyObject *, int, uint32_t);
static void refreshWhileScrolling_DocumentWidget_ (iAny *);
static iBool requestMedia_DocumentWidget_ (iDocumentWidget *d, iGmLinkId linkId, iBool enableFilters);
/* TODO: The following methods are called from DocumentView, which goes the wrong way. */
static iRangecc selectMark_DocumentWidget_(const iDocumentWidget *d) {
/* Normalize so start < end. */
iRangecc norm = d->selectMark;
if (norm.start > norm.end) {
iSwap(const char *, norm.start, norm.end);
}
return norm;
}
static int phoneToolbarHeight_DocumentWidget_(const iDocumentWidget *d) {
if (!d->phoneToolbar) {
return 0;
}
const iWidget *w = constAs_Widget(d);
return bottom_Rect(rect_Root(w->root)) - top_Rect(boundsWithoutVisualOffset_Widget(d->phoneToolbar));
}
static int footerHeight_DocumentWidget_(const iDocumentWidget *d) {
int hgt = height_Widget(d->footerButtons);
if (isPortraitPhone_App()) {
hgt += phoneToolbarHeight_DocumentWidget_(d);
}
return hgt;
}
static iBool isHoverAllowed_DocumentWidget_(const iDocumentWidget *d) {
if (!isHover_Widget(d)) {
return iFalse;
}
if (!(d->state == ready_RequestState || d->state == receivedPartialResponse_RequestState)) {
return iFalse;
}
if (d->flags & (noHoverWhileScrolling_DocumentWidgetFlag |
drawDownloadCounter_DocumentWidgetFlag)) {
return iFalse;
}
if (d->flags & pinchZoom_DocumentWidgetFlag) {
return iFalse;
}
if (flags_Widget(constAs_Widget(d)) & touchDrag_WidgetFlag) {
return iFalse;
}
if (flags_Widget(constAs_Widget(d->scroll)) & pressed_WidgetFlag) {
return iFalse;
}
return iTrue;
}
static iMediaRequest *findMediaRequest_DocumentWidget_(const iDocumentWidget *d, iGmLinkId linkId) {
iConstForEach(ObjectList, i, d->media) {
const iMediaRequest *req = (const iMediaRequest *) i.object;
if (req->linkId == linkId) {
return iConstCast(iMediaRequest *, req);
}
}
return NULL;
}
static size_t linkOrdinalFromKey_DocumentWidget_(const iDocumentWidget *d, int key) {
size_t ord = iInvalidPos;
if (d->ordinalMode == numbersAndAlphabet_DocumentLinkOrdinalMode) {
if (key >= '1' && key <= '9') {
return key - '1';
}
if (key < 'a' || key > 'z') {
return iInvalidPos;
}
ord = key - 'a' + 9;
#if defined (iPlatformApple)
/* Skip keys that would conflict with default system shortcuts: hide, minimize, quit, close. */
if (key == 'h' || key == 'm' || key == 'q' || key == 'w') {
return iInvalidPos;
}
if (key > 'h') ord--;
if (key > 'm') ord--;
if (key > 'q') ord--;
if (key > 'w') ord--;
#endif
}
else {
iForIndices(i, homeRowKeys_) {
if (homeRowKeys_[i] == key) {
return i;
}
}
}
return ord;
}
static iChar linkOrdinalChar_DocumentWidget_(const iDocumentWidget *d, size_t ord) {
if (d->ordinalMode == numbersAndAlphabet_DocumentLinkOrdinalMode) {
if (ord < 9) {
return '1' + ord;
}
#if defined (iPlatformApple)
if (ord < 9 + 22) {
int key = 'a' + ord - 9;
if (key >= 'h') key++;
if (key >= 'm') key++;
if (key >= 'q') key++;
if (key >= 'w') key++;
return 'A' + key - 'a';
}
#else
if (ord < 9 + 26) {
return 'A' + ord - 9;
}
#endif
}
else {
if (ord < iElemCount(homeRowKeys_)) {
return 'A' + homeRowKeys_[ord] - 'a';
}
}
return 0;
}
/*----------------------------------------------------------------------------------------------*/
void init_DocumentView(iDocumentView *d) {
d->owner = NULL;
d->doc = new_GmDocument();
d->invalidRuns = new_PtrSet();
d->drawBufs = new_DrawBufs();
d->pageMargin = 5;
d->hoverPre = NULL;
d->hoverAltPre = NULL;
d->hoverLink = NULL;
d->animWideRunId = 0;
init_Anim(&d->animWideRunOffset, 0);
iZap(d->renderRuns);
iZap(d->visibleRuns);
d->visBuf = new_VisBuf(); {
d->visBufMeta = malloc(sizeof(iVisBufMeta) * numBuffers_VisBuf);
/* Additional metadata for each buffer. */
d->visBuf->bufferInvalidated = visBufInvalidated_;
for (size_t i = 0; i < numBuffers_VisBuf; i++) {
d->visBuf->buffers[i].user = d->visBufMeta + i;
}
}
init_Anim(&d->sideOpacity, 0);
init_Anim(&d->altTextOpacity, 0);
init_PtrArray(&d->visibleLinks);
init_PtrArray(&d->visiblePre);
init_PtrArray(&d->visibleWideRuns);
init_Array(&d->wideRunOffsets, sizeof(int));
init_PtrArray(&d->visibleMedia);
}
void deinit_DocumentView(iDocumentView *d) {
delete_DrawBufs(d->drawBufs);
delete_VisBuf(d->visBuf);
free(d->visBufMeta);
delete_PtrSet(d->invalidRuns);
deinit_Array(&d->wideRunOffsets);
deinit_PtrArray(&d->visibleMedia);
deinit_PtrArray(&d->visibleWideRuns);
deinit_PtrArray(&d->visiblePre);
deinit_PtrArray(&d->visibleLinks);
iReleasePtr(&d->doc);
}
static void setOwner_DocumentView_(iDocumentView *d, iDocumentWidget *doc) {
d->owner = doc;
init_SmoothScroll(&d->scrollY, as_Widget(doc), scrollBegan_DocumentWidget_);
if (deviceType_App() != desktop_AppDeviceType) {
d->scrollY.flags |= pullDownAction_SmoothScrollFlag; /* pull to refresh */
}
}
static void resetWideRuns_DocumentView_(iDocumentView *d) {
clear_Array(&d->wideRunOffsets);
d->animWideRunId = 0;
init_Anim(&d->animWideRunOffset, 0);
iZap(d->animWideRunRange);
}
static int documentWidth_DocumentView_(const iDocumentView *d) {
const iWidget *w = constAs_Widget(d->owner);
const iRect bounds = bounds_Widget(w);
const iPrefs * prefs = prefs_App();
const int minWidth = 50 * gap_UI; /* lines must fit a word at least */
const float adjust = iClamp((float) bounds.size.x / gap_UI / 11 - 12,
-1.0f, 10.0f); /* adapt to width */
//printf("%f\n", adjust); fflush(stdout);
return iMini(iMax(minWidth, bounds.size.x - gap_UI * (d->pageMargin + adjust) * 2),
fontSize_UI * //emRatio_Text(paragraph_FontId) * /* dependent on avg. glyph width */
prefs->lineWidth * prefs->zoomPercent / 100);
}
static int documentTopPad_DocumentView_(const iDocumentView *d) {
/* Amount of space between banner and top of the document. */
return isEmpty_Banner(d->owner->banner) ? 0 : lineHeight_Text(paragraph_FontId);
}
static int documentTopMargin_DocumentView_(const iDocumentView *d) {
return (isEmpty_Banner(d->owner->banner) ? d->pageMargin * gap_UI : height_Banner(d->owner->banner)) +
documentTopPad_DocumentView_(d);
}
static int pageHeight_DocumentView_(const iDocumentView *d) {
return height_Banner(d->owner->banner) + documentTopPad_DocumentView_(d) + size_GmDocument(d->doc).y;
}
static iRect documentBounds_DocumentView_(const iDocumentView *d) {
const iRect bounds = bounds_Widget(constAs_Widget(d->owner));
const int margin = gap_UI * d->pageMargin;
iRect rect;
rect.size.x = documentWidth_DocumentView_(d);
rect.pos.x = mid_Rect(bounds).x - rect.size.x / 2;
rect.pos.y = top_Rect(bounds) + margin;
rect.size.y = height_Rect(bounds) - margin;
iBool wasCentered = iFalse;
/* TODO: Further separation of View and Widget: configure header and footer heights
without involving the widget here. */
if (d->owner->flags & centerVertically_DocumentWidgetFlag) {
const int docSize = size_GmDocument(d->doc).y +
documentTopMargin_DocumentView_(d);
if (size_GmDocument(d->doc).y == 0) {
/* Document is empty; maybe just showing an error banner. */
rect.pos.y = top_Rect(bounds) + height_Rect(bounds) / 2 -
documentTopPad_DocumentView_(d) - height_Banner(d->owner->banner) / 2;
rect.size.y = 0;
wasCentered = iTrue;
}
else if (docSize < rect.size.y - footerHeight_DocumentWidget_(d->owner)) {
/* TODO: Phone toolbar? */
/* Center vertically when the document is short. */
const int relMidY = (height_Rect(bounds) - footerHeight_DocumentWidget_(d->owner)) / 2;
const int visHeight = size_GmDocument(d->doc).y;
const int offset = -height_Banner(d->owner->banner) - documentTopPad_DocumentView_(d);
rect.pos.y = top_Rect(bounds) + iMaxi(0, relMidY - visHeight / 2 + offset);
rect.size.y = size_GmDocument(d->doc).y + documentTopMargin_DocumentView_(d);
wasCentered = iTrue;
}
}
if (!wasCentered) {
/* The banner overtakes the top margin. */
if (!isEmpty_Banner(d->owner->banner)) {
rect.pos.y -= margin;
}
else {
rect.size.y -= margin;
}
}
return rect;
}
static int viewPos_DocumentView_(const iDocumentView *d) {
return height_Banner(d->owner->banner) + documentTopPad_DocumentView_(d) -
pos_SmoothScroll(&d->scrollY);
}
static iInt2 documentPos_DocumentView_(const iDocumentView *d, iInt2 pos) {
return addY_I2(sub_I2(pos, topLeft_Rect(documentBounds_DocumentView_(d))),
-viewPos_DocumentView_(d));
}
static iRangei visibleRange_DocumentView_(const iDocumentView *d) {
int top = pos_SmoothScroll(&d->scrollY) - height_Banner(d->owner->banner) -
documentTopPad_DocumentView_(d);
if (isEmpty_Banner(d->owner->banner)) {
/* Top padding is not collapsed. */
top -= d->pageMargin * gap_UI;
}
return (iRangei){ top, top + height_Rect(bounds_Widget(constAs_Widget(d->owner))) };
}
static void addVisible_DocumentView_(void *context, const iGmRun *run) {
iDocumentView *d = context;
if (~run->flags & decoration_GmRunFlag && !run->mediaId) {
if (!d->visibleRuns.start) {
d->visibleRuns.start = run;
}
d->visibleRuns.end = run;
}
if (preId_GmRun(run)) {
pushBack_PtrArray(&d->visiblePre, run);
if (run->flags & wide_GmRunFlag) {
pushBack_PtrArray(&d->visibleWideRuns, run);
}
}
/* Image runs are static so they're drawn as part of the content. */
if (isMedia_GmRun(run) && run->mediaType != image_MediaType) {
iAssert(run->mediaId);
pushBack_PtrArray(&d->visibleMedia, run);
}
if (run->linkId) {
pushBack_PtrArray(&d->visibleLinks, run);
}
}
static const iGmRun *lastVisibleLink_DocumentView_(const iDocumentView *d) {
iReverseConstForEach(PtrArray, i, &d->visibleLinks) {
const iGmRun *run = i.ptr;
if (run->flags & decoration_GmRunFlag && run->linkId) {
return run;
}
}
return NULL;
}
static float normScrollPos_DocumentView_(const iDocumentView *d) {
const int docSize = pageHeight_DocumentView_(d);
if (docSize) {
float pos = pos_SmoothScroll(&d->scrollY) / (float) docSize;
return iMax(pos, 0.0f);
}
return 0;
}
static int scrollMax_DocumentView_(const iDocumentView *d) {
const iWidget *w = constAs_Widget(d->owner);
int sm = pageHeight_DocumentView_(d) +
(isEmpty_Banner(d->owner->banner) ? 2 : 1) * d->pageMargin * gap_UI + /* top and bottom margins */
footerHeight_DocumentWidget_(d->owner) - height_Rect(bounds_Widget(w));
return sm;
}
static void invalidateLink_DocumentView_(iDocumentView *d, iGmLinkId id) {
/* A link has multiple runs associated with it. */
iConstForEach(PtrArray, i, &d->visibleLinks) {
const iGmRun *run = i.ptr;
if (run->linkId == id) {
insert_PtrSet(d->invalidRuns, run);
}
}
}
static void invalidateVisibleLinks_DocumentView_(iDocumentView *d) {
iConstForEach(PtrArray, i, &d->visibleLinks) {
const iGmRun *run = i.ptr;
if (run->linkId) {
insert_PtrSet(d->invalidRuns, run);
}
}
}
static int runOffset_DocumentView_(const iDocumentView *d, const iGmRun *run) {
if (preId_GmRun(run) && run->flags & wide_GmRunFlag) {
if (d->animWideRunId == preId_GmRun(run)) {
return -value_Anim(&d->animWideRunOffset);
}
const size_t numOffsets = size_Array(&d->wideRunOffsets);
const int *offsets = constData_Array(&d->wideRunOffsets);
if (preId_GmRun(run) <= numOffsets) {
return -offsets[preId_GmRun(run) - 1];
}
}
return 0;
}
static void invalidateWideRunsWithNonzeroOffset_DocumentView_(iDocumentView *d) {
iConstForEach(PtrArray, i, &d->visibleWideRuns) {
const iGmRun *run = i.ptr;
if (runOffset_DocumentView_(d, run)) {
insert_PtrSet(d->invalidRuns, run);
}
}
}
static void updateHover_DocumentView_(iDocumentView *d, iInt2 mouse) {
const iWidget *w = constAs_Widget(d->owner);
const iRect docBounds = documentBounds_DocumentView_(d);
const iGmRun * oldHoverLink = d->hoverLink;
d->hoverPre = NULL;
d->hoverLink = NULL;
const iInt2 hoverPos = addY_I2(sub_I2(mouse, topLeft_Rect(docBounds)),
-viewPos_DocumentView_(d));
if (isHoverAllowed_DocumentWidget_(d->owner)) {
iConstForEach(PtrArray, i, &d->visibleLinks) {
const iGmRun *run = i.ptr;
/* Click targets are slightly expanded so there are no gaps between links. */
if (contains_Rect(expanded_Rect(run->bounds, init1_I2(gap_Text / 2)), hoverPos)) {
d->hoverLink = run;
break;
}
}
}
if (d->hoverLink != oldHoverLink) {
if (oldHoverLink) {
invalidateLink_DocumentView_(d, oldHoverLink->linkId);
}
if (d->hoverLink) {
invalidateLink_DocumentView_(d, d->hoverLink->linkId);
}
if (update_LinkInfo(d->owner->linkInfo,
d->doc,
d->hoverLink ? d->hoverLink->linkId : 0,
width_Widget(w))) {
animate_DocumentWidget_(d->owner);
}
refresh_Widget(w);
}
/* Hovering over preformatted blocks. */
if (isHoverAllowed_DocumentWidget_(d->owner)) {
iConstForEach(PtrArray, j, &d->visiblePre) {
const iGmRun *run = j.ptr;
if (contains_Rect(run->bounds, hoverPos)) {
d->hoverPre = run;
d->hoverAltPre = run;
break;
}
}
}
if (!d->hoverPre) {
setValueSpeed_Anim(&d->altTextOpacity, 0.0f, 1.5f);
if (!isFinished_Anim(&d->altTextOpacity)) {
animate_DocumentWidget_(d->owner);
}
}
else if (d->hoverPre &&
preHasAltText_GmDocument(d->doc, preId_GmRun(d->hoverPre)) &&
~d->owner->flags & noHoverWhileScrolling_DocumentWidgetFlag) {
setValueSpeed_Anim(&d->altTextOpacity, 1.0f, 1.5f);
if (!isFinished_Anim(&d->altTextOpacity)) {
animate_DocumentWidget_(d->owner);
}
}
if (isHover_Widget(w) && !contains_Widget(constAs_Widget(d->owner->scroll), mouse)) {
setCursor_Window(get_Window(),
d->hoverLink || d->hoverPre ? SDL_SYSTEM_CURSOR_HAND
: SDL_SYSTEM_CURSOR_IBEAM);
if (d->hoverLink &&
linkFlags_GmDocument(d->doc, d->hoverLink->linkId) & permanent_GmLinkFlag) {
setCursor_Window(get_Window(), SDL_SYSTEM_CURSOR_ARROW); /* not dismissable */
}
}
}
static void updateSideOpacity_DocumentView_(iDocumentView *d, iBool isAnimated) {
float opacity = 0.0f;
if (!isEmpty_Banner(d->owner->banner) &&
height_Banner(d->owner->banner) < pos_SmoothScroll(&d->scrollY)) {
opacity = 1.0f;
}
setValue_Anim(&d->sideOpacity, opacity, isAnimated ? (opacity < 0.5f ? 100 : 200) : 0);
animate_DocumentWidget_(d->owner);
}
static iRangecc currentHeading_DocumentView_(const iDocumentView *d) {
iRangecc heading = iNullRange;
if (d->visibleRuns.start) {
iConstForEach(Array, i, headings_GmDocument(d->doc)) {
const iGmHeading *head = i.value;
if (head->level == 0) {
if (head->text.start <= d->visibleRuns.start->text.start) {
heading = head->text;
}
if (d->visibleRuns.end && head->text.start > d->visibleRuns.end->text.start) {
break;
}
}
}
}
return heading;
}
static int updateScrollMax_DocumentView_(iDocumentView *d) {
arrange_Widget(d->owner->footerButtons); /* scrollMax depends on footer height */
const int scrollMax = scrollMax_DocumentView_(d);
setMax_SmoothScroll(&d->scrollY, scrollMax);
return scrollMax;
}
static void updateVisible_DocumentView_(iDocumentView *d) {
/* TODO: The concerns of Widget and View are too tangled together here. */
iChangeFlags(d->owner->flags,
centerVertically_DocumentWidgetFlag,
prefs_App()->centerShortDocs || startsWithCase_String(d->owner->mod.url, "about:") ||
!isSuccess_GmStatusCode(d->owner->sourceStatus));
iScrollWidget *scrollBar = d->owner->scroll;
const iRangei visRange = visibleRange_DocumentView_(d);
// printf("visRange: %d...%d\n", visRange.start, visRange.end);
const iRect bounds = bounds_Widget(as_Widget(d->owner));
const int scrollMax = updateScrollMax_DocumentView_(d);
/* Reposition the footer buttons as appropriate. */
setRange_ScrollWidget(scrollBar, (iRangei){ 0, scrollMax });
const int docSize = pageHeight_DocumentView_(d) + footerHeight_DocumentWidget_(d->owner);
const float scrollPos = pos_SmoothScroll(&d->scrollY);
setThumb_ScrollWidget(scrollBar,
pos_SmoothScroll(&d->scrollY),
docSize > 0 ? height_Rect(bounds) * size_Range(&visRange) / docSize : 0);
if (d->owner->footerButtons) {
const iRect bounds = bounds_Widget(as_Widget(d->owner));
const iRect docBounds = documentBounds_DocumentView_(d);
const int hPad = (width_Rect(bounds) - iMin(120 * gap_UI, width_Rect(docBounds))) / 2;
const int vPad = 3 * gap_UI;
setPadding_Widget(d->owner->footerButtons, hPad, 0, hPad, vPad);
d->owner->footerButtons->rect.pos.y = height_Rect(bounds) -
footerHeight_DocumentWidget_(d->owner) +
(scrollMax > 0 ? scrollMax - scrollPos : 0);
}
clear_PtrArray(&d->visibleLinks);
clear_PtrArray(&d->visibleWideRuns);
clear_PtrArray(&d->visiblePre);
clear_PtrArray(&d->visibleMedia);
const iRangecc oldHeading = currentHeading_DocumentView_(d);
/* Scan for visible runs. */ {
iZap(d->visibleRuns);
render_GmDocument(d->doc, visRange, addVisible_DocumentView_, d);
}
const iRangecc newHeading = currentHeading_DocumentView_(d);
if (memcmp(&oldHeading, &newHeading, sizeof(oldHeading))) {
d->drawBufs->flags |= updateSideBuf_DrawBufsFlag;
}
updateHover_DocumentView_(d, mouseCoord_Window(get_Window(), 0));
updateSideOpacity_DocumentView_(d, iTrue);
animateMedia_DocumentWidget_(d->owner);
/* Remember scroll positions of recently visited pages. */ {
iRecentUrl *recent = mostRecentUrl_History(d->owner->mod.history);
if (recent && docSize && d->owner->state == ready_RequestState &&
equal_String(&recent->url, d->owner->mod.url)) {
recent->normScrollY = normScrollPos_DocumentView_(d);
}
}
/* After scrolling/resizing stops, begin pre-rendering the visbuf contents. */ {
removeTicker_App(prerender_DocumentWidget_, d->owner);
remove_Periodic(periodic_App(), d);
add_Periodic(periodic_App(), d->owner, "document.render");
}
}
static void swap_DocumentView_(iDocumentView *d, iDocumentView *swapBuffersWith) {
d->scrollY = swapBuffersWith->scrollY;
d->scrollY.widget = as_Widget(d->owner);
iSwap(iVisBuf *, d->visBuf, swapBuffersWith->visBuf);
iSwap(iVisBufMeta *, d->visBufMeta, swapBuffersWith->visBufMeta);
iSwap(iDrawBufs *, d->drawBufs, swapBuffersWith->drawBufs);
updateVisible_DocumentView_(d);
updateVisible_DocumentView_(swapBuffersWith);
}
static void updateTimestampBuf_DocumentView_(const iDocumentView *d) {
if (!isExposed_Window(get_Window())) {
return;
}
if (d->drawBufs->timestampBuf) {
delete_TextBuf(d->drawBufs->timestampBuf);
d->drawBufs->timestampBuf = NULL;
}
if (isValid_Time(&d->owner->sourceTime)) {
iString *fmt = timeFormatHourPreference_Lang("page.timestamp");
d->drawBufs->timestampBuf = newRange_TextBuf(
uiLabel_FontId,
white_ColorId,
range_String(collect_String(format_Time(&d->owner->sourceTime, cstr_String(fmt)))));
delete_String(fmt);
}
d->drawBufs->flags &= ~updateTimestampBuf_DrawBufsFlag;
}
static void invalidate_DocumentView_(iDocumentView *d) {
invalidate_VisBuf(d->visBuf);
clear_PtrSet(d->invalidRuns);
}
static void documentRunsInvalidated_DocumentView_(iDocumentView *d) {
d->hoverPre = NULL;
d->hoverAltPre = NULL;
d->hoverLink = NULL;
clear_PtrArray(&d->visibleMedia);
iZap(d->visibleRuns);
iZap(d->renderRuns);
}
static void resetScroll_DocumentView_(iDocumentView *d) {
reset_SmoothScroll(&d->scrollY);
init_Anim(&d->sideOpacity, 0);
init_Anim(&d->altTextOpacity, 0);
resetWideRuns_DocumentView_(d);
}
static void updateWidth_DocumentView_(iDocumentView *d) {
updateWidth_GmDocument(d->doc, documentWidth_DocumentView_(d), width_Widget(d->owner));
}
static void updateWidthAndRedoLayout_DocumentView_(iDocumentView *d) {
setWidth_GmDocument(d->doc, documentWidth_DocumentView_(d), width_Widget(d->owner));
}
static void clampScroll_DocumentView_(iDocumentView *d) {
move_SmoothScroll(&d->scrollY, 0);
}
static void immediateScroll_DocumentView_(iDocumentView *d, int offset) {
move_SmoothScroll(&d->scrollY, offset);
}
static void smoothScroll_DocumentView_(iDocumentView *d, int offset, int duration) {
moveSpan_SmoothScroll(&d->scrollY, offset, duration);
}
static void scrollTo_DocumentView_(iDocumentView *d, int documentY, iBool centered) {
if (!isEmpty_Banner(d->owner->banner)) {
documentY += height_Banner(d->owner->banner) + documentTopPad_DocumentView_(d);
}
else {
documentY += documentTopPad_DocumentView_(d) + d->pageMargin * gap_UI;
}
init_Anim(&d->scrollY.pos,
documentY - (centered ? documentBounds_DocumentView_(d).size.y / 2
: lineHeight_Text(paragraph_FontId)));
clampScroll_DocumentView_(d);
}
static void scrollToHeading_DocumentView_(iDocumentView *d, const char *heading) {
iConstForEach(Array, h, headings_GmDocument(d->doc)) {
const iGmHeading *head = h.value;
if (startsWithCase_Rangecc(head->text, heading)) {
postCommandf_Root(as_Widget(d->owner)->root, "document.goto loc:%p", head->text.start);
break;
}
}
}
static iBool scrollWideBlock_DocumentView_(iDocumentView *d, iInt2 mousePos, int delta,
int duration) {
if (delta == 0 || d->owner->flags & eitherWheelSwipe_DocumentWidgetFlag) {
return iFalse;
}
const iInt2 docPos = documentPos_DocumentView_(d, mousePos);
iConstForEach(PtrArray, i, &d->visibleWideRuns) {
const iGmRun *run = i.ptr;
if (docPos.y >= top_Rect(run->bounds) && docPos.y <= bottom_Rect(run->bounds)) {
/* We can scroll this run. First find out how much is allowed. */
const iGmRunRange range = findPreformattedRange_GmDocument(d->doc, run);
int maxWidth = 0;
for (const iGmRun *r = range.start; r != range.end; r++) {
maxWidth = iMax(maxWidth, width_Rect(r->visBounds));
}
const int maxOffset = maxWidth - documentWidth_DocumentView_(d) + d->pageMargin * gap_UI;
if (size_Array(&d->wideRunOffsets) <= preId_GmRun(run)) {
resize_Array(&d->wideRunOffsets, preId_GmRun(run) + 1);
}
int *offset = at_Array(&d->wideRunOffsets, preId_GmRun(run) - 1);
const int oldOffset = *offset;
*offset = iClamp(*offset + delta, 0, maxOffset);
/* Make sure the whole block gets redraw. */
if (oldOffset != *offset) {
for (const iGmRun *r = range.start; r != range.end; r++) {
insert_PtrSet(d->invalidRuns, r);
}
refresh_Widget(d->owner);
d->owner->selectMark = iNullRange;
d->owner->foundMark = iNullRange;
}
if (duration) {
if (d->animWideRunId != preId_GmRun(run) || isFinished_Anim(&d->animWideRunOffset)) {
d->animWideRunId = preId_GmRun(run);
init_Anim(&d->animWideRunOffset, oldOffset);
}
setValueEased_Anim(&d->animWideRunOffset, *offset, duration);
d->animWideRunRange = range;
addTicker_App(refreshWhileScrolling_DocumentWidget_, d->owner);
}
else {
d->animWideRunId = 0;
init_Anim(&d->animWideRunOffset, 0);
}
return iTrue;
}
}
return iFalse;
}
static iRangecc sourceLoc_DocumentView_(const iDocumentView *d, iInt2 pos) {
return findLoc_GmDocument(d->doc, documentPos_DocumentView_(d, pos));
}
iDeclareType(MiddleRunParams)
struct Impl_MiddleRunParams {
int midY;
const iGmRun *closest;
int distance;
};
static void find_MiddleRunParams_(void *params, const iGmRun *run) {
iMiddleRunParams *d = params;
if (isEmpty_Rect(run->bounds)) {
return;
}
const int distance = iAbs(mid_Rect(run->bounds).y - d->midY);
if (!d->closest || distance < d->distance) {
d->closest = run;
d->distance = distance;
}
}
static const iGmRun *middleRun_DocumentView_(const iDocumentView *d) {
iRangei visRange = visibleRange_DocumentView_(d);
iMiddleRunParams params = { (visRange.start + visRange.end) / 2, NULL, 0 };
render_GmDocument(d->doc, visRange, find_MiddleRunParams_, ¶ms);
return params.closest;
}
static void allocVisBuffer_DocumentView_(const iDocumentView *d) {
const iWidget *w = constAs_Widget(d->owner);
const iBool isVisible = isVisible_Widget(w);
const iInt2 size = bounds_Widget(w).size;
if (isVisible) {
alloc_VisBuf(d->visBuf, size, 1);
}
else {
dealloc_VisBuf(d->visBuf);
}
}
static size_t visibleLinkOrdinal_DocumentView_(const iDocumentView *d, iGmLinkId linkId) {
size_t ord = 0;
const iRangei visRange = visibleRange_DocumentView_(d);
iConstForEach(PtrArray, i, &d->visibleLinks) {
const iGmRun *run = i.ptr;
if (top_Rect(run->visBounds) >= visRange.start + gap_UI * d->pageMargin * 4 / 5) {
if (run->flags & decoration_GmRunFlag && run->linkId) {
if (run->linkId == linkId) return ord;
ord++;
}
}
}
return iInvalidPos;
}
static void documentRunsInvalidated_DocumentWidget_(iDocumentWidget *d) {
d->foundMark = iNullRange;
d->selectMark = iNullRange;
d->contextLink = NULL;
documentRunsInvalidated_DocumentView_(&d->view);
}
static iBool updateDocumentWidthRetainingScrollPosition_DocumentView_(iDocumentView *d,
iBool keepCenter) {
const int newWidth = documentWidth_DocumentView_(d);
if (newWidth == size_GmDocument(d->doc).x && !keepCenter /* not a font change */) {
return iFalse;
}
/* Font changes (i.e., zooming) will keep the view centered, otherwise keep the top
of the visible area fixed. */
const iGmRun *run = keepCenter ? middleRun_DocumentView_(d) : d->visibleRuns.start;
const char * runLoc = (run ? run->text.start : NULL);
int voffset = 0;
if (!keepCenter && run) {
/* Keep the first visible run visible at the same position. */
/* TODO: First *fully* visible run? */
voffset = visibleRange_DocumentView_(d).start - top_Rect(run->visBounds);
}
setWidth_GmDocument(d->doc, newWidth, width_Widget(d->owner));
setWidth_Banner(d->owner->banner, newWidth);
documentRunsInvalidated_DocumentWidget_(d->owner);
if (runLoc && !keepCenter) {
run = findRunAtLoc_GmDocument(d->doc, runLoc);
if (run) {
scrollTo_DocumentView_(
d, top_Rect(run->visBounds) + lineHeight_Text(paragraph_FontId) + voffset, iFalse);
}
}
else if (runLoc && keepCenter) {
run = findRunAtLoc_GmDocument(d->doc, runLoc);
if (run) {
scrollTo_DocumentView_(d, mid_Rect(run->bounds).y, iTrue);
}
}
return iTrue;
}
static iRect runRect_DocumentView_(const iDocumentView *d, const iGmRun *run) {
const iRect docBounds = documentBounds_DocumentView_(d);
return moved_Rect(run->bounds, addY_I2(topLeft_Rect(docBounds), viewPos_DocumentView_(d)));
}
iDeclareType(DrawContext)
struct Impl_DrawContext {
const iDocumentView *view;
iRect widgetBounds;
iRect docBounds;
iRangei vis;
iInt2 viewPos; /* document area origin */
iPaint paint;
iBool inSelectMark;
iBool inFoundMark;
iBool showLinkNumbers;
iRect firstMarkRect;
iRect lastMarkRect;
iGmRunRange runsDrawn;
};
static void fillRange_DrawContext_(iDrawContext *d, const iGmRun *run, enum iColorId color,
iRangecc mark, iBool *isInside) {
if (mark.start > mark.end) {
/* Selection may be done in either direction. */
iSwap(const char *, mark.start, mark.end);
}
if (*isInside || (contains_Range(&run->text, mark.start) ||
contains_Range(&mark, run->text.start))) {
int x = 0;
if (!*isInside) {
x = measureRange_Text(run->font,
(iRangecc){ run->text.start, iMax(run->text.start, mark.start) })
.advance.x;
}
int w = width_Rect(run->visBounds) - x;
if (contains_Range(&run->text, mark.end) || mark.end < run->text.start) {
iRangecc mk = !*isInside ? mark
: (iRangecc){ run->text.start, iMax(run->text.start, mark.end) };
mk.start = iMax(mk.start, run->text.start);
w = measureRange_Text(run->font, mk).advance.x;
*isInside = iFalse;
}
else {
*isInside = iTrue; /* at least until the next run */
}
if (w > width_Rect(run->visBounds) - x) {
w = width_Rect(run->visBounds) - x;
}
if (~run->flags & decoration_GmRunFlag) {
const iInt2 visPos =
add_I2(run->bounds.pos, addY_I2(d->viewPos, viewPos_DocumentView_(d->view)));
const iRect rangeRect = { addX_I2(visPos, x), init_I2(w, height_Rect(run->bounds)) };
if (rangeRect.size.x) {
fillRect_Paint(&d->paint, rangeRect, color);
/* Keep track of the first and last marked rects. */
if (d->firstMarkRect.size.x == 0) {
d->firstMarkRect = rangeRect;
}
d->lastMarkRect = rangeRect;
}
}
}
/* Link URLs are not part of the visible document, so they are ignored above. Handle
these ranges as a special case. */
if (run->linkId && run->flags & decoration_GmRunFlag) {
const iRangecc url = linkUrlRange_GmDocument(d->view->doc, run->linkId);
if (contains_Range(&url, mark.start) &&
(contains_Range(&url, mark.end) || url.end == mark.end)) {
fillRect_Paint(
&d->paint,
moved_Rect(run->visBounds, addY_I2(d->viewPos, viewPos_DocumentView_(d->view))),
color);
}
}
}
static void drawMark_DrawContext_(void *context, const iGmRun *run) {
iDrawContext *d = context;
if (!isMedia_GmRun(run)) {
fillRange_DrawContext_(d, run, uiMatching_ColorId, d->view->owner->foundMark, &d->inFoundMark);
fillRange_DrawContext_(d, run, uiMarked_ColorId, d->view->owner->selectMark, &d->inSelectMark);
}
}
static void drawRun_DrawContext_(void *context, const iGmRun *run) {
iDrawContext *d = context;
const iInt2 origin = d->viewPos;
/* Keep track of the drawn visible runs. */ {
if (!d->runsDrawn.start || run < d->runsDrawn.start) {
d->runsDrawn.start = run;
}
if (!d->runsDrawn.end || run > d->runsDrawn.end) {
d->runsDrawn.end = run;
}
}
if (run->mediaType == image_MediaType) {
SDL_Texture *tex = imageTexture_Media(media_GmDocument(d->view->doc), mediaId_GmRun(run));
const iRect dst = moved_Rect(run->visBounds, origin);
if (tex) {
fillRect_Paint(&d->paint, dst, tmBackground_ColorId); /* in case the image has alpha */
SDL_RenderCopy(d->paint.dst->render, tex, NULL,
&(SDL_Rect){ dst.pos.x, dst.pos.y, dst.size.x, dst.size.y });
}
else {
drawRect_Paint(&d->paint, dst, tmQuoteIcon_ColorId);
drawCentered_Text(uiLabel_FontId,
dst,
iFalse,
tmQuote_ColorId,
explosion_Icon " Error Loading Image");
}
return;
}
else if (isMedia_GmRun(run)) {
/* Media UIs are drawn afterwards as a dynamic overlay. */
return;
}
enum iColorId fg = run->color;
const iGmDocument *doc = d->view->doc;
const int linkFlags = linkFlags_GmDocument(doc, run->linkId);
/* Hover state of a link. */
const iBool isPartOfHover = (run->linkId && d->view->hoverLink &&
run->linkId == d->view->hoverLink->linkId);
iBool isHover = (isPartOfHover && ~run->flags & decoration_GmRunFlag);
/* Visible (scrolled) position of the run. */
const iInt2 visPos = addX_I2(add_I2(run->visBounds.pos, origin),
/* Preformatted runs can be scrolled. */
runOffset_DocumentView_(d->view, run));
const iRect visRect = { visPos, run->visBounds.size };
/* Fill the background. */ {
#if 0
iBool isInlineImageCaption = run->linkId && linkFlags & content_GmLinkFlag &&
~linkFlags & permanent_GmLinkFlag;
if (run->flags & decoration_GmRunFlag && ~run->flags & startOfLine_GmRunFlag) {
/* This is the metadata. */
isInlineImageCaption = iFalse;
}
#endif
iBool isMobileHover = deviceType_App() != desktop_AppDeviceType &&
(isPartOfHover || contains_PtrSet(d->view->invalidRuns, run)) &&
(~run->flags & decoration_GmRunFlag || run->flags & startOfLine_GmRunFlag
/* highlight link icon but not image captions */);
/* While this is consistent, it's a bit excessive to indicate that an inlined image
is open: the image itself is the indication. */
const iBool isInlineImageCaption = iFalse;
if (run->linkId && (linkFlags & isOpen_GmLinkFlag || isInlineImageCaption || isMobileHover)) {
/* Open links get a highlighted background. */
int bg = tmBackgroundOpenLink_ColorId;
if (isMobileHover && !isPartOfHover) {
bg = tmBackground_ColorId; /* hover ended and was invalidated */
}
// const int frame = tmFrameOpenLink_ColorId;
const int pad = gap_Text;
iRect wideRect = { init_I2(origin.x - pad, visPos.y),
init_I2(d->docBounds.size.x + 2 * pad,
height_Rect(run->visBounds)) };
adjustEdges_Rect(&wideRect,
run->flags & startOfLine_GmRunFlag ? -pad * 3 / 4 : 0, 0,
run->flags & endOfLine_GmRunFlag ? pad * 3 / 4 : 0, 0);
/* The first line is composed of two runs that may be drawn in either order, so
only draw half of the background. */
if (run->flags & decoration_GmRunFlag) {
wideRect.size.x = right_Rect(visRect) - left_Rect(wideRect);
}
else if (run->flags & startOfLine_GmRunFlag) {
wideRect.size.x = right_Rect(wideRect) - left_Rect(visRect);
wideRect.pos.x = left_Rect(visRect);
}
fillRect_Paint(&d->paint, wideRect, bg);
}
else {
/* Normal background for other runs. There are cases when runs get drawn multiple times,
e.g., at the buffer boundary, and there are slightly overlapping characters in
monospace blocks. Clearing the background here ensures a cleaner visual appearance
since only one glyph is visible at any given point. */
fillRect_Paint(&d->paint, visRect, tmBackground_ColorId);
}
}
if (run->linkId) {
if (run->flags & decoration_GmRunFlag && run->flags & startOfLine_GmRunFlag) {
/* Link icon. */
if (linkFlags & content_GmLinkFlag) {
fg = linkColor_GmDocument(doc, run->linkId, textHover_GmLinkPart);
}
}
else if (~run->flags & decoration_GmRunFlag) {
fg = linkColor_GmDocument(doc, run->linkId, isHover ? textHover_GmLinkPart : text_GmLinkPart);
if (linkFlags & content_GmLinkFlag) {
fg = linkColor_GmDocument(doc, run->linkId, textHover_GmLinkPart); /* link is inactive */
}
}
}
if (run->flags & altText_GmRunFlag) {
const iInt2 margin = preRunMargin_GmDocument(doc, preId_GmRun(run));
fillRect_Paint(&d->paint, (iRect){ visPos, run->visBounds.size }, tmBackgroundAltText_ColorId);
drawRect_Paint(&d->paint, (iRect){ visPos, run->visBounds.size }, tmFrameAltText_ColorId);
drawWrapRange_Text(run->font,
add_I2(visPos, margin),
run->visBounds.size.x - 2 * margin.x,
run->color,
run->text);
}
else {
if (d->showLinkNumbers && run->linkId && run->flags & decoration_GmRunFlag) {
const size_t ord = visibleLinkOrdinal_DocumentView_(d->view, run->linkId);
if (ord >= d->view->owner->ordinalBase) {
const iChar ordChar =
linkOrdinalChar_DocumentWidget_(d->view->owner, ord - d->view->owner->ordinalBase);
if (ordChar) {
const char *circle = "\u25ef"; /* Large Circle */
const int circleFont = FONT_ID(default_FontId, regular_FontStyle, contentRegular_FontSize);
iRect nbArea = { init_I2(d->viewPos.x - gap_UI / 3, visPos.y),
init_I2(3.95f * gap_Text, 1.0f * lineHeight_Text(circleFont)) };
drawRange_Text(
circleFont, topLeft_Rect(nbArea), tmQuote_ColorId, range_CStr(circle));
iRect circleArea = visualBounds_Text(circleFont, range_CStr(circle));
addv_I2(&circleArea.pos, topLeft_Rect(nbArea));
drawCentered_Text(FONT_ID(default_FontId, regular_FontStyle, contentSmall_FontSize),
circleArea,
iTrue,
tmQuote_ColorId,
"%lc",
(int) ordChar);
goto runDrawn;
}
}
}
if (run->flags & quoteBorder_GmRunFlag) {
drawVLine_Paint(&d->paint,
addX_I2(visPos,
!run->isRTL
? -gap_Text * 5 / 2
: (width_Rect(run->visBounds) + gap_Text * 5 / 2)),
height_Rect(run->visBounds),
tmQuoteIcon_ColorId);
}
/* Base attributes. */ {
int f, c;
runBaseAttributes_GmDocument(doc, run, &f, &c);
setBaseAttributes_Text(f, c);
}
/* Fancy date in Gemini feed links. */ {
if (run->linkId && run->flags & startOfLine_GmRunFlag && ~run->flags & decoration_GmRunFlag) {
static iRegExp *datePattern_;
if (!datePattern_) {
datePattern_ = new_RegExp("^[12][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]\\s", 0);
}
iRegExpMatch m;
init_RegExpMatch(&m);
if (matchRange_RegExp(datePattern_, run->text, &m)) {
/* The date uses regular weight and a dimmed color. */
iString styled;
initRange_String(&styled, run->text);
insertData_Block(&styled.chars, 10, "\x1b[0m", 4); /* restore */
iBlock buf;
init_Block(&buf, 0);
appendCStr_Block(&buf, "\x1b[10m"); /* regular font weight */
appendCStr_Block(&buf, escape_Color(isHover ? fg : tmLinkFeedEntryDate_ColorId));
insertData_Block(&styled.chars, 0, constData_Block(&buf), size_Block(&buf));
deinit_Block(&buf);
const int oldAnsi = ansiFlags_Text();
setAnsiFlags_Text(oldAnsi | allowFontStyle_AnsiFlag);
setBaseAttributes_Text(run->font, fg);
drawBoundRange_Text(run->font,
visPos,
(run->isRTL ? -1 : 1) * width_Rect(run->visBounds),
fg,
range_String(&styled));
setAnsiFlags_Text(oldAnsi);
deinit_String(&styled);
goto runDrawn;
}
}
}
drawBoundRange_Text(run->font,
visPos,
(run->isRTL ? -1 : 1) * width_Rect(run->visBounds),
fg,
run->text);
runDrawn:;
setBaseAttributes_Text(-1, -1);
}
/* Presentation of links. */
if (run->linkId && ~run->flags & decoration_GmRunFlag) {
const int metaFont = paragraph_FontId;
/* TODO: Show status of an ongoing media request. */
const int flags = linkFlags;
const iRect linkRect = moved_Rect(run->visBounds, origin);
iMediaRequest *mr = NULL;
/* Show metadata about inline content. */
if (flags & content_GmLinkFlag && run->flags & endOfLine_GmRunFlag) {
fg = linkColor_GmDocument(doc, run->linkId, textHover_GmLinkPart);
iString text;
init_String(&text);
const iMediaId linkMedia = findMediaForLink_Media(constMedia_GmDocument(doc),
run->linkId, none_MediaType);
iAssert(linkMedia.type != none_MediaType);
iGmMediaInfo info;
info_Media(constMedia_GmDocument(doc), linkMedia, &info);
switch (linkMedia.type) {
case image_MediaType: {
/* There's a separate decorative GmRun for the metadata. */
break;
}
case audio_MediaType:
format_String(&text, "%s", info.type);
break;
case download_MediaType:
format_String(&text, "%s", info.type);
break;
default:
break;
}
if (linkMedia.type != download_MediaType && /* can't cancel downloads currently */
linkMedia.type != image_MediaType &&
findMediaRequest_DocumentWidget_(d->view->owner, run->linkId)) {
appendFormat_String(
&text, " %s" close_Icon, isHover ? escape_Color(tmLinkText_ColorId) : "");
}
const iInt2 size = measureRange_Text(metaFont, range_String(&text)).bounds.size;
if (size.x) {
fillRect_Paint(
&d->paint,
(iRect){ add_I2(origin, addX_I2(topRight_Rect(run->bounds), -size.x - gap_UI)),
addX_I2(size, 2 * gap_UI) },
tmBackground_ColorId);
drawAlign_Text(metaFont,
add_I2(topRight_Rect(run->bounds), origin),
fg,
right_Alignment,
"%s", cstr_String(&text));
}
deinit_String(&text);
}
else if (run->flags & endOfLine_GmRunFlag &&
(mr = findMediaRequest_DocumentWidget_(d->view->owner, run->linkId)) != NULL) {
if (!isFinished_GmRequest(mr->req)) {
draw_Text(metaFont,
topRight_Rect(linkRect),
tmInlineContentMetadata_ColorId,
translateCStr_Lang(" \u2014 ${doc.fetching}\u2026 (%.1f ${mb})"),
(float) bodySize_GmRequest(mr->req) / 1.0e6f);
}
}
}
if (0) {
drawRect_Paint(&d->paint, (iRect){ visPos, run->bounds.size }, green_ColorId);
drawRect_Paint(&d->paint, (iRect){ visPos, run->visBounds.size }, red_ColorId);
}
}
static int drawSideRect_(iPaint *p, iRect rect) {
int bg = tmBannerBackground_ColorId;
int fg = tmBannerIcon_ColorId;
if (equal_Color(get_Color(bg), get_Color(tmBackground_ColorId))) {
bg = tmBannerIcon_ColorId;
fg = tmBannerBackground_ColorId;
}
fillRect_Paint(p, rect, bg);
return fg;
}
static int sideElementAvailWidth_DocumentView_(const iDocumentView *d) {
return left_Rect(documentBounds_DocumentView_(d)) -
left_Rect(bounds_Widget(constAs_Widget(d->owner))) - 2 * d->pageMargin * gap_UI;
}
static iBool isSideHeadingVisible_DocumentView_(const iDocumentView *d) {
return sideElementAvailWidth_DocumentView_(d) >= lineHeight_Text(banner_FontId) * 4.5f;
}
static void updateSideIconBuf_DocumentView_(const iDocumentView *d) {
if (!isExposed_Window(get_Window())) {
return;
}
iDrawBufs *dbuf = d->drawBufs;
dbuf->flags &= ~updateSideBuf_DrawBufsFlag;
if (dbuf->sideIconBuf) {
SDL_DestroyTexture(dbuf->sideIconBuf);
dbuf->sideIconBuf = NULL;
}
// const iGmRun *banner = siteBanner_GmDocument(d->doc);
if (isEmpty_Banner(d->owner->banner)) {
return;
}
const int margin = gap_UI * d->pageMargin;
const int minBannerSize = lineHeight_Text(banner_FontId) * 2;
const iChar icon = siteIcon_GmDocument(d->doc);
const int avail = sideElementAvailWidth_DocumentView_(d) - margin;
iBool isHeadingVisible = isSideHeadingVisible_DocumentView_(d);
/* Determine the required size. */
iInt2 bufSize = init1_I2(minBannerSize);
const int sideHeadingFont = FONT_ID(documentHeading_FontId, regular_FontStyle, contentBig_FontSize);
if (isHeadingVisible) {
const iInt2 headingSize = measureWrapRange_Text(sideHeadingFont, avail,
currentHeading_DocumentView_(d)).bounds.size;
if (headingSize.x > 0) {
bufSize.y += gap_Text + headingSize.y;
bufSize.x = iMax(bufSize.x, headingSize.x);
}
else {
isHeadingVisible = iFalse;
}
}
SDL_Renderer *render = renderer_Window(get_Window());
dbuf->sideIconBuf = SDL_CreateTexture(render,
SDL_PIXELFORMAT_RGBA4444,
SDL_TEXTUREACCESS_STATIC | SDL_TEXTUREACCESS_TARGET,
bufSize.x, bufSize.y);
iPaint p;
init_Paint(&p);
beginTarget_Paint(&p, dbuf->sideIconBuf);
const iColor back = get_Color(tmBannerSideTitle_ColorId);
SDL_SetRenderDrawColor(render, back.r, back.g, back.b, 0); /* better blending of the edge */
SDL_RenderClear(render);
const iRect iconRect = { zero_I2(), init1_I2(minBannerSize) };
int fg = drawSideRect_(&p, iconRect);
iString str;
initUnicodeN_String(&str, &icon, 1);
drawCentered_Text(banner_FontId, iconRect, iTrue, fg, "%s", cstr_String(&str));
deinit_String(&str);
if (isHeadingVisible) {
iRangecc text = currentHeading_DocumentView_(d);
iInt2 pos = addY_I2(bottomLeft_Rect(iconRect), gap_Text);
const int font = sideHeadingFont;
drawWrapRange_Text(font, pos, avail, tmBannerSideTitle_ColorId, text);
}
endTarget_Paint(&p);
SDL_SetTextureBlendMode(dbuf->sideIconBuf, SDL_BLENDMODE_BLEND);
}
static void drawSideElements_DocumentView_(const iDocumentView *d) {
const iWidget *w = constAs_Widget(d->owner);
const iRect bounds = bounds_Widget(w);
const iRect docBounds = documentBounds_DocumentView_(d);
const int margin = gap_UI * d->pageMargin;
float opacity = value_Anim(&d->sideOpacity);
const int avail = left_Rect(docBounds) - left_Rect(bounds) - 2 * margin;
iDrawBufs * dbuf = d->drawBufs;
iPaint p;
init_Paint(&p);
setClip_Paint(&p, boundsWithoutVisualOffset_Widget(w));
/* Side icon and current heading. */
if (prefs_App()->sideIcon && opacity > 0 && dbuf->sideIconBuf) {
const iInt2 texSize = size_SDLTexture(dbuf->sideIconBuf);
if (avail > texSize.x) {
const int minBannerSize = lineHeight_Text(banner_FontId) * 2;
iInt2 pos = addY_I2(add_I2(topLeft_Rect(bounds), init_I2(margin, 0)),
height_Rect(bounds) / 2 - minBannerSize / 2 -
(texSize.y > minBannerSize
? (gap_Text + lineHeight_Text(heading3_FontId)) / 2
: 0));
SDL_SetTextureAlphaMod(dbuf->sideIconBuf, 255 * opacity);
SDL_RenderCopy(renderer_Window(get_Window()),
dbuf->sideIconBuf, NULL,
&(SDL_Rect){ pos.x, pos.y, texSize.x, texSize.y });
}
}
/* Reception timestamp. */
if (dbuf->timestampBuf && dbuf->timestampBuf->size.x <= avail) {
draw_TextBuf(
dbuf->timestampBuf,
add_I2(
bottomLeft_Rect(bounds),
init_I2(margin,
-margin + -dbuf->timestampBuf->size.y +
iMax(0, d->scrollY.max - pos_SmoothScroll(&d->scrollY)))),
tmQuoteIcon_ColorId);
}
unsetClip_Paint(&p);
}
static void drawMedia_DocumentView_(const iDocumentView *d, iPaint *p) {
iConstForEach(PtrArray, i, &d->visibleMedia) {
const iGmRun * run = i.ptr;
if (run->mediaType == audio_MediaType) {
iPlayerUI ui;
init_PlayerUI(&ui,
audioPlayer_Media(media_GmDocument(d->doc), mediaId_GmRun(run)),
runRect_DocumentView_(d, run));
draw_PlayerUI(&ui, p);
}
else if (run->mediaType == download_MediaType) {
iDownloadUI ui;
init_DownloadUI(&ui, constMedia_GmDocument(d->doc), run->mediaId,
runRect_DocumentView_(d, run));
draw_DownloadUI(&ui, p);
}
}
}
static void extend_GmRunRange_(iGmRunRange *runs) {
if (runs->start) {
runs->start--;
runs->end++;
}
}
static iBool render_DocumentView_(const iDocumentView *d, iDrawContext *ctx, iBool prerenderExtra) {
iBool didDraw = iFalse;
const iRect bounds = bounds_Widget(constAs_Widget(d->owner));
const iRect ctxWidgetBounds =
init_Rect(0,
0,
width_Rect(bounds) - constAs_Widget(d->owner->scroll)->rect.size.x,
height_Rect(bounds));
const iRangei full = { 0, size_GmDocument(d->doc).y };
const iRangei vis = ctx->vis;
iVisBuf *visBuf = d->visBuf; /* will be updated now */
d->drawBufs->lastRenderTime = SDL_GetTicks();
/* Swap buffers around to have room available both before and after the visible region. */
allocVisBuffer_DocumentView_(d);
reposition_VisBuf(visBuf, vis);
/* Redraw the invalid ranges. */
if (~flags_Widget(constAs_Widget(d->owner)) & destroyPending_WidgetFlag) {
iPaint *p = &ctx->paint;
init_Paint(p);
iForIndices(i, visBuf->buffers) {
iVisBufTexture *buf = &visBuf->buffers[i];
iVisBufMeta *meta = buf->user;
const iRangei bufRange = intersect_Rangei(bufferRange_VisBuf(visBuf, i), full);
const iRangei bufVisRange = intersect_Rangei(bufRange, vis);
ctx->widgetBounds = moved_Rect(ctxWidgetBounds, init_I2(0, -buf->origin));
ctx->viewPos = init_I2(left_Rect(ctx->docBounds) - left_Rect(bounds), -buf->origin);
// printf(" buffer %zu: buf vis range %d...%d\n", i, bufVisRange.start, bufVisRange.end);
if (!prerenderExtra && !isEmpty_Range(&bufVisRange)) {
didDraw = iTrue;
if (isEmpty_Rangei(buf->validRange)) {
/* Fill the required currently visible range (vis). */
const iRangei bufVisRange = intersect_Rangei(bufRange, vis);
if (!isEmpty_Range(&bufVisRange)) {
beginTarget_Paint(p, buf->texture);
fillRect_Paint(p, (iRect){ zero_I2(), visBuf->texSize }, tmBackground_ColorId);
iZap(ctx->runsDrawn);
render_GmDocument(d->doc, bufVisRange, drawRun_DrawContext_, ctx);
meta->runsDrawn = ctx->runsDrawn;
extend_GmRunRange_(&meta->runsDrawn);
buf->validRange = bufVisRange;
// printf(" buffer %zu valid %d...%d\n", i, bufRange.start, bufRange.end);
}
}
else {
/* Progressively fill the required runs. */
if (meta->runsDrawn.start) {
beginTarget_Paint(p, buf->texture);
meta->runsDrawn.start = renderProgressive_GmDocument(d->doc, meta->runsDrawn.start,
-1, iInvalidSize,
bufVisRange,
drawRun_DrawContext_,
ctx);
buf->validRange.start = bufVisRange.start;
}
if (meta->runsDrawn.end) {
beginTarget_Paint(p, buf->texture);
meta->runsDrawn.end = renderProgressive_GmDocument(d->doc, meta->runsDrawn.end,
+1, iInvalidSize,
bufVisRange,
drawRun_DrawContext_,
ctx);
buf->validRange.end = bufVisRange.end;
}
}
}
/* Progressively draw the rest of the buffer if it isn't fully valid. */
if (prerenderExtra && !equal_Rangei(bufRange, buf->validRange)) {
const iGmRun *next;
// printf("%zu: prerenderExtra (start:%p end:%p)\n", i, meta->runsDrawn.start, meta->runsDrawn.end);
if (meta->runsDrawn.start == NULL) {
/* Haven't drawn anything yet in this buffer, so let's try seeding it. */
const int rh = lineHeight_Text(paragraph_FontId);
const int y = i >= iElemCount(visBuf->buffers) / 2 ? bufRange.start : (bufRange.end - rh);
beginTarget_Paint(p, buf->texture);
fillRect_Paint(p, (iRect){ zero_I2(), visBuf->texSize }, tmBackground_ColorId);
buf->validRange = (iRangei){ y, y + rh };
iZap(ctx->runsDrawn);
render_GmDocument(d->doc, buf->validRange, drawRun_DrawContext_, ctx);
meta->runsDrawn = ctx->runsDrawn;
extend_GmRunRange_(&meta->runsDrawn);
// printf("%zu: seeded, next %p:%p\n", i, meta->runsDrawn.start, meta->runsDrawn.end);
didDraw = iTrue;
}
else {
if (meta->runsDrawn.start) {
const iRangei upper = intersect_Rangei(bufRange, (iRangei){ full.start, buf->validRange.start });
if (upper.end > upper.start) {
beginTarget_Paint(p, buf->texture);
next = renderProgressive_GmDocument(d->doc, meta->runsDrawn.start,
-1, 1, upper,
drawRun_DrawContext_,
ctx);
if (next && meta->runsDrawn.start != next) {
meta->runsDrawn.start = next;
buf->validRange.start = bottom_Rect(next->visBounds);
didDraw = iTrue;
}
else {
buf->validRange.start = bufRange.start;
}
}
}
if (!didDraw && meta->runsDrawn.end) {
const iRangei lower = intersect_Rangei(bufRange, (iRangei){ buf->validRange.end, full.end });
if (lower.end > lower.start) {
beginTarget_Paint(p, buf->texture);
next = renderProgressive_GmDocument(d->doc, meta->runsDrawn.end,
+1, 1, lower,
drawRun_DrawContext_,
ctx);
if (next && meta->runsDrawn.end != next) {
meta->runsDrawn.end = next;
buf->validRange.end = top_Rect(next->visBounds);
didDraw = iTrue;
}
else {
buf->validRange.end = bufRange.end;
}
}
}
}
}
/* Draw any invalidated runs that fall within this buffer. */
if (!prerenderExtra) {
const iRangei bufRange = { buf->origin, buf->origin + visBuf->texSize.y };
/* Clear full-width backgrounds first in case there are any dynamic elements. */ {
iConstForEach(PtrSet, r, d->invalidRuns) {
const iGmRun *run = *r.value;
if (isOverlapping_Rangei(bufRange, ySpan_Rect(run->visBounds))) {
beginTarget_Paint(p, buf->texture);
fillRect_Paint(p,
init_Rect(0,
run->visBounds.pos.y - buf->origin,
visBuf->texSize.x,
run->visBounds.size.y),
tmBackground_ColorId);
}
}
}
setAnsiFlags_Text(ansiEscapes_GmDocument(d->doc));
iConstForEach(PtrSet, r, d->invalidRuns) {
const iGmRun *run = *r.value;
if (isOverlapping_Rangei(bufRange, ySpan_Rect(run->visBounds))) {
beginTarget_Paint(p, buf->texture);
drawRun_DrawContext_(ctx, run);
}
}
setAnsiFlags_Text(allowAll_AnsiFlag);
}
endTarget_Paint(p);
if (prerenderExtra && didDraw) {
/* Just a run at a time. */
break;
}
}
if (!prerenderExtra) {
clear_PtrSet(d->invalidRuns);
}
}
return didDraw;
}
static void draw_DocumentView_(const iDocumentView *d) {
const iWidget *w = constAs_Widget(d->owner);
const iRect bounds = bounds_Widget(w);
const iRect boundsWithoutVisOff = boundsWithoutVisualOffset_Widget(w);
const iRect clipBounds = intersect_Rect(bounds, boundsWithoutVisOff);
/* Each document has its own palette, but the drawing routines rely on a global one.
As we're now drawing a document, ensure that the right palette is in effect.
Document theme colors can be used elsewhere, too, but first a document's palette
must be made global. */
makePaletteGlobal_GmDocument(d->doc);
if (d->drawBufs->flags & updateTimestampBuf_DrawBufsFlag) {
updateTimestampBuf_DocumentView_(d);
}
if (d->drawBufs->flags & updateSideBuf_DrawBufsFlag) {
updateSideIconBuf_DocumentView_(d);
}
const iRect docBounds = documentBounds_DocumentView_(d);
const iRangei vis = visibleRange_DocumentView_(d);
iDrawContext ctx = {
.view = d,
.docBounds = docBounds,
.vis = vis,
.showLinkNumbers = (d->owner->flags & showLinkNumbers_DocumentWidgetFlag) != 0,
};
init_Paint(&ctx.paint);
render_DocumentView_(d, &ctx, iFalse /* just the mandatory parts */);
iBanner *banner = d->owner->banner;
int yTop = docBounds.pos.y + viewPos_DocumentView_(d);
const iBool isDocEmpty = size_GmDocument(d->doc).y == 0;
const iBool isTouchSelecting = (flags_Widget(w) & touchDrag_WidgetFlag) != 0;
if (!isDocEmpty || !isEmpty_Banner(banner)) {
const int docBgColor = isDocEmpty ? tmBannerBackground_ColorId : tmBackground_ColorId;
setClip_Paint(&ctx.paint, clipBounds);
if (!isDocEmpty) {
draw_VisBuf(d->visBuf, init_I2(bounds.pos.x, yTop), ySpan_Rect(bounds));
}
/* Text markers. */
if (!isEmpty_Range(&d->owner->foundMark) || !isEmpty_Range(&d->owner->selectMark)) {
SDL_Renderer *render = renderer_Window(get_Window());
ctx.firstMarkRect = zero_Rect();
ctx.lastMarkRect = zero_Rect();
SDL_SetRenderDrawBlendMode(render,
isDark_ColorTheme(colorTheme_App()) ? SDL_BLENDMODE_ADD
: SDL_BLENDMODE_BLEND);
ctx.viewPos = topLeft_Rect(docBounds);
/* Marker starting outside the visible range? */
if (d->visibleRuns.start) {
if (!isEmpty_Range(&d->owner->selectMark) &&
d->owner->selectMark.start < d->visibleRuns.start->text.start &&
d->owner->selectMark.end > d->visibleRuns.start->text.start) {
ctx.inSelectMark = iTrue;
}
if (isEmpty_Range(&d->owner->foundMark) &&
d->owner->foundMark.start < d->visibleRuns.start->text.start &&
d->owner->foundMark.end > d->visibleRuns.start->text.start) {
ctx.inFoundMark = iTrue;
}
}
render_GmDocument(d->doc, vis, drawMark_DrawContext_, &ctx);
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_NONE);
/* Selection range pins. */
if (isTouchSelecting) {
drawPin_Paint(&ctx.paint, ctx.firstMarkRect, 0, tmQuote_ColorId);
drawPin_Paint(&ctx.paint, ctx.lastMarkRect, 1, tmQuote_ColorId);
}
}
drawMedia_DocumentView_(d, &ctx.paint);
/* Fill the top and bottom, in case the document is short. */
if (yTop > top_Rect(bounds)) {
fillRect_Paint(&ctx.paint,
(iRect){ bounds.pos, init_I2(bounds.size.x, yTop - top_Rect(bounds)) },
!isEmpty_Banner(banner) ? tmBannerBackground_ColorId
: docBgColor);
}
/* Banner. */
if (!isDocEmpty || numItems_Banner(banner) > 0) {
/* Fill the part between the banner and the top of the document. */
fillRect_Paint(&ctx.paint,
(iRect){ init_I2(left_Rect(bounds),
top_Rect(docBounds) + viewPos_DocumentView_(d) -
documentTopPad_DocumentView_(d)),
init_I2(bounds.size.x, documentTopPad_DocumentView_(d)) },
docBgColor);
setPos_Banner(banner, addY_I2(topLeft_Rect(docBounds),
-pos_SmoothScroll(&d->scrollY)));
draw_Banner(banner);
}
const int yBottom = yTop + size_GmDocument(d->doc).y;
if (yBottom < bottom_Rect(bounds)) {
fillRect_Paint(&ctx.paint,
init_Rect(bounds.pos.x, yBottom, bounds.size.x, bottom_Rect(bounds) - yBottom),
!isDocEmpty ? docBgColor : tmBannerBackground_ColorId);
}
unsetClip_Paint(&ctx.paint);
drawSideElements_DocumentView_(d);
/* Alt text. */
const float altTextOpacity = value_Anim(&d->altTextOpacity) * 6 - 5;
if (d->hoverAltPre && altTextOpacity > 0) {
const iGmPreMeta *meta = preMeta_GmDocument(d->doc, preId_GmRun(d->hoverAltPre));
if (meta->flags & topLeft_GmPreMetaFlag && ~meta->flags & decoration_GmRunFlag &&
!isEmpty_Range(&meta->altText)) {
const int margin = 3 * gap_UI / 2;
const int altFont = uiLabel_FontId;
const int wrap = docBounds.size.x - 2 * margin;
iInt2 pos = addY_I2(add_I2(docBounds.pos, meta->pixelRect.pos),
viewPos_DocumentView_(d));
const iInt2 textSize = measureWrapRange_Text(altFont, wrap, meta->altText).bounds.size;
pos.y -= textSize.y + gap_UI;
pos.y = iMax(pos.y, top_Rect(bounds));
const iRect altRect = { pos, init_I2(docBounds.size.x, textSize.y) };
ctx.paint.alpha = altTextOpacity * 255;
if (altTextOpacity < 1) {
SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_BLEND);
}
fillRect_Paint(&ctx.paint, altRect, tmBackgroundAltText_ColorId);
drawRect_Paint(&ctx.paint, altRect, tmFrameAltText_ColorId);
setOpacity_Text(altTextOpacity);
drawWrapRange_Text(altFont, addX_I2(pos, margin), wrap,
tmQuote_ColorId, meta->altText);
SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_NONE);
setOpacity_Text(1.0f);
}
}
/* Touch selection indicator. */
if (isTouchSelecting) {
iRect rect = { topLeft_Rect(bounds),
init_I2(width_Rect(bounds), lineHeight_Text(uiLabelBold_FontId)) };
fillRect_Paint(&ctx.paint, rect, uiTextAction_ColorId);
const iRangecc mark = selectMark_DocumentWidget_(d->owner);
drawCentered_Text(uiLabelBold_FontId,
rect,
iFalse,
uiBackground_ColorId,
"%zu bytes selected", /* TODO: i18n */
size_Range(&mark));
}
}
}
/*----------------------------------------------------------------------------------------------*/
static void enableActions_DocumentWidget_(iDocumentWidget *d, iBool enable) {
/* Actions are invisible child widgets of the DocumentWidget. */
iForEach(ObjectList, i, children_Widget(d)) {
if (isAction_Widget(i.object)) {
setFlags_Widget(i.object, disabled_WidgetFlag, !enable);
}
}
}
static void setLinkNumberMode_DocumentWidget_(iDocumentWidget *d, iBool set) {
if (((d->flags & showLinkNumbers_DocumentWidgetFlag) != 0) != set) {
iChangeFlags(d->flags, showLinkNumbers_DocumentWidgetFlag, set);
/* Children have priority when handling events. */
enableActions_DocumentWidget_(d, !set);
#if defined (iPlatformAppleDesktop)
enableMenuItemsOnHomeRow_MacOS(!set);
#endif
/* Ensure all keyboard events come here first. */
setKeyboardGrab_Widget(set ? as_Widget(d) : NULL);
if (d->menu) {
setFlags_Widget(d->menu, disabled_WidgetFlag, set);
}
}
}
static void requestUpdated_DocumentWidget_(iAnyObject *obj) {
iDocumentWidget *d = obj;
const int wasUpdated = exchange_Atomic(&d->isRequestUpdated, iTrue);
if (!wasUpdated) {
postCommand_Widget(obj,
"document.request.updated doc:%p reqid:%u request:%p",
d,
id_GmRequest(d->request),
d->request);
}
}
static void requestFinished_DocumentWidget_(iAnyObject *obj) {
iDocumentWidget *d = obj;
postCommand_Widget(obj,
"document.request.finished doc:%p reqid:%u request:%p",
d,
id_GmRequest(d->request),
d->request);
}
static void animate_DocumentWidget_(void *ticker) {
iDocumentWidget *d = ticker;
iAssert(isInstance_Object(d, &Class_DocumentWidget));
refresh_Widget(d);
if (!isFinished_Anim(&d->view.sideOpacity) || !isFinished_Anim(&d->view.altTextOpacity) ||
(d->linkInfo && !isFinished_Anim(&d->linkInfo->opacity))) {
addTicker_App(animate_DocumentWidget_, d);
}
}
static uint32_t mediaUpdateInterval_DocumentWidget_(const iDocumentWidget *d) {
if (document_App() != d) {
return 0;
}
if (as_MainWindow(window_Widget(d))->isDrawFrozen) {
return 0;
}
static const uint32_t invalidInterval_ = ~0u;
uint32_t interval = invalidInterval_;
iConstForEach(PtrArray, i, &d->view.visibleMedia) {
const iGmRun *run = i.ptr;
if (run->mediaType == audio_MediaType) {
iPlayer *plr = audioPlayer_Media(media_GmDocument(d->view.doc), mediaId_GmRun(run));
if (flags_Player(plr) & adjustingVolume_PlayerFlag ||
(isStarted_Player(plr) && !isPaused_Player(plr))) {
interval = iMin(interval, 1000 / 15);
}
}
else if (run->mediaType == download_MediaType) {
interval = iMin(interval, 1000);
}
}
return interval != invalidInterval_ ? interval : 0;
}
static uint32_t postMediaUpdate_DocumentWidget_(uint32_t interval, void *context) {
/* Called in timer thread; don't access the widget. */
iUnused(context);
postCommand_App("media.player.update");
return interval;
}
static void updateMedia_DocumentWidget_(iDocumentWidget *d) {
if (document_App() == d) {
refresh_Widget(d);
iConstForEach(PtrArray, i, &d->view.visibleMedia) {
const iGmRun *run = i.ptr;
if (run->mediaType == audio_MediaType) {
iPlayer *plr = audioPlayer_Media(media_GmDocument(d->view.doc), mediaId_GmRun(run));
if (idleTimeMs_Player(plr) > 3000 && ~flags_Player(plr) & volumeGrabbed_PlayerFlag &&
flags_Player(plr) & adjustingVolume_PlayerFlag) {
setFlags_Player(plr, adjustingVolume_PlayerFlag, iFalse);
}
}
}
}
if (d->mediaTimer && mediaUpdateInterval_DocumentWidget_(d) == 0) {
SDL_RemoveTimer(d->mediaTimer);
d->mediaTimer = 0;
}
}
static void animateMedia_DocumentWidget_(iDocumentWidget *d) {
if (document_App() != d) {
if (d->mediaTimer) {
SDL_RemoveTimer(d->mediaTimer);
d->mediaTimer = 0;
}
return;
}
uint32_t interval = mediaUpdateInterval_DocumentWidget_(d);
if (interval && !d->mediaTimer) {
d->mediaTimer = SDL_AddTimer(interval, postMediaUpdate_DocumentWidget_, d);
}
}
static void updateWindowTitle_DocumentWidget_(const iDocumentWidget *d) {
iLabelWidget *tabButton = tabPageButton_Widget(findChild_Widget(root_Widget(constAs_Widget(d)),
"doctabs"), d);
if (!tabButton) {
/* Not part of the UI at the moment. */
return;
}
iStringArray *title = iClob(new_StringArray());
if (!isEmpty_String(title_GmDocument(d->view.doc))) {
pushBack_StringArray(title, title_GmDocument(d->view.doc));
}
if (!isEmpty_String(d->titleUser)) {
pushBack_StringArray(title, d->titleUser);
}
else {
iUrl parts;
init_Url(&parts, d->mod.url);
if (equalCase_Rangecc(parts.scheme, "about")) {
if (!findWidget_App("winbar")) {
pushBackCStr_StringArray(title, "Lagrange");
}
}
else if (!isEmpty_Range(&parts.host)) {
pushBackRange_StringArray(title, parts.host);
}
}
if (isEmpty_StringArray(title)) {
pushBackCStr_StringArray(title, "Lagrange");
}
/* Take away parts if it doesn't fit. */
const int avail = bounds_Widget(as_Widget(tabButton)).size.x - 7 * gap_UI;
iBool setWindow = (document_App() == d && isUnderKeyRoot_Widget(d));
const int font = uiLabel_FontId;
for (;;) {
iString *text = collect_String(joinCStr_StringArray(title, " \u2014 "));
if (setWindow) {
/* Longest version for the window title, and omit the icon. */
setTitle_MainWindow(get_MainWindow(), text);
setWindow = iFalse;
}
const iChar siteIcon = siteIcon_GmDocument(d->view.doc);
if (siteIcon) {
if (!isEmpty_String(text)) {
prependCStr_String(text, " " restore_ColorEscape);
}
prependChar_String(text, siteIcon);
prependCStr_String(text, escape_Color(uiIcon_ColorId));
}
const int width = measureRange_Text(font, range_String(text)).advance.x;
const int ellipsisWidth = measure_Text(font, "...").advance.x;
setTextColor_LabelWidget(tabButton, none_ColorId);
iWidget *tabCloseButton = child_Widget(as_Widget(tabButton), 0);
setFlags_Widget(tabCloseButton, visibleOnParentHover_WidgetFlag,
avail > width_Widget(tabCloseButton));
if (width <= avail || isEmpty_StringArray(title)) {
updateText_LabelWidget(tabButton, text);
break;
}
if (size_StringArray(title) == 1) {
/* Just truncate to fit. */
if (siteIcon && avail <= 4 * ellipsisWidth) {
updateText_LabelWidget(tabButton, collect_String(newUnicodeN_String(&siteIcon, 1)));
setTextColor_LabelWidget(tabButton, uiIcon_ColorId);
break;
}
const char *endPos;
tryAdvanceNoWrap_Text(font,
range_String(text),
avail - ellipsisWidth,
&endPos);
updateText_LabelWidget(
tabButton,
collectNewFormat_String(
"%s...", cstr_Rangecc((iRangecc){ constBegin_String(text), endPos })));
break;
}
remove_StringArray(title, size_StringArray(title) - 1);
}
}
static void invalidate_DocumentWidget_(iDocumentWidget *d) {
if (flags_Widget(as_Widget(d)) & destroyPending_WidgetFlag) {
return;
}
if (d->flags & invalidationPending_DocumentWidgetFlag) {
return;
}
if (isAffectedByVisualOffset_Widget(as_Widget(d))) {
d->flags |= invalidationPending_DocumentWidgetFlag;
return;
}
d->flags &= ~invalidationPending_DocumentWidgetFlag;
invalidate_DocumentView_(&d->view);
// printf("[%p] '%s' invalidated\n", d, cstr_String(id_Widget(as_Widget(d))));
}
static iRangecc siteText_DocumentWidget_(const iDocumentWidget *d) {
return isEmpty_String(d->titleUser) ? urlHost_String(d->mod.url)
: range_String(d->titleUser);
}
static iBool isPinned_DocumentWidget_(const iDocumentWidget *d) {
if (deviceType_App() == phone_AppDeviceType) {
return iFalse;
}
if (d->flags & otherRootByDefault_DocumentWidgetFlag) {
return iTrue;
}
const iWidget *w = constAs_Widget(d);
const iWindow *win = get_Window();
if (numRoots_Window(win) == 1) {
return iFalse;
}
const iPrefs *prefs = prefs_App();
return (prefs->pinSplit == 1 && w->root == win->roots[0]) ||
(prefs->pinSplit == 2 && w->root == win->roots[1]);
}
static void showOrHidePinningIndicator_DocumentWidget_(iDocumentWidget *d) {
iWidget *w = as_Widget(d);
showCollapsed_Widget(findChild_Widget(root_Widget(w), "document.pinned"),
isPinned_DocumentWidget_(d));
}
static void updateBanner_DocumentWidget_(iDocumentWidget *d) {
setSite_Banner(d->banner, siteText_DocumentWidget_(d), siteIcon_GmDocument(d->view.doc));
}
static void documentWasChanged_DocumentWidget_(iDocumentWidget *d) {
iChangeFlags(d->flags, selecting_DocumentWidgetFlag, iFalse);
setFlags_Widget(as_Widget(d), touchDrag_WidgetFlag, iFalse);
d->requestLinkId = 0;
updateVisitedLinks_GmDocument(d->view.doc);
documentRunsInvalidated_DocumentWidget_(d);
updateWindowTitle_DocumentWidget_(d);
updateBanner_DocumentWidget_(d);
updateVisible_DocumentView_(&d->view);
d->view.drawBufs->flags |= updateSideBuf_DrawBufsFlag;
invalidate_DocumentWidget_(d);
refresh_Widget(as_Widget(d));
/* Check for special bookmark tags. */
d->flags &= ~otherRootByDefault_DocumentWidgetFlag;
const uint16_t bmid = findUrl_Bookmarks(bookmarks_App(), d->mod.url);
if (bmid) {
const iBookmark *bm = get_Bookmarks(bookmarks_App(), bmid);
if (bm->flags & linkSplit_BookmarkFlag) {
d->flags |= otherRootByDefault_DocumentWidgetFlag;
}
}
showOrHidePinningIndicator_DocumentWidget_(d);
if (~d->flags & fromCache_DocumentWidgetFlag) {
setCachedDocument_History(d->mod.history, d->view.doc /* keeps a ref */);
}
}
static void replaceDocument_DocumentWidget_(iDocumentWidget *d, iGmDocument *newDoc) {
pauseAllPlayers_Media(media_GmDocument(d->view.doc), iTrue);
iRelease(d->view.doc);
d->view.doc = ref_Object(newDoc);
documentWasChanged_DocumentWidget_(d);
}
static void updateTheme_DocumentWidget_(iDocumentWidget *d) {
if (document_App() != d || category_GmStatusCode(d->sourceStatus) == categoryInput_GmStatusCode) {
return;
}
d->view.drawBufs->flags |= updateTimestampBuf_DrawBufsFlag;
updateBanner_DocumentWidget_(d);
}
static void makeFooterButtons_DocumentWidget_(iDocumentWidget *d, const iMenuItem *items, size_t count) {
iWidget *w = as_Widget(d);
destroy_Widget(d->footerButtons);
d->footerButtons = NULL;
if (count == 0) {
return;
}
d->footerButtons = new_Widget();
setFlags_Widget(d->footerButtons,
unhittable_WidgetFlag | arrangeVertical_WidgetFlag |
resizeWidthOfChildren_WidgetFlag | arrangeHeight_WidgetFlag |
fixedPosition_WidgetFlag | resizeToParentWidth_WidgetFlag,
iTrue);
for (size_t i = 0; i < count; ++i) {
iLabelWidget *button = addChildFlags_Widget(
d->footerButtons,
iClob(newKeyMods_LabelWidget(
items[i].label, items[i].key, items[i].kmods, items[i].command)),
alignLeft_WidgetFlag | drawKey_WidgetFlag | extraPadding_WidgetFlag);
setPadding1_Widget(as_Widget(button), gap_UI / 2);
checkIcon_LabelWidget(button);
setFont_LabelWidget(button, uiContent_FontId);
setBackgroundColor_Widget(as_Widget(button), uiBackgroundSidebar_ColorId);
}
addChild_Widget(as_Widget(d), iClob(d->footerButtons));
arrange_Widget(d->footerButtons);
arrange_Widget(w);
updateVisible_DocumentView_(&d->view); /* final placement for the buttons */
}
static void showErrorPage_DocumentWidget_(iDocumentWidget *d, enum iGmStatusCode code,
const iString *meta) {
iString *src = collectNew_String();
const iGmError *msg = get_GmError(code);
destroy_Widget(d->footerButtons);
d->footerButtons = NULL;
const iString *serverErrorMsg = NULL;
if (meta) {
switch (code) {
case schemeChangeRedirect_GmStatusCode:
case tooManyRedirects_GmStatusCode:
appendFormat_String(src, "=> %s\n", cstr_String(meta));
break;
case tlsServerCertificateExpired_GmStatusCode:
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){ { rightArrowhead_Icon " ${menu.unexpire}",
SDLK_RETURN, 0, "server.unexpire"
},
{ info_Icon " ${menu.pageinfo}",
SDLK_i,
KMOD_PRIMARY,
"document.info" } },
2);
break;
case tlsServerCertificateNotVerified_GmStatusCode:
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){ { info_Icon " ${menu.pageinfo}",
SDLK_i,
KMOD_PRIMARY,
"document.info" } },
1);
break;
case failedToOpenFile_GmStatusCode:
case certificateNotValid_GmStatusCode:
// appendFormat_String(src, "%s", cstr_String(meta));
break;
case unsupportedMimeType_GmStatusCode: {
iString *key = collectNew_String();
toString_Sym(SDLK_s, KMOD_PRIMARY, key);
// appendFormat_String(src, "\n```\n%s\n```\n", cstr_String(meta));
const char *mtype = mediaTypeFromFileExtension_String(d->mod.url);
iArray items;
init_Array(&items, sizeof(iMenuItem));
if (iCmpStr(mtype, "application/octet-stream")) {
pushBack_Array(
&items,
&(iMenuItem){ translateCStr_Lang(format_CStr("View as \"%s\"", mtype)),
SDLK_RETURN,
0,
format_CStr("document.setmediatype mime:%s", mtype) });
}
pushBack_Array(&items,
&(iMenuItem){ export_Icon " ${menu.open.external}",
SDLK_RETURN,
KMOD_PRIMARY,
"document.save extview:1" });
pushBack_Array(
&items,
&(iMenuItem){ translateCStr_Lang(download_Icon " " saveToDownloads_Label),
0,
0,
"document.save" });
makeFooterButtons_DocumentWidget_(d, data_Array(&items), size_Array(&items));
deinit_Array(&items);
serverErrorMsg = collectNewFormat_String("%s (%s)", msg->title, cstr_String(meta));
break;
}
default:
if (!isEmpty_String(meta)) {
serverErrorMsg = meta;
}
break;
}
}
if (category_GmStatusCode(code) == categoryClientCertificate_GmStatus) {
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){
{ leftHalf_Icon " ${menu.show.identities}",
'4',
KMOD_PRIMARY,
deviceType_App() == desktop_AppDeviceType ? "sidebar.mode arg:3 show:1"
: "preferences idents:1" },
{ person_Icon " ${menu.identity.new}", newIdentity_KeyShortcut, "ident.new" } },
2);
}
/* Make a new document for the error page.*/
iGmDocument *errorDoc = new_GmDocument();
setWidth_GmDocument(errorDoc, documentWidth_DocumentView_(&d->view), width_Widget(d));
setUrl_GmDocument(errorDoc, d->mod.url);
setFormat_GmDocument(errorDoc, gemini_SourceFormat);
replaceDocument_DocumentWidget_(d, errorDoc);
iRelease(errorDoc);
clear_Banner(d->banner);
add_Banner(d->banner, error_BannerType, code, serverErrorMsg, NULL);
d->state = ready_RequestState;
setSource_DocumentWidget(d, src);
updateTheme_DocumentWidget_(d);
resetScroll_DocumentView_(&d->view);
}
static void updateFetchProgress_DocumentWidget_(iDocumentWidget *d) {
iLabelWidget *prog = findChild_Widget(root_Widget(as_Widget(d)), "document.progress");
const size_t dlSize = d->request ? bodySize_GmRequest(d->request) : 0;
showCollapsed_Widget(as_Widget(prog), dlSize >= 250000);
if (isVisible_Widget(prog)) {
updateText_LabelWidget(prog,
collectNewFormat_String("%s%.3f ${mb}",
isFinished_GmRequest(d->request)
? uiHeading_ColorEscape
: uiTextCaution_ColorEscape,
dlSize / 1.0e6f));
}
}
static const char *zipPageHeading_(const iRangecc mime) {
if (equalCase_Rangecc(mime, "application/gpub+zip")) {
return book_Icon " Gempub";
}
else if (equalCase_Rangecc(mime, mimeType_FontPack)) {
return fontpack_Icon " Fontpack";
}
iRangecc type = iNullRange;
nextSplit_Rangecc(mime, "/", &type); /* skip the part before the slash */
nextSplit_Rangecc(mime, "/", &type);
if (startsWithCase_Rangecc(type, "x-")) {
type.start += 2;
}
iString *heading = upper_String(collectNewRange_String(type));
appendCStr_String(heading, " Archive");
prependCStr_String(heading, folder_Icon " ");
return cstrCollect_String(heading);
}
static void postProcessRequestContent_DocumentWidget_(iDocumentWidget *d, iBool isCached) {
iWidget *w = as_Widget(d);
/* Embedded images in data links should be shown immediately as they are already fetched
data that is part of the document. */ {
iGmDocument *doc = d->view.doc;
for (size_t linkId = 1; ; linkId++) {
const int linkFlags = linkFlags_GmDocument(doc, linkId);
const iString *linkUrl = linkUrl_GmDocument(doc, linkId);
if (!linkUrl) break;
if (scheme_GmLinkFlag(linkFlags) == data_GmLinkScheme &&
(linkFlags & imageFileExtension_GmLinkFlag)) {
requestMedia_DocumentWidget_(d, linkId, 0);
}
}
}
/* Gempub page behavior and footer actions. */ {
/* TODO: move this to gempub.c */
delete_Gempub(d->sourceGempub);
d->sourceGempub = NULL;
if (!cmpCase_String(&d->sourceMime, "application/octet-stream") ||
!cmpCase_String(&d->sourceMime, mimeType_Gempub) ||
endsWithCase_String(d->mod.url, ".gpub")) {
iGempub *gempub = new_Gempub();
if (open_Gempub(gempub, &d->sourceContent)) {
setBaseUrl_Gempub(gempub, d->mod.url);
setSource_DocumentWidget(d, collect_String(coverPageSource_Gempub(gempub)));
setCStr_String(&d->sourceMime, mimeType_Gempub);
d->sourceGempub = gempub;
}
else {
delete_Gempub(gempub);
}
}
if (!d->sourceGempub) {
const iString *localPath = collect_String(localFilePathFromUrl_String(d->mod.url));
iBool isInside = iFalse;
if (localPath && !fileExists_FileInfo(localPath)) {
/* This URL may refer to a file inside the archive. */
localPath = findContainerArchive_Path(localPath);
isInside = iTrue;
}
if (localPath && equal_CStr(mediaType_Path(localPath), mimeType_Gempub)) {
iGempub *gempub = new_Gempub();
if (openFile_Gempub(gempub, localPath)) {
setBaseUrl_Gempub(gempub, collect_String(makeFileUrl_String(localPath)));
if (!isInside) {
setSource_DocumentWidget(d, collect_String(coverPageSource_Gempub(gempub)));
setCStr_String(&d->sourceMime, mimeType_Gempub);
}
d->sourceGempub = gempub;
}
else {
delete_Gempub(gempub);
}
}
}
if (d->sourceGempub) {
if (equal_String(d->mod.url, coverPageUrl_Gempub(d->sourceGempub))) {
if (!isRemote_Gempub(d->sourceGempub)) {
iArray *items = collectNew_Array(sizeof(iMenuItem));
pushBack_Array(
items,
&(iMenuItem){ book_Icon " ${gempub.cover.view}",
0,
0,
format_CStr("!open url:%s",
cstr_String(indexPageUrl_Gempub(d->sourceGempub))) });
if (navSize_Gempub(d->sourceGempub) > 0) {
pushBack_Array(
items,
&(iMenuItem){
format_CStr(forwardArrow_Icon " %s",
cstr_String(navLinkLabel_Gempub(d->sourceGempub, 0))),
SDLK_RIGHT,
0,
format_CStr("!open url:%s",
cstr_String(navLinkUrl_Gempub(d->sourceGempub, 0))) });
}
makeFooterButtons_DocumentWidget_(d, constData_Array(items), size_Array(items));
}
else {
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){ { book_Icon " ${menu.save.downloads.open}",
SDLK_s,
KMOD_PRIMARY | KMOD_SHIFT,
"document.save open:1" },
{ download_Icon " " saveToDownloads_Label,
SDLK_s,
KMOD_PRIMARY,
"document.save" } },
2);
}
if (preloadCoverImage_Gempub(d->sourceGempub, d->view.doc)) {
redoLayout_GmDocument(d->view.doc);
updateVisible_DocumentView_(&d->view);
invalidate_DocumentWidget_(d);
}
}
else if (equal_String(d->mod.url, indexPageUrl_Gempub(d->sourceGempub))) {
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){ { format_CStr(book_Icon " %s",
cstr_String(property_Gempub(d->sourceGempub,
title_GempubProperty))),
SDLK_LEFT,
0,
format_CStr("!open url:%s",
cstr_String(coverPageUrl_Gempub(d->sourceGempub))) } },
1);
}
else {
/* Navigation buttons. */
iArray *items = collectNew_Array(sizeof(iMenuItem));
const size_t navIndex = navIndex_Gempub(d->sourceGempub, d->mod.url);
if (navIndex != iInvalidPos) {
if (navIndex < navSize_Gempub(d->sourceGempub) - 1) {
pushBack_Array(
items,
&(iMenuItem){
format_CStr(forwardArrow_Icon " %s",
cstr_String(navLinkLabel_Gempub(d->sourceGempub, navIndex + 1))),
SDLK_RIGHT,
0,
format_CStr("!open url:%s",
cstr_String(navLinkUrl_Gempub(d->sourceGempub, navIndex + 1))) });
}
if (navIndex > 0) {
pushBack_Array(
items,
&(iMenuItem){
format_CStr(backArrow_Icon " %s",
cstr_String(navLinkLabel_Gempub(d->sourceGempub, navIndex - 1))),
SDLK_LEFT,
0,
format_CStr("!open url:%s",
cstr_String(navLinkUrl_Gempub(d->sourceGempub, navIndex - 1))) });
}
else if (!equalCase_String(d->mod.url, indexPageUrl_Gempub(d->sourceGempub))) {
pushBack_Array(
items,
&(iMenuItem){
format_CStr(book_Icon " %s",
cstr_String(property_Gempub(d->sourceGempub, title_GempubProperty))),
SDLK_LEFT,
0,
format_CStr("!open url:%s",
cstr_String(coverPageUrl_Gempub(d->sourceGempub))) });
}
}
if (!isEmpty_Array(items)) {
makeFooterButtons_DocumentWidget_(d, constData_Array(items), size_Array(items));
}
}
if (!isCached && prefs_App()->pinSplit &&
equal_String(d->mod.url, indexPageUrl_Gempub(d->sourceGempub))) {
const iString *navStart = navStartLinkUrl_Gempub(d->sourceGempub);
if (navStart) {
iWindow *win = get_Window();
/* Auto-split to show index and the first navigation link. */
if (numRoots_Window(win) == 2) {
/* This document is showing the index page. */
iRoot *other = otherRoot_Window(win, w->root);
postCommandf_Root(other, "open url:%s", cstr_String(navStart));
if (prefs_App()->pinSplit == 1 && w->root == win->roots[1]) {
/* On the wrong side. */
postCommand_App("ui.split swap:1");
}
}
else {
postCommandf_App(
"open splitmode:1 newtab:%d url:%s", otherRoot_OpenTabFlag, cstr_String(navStart));
}
}
}
}
}
}
static void updateDocument_DocumentWidget_(iDocumentWidget *d,
const iGmResponse *response,
iGmDocument *cachedDoc,
const iBool isInitialUpdate) {
if (d->state == ready_RequestState) {
return;
}
const iBool isRequestFinished = isFinished_GmRequest(d->request);
/* TODO: Do document update in the background. However, that requires a text metrics calculator
that does not try to cache the glyph bitmaps. */
const enum iGmStatusCode statusCode = response->statusCode;
if (category_GmStatusCode(statusCode) != categoryInput_GmStatusCode) {
iBool setSource = iTrue;
iString str;
invalidate_DocumentWidget_(d);
if (document_App() == d) {
updateTheme_DocumentWidget_(d);
}
clear_String(&d->sourceMime);
d->sourceTime = response->when;
d->view.drawBufs->flags |= updateTimestampBuf_DrawBufsFlag;
initBlock_String(&str, &response->body); /* Note: Body may be megabytes in size. */
if (isSuccess_GmStatusCode(statusCode)) {
/* Check the MIME type. */
iRangecc charset = range_CStr("utf-8");
enum iSourceFormat docFormat = undefined_SourceFormat;
const iString *mimeStr = collect_String(lower_String(&response->meta)); /* for convenience */
set_String(&d->sourceMime, mimeStr);
iRangecc mime = range_String(mimeStr);
iRangecc seg = iNullRange;
while (nextSplit_Rangecc(mime, ";", &seg)) {
iRangecc param = seg;
trim_Rangecc(¶m);
/* Detect fontpacks even if the server doesn't use the right media type. */
if (isRequestFinished && equal_Rangecc(param, "application/octet-stream")) {
if (detect_FontPack(&response->body)) {
param = range_CStr(mimeType_FontPack);
}
}
if (equal_Rangecc(param, "text/gemini")) {
docFormat = gemini_SourceFormat;
setRange_String(&d->sourceMime, param);
}
else if (equal_Rangecc(param, "text/markdown")) {
docFormat = markdown_SourceFormat;
setRange_String(&d->sourceMime, param);
}
else if (startsWith_Rangecc(param, "text/") ||
equal_Rangecc(param, "application/json") ||
equal_Rangecc(param, "application/x-pem-file") ||
equal_Rangecc(param, "application/pem-certificate-chain")) {
docFormat = plainText_SourceFormat;
setRange_String(&d->sourceMime, param);
}
else if (isRequestFinished && equal_Rangecc(param, "font/ttf")) {
clear_String(&str);
docFormat = gemini_SourceFormat;
setRange_String(&d->sourceMime, param);
format_String(&str, "# TrueType Font\n");
iString *decUrl = collect_String(urlDecode_String(d->mod.url));
iRangecc name = baseNameSep_Path(decUrl, "/");
iBool isInstalled = iFalse;
if (startsWith_String(collect_String(localFilePathFromUrl_String(d->mod.url)),
cstr_String(dataDir_App()))) {
isInstalled = iTrue;
}
appendCStr_String(&str, "## ");
appendRange_String(&str, name);
appendCStr_String(&str, "\n\n");
appendCStr_String(
&str, cstr_Lang(isInstalled ? "truetype.help.installed" : "truetype.help"));
appendCStr_String(&str, "\n");
if (!isInstalled) {
makeFooterButtons_DocumentWidget_(
d,
(iMenuItem[]){
{ add_Icon " ${fontpack.install.ttf}",
SDLK_RETURN,
0,
format_CStr("!fontpack.install ttf:1 name:%s",
cstr_Rangecc(name)) },
{ folder_Icon " ${fontpack.open.fontsdir}",
SDLK_d,
0,
format_CStr("!open url:%s/fonts",
cstrCollect_String(makeFileUrl_String(dataDir_App())))
}
}, 2);
}
}
else if (isRequestFinished &&
(equal_Rangecc(param, "application/zip") ||
(startsWith_Rangecc(param, "application/") &&
endsWithCase_Rangecc(param, "+zip")))) {
clear_String(&str);
docFormat = gemini_SourceFormat;
setRange_String(&d->sourceMime, param);
if (equal_Rangecc(param, mimeType_FontPack)) {
/* Show some information about fontpacks, and set up footer actions. */
iArchive *zip = iClob(new_Archive());
if (openData_Archive(zip, &response->body)) {
iFontPack *fp = new_FontPack();
setUrl_FontPack(fp, d->mod.url);
setStandalone_FontPack(fp, iTrue);
if (loadArchive_FontPack(fp, zip)) {
appendFormat_String(&str, "# " fontpack_Icon "%s\n%s",
cstr_String(id_FontPack(fp).id),
cstrCollect_String(infoText_FontPack(fp, iTrue)));
}
appendCStr_String(&str, "\n");
appendCStr_String(&str, cstr_Lang("fontpack.help"));
appendCStr_String(&str, "\n");
const iArray *actions = actions_FontPack(fp, iTrue);
makeFooterButtons_DocumentWidget_(d, constData_Array(actions),
size_Array(actions));
delete_FontPack(fp);
}
}
else {
format_String(&str, "# %s\n", zipPageHeading_(param));
appendFormat_String(&str,
cstr_Lang("doc.archive"),
cstr_Rangecc(baseName_Path(d->mod.url)));
appendCStr_String(&str, "\n");
}
appendCStr_String(&str, "\n");
iString *localPath = localFilePathFromUrl_String(d->mod.url);
if (!localPath) {
iString *key = collectNew_String();
toString_Sym(SDLK_s, KMOD_PRIMARY, key);
appendFormat_String(&str, "%s\n\n",
format_CStr(cstr_Lang("error.unsupported.suggestsave"),
cstr_String(key),
saveToDownloads_Label));
}
delete_String(localPath);
if (equalCase_Rangecc(urlScheme_String(d->mod.url), "file")) {
appendFormat_String(&str, "=> %s/ " folder_Icon " ${doc.archive.view}\n",
cstr_String(withSpacesEncoded_String(d->mod.url)));
}
translate_Lang(&str);
}
else if (startsWith_Rangecc(param, "image/") ||
startsWith_Rangecc(param, "audio/")) {
const iBool isAudio = startsWith_Rangecc(param, "audio/");
/* Make a simple document with an image or audio player. */
clear_String(&str);
docFormat = gemini_SourceFormat;
setRange_String(&d->sourceMime, param);
const iGmLinkId imgLinkId = 1; /* there's only the one link */
/* TODO: Do the image loading in `postProcessRequestContent_DocumentWidget_()` */
if ((isAudio && isInitialUpdate) || (!isAudio && isRequestFinished)) {
const char *linkTitle = cstr_Lang(
startsWith_String(mimeStr, "image/") ? "media.untitled.image"
: "media.untitled.audio");
iUrl parts;
init_Url(&parts, d->mod.url);
if (!isEmpty_Range(&parts.path)) {
linkTitle =
baseName_Path(collect_String(newRange_String(parts.path))).start;
}
format_String(&str, "=> %s %s\n",
cstr_String(canonicalUrl_String(d->mod.url)),
linkTitle);
setData_Media(media_GmDocument(d->view.doc),
imgLinkId,
mimeStr,
&response->body,
!isRequestFinished ? partialData_MediaFlag : 0);
redoLayout_GmDocument(d->view.doc);
}
else if (isAudio && !isInitialUpdate) {
/* Update the audio content. */
setData_Media(media_GmDocument(d->view.doc),
imgLinkId,
mimeStr,
&response->body,
!isRequestFinished ? partialData_MediaFlag : 0);
refresh_Widget(d);
setSource = iFalse;
}
else {
clear_String(&str);
}
}
else if (startsWith_Rangecc(param, "charset=")) {
charset = (iRangecc){ param.start + 8, param.end };
/* Remove whitespace and quotes. */
trim_Rangecc(&charset);
if (*charset.start == '"' && *charset.end == '"') {
charset.start++;
charset.end--;
}
}
}
if (docFormat == undefined_SourceFormat) {
if (isRequestFinished) {
d->flags &= ~drawDownloadCounter_DocumentWidgetFlag;
showErrorPage_DocumentWidget_(d, unsupportedMimeType_GmStatusCode, &response->meta);
deinit_String(&str);
return;
}
d->flags |= drawDownloadCounter_DocumentWidgetFlag;
clear_PtrSet(d->view.invalidRuns);
documentRunsInvalidated_DocumentWidget_(d);
deinit_String(&str);
return;
}
setFormat_GmDocument(d->view.doc, docFormat);
/* Convert the source to UTF-8 if needed. */
if (!equalCase_Rangecc(charset, "utf-8")) {
set_String(&str,
collect_String(decode_Block(&str.chars, cstr_Rangecc(charset))));
}
}
if (cachedDoc) {
replaceDocument_DocumentWidget_(d, cachedDoc);
updateWidth_DocumentView_(&d->view);
}
else if (setSource) {
setSource_DocumentWidget(d, &str);
}
deinit_String(&str);
}
}
static void fetch_DocumentWidget_(iDocumentWidget *d) {
iAssert(~d->flags & animationPlaceholder_DocumentWidgetFlag);
/* Forget the previous request. */
if (d->request) {
iRelease(d->request);
d->request = NULL;
}
postCommandf_Root(as_Widget(d)->root,
"document.request.started doc:%p url:%s",
d,
cstr_String(d->mod.url));
setLinkNumberMode_DocumentWidget_(d, iFalse);
d->flags &= ~drawDownloadCounter_DocumentWidgetFlag;
d->state = fetching_RequestState;
set_Atomic(&d->isRequestUpdated, iFalse);
d->request = new_GmRequest(certs_App());
setUrl_GmRequest(d->request, d->mod.url);
iConnect(GmRequest, d->request, updated, d, requestUpdated_DocumentWidget_);
iConnect(GmRequest, d->request, finished, d, requestFinished_DocumentWidget_);
submit_GmRequest(d->request);
}
static void updateTrust_DocumentWidget_(iDocumentWidget *d, const iGmResponse *response) {
if (response) {
d->certFlags = response->certFlags;
d->certExpiry = response->certValidUntil;
set_Block(d->certFingerprint, &response->certFingerprint);
set_String(d->certSubject, &response->certSubject);
}
iLabelWidget *lock = findChild_Widget(root_Widget(as_Widget(d)), "navbar.lock");
if (~d->certFlags & available_GmCertFlag) {
setFlags_Widget(as_Widget(lock), disabled_WidgetFlag, iTrue);
updateTextCStr_LabelWidget(lock, gray50_ColorEscape openLock_Icon);
return;
}
setFlags_Widget(as_Widget(lock), disabled_WidgetFlag, iFalse);
const iBool isDarkMode = isDark_ColorTheme(colorTheme_App());
if (~d->certFlags & domainVerified_GmCertFlag ||
~d->certFlags & trusted_GmCertFlag) {
updateTextCStr_LabelWidget(lock, red_ColorEscape warning_Icon);
}
else if (~d->certFlags & timeVerified_GmCertFlag) {
updateTextCStr_LabelWidget(lock, isDarkMode ? orange_ColorEscape warning_Icon
: black_ColorEscape warning_Icon);
}
else {
updateTextCStr_LabelWidget(lock, green_ColorEscape closedLock_Icon);
}
}
static void parseUser_DocumentWidget_(iDocumentWidget *d) {
setRange_String(d->titleUser, urlUser_String(d->mod.url));
}
static void cacheRunGlyphs_(void *data, const iGmRun *run) {
iUnused(data);
if (!isEmpty_Range(&run->text)) {
cache_Text(run->font, run->text);
}
}
static void cacheDocumentGlyphs_DocumentWidget_(const iDocumentWidget *d) {
if (isFinishedLaunching_App() && isExposed_Window(get_Window()) &&
~d->flags & animationPlaceholder_DocumentWidgetFlag) {
/* Just cache the top of the document, since this is what we usually need. */
int maxY = height_Widget(&d->widget) * 2;
if (maxY == 0) {
maxY = size_GmDocument(d->view.doc).y;
}
render_GmDocument(d->view.doc, (iRangei){ 0, maxY }, cacheRunGlyphs_, NULL);
}
}
static void addBannerWarnings_DocumentWidget_(iDocumentWidget *d) {
updateBanner_DocumentWidget_(d);
/* Warnings are not shown on internal pages. */
if (equalCase_Rangecc(urlScheme_String(d->mod.url), "about")) {
clear_Banner(d->banner);
return;
}
/* Warnings related to certificates and trust. */
const int certFlags = d->certFlags;
const int req = timeVerified_GmCertFlag | domainVerified_GmCertFlag | trusted_GmCertFlag;
if (certFlags & available_GmCertFlag && (certFlags & req) != req &&
numItems_Banner(d->banner) == 0) {
iString *title = collectNewCStr_String(cstr_Lang("dlg.certwarn.title"));
iString *str = collectNew_String();
if (certFlags & timeVerified_GmCertFlag && certFlags & domainVerified_GmCertFlag) {
iUrl parts;
init_Url(&parts, d->mod.url);
const iTime oldUntil =
domainValidUntil_GmCerts(certs_App(), parts.host, port_Url(&parts));
iDate exp;
init_Date(&exp, &oldUntil);
iTime now;
initCurrent_Time(&now);
const int days = secondsSince_Time(&oldUntil, &now) / 3600 / 24;
if (days <= 30) {
appendCStr_String(str,
format_CStr(cstrCount_Lang("dlg.certwarn.mayberenewed.n", days),
cstrCollect_String(format_Date(&exp, "%Y-%m-%d")),
days));
}
else {
appendCStr_String(str, cstr_Lang("dlg.certwarn.different"));
}
}
else if (certFlags & domainVerified_GmCertFlag) {
setCStr_String(title, get_GmError(tlsServerCertificateExpired_GmStatusCode)->title);
appendFormat_String(str, cstr_Lang("dlg.certwarn.expired"),
cstrCollect_String(format_Date(&d->certExpiry, "%Y-%m-%d")));
}
else if (certFlags & timeVerified_GmCertFlag) {
appendFormat_String(str, cstr_Lang("dlg.certwarn.domain"),
cstr_String(d->certSubject));
}
else {
appendCStr_String(str, cstr_Lang("dlg.certwarn.domain.expired"));
}
add_Banner(d->banner, warning_BannerType, none_GmStatusCode, title, str);
}
/* Warnings related to page contents. */
int dismissed =
value_SiteSpec(collectNewRange_String(urlRoot_String(d->mod.url)),
dismissWarnings_SiteSpecKey) |
(!prefs_App()->warnAboutMissingGlyphs ? missingGlyphs_GmDocumentWarning : 0);
/* File pages don't allow dismissing warnings, so skip it. */
if (equalCase_Rangecc(urlScheme_String(d->mod.url), "file")) {
dismissed |= ansiEscapes_GmDocumentWarning;
}
const int warnings = warnings_GmDocument(d->view.doc) & ~dismissed;
if (warnings & missingGlyphs_GmDocumentWarning) {
add_Banner(d->banner, warning_BannerType, missingGlyphs_GmStatusCode, NULL, NULL);
/* TODO: List one or more of the missing characters and/or their Unicode blocks? */
}
if (warnings & ansiEscapes_GmDocumentWarning) {
add_Banner(d->banner, warning_BannerType, ansiEscapes_GmStatusCode, NULL, NULL);
}
}
static void updateFromCachedResponse_DocumentWidget_(iDocumentWidget *d, float normScrollY,
const iGmResponse *resp, iGmDocument *cachedDoc) {
// iAssert(width_Widget(d) > 0); /* must be laid out by now */
setLinkNumberMode_DocumentWidget_(d, iFalse);
clear_ObjectList(d->media);
delete_Gempub(d->sourceGempub);
d->sourceGempub = NULL;
pauseAllPlayers_Media(media_GmDocument(d->view.doc), iTrue);
destroy_Widget(d->footerButtons);
d->footerButtons = NULL;
iRelease(d->view.doc);
d->view.doc = new_GmDocument();
d->state = fetching_RequestState;
d->flags |= fromCache_DocumentWidgetFlag;
/* Do the fetch. */ {
d->initNormScrollY = normScrollY;
/* Use the cached response data. */
updateTrust_DocumentWidget_(d, resp);
d->sourceTime = resp->when;
d->sourceStatus = success_GmStatusCode;
format_String(&d->sourceHeader, cstr_Lang("pageinfo.header.cached"));
set_Block(&d->sourceContent, &resp->body);
if (!cachedDoc) {
updateWidthAndRedoLayout_DocumentView_(&d->view);
}
updateDocument_DocumentWidget_(d, resp, cachedDoc, iTrue);
clear_Banner(d->banner);
updateBanner_DocumentWidget_(d);
addBannerWarnings_DocumentWidget_(d);
}
d->state = ready_RequestState;
postProcessRequestContent_DocumentWidget_(d, iTrue);
resetScroll_DocumentView_(&d->view);
init_Anim(&d->view.scrollY.pos, d->initNormScrollY * pageHeight_DocumentView_(&d->view));
updateVisible_DocumentView_(&d->view);
moveSpan_SmoothScroll(&d->view.scrollY, 0, 0); /* clamp position to new max */
updateSideOpacity_DocumentView_(&d->view, iFalse);
cacheDocumentGlyphs_DocumentWidget_(d);
d->view.drawBufs->flags |= updateTimestampBuf_DrawBufsFlag | updateSideBuf_DrawBufsFlag;
d->flags &= ~(urlChanged_DocumentWidgetFlag | drawDownloadCounter_DocumentWidgetFlag);
postCommandf_Root(
as_Widget(d)->root, "document.changed doc:%p url:%s", d, cstr_String(d->mod.url));
}
static iBool updateFromHistory_DocumentWidget_(iDocumentWidget *d) {
const iRecentUrl *recent = constMostRecentUrl_History(d->mod.history);
if (recent && recent->cachedResponse && equalCase_String(&recent->url, d->mod.url)) {
updateFromCachedResponse_DocumentWidget_(
d, recent->normScrollY, recent->cachedResponse, recent->cachedDoc);
if (!recent->cachedDoc) {
/* We have a cached copy now. */
setCachedDocument_History(d->mod.history, d->view.doc);
}
return iTrue;
}
else if (!isEmpty_String(d->mod.url)) {
fetch_DocumentWidget_(d);
}
if (recent) {
/* Retain scroll position in refetched content as well. */
d->initNormScrollY = recent->normScrollY;
}
return iFalse;
}
static void refreshWhileScrolling_DocumentWidget_(iAny *ptr) {
iAssert(isInstance_Object(ptr, &Class_DocumentWidget));
iDocumentWidget *d = ptr;
iDocumentView *view = &d->view;
updateVisible_DocumentView_(view);
refresh_Widget(d);
if (view->animWideRunId) {
for (const iGmRun *r = view->animWideRunRange.start; r != view->animWideRunRange.end; r++) {
insert_PtrSet(view->invalidRuns, r);
}
}
if (isFinished_Anim(&view->animWideRunOffset)) {
view->animWideRunId = 0;
}
if (!isFinished_SmoothScroll(&view->scrollY) || !isFinished_Anim(&view->animWideRunOffset)) {
addTicker_App(refreshWhileScrolling_DocumentWidget_, d);
}
if (isFinished_SmoothScroll(&view->scrollY)) {
iChangeFlags(d->flags, noHoverWhileScrolling_DocumentWidgetFlag, iFalse);
updateHover_DocumentView_(view, mouseCoord_Window(get_Window(), 0));
}
}
static void scrollBegan_DocumentWidget_(iAnyObject *any, int offset, uint32_t duration) {
iDocumentWidget *d = any;
/* Get rid of link numbers when scrolling. */
if (offset && d->flags & showLinkNumbers_DocumentWidgetFlag) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
invalidateVisibleLinks_DocumentView_(&d->view);
}
/* Show and hide toolbar on scroll. */
if (deviceType_App() == phone_AppDeviceType) {
const float normPos = normScrollPos_DocumentView_(&d->view);
if (prefs_App()->hideToolbarOnScroll && iAbs(offset) > 5 && normPos >= 0) {
showToolbar_Root(as_Widget(d)->root, offset < 0);
}
}
updateVisible_DocumentView_(&d->view);
refresh_Widget(as_Widget(d));
if (duration > 0) {
iChangeFlags(d->flags, noHoverWhileScrolling_DocumentWidgetFlag, iTrue);
addTicker_App(refreshWhileScrolling_DocumentWidget_, d);
}
}
static void togglePreFold_DocumentWidget_(iDocumentWidget *d, uint16_t preId) {
d->view.hoverPre = NULL;
d->view.hoverAltPre = NULL;
d->selectMark = iNullRange;
foldPre_GmDocument(d->view.doc, preId);
redoLayout_GmDocument(d->view.doc);
clampScroll_DocumentView_(&d->view);
updateHover_DocumentView_(&d->view, mouseCoord_Window(get_Window(), 0));
invalidate_DocumentWidget_(d);
refresh_Widget(as_Widget(d));
}
static iString *makeQueryUrl_DocumentWidget_(const iDocumentWidget *d,
const iString *userEnteredText) {
iString *url = copy_String(d->mod.url);
/* Remove the existing query string. */
const size_t qPos = indexOfCStr_String(url, "?");
if (qPos != iInvalidPos) {
remove_Block(&url->chars, qPos, iInvalidSize);
}
appendCStr_String(url, "?");
iString *cleaned = copy_String(userEnteredText);
if (deviceType_App() != desktop_AppDeviceType) {
trimEnd_String(cleaned); /* autocorrect may insert an extra space */
if (isEmpty_String(cleaned)) {
set_String(cleaned, userEnteredText); /* user wanted just spaces? */
}
}
append_String(url, collect_String(urlEncode_String(cleaned)));
delete_String(cleaned);
return url;
}
static void inputQueryValidator_(iInputWidget *input, void *context) {
iDocumentWidget *d = context;
iString *url = makeQueryUrl_DocumentWidget_(d, text_InputWidget(input));
iWidget *dlg = parent_Widget(input);
iLabelWidget *counter = findChild_Widget(dlg, "valueinput.counter");
iAssert(counter);
int avail = 1024 - (int) size_String(url);
setFlags_Widget(findChild_Widget(dlg, "default"), disabled_WidgetFlag, avail < 0);
setEnterKeyEnabled_InputWidget(input, avail >= 0);
int len = length_String(text_InputWidget(input));
if (len > 1024) {
iString *trunc = copy_String(text_InputWidget(input));
truncate_String(trunc, 1024);
setText_InputWidget(input, trunc);
delete_String(trunc);
}
setTextCStr_LabelWidget(counter, format_CStr("%d", avail)); /* Gemini URL maxlen */
setTextColor_LabelWidget(counter,
avail < 0 ? uiTextCaution_ColorId :
avail < 128 ? uiTextStrong_ColorId
: uiTextDim_ColorId);
delete_String(url);
arrange_Widget(findChild_Widget(dlg, "dialogbuttons"));
}
static const char *humanReadableStatusCode_(enum iGmStatusCode code) {
if (code <= 0) {
return "";
}
return format_CStr("%d ", code);
}
static void setUrl_DocumentWidget_(iDocumentWidget *d, const iString *url) {
url = canonicalUrl_String(url);
if (!equal_String(d->mod.url, url)) {
d->flags |= urlChanged_DocumentWidgetFlag;
set_String(d->mod.url, url);
}
}
static void checkResponse_DocumentWidget_(iDocumentWidget *d) {
if (!d->request) {
return;
}
enum iGmStatusCode statusCode = status_GmRequest(d->request);
if (statusCode == none_GmStatusCode) {
return;
}
iGmResponse *resp = lockResponse_GmRequest(d->request);
if (d->state == fetching_RequestState) {
/* Under certain conditions, inline any image response into the current document. */
if (d->requestLinkId &&
isSuccess_GmStatusCode(d->sourceStatus) &&
startsWithCase_String(&d->sourceMime, "text/gemini") &&
isSuccess_GmStatusCode(statusCode) &&
startsWithCase_String(&resp->meta, "image/")) {
/* This request is turned into a new media request in the current document. */
iDisconnect(GmRequest, d->request, updated, d, requestUpdated_DocumentWidget_);
iDisconnect(GmRequest, d->request, finished, d, requestFinished_DocumentWidget_);
iMediaRequest *mr = newReused_MediaRequest(d, d->requestLinkId, d->request);
unlockResponse_GmRequest(d->request);
d->request = NULL; /* ownership moved */
postCommand_Widget(d, "document.request.cancelled doc:%p", d);
pushBack_ObjectList(d->media, mr);
iRelease(mr);
/* Reset the fetch state, returning to the originating page. */
d->state = ready_RequestState;
if (equal_String(&mostRecentUrl_History(d->mod.history)->url, url_GmRequest(mr->req))) {
undo_History(d->mod.history);
}
setUrl_DocumentWidget_(d, url_GmDocument(d->view.doc));
updateFetchProgress_DocumentWidget_(d);
postCommand_Widget(d, "media.updated link:%u request:%p", d->requestLinkId, mr);
if (isFinished_GmRequest(mr->req)) {
postCommand_Widget(d, "media.finished link:%u request:%p", d->requestLinkId, mr);
}
return;
}
/* Get ready for the incoming new document. */
d->state = receivedPartialResponse_RequestState;
d->flags &= ~fromCache_DocumentWidgetFlag;
clear_ObjectList(d->media);
updateTrust_DocumentWidget_(d, resp);
if (isSuccess_GmStatusCode(statusCode)) {
clear_Banner(d->banner);
updateTheme_DocumentWidget_(d);
}
if (~d->certFlags & trusted_GmCertFlag &&
isSuccess_GmStatusCode(statusCode) &&
equalCase_Rangecc(urlScheme_String(d->mod.url), "gemini")) {
statusCode = tlsServerCertificateNotVerified_GmStatusCode;
}
init_Anim(&d->view.sideOpacity, 0);
init_Anim(&d->view.altTextOpacity, 0);
format_String(&d->sourceHeader,
"%s%s",
humanReadableStatusCode_(statusCode),
isEmpty_String(&resp->meta) && !isSuccess_GmStatusCode(statusCode)
? get_GmError(statusCode)->title
: cstr_String(&resp->meta));
d->sourceStatus = statusCode;
switch (category_GmStatusCode(statusCode)) {
case categoryInput_GmStatusCode: {
/* Let the navigation history know that we have been to this URL even though
it is only displayed as an input dialog. */
visitUrl_Visited(visited_App(), d->mod.url, transient_VisitedUrlFlag);
iUrl parts;
init_Url(&parts, d->mod.url);
iWidget *dlg = makeValueInput_Widget(
as_Widget(d),
NULL,
format_CStr(uiHeading_ColorEscape "%s", cstr_Rangecc(parts.host)),
isEmpty_String(&resp->meta)
? format_CStr(cstr_Lang("dlg.input.prompt"), cstr_Rangecc(parts.path))
: cstr_String(&resp->meta),
uiTextCaution_ColorEscape "${dlg.input.send}",
format_CStr("!document.input.submit doc:%p", d));
iWidget *buttons = findChild_Widget(dlg, "dialogbuttons");
iLabelWidget *lineBreak = NULL;
if (statusCode != sensitiveInput_GmStatusCode) {
/* The line break and URL length counters are positioned differently on mobile.
There is no line breaks in sensitive input. */
if (deviceType_App() == desktop_AppDeviceType) {
iString *keyStr = collectNew_String();
toString_Sym(SDLK_RETURN,
lineBreakKeyMod_ReturnKeyBehavior(prefs_App()->returnKey),
keyStr);
lineBreak = new_LabelWidget(
format_CStr("${dlg.input.linebreak}" uiTextAction_ColorEscape " %s",
cstr_String(keyStr)),
NULL);
insertChildAfter_Widget(buttons, iClob(lineBreak), 0);
}
if (lineBreak) {
setFlags_Widget(as_Widget(lineBreak), frameless_WidgetFlag, iTrue);
setTextColor_LabelWidget(lineBreak, uiTextDim_ColorId);
}
}
iWidget *counter = (iWidget *) new_LabelWidget("", NULL);
setId_Widget(counter, "valueinput.counter");
setFlags_Widget(counter, frameless_WidgetFlag | resizeToParentHeight_WidgetFlag, iTrue);
if (deviceType_App() == desktop_AppDeviceType) {
addChildPos_Widget(buttons, iClob(counter), front_WidgetAddPos);
}
else {
insertChildAfter_Widget(buttons, iClob(counter), 1);
}
if (lineBreak && deviceType_App() != desktop_AppDeviceType) {
addChildPos_Widget(buttons, iClob(lineBreak), front_WidgetAddPos);
}
/* Menu for additional actions, past entries. */ {
iMenuItem items[] = { { "${menu.input.precedingline}",
SDLK_v,
KMOD_PRIMARY | KMOD_SHIFT,
format_CStr("!valueinput.set ptr:%p text:%s",
buttons,
cstr_String(&d->linePrecedingLink)) } };
iLabelWidget *menu = makeMenuButton_LabelWidget(midEllipsis_Icon, items, 1);
if (deviceType_App() == desktop_AppDeviceType) {
addChildPos_Widget(buttons, iClob(menu), front_WidgetAddPos);
}
else {
insertChildAfterFlags_Widget(buttons, iClob(menu), 0,
frameless_WidgetFlag | noBackground_WidgetFlag);
setFont_LabelWidget(menu, font_LabelWidget((iLabelWidget *) lastChild_Widget(buttons)));
setTextColor_LabelWidget(menu, uiTextAction_ColorId);
}
}
setValidator_InputWidget(findChild_Widget(dlg, "input"), inputQueryValidator_, d);
setSensitiveContent_InputWidget(findChild_Widget(dlg, "input"),
statusCode == sensitiveInput_GmStatusCode);
if (document_App() != d) {
postCommandf_App("tabs.switch page:%p", d);
}
else {
updateTheme_DocumentWidget_(d);
}
break;
}
case categorySuccess_GmStatusCode:
if (d->flags & urlChanged_DocumentWidgetFlag) {
/* Keep scroll position when reloading the same page. */
resetScroll_DocumentView_(&d->view);
}
d->view.scrollY.pullActionTriggered = 0;
pauseAllPlayers_Media(media_GmDocument(d->view.doc), iTrue);
iReleasePtr(&d->view.doc); /* new content incoming */
delete_Gempub(d->sourceGempub);
d->sourceGempub = NULL;
destroy_Widget(d->footerButtons);
d->footerButtons = NULL;
d->view.doc = new_GmDocument();
resetWideRuns_DocumentView_(&d->view);
updateDocument_DocumentWidget_(d, resp, NULL, iTrue);
break;
case categoryRedirect_GmStatusCode:
if (isEmpty_String(&resp->meta)) {
showErrorPage_DocumentWidget_(d, invalidRedirect_GmStatusCode, NULL);
}
else {
/* Only accept redirects that use gemini scheme. */
const iString *dstUrl = absoluteUrl_String(d->mod.url, &resp->meta);
const iRangecc srcScheme = urlScheme_String(d->mod.url);
const iRangecc dstScheme = urlScheme_String(dstUrl);
if (d->redirectCount >= 5) {
showErrorPage_DocumentWidget_(d, tooManyRedirects_GmStatusCode, dstUrl);
}
/* Redirects with the same scheme are automatic, and switching automatically
between "gemini" and "titan" is allowed. */
else if (equalRangeCase_Rangecc(dstScheme, srcScheme) ||
(equalCase_Rangecc(srcScheme, "titan") &&
equalCase_Rangecc(dstScheme, "gemini")) ||
(equalCase_Rangecc(srcScheme, "gemini") &&
equalCase_Rangecc(dstScheme, "titan"))) {
visitUrl_Visited(visited_App(), d->mod.url, transient_VisitedUrlFlag);
postCommandf_Root(as_Widget(d)->root,
"open doc:%p redirect:%d url:%s", d, d->redirectCount + 1, cstr_String(dstUrl));
}
else {
/* Scheme changes must be manually approved. */
showErrorPage_DocumentWidget_(d, schemeChangeRedirect_GmStatusCode, dstUrl);
}
unlockResponse_GmRequest(d->request);
iReleasePtr(&d->request);
}
break;
default:
if (isDefined_GmError(statusCode)) {
showErrorPage_DocumentWidget_(d, statusCode, &resp->meta);
}
else if (category_GmStatusCode(statusCode) ==
categoryTemporaryFailure_GmStatusCode) {
showErrorPage_DocumentWidget_(
d, temporaryFailure_GmStatusCode, &resp->meta);
}
else if (category_GmStatusCode(statusCode) ==
categoryPermanentFailure_GmStatusCode) {
showErrorPage_DocumentWidget_(
d, permanentFailure_GmStatusCode, &resp->meta);
}
else {
showErrorPage_DocumentWidget_(d, unknownStatusCode_GmStatusCode, &resp->meta);
}
break;
}
}
else if (d->state == receivedPartialResponse_RequestState) {
d->flags &= ~fromCache_DocumentWidgetFlag;
switch (category_GmStatusCode(statusCode)) {
case categorySuccess_GmStatusCode:
/* More content available. */
updateDocument_DocumentWidget_(d, resp, NULL, iFalse);
break;
default:
break;
}
}
unlockResponse_GmRequest(d->request);
}
static void removeMediaRequest_DocumentWidget_(iDocumentWidget *d, iGmLinkId linkId) {
iForEach(ObjectList, i, d->media) {
iMediaRequest *req = (iMediaRequest *) i.object;
if (req->linkId == linkId) {
remove_ObjectListIterator(&i);
break;
}
}
}
static iBool requestMedia_DocumentWidget_(iDocumentWidget *d, iGmLinkId linkId, iBool enableFilters) {
if (!findMediaRequest_DocumentWidget_(d, linkId)) {
const iString *mediaUrl = absoluteUrl_String(d->mod.url, linkUrl_GmDocument(d->view.doc, linkId));
pushBack_ObjectList(d->media, iClob(new_MediaRequest(d, linkId, mediaUrl, enableFilters)));
invalidate_DocumentWidget_(d);
return iTrue;
}
return iFalse;
}
static iBool isDownloadRequest_DocumentWidget(const iDocumentWidget *d, const iMediaRequest *req) {
return findMediaForLink_Media(constMedia_GmDocument(d->view.doc), req->linkId, download_MediaType).type != 0;
}
static iBool handleMediaCommand_DocumentWidget_(iDocumentWidget *d, const char *cmd) {
iMediaRequest *req = pointerLabel_Command(cmd, "request");
iBool isOurRequest = iFalse;
/* This request may already be deleted so treat the pointer with caution. */
iConstForEach(ObjectList, m, d->media) {
if (m.object == req) {
isOurRequest = iTrue;
break;
}
}
if (!isOurRequest) {
return iFalse;
}
if (equal_Command(cmd, "media.updated")) {
/* Pass new data to media players. */
const enum iGmStatusCode code = status_GmRequest(req->req);
if (isSuccess_GmStatusCode(code)) {
iGmResponse *resp = lockResponse_GmRequest(req->req);
if (isDownloadRequest_DocumentWidget(d, req) ||
startsWith_String(&resp->meta, "audio/")) {
/* TODO: Use a helper? This is same as below except for the partialData flag. */
if (setData_Media(media_GmDocument(d->view.doc),
req->linkId,
&resp->meta,
&resp->body,
partialData_MediaFlag | allowHide_MediaFlag)) {
redoLayout_GmDocument(d->view.doc);
}
updateVisible_DocumentView_(&d->view);
invalidate_DocumentWidget_(d);
refresh_Widget(as_Widget(d));
}
unlockResponse_GmRequest(req->req);
}
/* Update the link's progress. */
invalidateLink_DocumentView_(&d->view, req->linkId);
refresh_Widget(d);
return iTrue;
}
else if (equal_Command(cmd, "media.finished")) {
const enum iGmStatusCode code = status_GmRequest(req->req);
/* Give the media to the document for presentation. */
if (isSuccess_GmStatusCode(code)) {
if (isDownloadRequest_DocumentWidget(d, req) ||
startsWith_String(meta_GmRequest(req->req), "image/") ||
startsWith_String(meta_GmRequest(req->req), "audio/")) {
setData_Media(media_GmDocument(d->view.doc),
req->linkId,
meta_GmRequest(req->req),
body_GmRequest(req->req),
allowHide_MediaFlag);
redoLayout_GmDocument(d->view.doc);
iZap(d->view.visibleRuns); /* pointers invalidated */
updateVisible_DocumentView_(&d->view);
invalidate_DocumentWidget_(d);
refresh_Widget(as_Widget(d));
}
}
else {
const iGmError *err = get_GmError(code);
makeSimpleMessage_Widget(format_CStr(uiTextCaution_ColorEscape "%s", err->title), err->info);
removeMediaRequest_DocumentWidget_(d, req->linkId);
}
return iTrue;
}
return iFalse;
}
static iBool fetchNextUnfetchedImage_DocumentWidget_(iDocumentWidget *d) {
iConstForEach(PtrArray, i, &d->view.visibleLinks) {
const iGmRun *run = i.ptr;
if (run->linkId && run->mediaType == none_MediaType &&
~run->flags & decoration_GmRunFlag) {
const int linkFlags = linkFlags_GmDocument(d->view.doc, run->linkId);
if (isMediaLink_GmDocument(d->view.doc, run->linkId) &&
linkFlags & imageFileExtension_GmLinkFlag &&
~linkFlags & content_GmLinkFlag && ~linkFlags & permanent_GmLinkFlag ) {
if (requestMedia_DocumentWidget_(d, run->linkId, iTrue)) {
return iTrue;
}
}
}
}
return iFalse;
}
static iBool saveToFile_(const iString *savePath, const iBlock *content, iBool showDialog) {
iBool ok = iFalse;
/* Write the file. */ {
iFile *f = new_File(savePath);
if (open_File(f, writeOnly_FileMode)) {
write_File(f, content);
close_File(f);
const size_t size = size_Block(content);
const iBool isMega = size >= 1000000;
#if defined (iPlatformAppleMobile)
exportDownloadedFile_iOS(savePath);
#else
if (showDialog) {
const iMenuItem items[2] = {
{ "${dlg.save.opendownload}", 0, 0,
format_CStr("!open url:%s", cstrCollect_String(makeFileUrl_String(savePath))) },
{ "${dlg.message.ok}", 0, 0, "message.ok" },
};
makeMessage_Widget(uiHeading_ColorEscape "${heading.save}",
format_CStr("%s\n${dlg.save.size} %.3f %s",
cstr_String(path_File(f)),
isMega ? size / 1.0e6f : (size / 1.0e3f),
isMega ? "${mb}" : "${kb}"),
items,
iElemCount(items));
}
#endif
ok = iTrue;
}
else {
makeSimpleMessage_Widget(uiTextCaution_ColorEscape "${heading.save.error}",
strerror(errno));
}
iRelease(f);
}
return ok;
}
static const iString *saveToDownloads_(const iString *url, const iString *mime, const iBlock *content,
iBool showDialog) {
const iString *savePath = downloadPathForUrl_App(url, mime);
if (!saveToFile_(savePath, content, showDialog)) {
return collectNew_String();
}
return savePath;
}
static void addAllLinks_(void *context, const iGmRun *run) {
iPtrArray *links = context;
if (~run->flags & decoration_GmRunFlag && run->linkId) {
pushBack_PtrArray(links, run);
}
}
static iBool handlePinch_DocumentWidget_(iDocumentWidget *d, const char *cmd) {
if (equal_Command(cmd, "pinch.began")) {
d->pinchZoomInitial = d->pinchZoomPosted = prefs_App()->zoomPercent;
d->flags |= pinchZoom_DocumentWidgetFlag;
refresh_Widget(d);
}
else if (equal_Command(cmd, "pinch.moved")) {
const float rel = argf_Command(cmd);
int zoom = iRound(d->pinchZoomInitial * rel / 5.0f) * 5;
zoom = iClamp(zoom, 50, 200);
if (d->pinchZoomPosted != zoom) {
#if defined (iPlatformAppleMobile)
if (zoom == 100) {
playHapticEffect_iOS(tap_HapticEffect);
}
#endif
d->pinchZoomPosted = zoom;
postCommandf_App("zoom.set arg:%d", zoom);
}
}
else if (equal_Command(cmd, "pinch.ended")) {
d->flags &= ~pinchZoom_DocumentWidgetFlag;
refresh_Widget(d);
}
return iTrue;
}
static void swap_DocumentWidget_(iDocumentWidget *d, iGmDocument *doc,
iDocumentWidget *swapBuffersWith) {
if (doc) {
iAssert(isInstance_Object(doc, &Class_GmDocument));
replaceDocument_DocumentWidget_(d, doc);
iSwap(iBanner *, d->banner, swapBuffersWith->banner);
setOwner_Banner(d->banner, d);
setOwner_Banner(swapBuffersWith->banner, swapBuffersWith);
swap_DocumentView_(&d->view, &swapBuffersWith->view);
// invalidate_DocumentWidget_(swapBuffersWith);
}
}
static iWidget *swipeParent_DocumentWidget_(iDocumentWidget *d) {
return findChild_Widget(as_Widget(d)->root->widget, "doctabs");
}
static void setupSwipeOverlay_DocumentWidget_(iDocumentWidget *d, iWidget *overlay) {
iWidget *w = as_Widget(d);
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
/* The target takes the old document and jumps on top. */
overlay->rect.pos = windowToInner_Widget(swipeParent, innerToWindow_Widget(w, zero_I2()));
/* Note: `innerToWindow_Widget` does not apply visual offset. */
overlay->rect.size = w->rect.size;
setFlags_Widget(overlay, fixedPosition_WidgetFlag | fixedSize_WidgetFlag, iTrue);
// swap_DocumentWidget_(target, d->doc, d);
setFlags_Widget(as_Widget(d), refChildrenOffset_WidgetFlag, iTrue);
as_Widget(d)->offsetRef = swipeParent;
/* `overlay` animates off the screen to the right. */
const int fromPos = value_Anim(&w->visualOffset);
const int toPos = width_Widget(overlay);
setVisualOffset_Widget(overlay, fromPos, 0, 0);
/* Bigger screen, faster swipes. */
if (deviceType_App() == desktop_AppDeviceType) {
setVisualOffset_Widget(overlay, toPos, 250, easeOut_AnimFlag | softer_AnimFlag);
}
else {
const float devFactor = (deviceType_App() == phone_AppDeviceType ? 1.0f : 2.0f);
float swipe = iClamp(d->swipeSpeed, devFactor * 400, devFactor * 1000) * gap_UI;
uint32_t span = ((toPos - fromPos) / swipe) * 1000;
// printf("from:%d to:%d swipe:%f span:%u\n", fromPos, toPos, d->swipeSpeed, span);
setVisualOffset_Widget(overlay, toPos, span, deviceType_App() == tablet_AppDeviceType ?
easeOut_AnimFlag : 0);
}
setVisualOffset_Widget(w, 0, 0, 0);
}
static iBool handleSwipe_DocumentWidget_(iDocumentWidget *d, const char *cmd) {
/* TODO: Cleanup
If DocumentWidget is refactored to split the document presentation from state
and request management (a new DocumentView class), plain views could be used for this
animation without having to mess with the complete state of the DocumentWidget. That
seems like a less error-prone approach -- the current implementation will likely break
down (again) if anything is changed in the document internals.
*/
iWidget *w = as_Widget(d);
/* The swipe animation is implemented in a rather complex way. It utilizes both cached
GmDocument content and temporary underlay/overlay DocumentWidgets. Depending on the
swipe direction, the DocumentWidget `d` may wait until the finger is released to actually
perform the navigation action. */
if (equal_Command(cmd, "edgeswipe.moved")) {
//printf("[%p] responds to edgeswipe.moved\n", d);
as_Widget(d)->offsetRef = NULL;
const int side = argLabel_Command(cmd, "side");
const int offset = arg_Command(cmd);
if (side == 1) { /* left edge */
if (atOldest_History(d->mod.history)) {
return iTrue;
}
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
if (findChild_Widget(swipeParent, "swipeout")) {
return iTrue; /* too fast, previous animation hasn't finished */
}
/* The temporary "swipein" will display the previous page until the finger is lifted. */
iDocumentWidget *swipeIn = findChild_Widget(swipeParent, "swipein");
if (!swipeIn) {
swipeIn = new_DocumentWidget();
swipeIn->flags |= animationPlaceholder_DocumentWidgetFlag;
setId_Widget(as_Widget(swipeIn), "swipein");
setFlags_Widget(as_Widget(swipeIn),
disabled_WidgetFlag | refChildrenOffset_WidgetFlag |
fixedPosition_WidgetFlag | fixedSize_WidgetFlag, iTrue);
setFlags_Widget(findChild_Widget(as_Widget(swipeIn), "scroll"), hidden_WidgetFlag, iTrue);
swipeIn->widget.rect.pos = windowToInner_Widget(swipeParent, localToWindow_Widget(w, w->rect.pos));
swipeIn->widget.rect.size = d->widget.rect.size;
swipeIn->widget.offsetRef = parent_Widget(w);
/* Use a cached document for the layer underneath. */ {
lock_History(d->mod.history);
iRecentUrl *recent = precedingLocked_History(d->mod.history);
if (recent && recent->cachedResponse) {
setUrl_DocumentWidget_(swipeIn, &recent->url);
updateFromCachedResponse_DocumentWidget_(swipeIn,
recent->normScrollY,
recent->cachedResponse,
recent->cachedDoc);
parseUser_DocumentWidget_(swipeIn);
updateBanner_DocumentWidget_(swipeIn);
}
else {
setUrlAndSource_DocumentWidget(swipeIn, &recent->url,
collectNewCStr_String("text/gemini"),
collect_Block(new_Block(0)));
}
unlock_History(d->mod.history);
}
addChildPos_Widget(swipeParent, iClob(swipeIn), front_WidgetAddPos);
}
}
if (side == 2) { /* right edge */
if (offset < -get_Window()->pixelRatio * 10) {
int animSpan = 10;
if (!atNewest_History(d->mod.history) && ~flags_Widget(w) & dragged_WidgetFlag) {
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
if (findChild_Widget(swipeParent, "swipeout")) {
return iTrue; /* too fast, previous animation hasn't finished */
}
/* Setup the drag. `d` will be moving with the finger. */
animSpan = 0;
postCommand_Widget(d, "navigate.forward");
setFlags_Widget(w, dragged_WidgetFlag, iTrue);
/* Set up the swipe dummy. */
iDocumentWidget *target = new_DocumentWidget();
target->flags |= animationPlaceholder_DocumentWidgetFlag;
setId_Widget(as_Widget(target), "swipeout");
/* "swipeout" takes `d`'s document and goes underneath. */
target->widget.rect.pos = windowToInner_Widget(swipeParent, localToWindow_Widget(w, w->rect.pos));
target->widget.rect.size = d->widget.rect.size;
setFlags_Widget(as_Widget(target), fixedPosition_WidgetFlag | fixedSize_WidgetFlag, iTrue);
swap_DocumentWidget_(target, d->view.doc, d);
addChildPos_Widget(swipeParent, iClob(target), front_WidgetAddPos);
setFlags_Widget(as_Widget(target), refChildrenOffset_WidgetFlag, iTrue);
as_Widget(target)->offsetRef = parent_Widget(w);
/* Mark it for deletion after animation finishes. */
destroy_Widget(as_Widget(target));
/* The `d` document will now navigate forward and be replaced with a cached
copy. However, if a cached response isn't available, we'll need to show a
blank page. */
setUrlAndSource_DocumentWidget(d,
collectNewCStr_String("about:blank"),
collectNewCStr_String("text/gemini"),
collect_Block(new_Block(0)));
}
if (flags_Widget(w) & dragged_WidgetFlag) {
setVisualOffset_Widget(w, width_Widget(w) +
width_Widget(d) * offset / size_Root(w->root).x,
animSpan, 0);
}
else {
setVisualOffset_Widget(w, offset / 4, animSpan, 0);
}
}
return iTrue;
}
}
if (equal_Command(cmd, "edgeswipe.ended") && argLabel_Command(cmd, "side") == 2) {
if (argLabel_Command(cmd, "abort") && flags_Widget(w) & dragged_WidgetFlag) {
setFlags_Widget(w, dragged_WidgetFlag, iFalse);
postCommand_Widget(d, "navigate.back");
/* We must now undo the swap that was done when the drag started. */
/* TODO: Currently not animated! What exactly is the appropriate thing to do here? */
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
iDocumentWidget *swipeOut = findChild_Widget(swipeParent, "swipeout");
swap_DocumentWidget_(d, swipeOut->view.doc, swipeOut);
// const int visOff = visualOffsetByReference_Widget(w);
w->offsetRef = NULL;
// setVisualOffset_Widget(w, visOff, 0, 0);
// setVisualOffset_Widget(w, 0, 150, 0);
setVisualOffset_Widget(w, 0, 0, 0);
/* Make it an overlay instead. */
// removeChild_Widget(swipeParent, swipeOut);
// addChildPos_Widget(swipeParent, iClob(swipeOut), back_WidgetAddPos);
// setupSwipeOverlay_DocumentWidget_(d, as_Widget(swipeOut));
return iTrue;
}
iAssert(~d->flags & animationPlaceholder_DocumentWidgetFlag);
setFlags_Widget(w, dragged_WidgetFlag, iFalse);
setVisualOffset_Widget(w, 0, 250, easeOut_AnimFlag | softer_AnimFlag);
return iTrue;
}
if (equal_Command(cmd, "edgeswipe.ended") && argLabel_Command(cmd, "side") == 1) {
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
iDocumentWidget *swipeIn = findChild_Widget(swipeParent, "swipein");
d->swipeSpeed = argLabel_Command(cmd, "speed") / gap_UI;
/* "swipe.back" will soon follow. The `d` document will do the actual back navigation,
switching immediately to a cached page. However, if one is not available, we'll need
to show a blank page for a while. */
if (swipeIn) {
if (!argLabel_Command(cmd, "abort")) {
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
/* What was being shown in the `d` document is now being swapped to
the outgoing page animation. */
iDocumentWidget *target = new_DocumentWidget();
target->flags |= animationPlaceholder_DocumentWidgetFlag;
addChildPos_Widget(swipeParent, iClob(target), back_WidgetAddPos);
setId_Widget(as_Widget(target), "swipeout");
setFlags_Widget(as_Widget(target), disabled_WidgetFlag, iTrue);
swap_DocumentWidget_(target, d->view.doc, d);
setUrlAndSource_DocumentWidget(d,
swipeIn->mod.url,
collectNewCStr_String("text/gemini"),
collect_Block(new_Block(0)));
as_Widget(swipeIn)->offsetRef = NULL;
}
destroy_Widget(as_Widget(swipeIn));
}
}
if (equal_Command(cmd, "swipe.back")) {
iWidget *swipeParent = swipeParent_DocumentWidget_(d);
iDocumentWidget *target = findChild_Widget(swipeParent, "swipeout");
if (atOldest_History(d->mod.history)) {
setVisualOffset_Widget(w, 0, 100, 0);
if (target) {
destroy_Widget(as_Widget(target)); /* didn't need it after all */
}
return iTrue;
}
setupSwipeOverlay_DocumentWidget_(d, as_Widget(target));
destroy_Widget(as_Widget(target)); /* will be actually deleted after animation finishes */
postCommand_Widget(d, "navigate.back");
return iTrue;
}
return iFalse;
}
static iBool cancelRequest_DocumentWidget_(iDocumentWidget *d, iBool postBack) {
if (d->request) {
iWidget *w = as_Widget(d);
postCommandf_Root(w->root,
"document.request.cancelled doc:%p url:%s", d, cstr_String(d->mod.url));
iReleasePtr(&d->request);
if (d->state != ready_RequestState) {
d->state = ready_RequestState;
if (postBack) {
postCommand_Root(w->root, "navigate.back");
}
}
updateFetchProgress_DocumentWidget_(d);
return iTrue;
}
return iFalse;
}
static const int smoothDuration_DocumentWidget_(enum iScrollType type) {
return 600 /* milliseconds */ * scrollSpeedFactor_Prefs(prefs_App(), type);
}
static iBool handleCommand_DocumentWidget_(iDocumentWidget *d, const char *cmd) {
iWidget *w = as_Widget(d);
if (equal_Command(cmd, "document.openurls.changed")) {
if (d->flags & animationPlaceholder_DocumentWidgetFlag) {
return iFalse;
}
/* When any tab changes its document URL, update the open link indicators. */
if (updateOpenURLs_GmDocument(d->view.doc)) {
invalidate_DocumentWidget_(d);
refresh_Widget(d);
}
return iFalse;
}
if (equal_Command(cmd, "visited.changed")) {
updateVisitedLinks_GmDocument(d->view.doc);
invalidateVisibleLinks_DocumentView_(&d->view);
return iFalse;
}
if (equal_Command(cmd, "document.render")) /* `Periodic` makes direct dispatch to here */ {
// printf("%u: document.render\n", SDL_GetTicks());
if (SDL_GetTicks() - d->view.drawBufs->lastRenderTime > 150) {
remove_Periodic(periodic_App(), d);
/* Scrolling has stopped, begin filling up the buffer. */
if (d->view.visBuf->buffers[0].texture) {
addTicker_App(prerender_DocumentWidget_, d);
}
}
return iTrue;
}
else if (equal_Command(cmd, "window.resized") || equal_Command(cmd, "font.changed") ||
equal_Command(cmd, "keyroot.changed")) {
if (equal_Command(cmd, "font.changed")) {
invalidateCachedLayout_History(d->mod.history);
}
/* Alt/Option key may be involved in window size changes. */
setLinkNumberMode_DocumentWidget_(d, iFalse);
d->phoneToolbar = findWidget_App("toolbar");
const iBool keepCenter = equal_Command(cmd, "font.changed");
updateDocumentWidthRetainingScrollPosition_DocumentView_(&d->view, keepCenter);
d->view.drawBufs->flags |= updateSideBuf_DrawBufsFlag;
updateVisible_DocumentView_(&d->view);
invalidate_DocumentWidget_(d);
dealloc_VisBuf(d->view.visBuf);
updateWindowTitle_DocumentWidget_(d);
showOrHidePinningIndicator_DocumentWidget_(d);
refresh_Widget(w);
}
else if (equal_Command(cmd, "window.focus.lost")) {
if (d->flags & showLinkNumbers_DocumentWidgetFlag) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
invalidateVisibleLinks_DocumentView_(&d->view);
refresh_Widget(w);
}
return iFalse;
}
else if (equal_Command(cmd, "window.mouse.exited")) {
return iFalse;
}
else if (equal_Command(cmd, "theme.changed")) {
invalidatePalette_GmDocument(d->view.doc);
invalidateTheme_History(d->mod.history); /* forget cached color palettes */
if (document_App() == d) {
updateTheme_DocumentWidget_(d);
updateVisible_DocumentView_(&d->view);
updateTrust_DocumentWidget_(d, NULL);
d->view.drawBufs->flags |= updateSideBuf_DrawBufsFlag;
invalidate_DocumentWidget_(d);
refresh_Widget(w);
}
}
else if (equal_Command(cmd, "document.layout.changed") && document_Root(get_Root()) == d) {
if (argLabel_Command(cmd, "redo")) {
redoLayout_GmDocument(d->view.doc);
}
updateSize_DocumentWidget(d);
}
else if (equal_Command(cmd, "pinsplit.set")) {
postCommand_App("document.update.pin"); /* prefs value not set yet */
return iFalse;
}
else if (equal_Command(cmd, "document.update.pin")) {
showOrHidePinningIndicator_DocumentWidget_(d);
return iFalse;
}
else if (equal_Command(cmd, "tabs.changed")) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
if (cmp_String(id_Widget(w), suffixPtr_Command(cmd, "id")) == 0) {
/* Set palette for our document. */
updateTheme_DocumentWidget_(d);
updateTrust_DocumentWidget_(d, NULL);
updateSize_DocumentWidget(d);
showOrHidePinningIndicator_DocumentWidget_(d);
updateFetchProgress_DocumentWidget_(d);
updateHover_Window(window_Widget(w));
}
init_Anim(&d->view.sideOpacity, 0);
init_Anim(&d->view.altTextOpacity, 0);
updateSideOpacity_DocumentView_(&d->view, iFalse);
updateWindowTitle_DocumentWidget_(d);
allocVisBuffer_DocumentView_(&d->view);
animateMedia_DocumentWidget_(d);
remove_Periodic(periodic_App(), d);
removeTicker_App(prerender_DocumentWidget_, d);
return iFalse;
}
else if (equal_Command(cmd, "tab.created")) {
/* Space for tab buttons has changed. */
updateWindowTitle_DocumentWidget_(d);
return iFalse;
}
else if (equal_Command(cmd, "document.select") && d == document_App()) {
/* Touch selection mode. */
if (!arg_Command(cmd)) {
d->selectMark = iNullRange;
setFlags_Widget(w, touchDrag_WidgetFlag, iFalse);
setFadeEnabled_ScrollWidget(d->scroll, iTrue);
}
else {
setFlags_Widget(w, touchDrag_WidgetFlag, iTrue);
d->flags |= movingSelectMarkEnd_DocumentWidgetFlag |
selectWords_DocumentWidgetFlag; /* finger-based selection is imprecise */
d->flags &= ~selectLines_DocumentWidgetFlag;
setFadeEnabled_ScrollWidget(d->scroll, iFalse);
d->selectMark = sourceLoc_DocumentView_(&d->view, d->contextPos);
extendRange_Rangecc(&d->selectMark, range_String(source_GmDocument(d->view.doc)),
word_RangeExtension | bothStartAndEnd_RangeExtension);
d->initialSelectMark = d->selectMark;
}
return iTrue;
}
else if (equal_Command(cmd, "document.info") && d == document_App()) {
const char *unchecked = red_ColorEscape "\u2610";
const char *checked = green_ColorEscape "\u2611";
const iBool haveFingerprint = (d->certFlags & haveFingerprint_GmCertFlag) != 0;
const int requiredForTrust = (available_GmCertFlag | haveFingerprint_GmCertFlag |
timeVerified_GmCertFlag);
const iBool canTrust = ~d->certFlags & trusted_GmCertFlag &&
((d->certFlags & requiredForTrust) == requiredForTrust);
const iRecentUrl *recent = constMostRecentUrl_History(d->mod.history);
const iString *meta = &d->sourceMime;
if (recent && recent->cachedResponse) {
meta = &recent->cachedResponse->meta;
}
iString *msg = collectNew_String();
if (isEmpty_String(&d->sourceHeader)) {
appendFormat_String(msg,
"%s\n%s\n",
cstr_String(meta),
formatCStrs_Lang("num.bytes.n", size_Block(&d->sourceContent)));
}
else {
appendFormat_String(msg, "%s\n", cstr_String(&d->sourceHeader));
if (size_Block(&d->sourceContent)) {
appendFormat_String(
msg, "%s\n", formatCStrs_Lang("num.bytes.n", size_Block(&d->sourceContent)));
}
}
/* TODO: On mobile, omit the CA status. */
appendFormat_String(
msg,
"\n%s${pageinfo.cert.status}\n"
"%s%s %s\n"
"%s%s %s%s\n"
"%s%s %s (%04d-%02d-%02d %02d:%02d:%02d)\n"
"%s%s %s",
uiHeading_ColorEscape,
d->certFlags & authorityVerified_GmCertFlag ? checked
: uiTextAction_ColorEscape "\u2610",
uiText_ColorEscape,
d->certFlags & authorityVerified_GmCertFlag ? "${pageinfo.cert.ca.verified}"
: "${pageinfo.cert.ca.unverified}",
d->certFlags & domainVerified_GmCertFlag ? checked : unchecked,
uiText_ColorEscape,
d->certFlags & domainVerified_GmCertFlag ? "${pageinfo.domain.match}"
: "${pageinfo.domain.mismatch}",
~d->certFlags & domainVerified_GmCertFlag
? format_CStr(" (%s)", cstr_String(d->certSubject))
: "",
d->certFlags & timeVerified_GmCertFlag ? checked : unchecked,
uiText_ColorEscape,
d->certFlags & timeVerified_GmCertFlag ? "${pageinfo.cert.notexpired}"
: "${pageinfo.cert.expired}",
d->certExpiry.year,
d->certExpiry.month,
d->certExpiry.day,
d->certExpiry.hour,
d->certExpiry.minute,
d->certExpiry.second,
d->certFlags & trusted_GmCertFlag ? checked : unchecked,
uiText_ColorEscape,
d->certFlags & trusted_GmCertFlag ? "${pageinfo.cert.trusted}"
: "${pageinfo.cert.untrusted}");
setFocus_Widget(NULL);
iArray *items = new_Array(sizeof(iMenuItem));
if (canTrust) {
pushBack_Array(items,
&(iMenuItem){ uiTextCaution_ColorEscape "${dlg.cert.trust}",
SDLK_u,
KMOD_PRIMARY | KMOD_SHIFT,
"server.trustcert" });
}
if (haveFingerprint) {
pushBack_Array(items, &(iMenuItem){ "${dlg.cert.fingerprint}", 0, 0, "server.copycert" });
}
if (!isEmpty_Array(items)) {
pushBack_Array(items, &(iMenuItem){ "---", 0, 0, 0 });
}
pushBack_Array(items, &(iMenuItem){ "${close}", 0, 0, "message.ok" });
iWidget *dlg = makeQuestion_Widget(uiHeading_ColorEscape "${heading.pageinfo}",
cstr_String(msg),
data_Array(items),
size_Array(items));
delete_Array(items);
/* Enforce a minimum size. */
// iWidget *sizer = new_Widget();
// setFixedSize_Widget(sizer, init_I2(gap_UI * 65, 1));
// addChildFlags_Widget(dlg, iClob(sizer), frameless_WidgetFlag);
// setFlags_Widget(dlg, centerHorizontal_WidgetFlag, iFalse);
if (deviceType_App() == desktop_AppDeviceType) {
const iWidget *lockButton = findWidget_Root("navbar.lock");
setPos_Widget(dlg, windowToLocal_Widget(dlg, bottomLeft_Rect(bounds_Widget(lockButton))));
}
arrange_Widget(dlg);
addAction_Widget(dlg, SDLK_ESCAPE, 0, "message.ok");
addAction_Widget(dlg, SDLK_SPACE, 0, "message.ok");
return iTrue;
}
else if (equal_Command(cmd, "server.unexpire") && document_App() == d) {
const iRangecc host = urlHost_String(d->mod.url);
const uint16_t port = urlPort_String(d->mod.url);
if (!isEmpty_Block(d->certFingerprint) && !isEmpty_Range(&host)) {
iTime expiry;
initCurrent_Time(&expiry);
iTime oneHour; /* One hour is long enough for a single visit (?). */
initSeconds_Time(&oneHour, 3600);
add_Time(&expiry, &oneHour);
iDate expDate;
init_Date(&expDate, &expiry);
setTrusted_GmCerts(certs_App(), host, port, d->certFingerprint, &expDate);
postCommand_Widget(w, "navigate.reload");
}
return iTrue;
}
else if (equal_Command(cmd, "server.trustcert") && document_App() == d) {
const iRangecc host = urlHost_String(d->mod.url);
const uint16_t port = urlPort_String(d->mod.url);
if (!isEmpty_Block(d->certFingerprint) && !isEmpty_Range(&host)) {
setTrusted_GmCerts(certs_App(), host, port, d->certFingerprint, &d->certExpiry);
postCommand_Widget(w, "navigate.reload");
}
return iTrue;
}
else if (equal_Command(cmd, "server.copycert") && document_App() == d) {
SDL_SetClipboardText(cstrCollect_String(hexEncode_Block(d->certFingerprint)));
return iTrue;
}
else if (equal_Command(cmd, "copy") && document_App() == d && !focus_Widget()) {
iString *copied;
if (d->selectMark.start) {
iRangecc mark = d->selectMark;
if (mark.start > mark.end) {
iSwap(const char *, mark.start, mark.end);
}
copied = newRange_String(mark);
}
else {
/* Full document. */
copied = copy_String(source_GmDocument(d->view.doc));
}
if (argLabel_Command(cmd, "share")) {
#if defined (iPlatformAppleMobile)
openTextActivityView_iOS(copied);
#endif
}
else {
SDL_SetClipboardText(cstr_String(copied));
}
delete_String(copied);
if (flags_Widget(w) & touchDrag_WidgetFlag) {
postCommand_Widget(w, "document.select arg:0");
}
return iTrue;
}
else if (equal_Command(cmd, "document.copylink") && document_App() == d) {
if (d->contextLink) {
SDL_SetClipboardText(cstr_String(canonicalUrl_String(absoluteUrl_String(
d->mod.url, linkUrl_GmDocument(d->view.doc, d->contextLink->linkId)))));
}
else {
SDL_SetClipboardText(cstr_String(canonicalUrl_String(d->mod.url)));
}
return iTrue;
}
else if (equalWidget_Command(cmd, w, "document.downloadlink")) {
if (d->contextLink) {
const iGmLinkId linkId = d->contextLink->linkId;
setUrl_Media(media_GmDocument(d->view.doc),
linkId,
download_MediaType,
linkUrl_GmDocument(d->view.doc, linkId));
requestMedia_DocumentWidget_(d, linkId, iFalse /* no filters */);
redoLayout_GmDocument(d->view.doc); /* inline downloader becomes visible */
updateVisible_DocumentView_(&d->view);
invalidate_DocumentWidget_(d);
refresh_Widget(w);
}
return iTrue;
}
else if (equal_Command(cmd, "document.input.submit") && document_Command(cmd) == d) {
postCommandf_Root(w->root,
/* use the `redirect:1` argument to cause the input query URL to be
replaced in History; we don't want to navigate onto it */
"open redirect:1 url:%s",
cstrCollect_String(makeQueryUrl_DocumentWidget_
(d, collect_String(suffix_Command(cmd, "value")))));
return iTrue;
}
else if (equal_Command(cmd, "valueinput.cancelled") &&
equal_Rangecc(range_Command(cmd, "id"), "!document.input.submit") && document_App() == d) {
postCommand_Root(get_Root(), "navigate.back");
return iTrue;
}
else if (equalWidget_Command(cmd, w, "document.request.updated") &&
id_GmRequest(d->request) == argU32Label_Command(cmd, "reqid")) {
if (document_App() == d) {
updateFetchProgress_DocumentWidget_(d);
}
checkResponse_DocumentWidget_(d);
set_Atomic(&d->isRequestUpdated, iFalse); /* ready to be notified again */
return iFalse;
}
else if (equalWidget_Command(cmd, w, "document.request.finished") &&
id_GmRequest(d->request) == argU32Label_Command(cmd, "reqid")) {
d->flags &= ~fromCache_DocumentWidgetFlag;
set_Block(&d->sourceContent, body_GmRequest(d->request));
if (!isSuccess_GmStatusCode(status_GmRequest(d->request))) {
/* TODO: Why is this here? Can it be removed? */
format_String(&d->sourceHeader,
"%s%s",
humanReadableStatusCode_(status_GmRequest(d->request)),
cstr_String(meta_GmRequest(d->request)));
}
updateFetchProgress_DocumentWidget_(d);
checkResponse_DocumentWidget_(d);
if (category_GmStatusCode(status_GmRequest(d->request)) == categorySuccess_GmStatusCode) {
init_Anim(&d->view.scrollY.pos, d->initNormScrollY * pageHeight_DocumentView_(&d->view));
/* TODO: unless user already scrolled! */
}
addBannerWarnings_DocumentWidget_(d);
iChangeFlags(d->flags,
urlChanged_DocumentWidgetFlag | drawDownloadCounter_DocumentWidgetFlag,
iFalse);
d->state = ready_RequestState;
postProcessRequestContent_DocumentWidget_(d, iFalse);
/* The response may be cached. */
if (d->request) {
iAssert(~d->flags & animationPlaceholder_DocumentWidgetFlag);
iAssert(~d->flags & fromCache_DocumentWidgetFlag);
if (!equal_Rangecc(urlScheme_String(d->mod.url), "about") &&
(startsWithCase_String(meta_GmRequest(d->request), "text/") ||
!cmp_String(&d->sourceMime, mimeType_Gempub))) {
setCachedResponse_History(d->mod.history, lockResponse_GmRequest(d->request));
unlockResponse_GmRequest(d->request);
}
}
iReleasePtr(&d->request);
updateVisible_DocumentView_(&d->view);
d->view.drawBufs->flags |= updateSideBuf_DrawBufsFlag;
postCommandf_Root(w->root,
"document.changed doc:%p status:%d url:%s",
d,
d->sourceStatus,
cstr_String(d->mod.url));
/* Check for a pending goto. */
if (!isEmpty_String(&d->pendingGotoHeading)) {
scrollToHeading_DocumentView_(&d->view, cstr_String(&d->pendingGotoHeading));
clear_String(&d->pendingGotoHeading);
}
cacheDocumentGlyphs_DocumentWidget_(d);
return iFalse;
}
else if (equal_Command(cmd, "document.translate") && d == document_App()) {
if (!d->translation) {
d->translation = new_Translation(d);
if (isUsingPanelLayout_Mobile()) {
const iRect safe = safeRect_Root(w->root);
d->translation->dlg->rect.pos = windowToLocal_Widget(w, zero_I2());
d->translation->dlg->rect.size = safe.size;
}
}
return iTrue;
}
else if (startsWith_CStr(cmd, "translation.") && d->translation) {
const iBool wasHandled = handleCommand_Translation(d->translation, cmd);
if (isFinished_Translation(d->translation)) {
delete_Translation(d->translation);
d->translation = NULL;
}
return wasHandled;
}
else if (equal_Command(cmd, "document.upload") && d == document_App()) {
if (findChild_Widget(root_Widget(w), "upload")) {
return iTrue; /* already open */
}
const iBool isGemini = equalCase_Rangecc(urlScheme_String(d->mod.url), "gemini");
if (isGemini || equalCase_Rangecc(urlScheme_String(d->mod.url), "titan")) {
iUploadWidget *upload = new_UploadWidget();
setUrl_UploadWidget(upload, d->mod.url);
setResponseViewer_UploadWidget(upload, d);
addChild_Widget(get_Root()->widget, iClob(upload));
setupSheetTransition_Mobile(as_Widget(upload), iTrue);
if (argLabel_Command(cmd, "copy") && isUtf8_Rangecc(range_Block(&d->sourceContent))) {
iString text;
initBlock_String(&text, &d->sourceContent);
setText_UploadWidget(upload, &text);
deinit_String(&text);
}
postRefresh_App();
}
return iTrue;
}
else if (equal_Command(cmd, "media.updated") || equal_Command(cmd, "media.finished")) {
return handleMediaCommand_DocumentWidget_(d, cmd);
}
else if (equal_Command(cmd, "media.player.started")) {
/* When one media player starts, pause the others that may be playing. */
const iPlayer *startedPlr = pointerLabel_Command(cmd, "player");
const iMedia * media = media_GmDocument(d->view.doc);
const size_t num = numAudio_Media(media);
for (size_t id = 1; id <= num; id++) {
iPlayer *plr = audioPlayer_Media(media, (iMediaId){ audio_MediaType, id });
if (plr != startedPlr) {
setPaused_Player(plr, iTrue);
}
}
}
else if (equal_Command(cmd, "media.player.update")) {
updateMedia_DocumentWidget_(d);
return iFalse;
}
else if (equal_Command(cmd, "document.stop") && document_App() == d) {
if (cancelRequest_DocumentWidget_(d, iTrue /* navigate back */)) {
return iTrue;
}
}
else if (equalWidget_Command(cmd, w, "document.media.save")) {
const iGmLinkId linkId = argLabel_Command(cmd, "link");
const iMediaRequest *media = findMediaRequest_DocumentWidget_(d, linkId);
if (media) {
saveToDownloads_(url_GmRequest(media->req), meta_GmRequest(media->req),
body_GmRequest(media->req), iTrue);
}
}
else if (equal_Command(cmd, "document.save") && document_App() == d) {
if (d->request) {
makeSimpleMessage_Widget(uiTextCaution_ColorEscape "${heading.save.incomplete}",
"${dlg.save.incomplete}");
}
else if (!isEmpty_Block(&d->sourceContent)) {
if (argLabel_Command(cmd, "extview")) {
if (equalCase_Rangecc(urlScheme_String(d->mod.url), "file")) {
/* Already a file so just open it directly. */
postCommandf_Root(w->root, "!open default:1 url:%s", cstr_String(d->mod.url));
}
else {
const iString *tmpPath = temporaryPathForUrl_App(d->mod.url, &d->sourceMime);
if (saveToFile_(tmpPath, &d->sourceContent, iFalse)) {
postCommandf_Root(w->root, "!open default:1 url:%s",
cstrCollect_String(makeFileUrl_String(tmpPath)));
}
}
}
else {
const iBool doOpen = argLabel_Command(cmd, "open");
const iString *savePath = saveToDownloads_(d->mod.url, &d->sourceMime,
&d->sourceContent, !doOpen);
if (!isEmpty_String(savePath) && doOpen) {
postCommandf_Root(
w->root, "!open url:%s", cstrCollect_String(makeFileUrl_String(savePath)));
}
}
}
return iTrue;
}
else if (equal_Command(cmd, "document.reload") && document_Command(cmd) == d) {
d->initNormScrollY = normScrollPos_DocumentView_(&d->view);
if (equalCase_Rangecc(urlScheme_String(d->mod.url), "titan")) {
/* Reopen so the Upload dialog gets shown. */
postCommandf_App("open url:%s", cstr_String(d->mod.url));
return iTrue;
}
fetch_DocumentWidget_(d);
return iTrue;
}
else if (equal_Command(cmd, "document.linkkeys") && document_App() == d) {
if (argLabel_Command(cmd, "release")) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
}
else if (argLabel_Command(cmd, "more")) {
if (d->flags & showLinkNumbers_DocumentWidgetFlag &&
d->ordinalMode == homeRow_DocumentLinkOrdinalMode) {
const size_t numKeys = iElemCount(homeRowKeys_);
const iGmRun *last = lastVisibleLink_DocumentView_(&d->view);
if (!last) {
d->ordinalBase = 0;
}
else {
d->ordinalBase += numKeys;
if (visibleLinkOrdinal_DocumentView_(&d->view, last->linkId) < d->ordinalBase) {
d->ordinalBase = 0;
}
}
}
else if (~d->flags & showLinkNumbers_DocumentWidgetFlag) {
d->ordinalMode = homeRow_DocumentLinkOrdinalMode;
d->ordinalBase = 0;
setLinkNumberMode_DocumentWidget_(d, iTrue);
}
}
else {
d->ordinalMode = arg_Command(cmd);
d->ordinalBase = 0;
setLinkNumberMode_DocumentWidget_(d, iTrue);
iChangeFlags(d->flags, setHoverViaKeys_DocumentWidgetFlag,
argLabel_Command(cmd, "hover") != 0);
iChangeFlags(d->flags, newTabViaHomeKeys_DocumentWidgetFlag,
argLabel_Command(cmd, "newtab") != 0);
}
invalidateVisibleLinks_DocumentView_(&d->view);
refresh_Widget(d);
return iTrue;
}
else if (equal_Command(cmd, "navigate.back") && document_App() == d) {
if (d->request) {
postCommandf_Root(w->root,
"document.request.cancelled doc:%p url:%s", d, cstr_String(d->mod.url));
iReleasePtr(&d->request);
updateFetchProgress_DocumentWidget_(d);
}
goBack_History(d->mod.history);
return iTrue;
}
else if (equal_Command(cmd, "navigate.forward") && document_App() == d) {
goForward_History(d->mod.history);
return iTrue;
}
else if (equal_Command(cmd, "navigate.parent") && document_App() == d) {
iUrl parts;
init_Url(&parts, d->mod.url);
if (endsWith_Rangecc(parts.path, "/index.gmi")) {
parts.path.end -= 9; /* This is the default index page. */
}
/* Remove the last path segment. */
if (size_Range(&parts.path) > 1) {
if (parts.path.end[-1] == '/') {
parts.path.end--;
}
while (parts.path.end > parts.path.start) {
if (parts.path.end[-1] == '/') break;
parts.path.end--;
}
iString *parentUrl = collectNewRange_String((iRangecc){ constBegin_String(d->mod.url),
parts.path.end });
/* Always go to a gophermap. */
setUrlItemType_Gopher(parentUrl, '1');
/* Hierarchical navigation doesn't make sense with Titan. */
if (startsWith_String(parentUrl, "titan://")) {
/* We have no way of knowing if the corresponding URL is valid for Gemini,
but let's try anyway. */
set_String(parentUrl, withScheme_String(parentUrl, "gemini"));
stripUrlPort_String(parentUrl);
}
if (!cmpCase_String(parentUrl, "about:")) {
setCStr_String(parentUrl, "about:about");
}
postCommandf_Root(w->root, "open url:%s", cstr_String(parentUrl));
}
return iTrue;
}
else if (equal_Command(cmd, "navigate.root") && document_App() == d) {
iString *rootUrl = collectNewRange_String(urlRoot_String(d->mod.url));
/* Always go to a gophermap. */
setUrlItemType_Gopher(rootUrl, '1');
/* Hierarchical navigation doesn't make sense with Titan. */
if (startsWith_String(rootUrl, "titan://")) {
/* We have no way of knowing if the corresponding URL is valid for Gemini,
but let's try anyway. */
set_String(rootUrl, withScheme_String(rootUrl, "gemini"));
stripUrlPort_String(rootUrl);
}
if (!cmpCase_String(rootUrl, "about:")) {
setCStr_String(rootUrl, "about:about");
}
else {
appendCStr_String(rootUrl, "/");
}
postCommandf_Root(w->root, "open url:%s", cstr_String(rootUrl));
return iTrue;
}
else if (equalWidget_Command(cmd, w, "scroll.moved")) {
init_Anim(&d->view.scrollY.pos, arg_Command(cmd));
updateVisible_DocumentView_(&d->view);
return iTrue;
}
else if (equal_Command(cmd, "scroll.page") && document_App() == d) {
const int dir = arg_Command(cmd);
if (dir > 0 && !argLabel_Command(cmd, "repeat") &&
prefs_App()->loadImageInsteadOfScrolling &&
fetchNextUnfetchedImage_DocumentWidget_(d)) {
return iTrue;
}
const float amount = argLabel_Command(cmd, "full") != 0 ? 1.0f : 0.5f;
smoothScroll_DocumentView_(&d->view,
dir * amount *
height_Rect(documentBounds_DocumentView_(&d->view)),
smoothDuration_DocumentWidget_(keyboard_ScrollType));
return iTrue;
}
else if (equal_Command(cmd, "scroll.top") && document_App() == d) {
if (argLabel_Command(cmd, "smooth")) {
stopWidgetMomentum_Touch(w);
smoothScroll_DocumentView_(&d->view, -pos_SmoothScroll(&d->view.scrollY), 500);
d->view.scrollY.flags |= muchSofter_AnimFlag;
return iTrue;
}
init_Anim(&d->view.scrollY.pos, 0);
invalidate_VisBuf(d->view.visBuf);
clampScroll_DocumentView_(&d->view);
updateVisible_DocumentView_(&d->view);
refresh_Widget(w);
return iTrue;
}
else if (equal_Command(cmd, "scroll.bottom") && document_App() == d) {
updateScrollMax_DocumentView_(&d->view); /* scrollY.max might not be fully updated */
init_Anim(&d->view.scrollY.pos, d->view.scrollY.max);
invalidate_VisBuf(d->view.visBuf);
clampScroll_DocumentView_(&d->view);
updateVisible_DocumentView_(&d->view);
refresh_Widget(w);
return iTrue;
}
else if (equal_Command(cmd, "scroll.step") && document_App() == d) {
const int dir = arg_Command(cmd);
if (dir > 0 && !argLabel_Command(cmd, "repeat") &&
prefs_App()->loadImageInsteadOfScrolling &&
fetchNextUnfetchedImage_DocumentWidget_(d)) {
return iTrue;
}
smoothScroll_DocumentView_(&d->view,
3 * lineHeight_Text(paragraph_FontId) * dir,
smoothDuration_DocumentWidget_(keyboard_ScrollType));
return iTrue;
}
else if (equal_Command(cmd, "document.goto") && document_App() == d) {
const char *heading = suffixPtr_Command(cmd, "heading");
if (heading) {
if (isRequestOngoing_DocumentWidget(d)) {
/* Scroll position set when request finishes. */
setCStr_String(&d->pendingGotoHeading, heading);
return iTrue;
}
scrollToHeading_DocumentView_(&d->view, heading);
return iTrue;
}
const char *loc = pointerLabel_Command(cmd, "loc");
const iGmRun *run = findRunAtLoc_GmDocument(d->view.doc, loc);
if (run) {
scrollTo_DocumentView_(&d->view, run->visBounds.pos.y, iFalse);
}
return iTrue;
}
else if ((equal_Command(cmd, "find.next") || equal_Command(cmd, "find.prev")) &&
document_App() == d) {
const int dir = equal_Command(cmd, "find.next") ? +1 : -1;
iRangecc (*finder)(const iGmDocument *, const iString *, const char *) =
dir > 0 ? findText_GmDocument : findTextBefore_GmDocument;
iInputWidget *find = findWidget_App("find.input");
if (isEmpty_String(text_InputWidget(find))) {
d->foundMark = iNullRange;
}
else {
const iBool wrap = d->foundMark.start != NULL;
d->foundMark = finder(d->view.doc, text_InputWidget(find), dir > 0 ? d->foundMark.end
: d->foundMark.start);
if (!d->foundMark.start && wrap) {
/* Wrap around. */
d->foundMark = finder(d->view.doc, text_InputWidget(find), NULL);
}
if (d->foundMark.start) {
const iGmRun *found;
if ((found = findRunAtLoc_GmDocument(d->view.doc, d->foundMark.start)) != NULL) {
scrollTo_DocumentView_(&d->view, mid_Rect(found->bounds).y, iTrue);
}
}
}
if (flags_Widget(w) & touchDrag_WidgetFlag) {
postCommand_Root(w->root, "document.select arg:0"); /* we can't handle both at the same time */
}
invalidateWideRunsWithNonzeroOffset_DocumentView_(&d->view); /* markers don't support offsets */
resetWideRuns_DocumentView_(&d->view);
refresh_Widget(w);
return iTrue;
}
else if (equal_Command(cmd, "find.clearmark")) {
if (d->foundMark.start) {
d->foundMark = iNullRange;
refresh_Widget(w);
}
return iTrue;
}
else if (equal_Command(cmd, "bookmark.links") && document_App() == d) {
iPtrArray *links = collectNew_PtrArray();
render_GmDocument(d->view.doc, (iRangei){ 0, size_GmDocument(d->view.doc).y }, addAllLinks_, links);
/* Find links that aren't already bookmarked. */
iForEach(PtrArray, i, links) {
const iGmRun *run = i.ptr;
uint32_t bmid;
if ((bmid = findUrl_Bookmarks(bookmarks_App(),
linkUrl_GmDocument(d->view.doc, run->linkId))) != 0) {
const iBookmark *bm = get_Bookmarks(bookmarks_App(), bmid);
/* We can import local copies of remote bookmarks. */
if (~bm->flags & remote_BookmarkFlag) {
remove_PtrArrayIterator(&i);
}
}
}
if (!isEmpty_PtrArray(links)) {
if (argLabel_Command(cmd, "confirm")) {
const size_t count = size_PtrArray(links);
makeQuestion_Widget(
uiHeading_ColorEscape "${heading.import.bookmarks}",
formatCStrs_Lang("dlg.import.found.n", count),
(iMenuItem[]){ { "${cancel}" },
{ format_CStr(cstrCount_Lang("dlg.import.add.n", (int) count),
uiTextAction_ColorEscape,
count),
0,
0,
"bookmark.links" } },
2);
}
else {
iConstForEach(PtrArray, j, links) {
const iGmRun *run = j.ptr;
add_Bookmarks(bookmarks_App(),
linkUrl_GmDocument(d->view.doc, run->linkId),
collect_String(newRange_String(run->text)),
NULL,
0x1f588 /* pin */);
}
postCommand_App("bookmarks.changed");
}
}
else {
makeSimpleMessage_Widget(uiHeading_ColorEscape "${heading.import.bookmarks}",
"${dlg.import.notnew}");
}
return iTrue;
}
else if (equalWidget_Command(cmd, w, "menu.closed")) {
updateHover_DocumentView_(&d->view, mouseCoord_Window(get_Window(), 0));
}
else if (equal_Command(cmd, "document.autoreload")) {
if (d->mod.reloadInterval) {
if (!isValid_Time(&d->sourceTime) || elapsedSeconds_Time(&d->sourceTime) >=
seconds_ReloadInterval_(d->mod.reloadInterval)) {
postCommand_Widget(w, "document.reload");
}
}
}
else if (equal_Command(cmd, "document.autoreload.menu") && document_App() == d) {
iArray *items = collectNew_Array(sizeof(iMenuItem));
for (int i = 0; i < max_ReloadInterval; ++i) {
pushBack_Array(items, &(iMenuItem){
format_CStr("%s%s", ((int) d->mod.reloadInterval == i ? "&" : "*"),
label_ReloadInterval_(i)),
0,
0,
format_CStr("document.autoreload.set arg:%d", i) });
}
pushBack_Array(items, &(iMenuItem){ "${cancel}", 0, 0, NULL });
makeQuestion_Widget(uiTextAction_ColorEscape "${heading.autoreload}",
"${dlg.autoreload}",
constData_Array(items), size_Array(items));
return iTrue;
}
else if (equal_Command(cmd, "document.autoreload.set") && document_App() == d) {
d->mod.reloadInterval = arg_Command(cmd);
}
else if (equalWidget_Command(cmd, w, "document.dismiss")) {
const iString *site = collectNewRange_String(urlRoot_String(d->mod.url));
const int dismissed = value_SiteSpec(site, dismissWarnings_SiteSpecKey);
const int arg = argLabel_Command(cmd, "warning");
setValue_SiteSpec(site, dismissWarnings_SiteSpecKey, dismissed | arg);
if (arg == ansiEscapes_GmDocumentWarning) {
remove_Banner(d->banner, ansiEscapes_GmStatusCode);
refresh_Widget(w);
}
return iTrue;
}
else if (startsWith_CStr(cmd, "pinch.") && document_Command(cmd) == d) {
return handlePinch_DocumentWidget_(d, cmd);
}
else if ((startsWith_CStr(cmd, "edgeswipe.") || startsWith_CStr(cmd, "swipe.")) &&
document_App() == d) {
return handleSwipe_DocumentWidget_(d, cmd);
}
else if (equal_Command(cmd, "document.setmediatype") && document_App() == d) {
if (!isRequestOngoing_DocumentWidget(d)) {
setUrlAndSource_DocumentWidget(d, d->mod.url, string_Command(cmd, "mime"),
&d->sourceContent);
}
return iTrue;
}
else if (equal_Command(cmd, "fontpack.install") && document_App() == d) {
if (argLabel_Command(cmd, "ttf")) {
iAssert(!cmp_String(&d->sourceMime, "font/ttf"));
installFontFile_Fonts(collect_String(suffix_Command(cmd, "name")), &d->sourceContent);
postCommand_App("open url:about:fonts");
}
else {
const iString *id = idFromUrl_FontPack(d->mod.url);
install_Fonts(id, &d->sourceContent);
postCommandf_App("open gotoheading:%s url:about:fonts", cstr_String(id));
}
return iTrue;
}
return iFalse;
}
static void setGrabbedPlayer_DocumentWidget_(iDocumentWidget *d, const iGmRun *run) {
if (run && run->mediaType == audio_MediaType) {
iPlayer *plr = audioPlayer_Media(media_GmDocument(d->view.doc), mediaId_GmRun(run));
setFlags_Player(plr, volumeGrabbed_PlayerFlag, iTrue);
d->grabbedStartVolume = volume_Player(plr);
d->grabbedPlayer = run;
refresh_Widget(d);
}
else if (d->grabbedPlayer) {
setFlags_Player(
audioPlayer_Media(media_GmDocument(d->view.doc), mediaId_GmRun(d->grabbedPlayer)),
volumeGrabbed_PlayerFlag,
iFalse);
d->grabbedPlayer = NULL;
refresh_Widget(d);
}
else {
iAssert(iFalse);
}
}
static iBool processMediaEvents_DocumentWidget_(iDocumentWidget *d, const SDL_Event *ev) {
if (ev->type != SDL_MOUSEBUTTONDOWN && ev->type != SDL_MOUSEBUTTONUP &&
ev->type != SDL_MOUSEMOTION) {
return iFalse;
}
if (d->grabbedPlayer) {
/* Updated in the drag. */
return iFalse;
}
const iInt2 mouse = init_I2(ev->button.x, ev->button.y);
iConstForEach(PtrArray, i, &d->view.visibleMedia) {
const iGmRun *run = i.ptr;
if (run->mediaType == download_MediaType) {
iDownloadUI ui;
init_DownloadUI(&ui, media_GmDocument(d->view.doc), mediaId_GmRun(run).id,
runRect_DocumentView_(&d->view, run));
if (processEvent_DownloadUI(&ui, ev)) {
return iTrue;
}
continue;
}
if (run->mediaType != audio_MediaType) {
continue;
}
if (ev->type == SDL_MOUSEBUTTONDOWN || ev->type == SDL_MOUSEBUTTONUP) {
if (ev->button.button != SDL_BUTTON_LEFT) {
return iFalse;
}
}
/* TODO: move this to mediaui.c */
const iRect rect = runRect_DocumentView_(&d->view, run);
iPlayer * plr = audioPlayer_Media(media_GmDocument(d->view.doc), mediaId_GmRun(run));
if (contains_Rect(rect, mouse)) {
iPlayerUI ui;
init_PlayerUI(&ui, plr, rect);
if (ev->type == SDL_MOUSEBUTTONDOWN && flags_Player(plr) & adjustingVolume_PlayerFlag &&
contains_Rect(adjusted_Rect(ui.volumeAdjustRect,
zero_I2(),
init_I2(-height_Rect(ui.volumeAdjustRect), 0)),
mouse)) {
setGrabbedPlayer_DocumentWidget_(d, run);
processEvent_Click(&d->click, ev);
/* The rest is done in the DocumentWidget click responder. */
refresh_Widget(d);
return iTrue;
}
else if (ev->type == SDL_MOUSEBUTTONDOWN || ev->type == SDL_MOUSEMOTION) {
refresh_Widget(d);
return iTrue;
}
if (contains_Rect(ui.playPauseRect, mouse)) {
setPaused_Player(plr, !isPaused_Player(plr));
animateMedia_DocumentWidget_(d);
return iTrue;
}
else if (contains_Rect(ui.rewindRect, mouse)) {
if (isStarted_Player(plr) && time_Player(plr) > 0.5f) {
stop_Player(plr);
start_Player(plr);
setPaused_Player(plr, iTrue);
}
refresh_Widget(d);
return iTrue;
}
else if (contains_Rect(ui.volumeRect, mouse)) {
setFlags_Player(plr,
adjustingVolume_PlayerFlag,
!(flags_Player(plr) & adjustingVolume_PlayerFlag));
animateMedia_DocumentWidget_(d);
refresh_Widget(d);
return iTrue;
}
else if (contains_Rect(ui.menuRect, mouse)) {
/* TODO: Add menu items for:
- output device
- Save to Downloads
*/
if (d->playerMenu) {
destroy_Widget(d->playerMenu);
d->playerMenu = NULL;
return iTrue;
}
d->playerMenu = makeMenu_Widget(
as_Widget(d),
(iMenuItem[]){
{ cstrCollect_String(metadataLabel_Player(plr)) },
},
1);
openMenu_Widget(d->playerMenu, bottomLeft_Rect(ui.menuRect));
return iTrue;
}
}
}
return iFalse;
}
static void beginMarkingSelection_DocumentWidget_(iDocumentWidget *d, iInt2 pos) {
setFocus_Widget(NULL); /* TODO: Focus this document? */
invalidateWideRunsWithNonzeroOffset_DocumentView_(&d->view);
resetWideRuns_DocumentView_(&d->view); /* Selections don't support horizontal scrolling. */
iChangeFlags(d->flags, selecting_DocumentWidgetFlag, iTrue);
d->initialSelectMark = d->selectMark = sourceLoc_DocumentView_(&d->view, pos);
refresh_Widget(as_Widget(d));
}
static void interactingWithLink_DocumentWidget_(iDocumentWidget *d, iGmLinkId id) {
iRangecc loc = linkUrlRange_GmDocument(d->view.doc, id);
if (!loc.start) {
clear_String(&d->linePrecedingLink);
return;
}
d->requestLinkId = id;
const char *start = range_String(source_GmDocument(d->view.doc)).start;
/* Find the preceding line. This is offered as a prefill option for a possible input query. */
while (loc.start > start && *loc.start != '\n') {
loc.start--;
}
loc.end = loc.start; /* End of the preceding line. */
if (loc.start > start) {
loc.start--;
}
while (loc.start > start && *loc.start != '\n') {
loc.start--;
}
if (*loc.start == '\n') {
loc.start++; /* Start of the preceding line. */
}
setRange_String(&d->linePrecedingLink, loc);
}
iLocalDef int wheelSwipeSide_DocumentWidget_(const iDocumentWidget *d) {
return (d->flags & rightWheelSwipe_DocumentWidgetFlag ? 2
: d->flags & leftWheelSwipe_DocumentWidgetFlag ? 1
: 0);
}
static void finishWheelSwipe_DocumentWidget_(iDocumentWidget *d) {
if (d->flags & eitherWheelSwipe_DocumentWidgetFlag &&
d->wheelSwipeState == direct_WheelSwipeState) {
const int side = wheelSwipeSide_DocumentWidget_(d);
int abort = ((side == 1 && d->swipeSpeed < 0) || (side == 2 && d->swipeSpeed > 0));
if (iAbs(d->wheelSwipeDistance) < width_Widget(d) / 4 && iAbs(d->swipeSpeed) < 4 * gap_UI) {
abort = 1;
}
postCommand_Widget(d, "edgeswipe.ended side:%d abort:%d", side, abort);
d->flags &= ~eitherWheelSwipe_DocumentWidgetFlag;
}
}
static iBool handleWheelSwipe_DocumentWidget_(iDocumentWidget *d, const SDL_MouseWheelEvent *ev) {
iWidget *w = as_Widget(d);
if (deviceType_App() != desktop_AppDeviceType) {
return iFalse;
}
if (~flags_Widget(w) & horizontalOffset_WidgetFlag) {
return iFalse;
}
iAssert(~d->flags & animationPlaceholder_DocumentWidgetFlag);
// printf("STATE:%d wheel x:%d inert:%d end:%d\n", d->wheelSwipeState,
// ev->x, isInertia_MouseWheelEvent(ev),
// isScrollFinished_MouseWheelEvent(ev));
// fflush(stdout);
switch (d->wheelSwipeState) {
case none_WheelSwipeState:
/* A new swipe starts. */
if (!isInertia_MouseWheelEvent(ev) && !isScrollFinished_MouseWheelEvent(ev)) {
int side = ev->x > 0 ? 1 : 2;
d->wheelSwipeDistance = ev->x * 2;
d->flags &= ~eitherWheelSwipe_DocumentWidgetFlag;
d->flags |= (side == 1 ? leftWheelSwipe_DocumentWidgetFlag
: rightWheelSwipe_DocumentWidgetFlag);
// printf("swipe starts at %d, side %d\n", d->wheelSwipeDistance, side);
d->wheelSwipeState = direct_WheelSwipeState;
d->swipeSpeed = 0;
postCommand_Widget(d, "edgeswipe.moved arg:%d side:%d", d->wheelSwipeDistance, side);
return iTrue;
}
break;
case direct_WheelSwipeState:
if (isInertia_MouseWheelEvent(ev) || isScrollFinished_MouseWheelEvent(ev)) {
finishWheelSwipe_DocumentWidget_(d);
d->wheelSwipeState = none_WheelSwipeState;
}
else {
int step = ev->x * 2;
d->wheelSwipeDistance += step;
/* Remember the maximum speed. */
if (d->swipeSpeed < 0 && step < 0) {
d->swipeSpeed = iMin(d->swipeSpeed, step);
}
else if (d->swipeSpeed > 0 && step > 0) {
d->swipeSpeed = iMax(d->swipeSpeed, step);
}
else {
d->swipeSpeed = step;
}
switch (wheelSwipeSide_DocumentWidget_(d)) {
case 1:
d->wheelSwipeDistance = iMax(0, d->wheelSwipeDistance);
d->wheelSwipeDistance = iMin(width_Widget(d), d->wheelSwipeDistance);
break;
case 2:
d->wheelSwipeDistance = iMin(0, d->wheelSwipeDistance);
d->wheelSwipeDistance = iMax(-width_Widget(d), d->wheelSwipeDistance);
break;
}
/* TODO: calculate speed, rememeber direction */
//printf("swipe moved to %d, side %d\n", d->wheelSwipeDistance, side);
postCommand_Widget(d, "edgeswipe.moved arg:%d side:%d", d->wheelSwipeDistance,
wheelSwipeSide_DocumentWidget_(d));
}
return iTrue;
}
return iFalse;
}
static iBool processEvent_DocumentWidget_(iDocumentWidget *d, const SDL_Event *ev) {
iWidget *w = as_Widget(d);
iDocumentView *view = &d->view;
if (isMetricsChange_UserEvent(ev)) {
updateSize_DocumentWidget(d);
}
else if (processEvent_SmoothScroll(&d->view.scrollY, ev)) {
return iTrue;
}
else if (ev->type == SDL_USEREVENT && ev->user.code == command_UserEventCode) {
if (isCommand_Widget(w, ev, "pullaction")) {
postCommand_Widget(w, "navigate.reload");
return iTrue;
}
if (!handleCommand_DocumentWidget_(d, command_UserEvent(ev))) {
/* Base class commands. */
return processEvent_Widget(w, ev);
}
return iTrue;
}
if (ev->type == SDL_KEYDOWN) {
const int key = ev->key.keysym.sym;
if ((d->flags & showLinkNumbers_DocumentWidgetFlag) &&
((key >= '1' && key <= '9') || (key >= 'a' && key <= 'z'))) {
const size_t ord = linkOrdinalFromKey_DocumentWidget_(d, key) + d->ordinalBase;
iConstForEach(PtrArray, i, &d->view.visibleLinks) {
if (ord == iInvalidPos) break;
const iGmRun *run = i.ptr;
if (run->flags & decoration_GmRunFlag &&
visibleLinkOrdinal_DocumentView_(view, run->linkId) == ord) {
if (d->flags & setHoverViaKeys_DocumentWidgetFlag) {
view->hoverLink = run;
}
else {
postCommandf_Root(
w->root,
"open newtab:%d url:%s",
(isPinned_DocumentWidget_(d) ? otherRoot_OpenTabFlag : 0) ^
(d->ordinalMode == numbersAndAlphabet_DocumentLinkOrdinalMode
? openTabMode_Sym(modState_Keys())
: (d->flags & newTabViaHomeKeys_DocumentWidgetFlag ? 1 : 0)),
cstr_String(absoluteUrl_String(
d->mod.url, linkUrl_GmDocument(view->doc, run->linkId))));
interactingWithLink_DocumentWidget_(d, run->linkId);
}
setLinkNumberMode_DocumentWidget_(d, iFalse);
invalidateVisibleLinks_DocumentView_(view);
refresh_Widget(d);
return iTrue;
}
}
}
switch (key) {
case SDLK_ESCAPE:
if (d->flags & showLinkNumbers_DocumentWidgetFlag && document_App() == d) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
invalidateVisibleLinks_DocumentView_(view);
refresh_Widget(d);
return iTrue;
}
break;
#if !defined (NDEBUG)
case SDLK_KP_1:
case '`': {
iBlock *seed = new_Block(64);
for (size_t i = 0; i < 64; ++i) {
setByte_Block(seed, i, iRandom(0, 256));
}
setThemeSeed_GmDocument(view->doc, seed);
delete_Block(seed);
invalidate_DocumentWidget_(d);
refresh_Widget(w);
break;
}
#endif
#if 0
case '0': {
extern int enableHalfPixelGlyphs_Text;
enableHalfPixelGlyphs_Text = !enableHalfPixelGlyphs_Text;
refresh_Widget(w);
printf("halfpixel: %d\n", enableHalfPixelGlyphs_Text);
fflush(stdout);
break;
}
#endif
#if 0
case '0': {
extern int enableKerning_Text;
enableKerning_Text = !enableKerning_Text;
invalidate_DocumentWidget_(d);
refresh_Widget(w);
printf("kerning: %d\n", enableKerning_Text);
fflush(stdout);
break;
}
#endif
}
}
#if defined (iPlatformAppleDesktop)
else if (ev->type == SDL_MOUSEWHEEL &&
ev->wheel.y == 0 &&
d->wheelSwipeState == direct_WheelSwipeState &&
handleWheelSwipe_DocumentWidget_(d, &ev->wheel)) {
return iTrue;
}
#endif
else if (ev->type == SDL_MOUSEWHEEL && isHover_Widget(w)) {
const iInt2 mouseCoord = coord_MouseWheelEvent(&ev->wheel);
if (isPerPixel_MouseWheelEvent(&ev->wheel)) {
const iInt2 wheel = init_I2(ev->wheel.x, ev->wheel.y);
stop_Anim(&d->view.scrollY.pos);
immediateScroll_DocumentView_(view, -wheel.y);
if (!scrollWideBlock_DocumentView_(view, mouseCoord, -wheel.x, 0) &&
wheel.x) {
handleWheelSwipe_DocumentWidget_(d, &ev->wheel);
}
}
else {
/* Traditional mouse wheel. */
const int amount = ev->wheel.y;
if (keyMods_Sym(modState_Keys()) == KMOD_PRIMARY) {
postCommandf_App("zoom.delta arg:%d", amount > 0 ? 10 : -10);
return iTrue;
}
smoothScroll_DocumentView_(view,
-3 * amount * lineHeight_Text(paragraph_FontId),
smoothDuration_DocumentWidget_(mouse_ScrollType));
scrollWideBlock_DocumentView_(
view, mouseCoord, -3 * ev->wheel.x * lineHeight_Text(paragraph_FontId), 167);
}
iChangeFlags(d->flags, noHoverWhileScrolling_DocumentWidgetFlag, iTrue);
return iTrue;
}
else if (ev->type == SDL_MOUSEMOTION) {
if (ev->motion.which != SDL_TOUCH_MOUSEID) {
iChangeFlags(d->flags, noHoverWhileScrolling_DocumentWidgetFlag, iFalse);
}
const iInt2 mpos = init_I2(ev->motion.x, ev->motion.y);
if (isVisible_Widget(d->menu)) {
setCursor_Window(get_Window(), SDL_SYSTEM_CURSOR_ARROW);
}
#if 0
else if (contains_Rect(siteBannerRect_DocumentWidget_(d), mpos)) {
setCursor_Window(get_Window(), SDL_SYSTEM_CURSOR_HAND);
}
#endif
else {
if (value_Anim(&view->altTextOpacity) < 0.833f) {
setValue_Anim(&view->altTextOpacity, 0, 0); /* keep it hidden while moving */
}
updateHover_DocumentView_(view, mpos);
}
}
if (ev->type == SDL_USEREVENT && ev->user.code == widgetTapBegins_UserEventCode) {
iChangeFlags(d->flags, noHoverWhileScrolling_DocumentWidgetFlag, iFalse);
return iTrue;
}
if (processMediaEvents_DocumentWidget_(d, ev)) {
return iTrue;
}
if (ev->type == SDL_MOUSEBUTTONDOWN) {
if (ev->button.button == SDL_BUTTON_X1) {
postCommand_Root(w->root, "navigate.back");
return iTrue;
}
if (ev->button.button == SDL_BUTTON_X2) {
postCommand_Root(w->root, "navigate.forward");
return iTrue;
}
if (ev->button.button == SDL_BUTTON_MIDDLE && view->hoverLink) {
interactingWithLink_DocumentWidget_(d, view->hoverLink->linkId);
postCommandf_Root(w->root, "open newtab:%d url:%s",
(isPinned_DocumentWidget_(d) ? otherRoot_OpenTabFlag : 0) |
(modState_Keys() & KMOD_SHIFT ? new_OpenTabFlag : newBackground_OpenTabFlag),
cstr_String(linkUrl_GmDocument(view->doc, view->hoverLink->linkId)));
return iTrue;
}
if (ev->button.button == SDL_BUTTON_RIGHT &&
contains_Widget(w, init_I2(ev->button.x, ev->button.y))) {
if (!isVisible_Widget(d->menu)) {
d->contextLink = view->hoverLink;
d->contextPos = init_I2(ev->button.x, ev->button.y);
if (d->menu) {
destroy_Widget(d->menu);
d->menu = NULL;
}
setFocus_Widget(NULL);
iArray items;
init_Array(&items, sizeof(iMenuItem));
if (d->contextLink) {
/* Context menu for a link. */
interactingWithLink_DocumentWidget_(d, d->contextLink->linkId); /* perhaps will be triggered */
const iString *linkUrl = linkUrl_GmDocument(view->doc, d->contextLink->linkId);
// const int linkFlags = linkFlags_GmDocument(d->doc, d->contextLink->linkId);
const iRangecc scheme = urlScheme_String(linkUrl);
const iBool isGemini = equalCase_Rangecc(scheme, "gemini");
iBool isNative = iFalse;
if (deviceType_App() != desktop_AppDeviceType) {
/* Show the link as the first, non-interactive item. */
iString *infoText = collectNew_String();
infoText_LinkInfo(d->view.doc, d->contextLink->linkId, infoText);
pushBack_Array(&items, &(iMenuItem){
format_CStr("```%s", cstr_String(infoText)),
0, 0, NULL });
}
if (willUseProxy_App(scheme) || isGemini ||
equalCase_Rangecc(scheme, "file") ||
equalCase_Rangecc(scheme, "finger") ||
equalCase_Rangecc(scheme, "gopher")) {
isNative = iTrue;
/* Regular links that we can open. */
pushBackN_Array(
&items,
(iMenuItem[]){ { openTab_Icon " ${link.newtab}",
0,
0,
format_CStr("!open newtab:1 origin:%s url:%s",
cstr_String(id_Widget(w)),
cstr_String(linkUrl)) },
{ openTabBg_Icon " ${link.newtab.background}",
0,
0,
format_CStr("!open newtab:2 origin:%s url:%s",
cstr_String(id_Widget(w)),
cstr_String(linkUrl)) },
{ "${link.side}",
0,
0,
format_CStr("!open newtab:4 origin:%s url:%s",
cstr_String(id_Widget(w)),
cstr_String(linkUrl)) },
{ "${link.side.newtab}",
0,
0,
format_CStr("!open newtab:5 origin:%s url:%s",
cstr_String(id_Widget(w)),
cstr_String(linkUrl)) } },
4);
if (deviceType_App() == phone_AppDeviceType) {
removeN_Array(&items, size_Array(&items) - 2, iInvalidSize);
}
if (equalCase_Rangecc(scheme, "file")) {
pushBack_Array(&items, &(iMenuItem){ "---" });
pushBack_Array(&items,
&(iMenuItem){ export_Icon " ${menu.open.external}",
0,
0,
format_CStr("!open default:1 url:%s",
cstr_String(linkUrl)) });
#if defined (iPlatformAppleDesktop)
pushBack_Array(&items,
&(iMenuItem){ "${menu.reveal.macos}",
0,
0,
format_CStr("!reveal url:%s",
cstr_String(linkUrl)) });
#endif
#if defined (iPlatformLinux)
pushBack_Array(&items,
&(iMenuItem){ "${menu.reveal.filemgr}",
0,
0,
format_CStr("!reveal url:%s",
cstr_String(linkUrl)) });
#endif
}
}
else if (!willUseProxy_App(scheme)) {
pushBack_Array(
&items,
&(iMenuItem){ openExt_Icon " ${link.browser}",
0,
0,
format_CStr("!open default:1 url:%s", cstr_String(linkUrl)) });
}
if (willUseProxy_App(scheme)) {
pushBackN_Array(
&items,
(iMenuItem[]){
{ "---" },
{ isGemini ? "${link.noproxy}" : openExt_Icon " ${link.browser}",
0,
0,
format_CStr("!open origin:%s noproxy:1 url:%s",
cstr_String(id_Widget(w)),
cstr_String(linkUrl)) } },
2);
}
iString *linkLabel = collectNewRange_String(
linkLabel_GmDocument(view->doc, d->contextLink->linkId));
urlEncodeSpaces_String(linkLabel);
pushBackN_Array(&items,
(iMenuItem[]){ { "---" },
{ "${link.copy}", 0, 0, "document.copylink" },
{ bookmark_Icon " ${link.bookmark}",
0,
0,
format_CStr("!bookmark.add title:%s url:%s",
cstr_String(linkLabel),
cstr_String(linkUrl)) },
},
3);
if (isNative && d->contextLink->mediaType != download_MediaType &&
!equalCase_Rangecc(scheme, "file")) {
pushBackN_Array(&items, (iMenuItem[]){
{ "---" },
{ download_Icon " ${link.download}", 0, 0, "document.downloadlink" },
}, 2);
}
iMediaRequest *mediaReq;
if ((mediaReq = findMediaRequest_DocumentWidget_(d, d->contextLink->linkId)) != NULL &&
d->contextLink->mediaType != download_MediaType) {
if (isFinished_GmRequest(mediaReq->req)) {
pushBack_Array(&items,
&(iMenuItem){ download_Icon " " saveToDownloads_Label,
0,
0,
format_CStr("document.media.save link:%u",
d->contextLink->linkId) });
}
}
if (equalCase_Rangecc(scheme, "file")) {
/* Local files may be deleted. */
pushBack_Array(&items, &(iMenuItem){ "---" });
pushBack_Array(
&items,
&(iMenuItem){ delete_Icon " " uiTextCaution_ColorEscape
"${link.file.delete}",
0,
0,
format_CStr("!file.delete confirm:1 path:%s",
cstrCollect_String(
localFilePathFromUrl_String(linkUrl))) });
}
}
else if (deviceType_App() == desktop_AppDeviceType) {
if (!isEmpty_Range(&d->selectMark)) {
pushBackN_Array(&items,
(iMenuItem[]){ { "${menu.copy}", 0, 0, "copy" },
{ "---", 0, 0, NULL } },
2);
}
pushBackN_Array(
&items,
(iMenuItem[]){
{ backArrow_Icon " ${menu.back}", navigateBack_KeyShortcut, "navigate.back" },
{ forwardArrow_Icon " ${menu.forward}", navigateForward_KeyShortcut, "navigate.forward" },
{ upArrow_Icon " ${menu.parent}", navigateParent_KeyShortcut, "navigate.parent" },
{ upArrowBar_Icon " ${menu.root}", navigateRoot_KeyShortcut, "navigate.root" },
{ "---" },
{ reload_Icon " ${menu.reload}", reload_KeyShortcut, "navigate.reload" },
{ timer_Icon " ${menu.autoreload}", 0, 0, "document.autoreload.menu" },
{ "---" },
{ bookmark_Icon " ${menu.page.bookmark}", SDLK_d, KMOD_PRIMARY, "bookmark.add" },
{ star_Icon " ${menu.page.subscribe}", subscribeToPage_KeyModifier, "feeds.subscribe" },
{ "---" },
{ book_Icon " ${menu.page.import}", 0, 0, "bookmark.links confirm:1" },
{ globe_Icon " ${menu.page.translate}", 0, 0, "document.translate" },
{ upload_Icon " ${menu.page.upload}", 0, 0, "document.upload" },
{ "${menu.page.upload.edit}", 0, 0, "document.upload copy:1" },
{ "---" },
{ "${menu.page.copyurl}", 0, 0, "document.copylink" } },
17);
if (isEmpty_Range(&d->selectMark)) {
pushBackN_Array(
&items,
(iMenuItem[]){
{ "${menu.page.copysource}", 'c', KMOD_PRIMARY, "copy" },
{ download_Icon " " saveToDownloads_Label, SDLK_s, KMOD_PRIMARY, "document.save" } },
2);
}
}
else {
/* Mobile text selection menu. */
#if 0
pushBackN_Array(
&items,
(iMenuItem[]){
{ "${menu.select}", 0, 0, "document.select arg:1" },
{ "${menu.select.word}", 0, 0, "document.select arg:2" },
{ "${menu.select.par}", 0, 0, "document.select arg:3" },
},
3);
#endif
postCommand_Root(w->root, "document.select arg:1");
return iTrue;
}
d->menu = makeMenu_Widget(w, data_Array(&items), size_Array(&items));
deinit_Array(&items);
setMenuItemDisabled_Widget(
d->menu,
"document.upload",
!equalCase_Rangecc(urlScheme_String(d->mod.url), "gemini") &&
!equalCase_Rangecc(urlScheme_String(d->mod.url), "titan"));
}
processContextMenuEvent_Widget(d->menu, ev, {});
}
}
if (processEvent_Banner(d->banner, ev)) {
return iTrue;
}
/* The left mouse button. */
switch (processEvent_Click(&d->click, ev)) {
case started_ClickResult:
if (d->grabbedPlayer) {
return iTrue;
}
/* Enable hover state now that scrolling has surely finished. */
if (d->flags & noHoverWhileScrolling_DocumentWidgetFlag) {
d->flags &= ~noHoverWhileScrolling_DocumentWidgetFlag;
updateHover_DocumentView_(view, mouseCoord_Window(get_Window(), ev->button.which));
}
if (~flags_Widget(w) & touchDrag_WidgetFlag) {
iChangeFlags(d->flags, selecting_DocumentWidgetFlag, iFalse);
iChangeFlags(d->flags, selectWords_DocumentWidgetFlag, d->click.count == 2);
iChangeFlags(d->flags, selectLines_DocumentWidgetFlag, d->click.count >= 3);
/* Double/triple clicks marks the selection immediately. */
if (d->click.count >= 2) {
beginMarkingSelection_DocumentWidget_(d, d->click.startPos);
extendRange_Rangecc(
&d->selectMark,
range_String(source_GmDocument(view->doc)),
bothStartAndEnd_RangeExtension |
(d->click.count == 2 ? word_RangeExtension : line_RangeExtension));
d->initialSelectMark = d->selectMark;
refresh_Widget(w);
}
else {
d->initialSelectMark = iNullRange;
}
}
return iTrue;
case drag_ClickResult: {
if (d->grabbedPlayer) {
iPlayer *plr =
audioPlayer_Media(media_GmDocument(view->doc), mediaId_GmRun(d->grabbedPlayer));
iPlayerUI ui;
init_PlayerUI(&ui, plr, runRect_DocumentView_(view, d->grabbedPlayer));
float off = (float) delta_Click(&d->click).x / (float) width_Rect(ui.volumeSlider);
setVolume_Player(plr, d->grabbedStartVolume + off);
refresh_Widget(w);
return iTrue;
}
/* Fold/unfold a preformatted block. */
if (~d->flags & selecting_DocumentWidgetFlag && view->hoverPre &&
preIsFolded_GmDocument(view->doc, preId_GmRun(view->hoverPre))) {
return iTrue;
}
/* Begin selecting a range of text. */
if (~d->flags & selecting_DocumentWidgetFlag) {
beginMarkingSelection_DocumentWidget_(d, d->click.startPos);
}
iRangecc loc = sourceLoc_DocumentView_(view, pos_Click(&d->click));
if (d->selectMark.start == NULL) {
d->selectMark = loc;
}
else if (loc.end) {
if (flags_Widget(w) & touchDrag_WidgetFlag) {
/* Choose which end to move. */
if (!(d->flags & (movingSelectMarkStart_DocumentWidgetFlag |
movingSelectMarkEnd_DocumentWidgetFlag))) {
const iRangecc mark = selectMark_DocumentWidget_(d);
const char * midMark = mark.start + size_Range(&mark) / 2;
const iRangecc loc = sourceLoc_DocumentView_(view, pos_Click(&d->click));
const iBool isCloserToStart = d->selectMark.start > d->selectMark.end ?
(loc.start > midMark) : (loc.start < midMark);
iChangeFlags(d->flags, movingSelectMarkStart_DocumentWidgetFlag, isCloserToStart);
iChangeFlags(d->flags, movingSelectMarkEnd_DocumentWidgetFlag, !isCloserToStart);
}
/* Move the start or the end depending on which is nearer. */
if (d->flags & movingSelectMarkStart_DocumentWidgetFlag) {
d->selectMark.start = loc.start;
}
else {
d->selectMark.end = (d->selectMark.end > d->selectMark.start ? loc.end : loc.start);
}
}
else {
d->selectMark.end = loc.end;// (d->selectMark.end > d->selectMark.start ? loc.end : loc.start);
if (loc.start < d->initialSelectMark.start) {
d->selectMark.end = loc.start;
}
if (isEmpty_Range(&d->selectMark)) {
d->selectMark = d->initialSelectMark;
}
}
}
iAssert((!d->selectMark.start && !d->selectMark.end) ||
( d->selectMark.start && d->selectMark.end));
/* Extend to full words/paragraphs. */
if (d->flags & (selectWords_DocumentWidgetFlag | selectLines_DocumentWidgetFlag)) {
extendRange_Rangecc(
&d->selectMark,
range_String(source_GmDocument(view->doc)),
(d->flags & movingSelectMarkStart_DocumentWidgetFlag ? moveStart_RangeExtension
: moveEnd_RangeExtension) |
(d->flags & selectWords_DocumentWidgetFlag ? word_RangeExtension
: line_RangeExtension));
if (d->flags & movingSelectMarkStart_DocumentWidgetFlag) {
d->initialSelectMark.start =
d->initialSelectMark.end = d->selectMark.start;
}
}
if (d->initialSelectMark.start) {
if (d->selectMark.end > d->selectMark.start) {
d->selectMark.start = d->initialSelectMark.start;
}
else if (d->selectMark.end < d->selectMark.start) {
d->selectMark.start = d->initialSelectMark.end;
}
}
// printf("mark %zu ... %zu\n", d->selectMark.start - cstr_String(source_GmDocument(d->doc)),
// d->selectMark.end - cstr_String(source_GmDocument(d->doc)));
// fflush(stdout);
refresh_Widget(w);
return iTrue;
}
case finished_ClickResult:
if (d->grabbedPlayer) {
setGrabbedPlayer_DocumentWidget_(d, NULL);
return iTrue;
}
if (isVisible_Widget(d->menu)) {
closeMenu_Widget(d->menu);
}
d->flags &= ~(movingSelectMarkStart_DocumentWidgetFlag |
movingSelectMarkEnd_DocumentWidgetFlag);
if (!isMoved_Click(&d->click)) {
setFocus_Widget(NULL);
/* Tap in tap selection mode. */
if (flags_Widget(w) & touchDrag_WidgetFlag) {
const iRangecc tapLoc = sourceLoc_DocumentView_(view, pos_Click(&d->click));
/* Tapping on the selection will show a menu. */
const iRangecc mark = selectMark_DocumentWidget_(d);
if (tapLoc.start >= mark.start && tapLoc.end <= mark.end) {
if (d->copyMenu) {
closeMenu_Widget(d->copyMenu);
destroy_Widget(d->copyMenu);
d->copyMenu = NULL;
}
const iMenuItem items[] = {
{ clipCopy_Icon " ${menu.copy}", 0, 0, "copy" },
#if defined (iPlatformAppleMobile)
{ export_Icon " ${menu.share}", 0, 0, "copy share:1" },
#endif
{ "---" },
{ close_Icon " ${menu.select.clear}", 0, 0, "document.select arg:0" },
};
d->copyMenu = makeMenu_Widget(w, items, iElemCount(items));
setFlags_Widget(d->copyMenu, noFadeBackground_WidgetFlag, iTrue);
openMenu_Widget(d->copyMenu, pos_Click(&d->click));
return iTrue;
}
else {
/* Tapping elsewhere exits selection mode. */
postCommand_Widget(d, "document.select arg:0");
return iTrue;
}
}
if (view->hoverPre) {
togglePreFold_DocumentWidget_(d, preId_GmRun(view->hoverPre));
return iTrue;
}
if (view->hoverLink) {
/* TODO: Move this to a method. */
const iGmLinkId linkId = view->hoverLink->linkId;
const iMediaId linkMedia = mediaId_GmRun(view->hoverLink);
const int linkFlags = linkFlags_GmDocument(view->doc, linkId);
iAssert(linkId);
/* Media links are opened inline by default. */
if (isMediaLink_GmDocument(view->doc, linkId)) {
if (linkFlags & content_GmLinkFlag && linkFlags & permanent_GmLinkFlag) {
/* We have the content and it cannot be dismissed, so nothing
further to do. */
return iTrue;
}
if (!requestMedia_DocumentWidget_(d, linkId, iTrue)) {
if (linkFlags & content_GmLinkFlag) {
/* Dismiss shown content on click. */
setData_Media(media_GmDocument(view->doc),
linkId,
NULL,
NULL,
allowHide_MediaFlag);
/* Cancel a partially received request. */ {
iMediaRequest *req = findMediaRequest_DocumentWidget_(d, linkId);
if (!isFinished_GmRequest(req->req)) {
cancel_GmRequest(req->req);
removeMediaRequest_DocumentWidget_(d, linkId);
/* Note: Some of the audio IDs have changed now, layout must
be redone. */
}
}
redoLayout_GmDocument(view->doc);
view->hoverLink = NULL;
clampScroll_DocumentView_(view);
updateVisible_DocumentView_(view);
invalidate_DocumentWidget_(d);
refresh_Widget(w);
return iTrue;
}
else {
/* Show the existing content again if we have it. */
iMediaRequest *req = findMediaRequest_DocumentWidget_(d, linkId);
if (req) {
setData_Media(media_GmDocument(view->doc),
linkId,
meta_GmRequest(req->req),
body_GmRequest(req->req),
allowHide_MediaFlag);
redoLayout_GmDocument(view->doc);
updateVisible_DocumentView_(view);
invalidate_DocumentWidget_(d);
refresh_Widget(w);
return iTrue;
}
}
}
refresh_Widget(w);
}
else if (linkMedia.type == download_MediaType ||
findMediaRequest_DocumentWidget_(d, linkId)) {
/* TODO: What should be done when clicking on an inline download?
Maybe dismiss if finished? */
return iTrue;
}
else if (linkFlags & supportedScheme_GmLinkFlag) {
int tabMode = openTabMode_Sym(modState_Keys());
if (isPinned_DocumentWidget_(d)) {
tabMode ^= otherRoot_OpenTabFlag;
}
interactingWithLink_DocumentWidget_(d, linkId);
postCommandf_Root(w->root, "open newtab:%d url:%s",
tabMode,
cstr_String(absoluteUrl_String(
d->mod.url, linkUrl_GmDocument(view->doc, linkId))));
}
else {
const iString *url = absoluteUrl_String(
d->mod.url, linkUrl_GmDocument(view->doc, linkId));
makeQuestion_Widget(
uiTextCaution_ColorEscape "${heading.openlink}",
format_CStr(
cstr_Lang("dlg.openlink.confirm"),
uiTextAction_ColorEscape,
cstr_String(url)),
(iMenuItem[]){
{ "${cancel}" },
{ uiTextCaution_ColorEscape "${dlg.openlink}",
0, 0, format_CStr("!open default:1 url:%s", cstr_String(url)) } },
2);
}
}
if (d->selectMark.start && !(d->flags & (selectLines_DocumentWidgetFlag |
selectWords_DocumentWidgetFlag))) {
d->selectMark = iNullRange;
refresh_Widget(w);
}
}
return iTrue;
case aborted_ClickResult:
if (d->grabbedPlayer) {
setGrabbedPlayer_DocumentWidget_(d, NULL);
return iTrue;
}
return iTrue;
default:
break;
}
return processEvent_Widget(w, ev);
}
static void checkPendingInvalidation_DocumentWidget_(const iDocumentWidget *d) {
if (d->flags & invalidationPending_DocumentWidgetFlag &&
!isAffectedByVisualOffset_Widget(constAs_Widget(d))) {
// printf("%p visoff: %d\n", d, left_Rect(bounds_Widget(w)) - left_Rect(boundsWithoutVisualOffset_Widget(w)));
iDocumentWidget *m = (iDocumentWidget *) d; /* Hrrm, not const... */
m->flags &= ~invalidationPending_DocumentWidgetFlag;
invalidate_DocumentWidget_(m);
}
}
static void prerender_DocumentWidget_(iAny *context) {
iAssert(isInstance_Object(context, &Class_DocumentWidget));
if (current_Root() == NULL) {
/* The widget has probably been removed from the widget tree, pending destruction.
Tickers are not cancelled until the widget is actually destroyed. */
return;
}
const iDocumentWidget *d = context;
iDrawContext ctx = {
.view = &d->view,
.docBounds = documentBounds_DocumentView_(&d->view),
.vis = visibleRange_DocumentView_(&d->view),
.showLinkNumbers = (d->flags & showLinkNumbers_DocumentWidgetFlag) != 0
};
// printf("%u prerendering\n", SDL_GetTicks());
if (d->view.visBuf->buffers[0].texture) {
makePaletteGlobal_GmDocument(d->view.doc);
if (render_DocumentView_(&d->view, &ctx, iTrue /* just fill up progressively */)) {
/* Something was drawn, should check later if there is still more to do. */
addTicker_App(prerender_DocumentWidget_, context);
}
}
}
static void draw_DocumentWidget_(const iDocumentWidget *d) {
const iWidget *w = constAs_Widget(d);
const iRect bounds = bounds_Widget(w);
const iRect boundsWithoutVisOff = boundsWithoutVisualOffset_Widget(w);
const iRect clipBounds = intersect_Rect(bounds, boundsWithoutVisOff);
if (width_Rect(bounds) <= 0) {
return;
}
checkPendingInvalidation_DocumentWidget_(d);
draw_DocumentView_(&d->view);
iPaint p;
init_Paint(&p);
if (colorTheme_App() == pureWhite_ColorTheme) {
drawHLine_Paint(&p, topLeft_Rect(bounds), width_Rect(bounds), uiSeparator_ColorId);
}
/* Pull action indicator. */
if (deviceType_App() != desktop_AppDeviceType) {
float pullPos = pullActionPos_SmoothScroll(&d->view.scrollY);
/* Account for the part where the indicator isn't yet visible. */
pullPos = (pullPos - 0.2f) / 0.8f;
iRect indRect = initCentered_Rect(init_I2(mid_Rect(bounds).x,
top_Rect(bounds) - 5 * gap_UI -
pos_SmoothScroll(&d->view.scrollY)),
init_I2(20 * gap_UI, 2 * gap_UI));
setClip_Paint(&p, clipBounds);
int color = pullPos < 1.0f ? tmBannerItemFrame_ColorId : tmBannerItemText_ColorId;
drawRect_Paint(&p, indRect, color);
if (pullPos > 0) {
shrink_Rect(&indRect, divi_I2(gap2_UI, 2));
indRect.size.x *= pullPos;
fillRect_Paint(&p, indRect, color);
}
unsetClip_Paint(&p);
}
/* Scroll bar. */
drawChildren_Widget(w);
/* Information about the hovered link. */
if (deviceType_App() == desktop_AppDeviceType && prefs_App()->hoverLink && d->linkInfo) {
const int pad = 0; /*gap_UI;*/
update_LinkInfo(d->linkInfo,
d->view.doc,
d->view.hoverLink ? d->view.hoverLink->linkId : 0,
width_Rect(bounds) - 2 * pad);
const iInt2 infoSize = size_LinkInfo(d->linkInfo);
iInt2 infoPos = add_I2(bottomLeft_Rect(bounds), init_I2(pad, -infoSize.y - pad));
if (d->view.hoverLink) {
const iRect runRect = runRect_DocumentView_(&d->view, d->view.hoverLink);
d->linkInfo->isAltPos =
(bottom_Rect(runRect) >= infoPos.y - lineHeight_Text(paragraph_FontId));
}
if (d->linkInfo->isAltPos) {
infoPos.y = top_Rect(bounds) + pad;
}
draw_LinkInfo(d->linkInfo, infoPos);
}
/* Full-sized download indicator. */
if (d->flags & drawDownloadCounter_DocumentWidgetFlag && isRequestOngoing_DocumentWidget(d)) {
const int font = uiLabelLarge_FontId;
const iInt2 sevenSegWidth = measureRange_Text(font, range_CStr("\U0001fbf0")).bounds.size;
drawSevenSegmentBytes_MediaUI(font,
add_I2(mid_Rect(bounds),
init_I2(sevenSegWidth.x * 4.5f, -sevenSegWidth.y / 2)),
tmQuote_ColorId, tmQuoteIcon_ColorId,
bodySize_GmRequest(d->request));
}
/* Pinch zoom indicator. */
if (d->flags & pinchZoom_DocumentWidgetFlag) {
const int font = uiLabelLargeBold_FontId;
const int height = lineHeight_Text(font) * 2;
const iInt2 size = init_I2(height * 2, height);
const iRect rect = { sub_I2(mid_Rect(bounds), divi_I2(size, 2)), size };
fillRect_Paint(&p, rect, d->pinchZoomPosted == 100 ? uiTextCaution_ColorId : uiTextAction_ColorId);
drawCentered_Text(font, bounds, iFalse, uiBackground_ColorId, "%d %%",
d->pinchZoomPosted);
}
/* Dimming during swipe animation. */
if (w->offsetRef) {
const int offX = visualOffsetByReference_Widget(w);
if (offX) {
setClip_Paint(&p, clipBounds);
SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_BLEND);
p.alpha = iAbs(offX) / (float) get_Window()->size.x * 300;
fillRect_Paint(&p, bounds, backgroundFadeColor_Widget());
SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_NONE);
unsetClip_Paint(&p);
}
else {
/* TODO: Should have a better place to do this; drawing is supposed to be immutable. */
iWidget *mut = iConstCast(iWidget *, w);
mut->offsetRef = NULL;
mut->flags &= ~refChildrenOffset_WidgetFlag;
}
}
// drawRect_Paint(&p, docBounds, red_ColorId);
if (deviceType_App() == phone_AppDeviceType) {
/* The phone toolbar uses the palette of the active tab, but there may be other
documents drawn before the toolbar, causing the colors to be incorrect. */
makePaletteGlobal_GmDocument(document_App()->view.doc);
}
}
/*----------------------------------------------------------------------------------------------*/
void init_DocumentWidget(iDocumentWidget *d) {
iWidget *w = as_Widget(d);
init_Widget(w);
setId_Widget(w, format_CStr("document%03d", ++docEnum_));
setFlags_Widget(w, hover_WidgetFlag | noBackground_WidgetFlag, iTrue);
#if defined (iPlatformAppleDesktop)
iBool enableSwipeNavigation = iTrue; /* swipes on the trackpad */
#else
iBool enableSwipeNavigation = (deviceType_App() != desktop_AppDeviceType);
#endif
if (enableSwipeNavigation) {
setFlags_Widget(w, leftEdgeDraggable_WidgetFlag | rightEdgeDraggable_WidgetFlag |
horizontalOffset_WidgetFlag, iTrue);
}
init_PersistentDocumentState(&d->mod);
d->flags = 0;
d->phoneToolbar = findWidget_App("toolbar");
d->footerButtons = NULL;
iZap(d->certExpiry);
d->certFingerprint = new_Block(0);
d->certFlags = 0;
d->certSubject = new_String();
d->state = blank_RequestState;
d->titleUser = new_String();
d->request = NULL;
d->requestLinkId = 0;
d->isRequestUpdated = iFalse;
d->media = new_ObjectList();
d->banner = new_Banner();
setOwner_Banner(d->banner, d);
d->redirectCount = 0;
d->ordinalBase = 0;
d->wheelSwipeState = none_WheelSwipeState;
d->selectMark = iNullRange;
d->foundMark = iNullRange;
d->contextLink = NULL;
d->sourceStatus = none_GmStatusCode;
init_String(&d->sourceHeader);
init_String(&d->sourceMime);
init_Block(&d->sourceContent, 0);
iZap(d->sourceTime);
d->sourceGempub = NULL;
d->initNormScrollY = 0;
d->grabbedPlayer = NULL;
d->mediaTimer = 0;
init_String(&d->pendingGotoHeading);
init_String(&d->linePrecedingLink);
init_Click(&d->click, d, SDL_BUTTON_LEFT);
d->linkInfo = (deviceType_App() == desktop_AppDeviceType ? new_LinkInfo() : NULL);
init_DocumentView(&d->view);
setOwner_DocumentView_(&d->view, d);
addChild_Widget(w, iClob(d->scroll = new_ScrollWidget()));
d->menu = NULL; /* created when clicking */
d->playerMenu = NULL;
d->copyMenu = NULL;
d->translation = NULL;
addChildFlags_Widget(w,
iClob(new_IndicatorWidget()),
resizeToParentWidth_WidgetFlag | resizeToParentHeight_WidgetFlag);
#if !defined (iPlatformAppleDesktop) /* in system menu */
addAction_Widget(w, reload_KeyShortcut, "navigate.reload");
addAction_Widget(w, closeTab_KeyShortcut, "tabs.close");
addAction_Widget(w, SDLK_d, KMOD_PRIMARY, "bookmark.add");
addAction_Widget(w, subscribeToPage_KeyModifier, "feeds.subscribe");
#endif
addAction_Widget(w, navigateBack_KeyShortcut, "navigate.back");
addAction_Widget(w, navigateForward_KeyShortcut, "navigate.forward");
addAction_Widget(w, navigateParent_KeyShortcut, "navigate.parent");
addAction_Widget(w, navigateRoot_KeyShortcut, "navigate.root");
}
void cancelAllRequests_DocumentWidget(iDocumentWidget *d) {
iForEach(ObjectList, i, d->media) {
iMediaRequest *mr = i.object;
cancel_GmRequest(mr->req);
}
if (d->request) {
cancel_GmRequest(d->request);
}
}
void deinit_DocumentWidget(iDocumentWidget *d) {
// printf("\n* * * * * * * *\nDEINIT DOCUMENT: %s\n* * * * * * * *\n\n",
// cstr_String(&d->widget.id)); fflush(stdout);
cancelAllRequests_DocumentWidget(d);
pauseAllPlayers_Media(media_GmDocument(d->view.doc), iTrue);
removeTicker_App(animate_DocumentWidget_, d);
removeTicker_App(prerender_DocumentWidget_, d);
remove_Periodic(periodic_App(), d);
delete_Translation(d->translation);
deinit_DocumentView(&d->view);
delete_LinkInfo(d->linkInfo);
iRelease(d->media);
iRelease(d->request);
delete_Gempub(d->sourceGempub);
deinit_String(&d->linePrecedingLink);
deinit_String(&d->pendingGotoHeading);
deinit_Block(&d->sourceContent);
deinit_String(&d->sourceMime);
deinit_String(&d->sourceHeader);
delete_Banner(d->banner);
if (d->mediaTimer) {
SDL_RemoveTimer(d->mediaTimer);
}
delete_Block(d->certFingerprint);
delete_String(d->certSubject);
delete_String(d->titleUser);
deinit_PersistentDocumentState(&d->mod);
}
void setSource_DocumentWidget(iDocumentWidget *d, const iString *source) {
setUrl_GmDocument(d->view.doc, d->mod.url);
const int docWidth = documentWidth_DocumentView_(&d->view);
setSource_GmDocument(d->view.doc,
source,
docWidth,
width_Widget(d),
isFinished_GmRequest(d->request) ? final_GmDocumentUpdate
: partial_GmDocumentUpdate);
setWidth_Banner(d->banner, docWidth);
documentWasChanged_DocumentWidget_(d);
}
iHistory *history_DocumentWidget(iDocumentWidget *d) {
return d->mod.history;
}
const iString *url_DocumentWidget(const iDocumentWidget *d) {
return d->mod.url;
}
const iGmDocument *document_DocumentWidget(const iDocumentWidget *d) {
return d->view.doc;
}
const iBlock *sourceContent_DocumentWidget(const iDocumentWidget *d) {
return &d->sourceContent;
}
int documentWidth_DocumentWidget(const iDocumentWidget *d) {
return documentWidth_DocumentView_(&d->view);
}
const iString *feedTitle_DocumentWidget(const iDocumentWidget *d) {
if (!isEmpty_String(title_GmDocument(d->view.doc))) {
return title_GmDocument(d->view.doc);
}
return bookmarkTitle_DocumentWidget(d);
}
const iString *bookmarkTitle_DocumentWidget(const iDocumentWidget *d) {
iStringArray *title = iClob(new_StringArray());
if (!isEmpty_String(title_GmDocument(d->view.doc))) {
pushBack_StringArray(title, title_GmDocument(d->view.doc));
}
if (!isEmpty_String(d->titleUser)) {
pushBack_StringArray(title, d->titleUser);
}
if (isEmpty_StringArray(title)) {
iUrl parts;
init_Url(&parts, d->mod.url);
if (!isEmpty_Range(&parts.host)) {
pushBackRange_StringArray(title, parts.host);
}
}
if (isEmpty_StringArray(title)) {
pushBackCStr_StringArray(title, cstr_Lang("bookmark.title.blank"));
}
return collect_String(joinCStr_StringArray(title, " \u2014 "));
}
void serializeState_DocumentWidget(const iDocumentWidget *d, iStream *outs) {
serialize_PersistentDocumentState(&d->mod, outs);
}
void deserializeState_DocumentWidget(iDocumentWidget *d, iStream *ins) {
deserialize_PersistentDocumentState(&d->mod, ins);
parseUser_DocumentWidget_(d);
updateFromHistory_DocumentWidget_(d);
}
void setUrlFlags_DocumentWidget(iDocumentWidget *d, const iString *url, int setUrlFlags) {
const iBool allowCache = (setUrlFlags & useCachedContentIfAvailable_DocumentWidgetSetUrlFlag) != 0;
setLinkNumberMode_DocumentWidget_(d, iFalse);
setUrl_DocumentWidget_(d, urlFragmentStripped_String(url));
/* See if there a username in the URL. */
parseUser_DocumentWidget_(d);
if (!allowCache || !updateFromHistory_DocumentWidget_(d)) {
fetch_DocumentWidget_(d);
}
}
void setUrlAndSource_DocumentWidget(iDocumentWidget *d, const iString *url, const iString *mime,
const iBlock *source) {
setLinkNumberMode_DocumentWidget_(d, iFalse);
setUrl_DocumentWidget_(d, url);
parseUser_DocumentWidget_(d);
iGmResponse *resp = new_GmResponse();
resp->statusCode = success_GmStatusCode;
initCurrent_Time(&resp->when);
set_String(&resp->meta, mime);
set_Block(&resp->body, source);
updateFromCachedResponse_DocumentWidget_(d, 0, resp, NULL);
updateBanner_DocumentWidget_(d);
delete_GmResponse(resp);
}
iDocumentWidget *duplicate_DocumentWidget(const iDocumentWidget *orig) {
iDocumentWidget *d = new_DocumentWidget();
delete_History(d->mod.history);
d->initNormScrollY = normScrollPos_DocumentView_(&d->view);
d->mod.history = copy_History(orig->mod.history);
setUrlFlags_DocumentWidget(d, orig->mod.url, useCachedContentIfAvailable_DocumentWidgetSetUrlFlag);
return d;
}
void setOrigin_DocumentWidget(iDocumentWidget *d, const iDocumentWidget *other) {
if (d != other) {
/* TODO: Could remember the other's ID? */
set_String(&d->linePrecedingLink, &other->linePrecedingLink);
}
}
void setUrl_DocumentWidget(iDocumentWidget *d, const iString *url) {
setUrlFlags_DocumentWidget(d, url, 0);
}
void setInitialScroll_DocumentWidget(iDocumentWidget *d, float normScrollY) {
d->initNormScrollY = normScrollY;
}
void setRedirectCount_DocumentWidget(iDocumentWidget *d, int count) {
d->redirectCount = count;
}
iBool isRequestOngoing_DocumentWidget(const iDocumentWidget *d) {
return d->request != NULL;
}
void takeRequest_DocumentWidget(iDocumentWidget *d, iGmRequest *finishedRequest) {
cancelRequest_DocumentWidget_(d, iFalse /* don't post anything */);
const iString *url = url_GmRequest(finishedRequest);
add_History(d->mod.history, url);
setUrl_DocumentWidget_(d, url);
d->state = fetching_RequestState;
iAssert(d->request == NULL);
d->request = finishedRequest;
postCommand_Widget(d,
"document.request.finished doc:%p reqid:%u request:%p",
d,
id_GmRequest(d->request),
d->request);
}
void updateSize_DocumentWidget(iDocumentWidget *d) {
iDocumentView *view = &d->view;
updateDocumentWidthRetainingScrollPosition_DocumentView_(view, iFalse);
resetWideRuns_DocumentView_(view);
view->drawBufs->flags |= updateSideBuf_DrawBufsFlag;
updateVisible_DocumentView_(view);
setWidth_Banner(d->banner, documentWidth_DocumentView_(view));
invalidate_DocumentWidget_(d);
arrange_Widget(d->footerButtons);
}
iBeginDefineSubclass(DocumentWidget, Widget)
.processEvent = (iAny *) processEvent_DocumentWidget_,
.draw = (iAny *) draw_DocumentWidget_,
iEndDefineSubclass(DocumentWidget)
|