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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "SimpleXULLeafFrame.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/Likely.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PresShell.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/Try.h"
#include "mozilla/intl/Segmenter.h"
#include "gfxUtils.h"
#include "nsAlgorithm.h"
#include "nsCOMPtr.h"
#include "nsComponentManagerUtils.h"
#include "nsFontMetrics.h"
#include "nsITreeView.h"
#include "nsPresContext.h"
#include "nsNameSpaceManager.h"
#include "nsTreeBodyFrame.h"
#include "nsTreeSelection.h"
#include "nsTreeImageListener.h"
#include "nsGkAtoms.h"
#include "nsCSSAnonBoxes.h"
#include "gfxContext.h"
#include "nsIContent.h"
#include "mozilla/ComputedStyle.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/ReferrerInfo.h"
#include "mozilla/intl/Segmenter.h"
#include "nsCSSRendering.h"
#include "nsString.h"
#include "nsContainerFrame.h"
#include "nsView.h"
#include "nsViewManager.h"
#include "nsVariant.h"
#include "nsWidgetsCID.h"
#include "nsIFrameInlines.h"
#include "nsTreeContentView.h"
#include "nsTreeUtils.h"
#include "nsStyleConsts.h"
#include "nsITheme.h"
#include "imgIRequest.h"
#include "imgIContainer.h"
#include "mozilla/dom/NodeInfo.h"
#include "nsContentUtils.h"
#include "nsLayoutUtils.h"
#include "nsIScrollableFrame.h"
#include "nsDisplayList.h"
#include "mozilla/dom/CustomEvent.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TreeColumnBinding.h"
#include <algorithm>
#include "ScrollbarActivity.h"
#ifdef ACCESSIBILITY
# include "nsAccessibilityService.h"
# include "nsIWritablePropertyBag2.h"
#endif
#include "nsBidiUtils.h"
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::gfx;
using namespace mozilla::image;
using namespace mozilla::layout;
enum CroppingStyle { CropNone, CropLeft, CropRight, CropCenter, CropAuto };
// FIXME: Maybe unify with MiddleCroppingBlockFrame?
static void CropStringForWidth(nsAString& aText, gfxContext& aRenderingContext,
nsFontMetrics& aFontMetrics, nscoord aWidth,
CroppingStyle aCropType) {
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
// See if the width is even smaller than the ellipsis
// If so, clear the text completely.
const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
aFontMetrics.SetTextRunRTL(false);
nscoord ellipsisWidth =
nsLayoutUtils::AppUnitWidthOfString(kEllipsis, aFontMetrics, drawTarget);
if (ellipsisWidth > aWidth) {
aText.Truncate(0);
return;
}
if (ellipsisWidth == aWidth) {
aText.Assign(kEllipsis);
return;
}
// We will be drawing an ellipsis, thank you very much.
// Subtract out the required width of the ellipsis.
// This is the total remaining width we have to play with.
aWidth -= ellipsisWidth;
using mozilla::intl::GraphemeClusterBreakIteratorUtf16;
using mozilla::intl::GraphemeClusterBreakReverseIteratorUtf16;
// Now we crop. This is quite basic: it will not be really accurate in the
// presence of complex scripts with contextual shaping, etc., as it measures
// each grapheme cluster in isolation, not in its proper context.
switch (aCropType) {
case CropAuto:
case CropNone:
case CropRight: {
const Span text(aText);
GraphemeClusterBreakIteratorUtf16 iter(text);
uint32_t pos = 0;
nscoord totalWidth = 0;
while (Maybe<uint32_t> nextPos = iter.Next()) {
const nscoord charWidth = nsLayoutUtils::AppUnitWidthOfString(
text.FromTo(pos, *nextPos), aFontMetrics, drawTarget);
if (totalWidth + charWidth > aWidth) {
break;
}
pos = *nextPos;
totalWidth += charWidth;
}
if (pos < aText.Length()) {
aText.Replace(pos, aText.Length() - pos, kEllipsis);
}
} break;
case CropLeft: {
const Span text(aText);
GraphemeClusterBreakReverseIteratorUtf16 iter(text);
uint32_t pos = text.Length();
nscoord totalWidth = 0;
// nextPos is decreasing since we use a reverse iterator.
while (Maybe<uint32_t> nextPos = iter.Next()) {
const nscoord charWidth = nsLayoutUtils::AppUnitWidthOfString(
text.FromTo(*nextPos, pos), aFontMetrics, drawTarget);
if (totalWidth + charWidth > aWidth) {
break;
}
pos = *nextPos;
totalWidth += charWidth;
}
if (pos > 0) {
aText.Replace(0, pos, kEllipsis);
}
} break;
case CropCenter: {
const Span text(aText);
nscoord totalWidth = 0;
GraphemeClusterBreakIteratorUtf16 leftIter(text);
GraphemeClusterBreakReverseIteratorUtf16 rightIter(text);
uint32_t leftPos = 0;
uint32_t rightPos = text.Length();
while (leftPos < rightPos) {
Maybe<uint32_t> nextPos = leftIter.Next();
nscoord charWidth = nsLayoutUtils::AppUnitWidthOfString(
text.FromTo(leftPos, *nextPos), aFontMetrics, drawTarget);
if (totalWidth + charWidth > aWidth) {
break;
}
leftPos = *nextPos;
totalWidth += charWidth;
if (leftPos >= rightPos) {
break;
}
nextPos = rightIter.Next();
charWidth = nsLayoutUtils::AppUnitWidthOfString(
text.FromTo(*nextPos, rightPos), aFontMetrics, drawTarget);
if (totalWidth + charWidth > aWidth) {
break;
}
rightPos = *nextPos;
totalWidth += charWidth;
}
if (leftPos < rightPos) {
aText.Replace(leftPos, rightPos - leftPos, kEllipsis);
}
} break;
}
}
// Function that cancels all the image requests in our cache.
void nsTreeBodyFrame::CancelImageRequests() {
for (nsTreeImageCacheEntry entry : mImageCache.Values()) {
// If our imgIRequest object was registered with the refresh driver
// then we need to deregister it.
nsLayoutUtils::DeregisterImageRequest(PresContext(), entry.request,
nullptr);
entry.request->UnlockImage();
entry.request->CancelAndForgetObserver(NS_BINDING_ABORTED);
}
}
//
// NS_NewTreeFrame
//
// Creates a new tree frame
//
nsIFrame* NS_NewTreeBodyFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
return new (aPresShell) nsTreeBodyFrame(aStyle, aPresShell->GetPresContext());
}
NS_IMPL_FRAMEARENA_HELPERS(nsTreeBodyFrame)
NS_QUERYFRAME_HEAD(nsTreeBodyFrame)
NS_QUERYFRAME_ENTRY(nsIScrollbarMediator)
NS_QUERYFRAME_ENTRY(nsTreeBodyFrame)
NS_QUERYFRAME_TAIL_INHERITING(SimpleXULLeafFrame)
// Constructor
nsTreeBodyFrame::nsTreeBodyFrame(ComputedStyle* aStyle,
nsPresContext* aPresContext)
: SimpleXULLeafFrame(aStyle, aPresContext, kClassID),
mTopRowIndex(0),
mPageLength(0),
mHorzPosition(0),
mOriginalHorzWidth(-1),
mHorzWidth(0),
mAdjustWidth(0),
mRowHeight(0),
mIndentation(0),
mUpdateBatchNest(0),
mRowCount(0),
mMouseOverRow(-1),
mFocused(false),
mHasFixedRowCount(false),
mVerticalOverflow(false),
mHorizontalOverflow(false),
mReflowCallbackPosted(false),
mCheckingOverflow(false) {
mColumns = new nsTreeColumns(this);
}
// Destructor
nsTreeBodyFrame::~nsTreeBodyFrame() {
CancelImageRequests();
DetachImageListeners();
}
static void GetBorderPadding(ComputedStyle* aStyle, nsMargin& aMargin) {
aMargin.SizeTo(0, 0, 0, 0);
aStyle->StylePadding()->GetPadding(aMargin);
aMargin += aStyle->StyleBorder()->GetComputedBorder();
}
static void AdjustForBorderPadding(ComputedStyle* aStyle, nsRect& aRect) {
nsMargin borderPadding(0, 0, 0, 0);
GetBorderPadding(aStyle, borderPadding);
aRect.Deflate(borderPadding);
}
void nsTreeBodyFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
nsIFrame* aPrevInFlow) {
SimpleXULLeafFrame::Init(aContent, aParent, aPrevInFlow);
mIndentation = GetIndentation();
mRowHeight = GetRowHeight();
// Call GetBaseElement so that mTree is assigned.
RefPtr<XULTreeElement> tree(GetBaseElement());
if (MOZ_LIKELY(tree)) {
nsAutoString rows;
if (tree->GetAttr(nsGkAtoms::rows, rows)) {
nsresult err;
mPageLength = rows.ToInteger(&err);
mHasFixedRowCount = true;
}
}
if (PresContext()->UseOverlayScrollbars()) {
mScrollbarActivity =
new ScrollbarActivity(static_cast<nsIScrollbarMediator*>(this));
}
}
void nsTreeBodyFrame::Destroy(DestroyContext& aContext) {
if (mScrollbarActivity) {
mScrollbarActivity->Destroy();
mScrollbarActivity = nullptr;
}
mScrollEvent.Revoke();
// Make sure we cancel any posted callbacks.
if (mReflowCallbackPosted) {
PresShell()->CancelReflowCallback(this);
mReflowCallbackPosted = false;
}
if (mColumns) mColumns->SetTree(nullptr);
RefPtr tree = mTree;
if (nsCOMPtr<nsITreeView> view = std::move(mView)) {
nsCOMPtr<nsITreeSelection> sel;
view->GetSelection(getter_AddRefs(sel));
if (sel) {
sel->SetTree(nullptr);
}
view->SetTree(nullptr);
}
// Make this call now because view->SetTree can run js which can undo this
// call.
if (tree) {
tree->BodyDestroyed(mTopRowIndex);
}
if (mTree && mTree != tree) {
mTree->BodyDestroyed(mTopRowIndex);
}
SimpleXULLeafFrame::Destroy(aContext);
}
void nsTreeBodyFrame::EnsureView() {
if (mView) {
return;
}
if (PresShell()->IsReflowLocked()) {
if (!mReflowCallbackPosted) {
mReflowCallbackPosted = true;
PresShell()->PostReflowCallback(this);
}
return;
}
AutoWeakFrame weakFrame(this);
RefPtr<XULTreeElement> tree = GetBaseElement();
if (!tree) {
return;
}
nsCOMPtr<nsITreeView> treeView = tree->GetView();
if (!treeView || !weakFrame.IsAlive()) {
return;
}
int32_t rowIndex = tree->GetCachedTopVisibleRow();
// Set our view.
SetView(treeView);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
// Scroll to the given row.
// XXX is this optimal if we haven't laid out yet?
ScrollToRow(rowIndex);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
}
void nsTreeBodyFrame::ManageReflowCallback() {
const nscoord horzWidth = CalcHorzWidth(GetScrollParts());
if (!mReflowCallbackPosted) {
if (!mLastReflowRect || !mLastReflowRect->IsEqualEdges(mRect) ||
mHorzWidth != horzWidth) {
PresShell()->PostReflowCallback(this);
mReflowCallbackPosted = true;
mOriginalHorzWidth = mHorzWidth;
}
} else if (mHorzWidth != horzWidth && mOriginalHorzWidth == horzWidth) {
// FIXME(emilio): This doesn't seem sound to me, if the rect changes in the
// block axis.
PresShell()->CancelReflowCallback(this);
mReflowCallbackPosted = false;
mOriginalHorzWidth = -1;
}
mLastReflowRect = Some(mRect);
mHorzWidth = horzWidth;
}
nscoord nsTreeBodyFrame::GetIntrinsicBSize() {
return mHasFixedRowCount ? mRowHeight * mPageLength : 0;
}
void nsTreeBodyFrame::DidReflow(nsPresContext* aPresContext,
const ReflowInput* aReflowInput) {
ManageReflowCallback();
SimpleXULLeafFrame::DidReflow(aPresContext, aReflowInput);
}
bool nsTreeBodyFrame::ReflowFinished() {
if (!mView) {
AutoWeakFrame weakFrame(this);
EnsureView();
NS_ENSURE_TRUE(weakFrame.IsAlive(), false);
}
if (mView) {
CalcInnerBox();
ScrollParts parts = GetScrollParts();
mHorzWidth = CalcHorzWidth(parts);
if (!mHasFixedRowCount) {
mPageLength =
(mRowHeight > 0) ? (mInnerBox.height / mRowHeight) : mRowCount;
}
int32_t lastPageTopRow = std::max(0, mRowCount - mPageLength);
if (mTopRowIndex > lastPageTopRow)
ScrollToRowInternal(parts, lastPageTopRow);
XULTreeElement* treeContent = GetBaseElement();
if (treeContent && treeContent->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::keepcurrentinview,
nsGkAtoms::_true, eCaseMatters)) {
// make sure that the current selected item is still
// visible after the tree changes size.
if (nsCOMPtr<nsITreeSelection> sel = GetSelection()) {
int32_t currentIndex;
sel->GetCurrentIndex(¤tIndex);
if (currentIndex != -1) {
EnsureRowIsVisibleInternal(parts, currentIndex);
}
}
}
if (!FullScrollbarsUpdate(false)) {
return false;
}
}
mReflowCallbackPosted = false;
return false;
}
void nsTreeBodyFrame::ReflowCallbackCanceled() {
mReflowCallbackPosted = false;
}
nsresult nsTreeBodyFrame::GetView(nsITreeView** aView) {
*aView = nullptr;
AutoWeakFrame weakFrame(this);
EnsureView();
NS_ENSURE_STATE(weakFrame.IsAlive());
NS_IF_ADDREF(*aView = mView);
return NS_OK;
}
nsresult nsTreeBodyFrame::SetView(nsITreeView* aView) {
if (aView == mView) {
return NS_OK;
}
// First clear out the old view.
nsCOMPtr<nsITreeView> oldView = std::move(mView);
if (oldView) {
AutoWeakFrame weakFrame(this);
nsCOMPtr<nsITreeSelection> sel;
oldView->GetSelection(getter_AddRefs(sel));
if (sel) {
sel->SetTree(nullptr);
}
oldView->SetTree(nullptr);
NS_ENSURE_STATE(weakFrame.IsAlive());
// Only reset the top row index and delete the columns if we had an old
// non-null view.
mTopRowIndex = 0;
}
// Tree, meet the view.
mView = aView;
// Changing the view causes us to refetch our data. This will
// necessarily entail a full invalidation of the tree.
Invalidate();
RefPtr<XULTreeElement> treeContent = GetBaseElement();
if (treeContent) {
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->TreeViewChanged(PresContext()->GetPresShell(), treeContent,
mView);
}
#endif // #ifdef ACCESSIBILITY
FireDOMEvent(u"TreeViewChanged"_ns, treeContent);
}
if (aView) {
// Give the view a new empty selection object to play with, but only if it
// doesn't have one already.
nsCOMPtr<nsITreeSelection> sel;
aView->GetSelection(getter_AddRefs(sel));
if (sel) {
sel->SetTree(treeContent);
} else {
NS_NewTreeSelection(treeContent, getter_AddRefs(sel));
aView->SetSelection(sel);
}
// View, meet the tree.
AutoWeakFrame weakFrame(this);
aView->SetTree(treeContent);
NS_ENSURE_STATE(weakFrame.IsAlive());
aView->GetRowCount(&mRowCount);
if (!PresShell()->IsReflowLocked()) {
// The scrollbar will need to be updated.
FullScrollbarsUpdate(false);
} else if (!mReflowCallbackPosted) {
mReflowCallbackPosted = true;
PresShell()->PostReflowCallback(this);
}
}
return NS_OK;
}
already_AddRefed<nsITreeSelection> nsTreeBodyFrame::GetSelection() const {
nsCOMPtr<nsITreeSelection> sel;
if (nsCOMPtr<nsITreeView> view = GetExistingView()) {
view->GetSelection(getter_AddRefs(sel));
}
return sel.forget();
}
nsresult nsTreeBodyFrame::SetFocused(bool aFocused) {
if (mFocused != aFocused) {
mFocused = aFocused;
if (nsCOMPtr<nsITreeSelection> sel = GetSelection()) {
sel->InvalidateSelection();
}
}
return NS_OK;
}
nsresult nsTreeBodyFrame::GetTreeBody(Element** aElement) {
// NS_ASSERTION(mContent, "no content, see bug #104878");
if (!mContent) return NS_ERROR_NULL_POINTER;
RefPtr<Element> element = mContent->AsElement();
element.forget(aElement);
return NS_OK;
}
int32_t nsTreeBodyFrame::RowHeight() const {
return nsPresContext::AppUnitsToIntCSSPixels(mRowHeight);
}
int32_t nsTreeBodyFrame::RowWidth() {
return nsPresContext::AppUnitsToIntCSSPixels(CalcHorzWidth(GetScrollParts()));
}
int32_t nsTreeBodyFrame::GetHorizontalPosition() const {
return nsPresContext::AppUnitsToIntCSSPixels(mHorzPosition);
}
Maybe<CSSIntRegion> nsTreeBodyFrame::GetSelectionRegion() {
if (!mView) {
return Nothing();
}
AutoWeakFrame wf(this);
nsCOMPtr<nsITreeSelection> selection = GetSelection();
if (!selection || !wf.IsAlive()) {
return Nothing();
}
nsIntRect rect = mRect.ToOutsidePixels(AppUnitsPerCSSPixel());
nsIFrame* rootFrame = PresShell()->GetRootFrame();
nsPoint origin = GetOffsetTo(rootFrame);
CSSIntRegion region;
// iterate through the visible rows and add the selected ones to the
// drag region
int32_t x = nsPresContext::AppUnitsToIntCSSPixels(origin.x);
int32_t y = nsPresContext::AppUnitsToIntCSSPixels(origin.y);
int32_t top = y;
int32_t end = LastVisibleRow();
int32_t rowHeight = nsPresContext::AppUnitsToIntCSSPixels(mRowHeight);
for (int32_t i = mTopRowIndex; i <= end; i++) {
bool isSelected;
selection->IsSelected(i, &isSelected);
if (isSelected) {
region.OrWith(CSSIntRect(x, y, rect.width, rowHeight));
}
y += rowHeight;
}
// clip to the tree boundary in case one row extends past it
region.AndWith(CSSIntRect(x, top, rect.width, rect.height));
return Some(region);
}
nsresult nsTreeBodyFrame::Invalidate() {
if (mUpdateBatchNest) return NS_OK;
InvalidateFrame();
return NS_OK;
}
nsresult nsTreeBodyFrame::InvalidateColumn(nsTreeColumn* aCol) {
if (mUpdateBatchNest) return NS_OK;
if (!aCol) return NS_ERROR_INVALID_ARG;
#ifdef ACCESSIBILITY
if (GetAccService()) {
FireInvalidateEvent(-1, -1, aCol, aCol);
}
#endif // #ifdef ACCESSIBILITY
nsRect columnRect;
nsresult rv = aCol->GetRect(this, mInnerBox.y, mInnerBox.height, &columnRect);
NS_ENSURE_SUCCESS(rv, rv);
// When false then column is out of view
if (OffsetForHorzScroll(columnRect, true))
InvalidateFrameWithRect(columnRect);
return NS_OK;
}
nsresult nsTreeBodyFrame::InvalidateRow(int32_t aIndex) {
if (mUpdateBatchNest) return NS_OK;
#ifdef ACCESSIBILITY
if (GetAccService()) {
FireInvalidateEvent(aIndex, aIndex, nullptr, nullptr);
}
#endif // #ifdef ACCESSIBILITY
aIndex -= mTopRowIndex;
if (aIndex < 0 || aIndex > mPageLength) return NS_OK;
nsRect rowRect(mInnerBox.x, mInnerBox.y + mRowHeight * aIndex,
mInnerBox.width, mRowHeight);
InvalidateFrameWithRect(rowRect);
return NS_OK;
}
nsresult nsTreeBodyFrame::InvalidateCell(int32_t aIndex, nsTreeColumn* aCol) {
if (mUpdateBatchNest) return NS_OK;
#ifdef ACCESSIBILITY
if (GetAccService()) {
FireInvalidateEvent(aIndex, aIndex, aCol, aCol);
}
#endif // #ifdef ACCESSIBILITY
aIndex -= mTopRowIndex;
if (aIndex < 0 || aIndex > mPageLength) return NS_OK;
if (!aCol) return NS_ERROR_INVALID_ARG;
nsRect cellRect;
nsresult rv = aCol->GetRect(this, mInnerBox.y + mRowHeight * aIndex,
mRowHeight, &cellRect);
NS_ENSURE_SUCCESS(rv, rv);
if (OffsetForHorzScroll(cellRect, true)) InvalidateFrameWithRect(cellRect);
return NS_OK;
}
nsresult nsTreeBodyFrame::InvalidateRange(int32_t aStart, int32_t aEnd) {
if (mUpdateBatchNest) return NS_OK;
if (aStart == aEnd) return InvalidateRow(aStart);
int32_t last = LastVisibleRow();
if (aStart > aEnd || aEnd < mTopRowIndex || aStart > last) return NS_OK;
if (aStart < mTopRowIndex) aStart = mTopRowIndex;
if (aEnd > last) aEnd = last;
#ifdef ACCESSIBILITY
if (GetAccService()) {
int32_t end =
mRowCount > 0 ? ((mRowCount <= aEnd) ? mRowCount - 1 : aEnd) : 0;
FireInvalidateEvent(aStart, end, nullptr, nullptr);
}
#endif // #ifdef ACCESSIBILITY
nsRect rangeRect(mInnerBox.x,
mInnerBox.y + mRowHeight * (aStart - mTopRowIndex),
mInnerBox.width, mRowHeight * (aEnd - aStart + 1));
InvalidateFrameWithRect(rangeRect);
return NS_OK;
}
static void FindScrollParts(nsIFrame* aCurrFrame,
nsTreeBodyFrame::ScrollParts* aResult) {
if (!aResult->mColumnsScrollFrame) {
nsIScrollableFrame* f = do_QueryFrame(aCurrFrame);
if (f) {
aResult->mColumnsFrame = aCurrFrame;
aResult->mColumnsScrollFrame = f;
}
}
if (nsScrollbarFrame* sf = do_QueryFrame(aCurrFrame)) {
if (!sf->IsHorizontal()) {
if (!aResult->mVScrollbar) {
aResult->mVScrollbar = sf;
}
} else {
if (!aResult->mHScrollbar) {
aResult->mHScrollbar = sf;
}
}
// don't bother searching inside a scrollbar
return;
}
nsIFrame* child = aCurrFrame->PrincipalChildList().FirstChild();
while (child && !child->GetContent()->IsRootOfNativeAnonymousSubtree() &&
(!aResult->mVScrollbar || !aResult->mHScrollbar ||
!aResult->mColumnsScrollFrame)) {
FindScrollParts(child, aResult);
child = child->GetNextSibling();
}
}
nsTreeBodyFrame::ScrollParts nsTreeBodyFrame::GetScrollParts() {
ScrollParts result = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
XULTreeElement* tree = GetBaseElement();
if (nsIFrame* treeFrame = tree ? tree->GetPrimaryFrame() : nullptr) {
// The way we do this, searching through the entire frame subtree, is pretty
// dumb! We should know where these frames are.
FindScrollParts(treeFrame, &result);
if (result.mHScrollbar) {
result.mHScrollbar->SetScrollbarMediatorContent(GetContent());
result.mHScrollbarContent = result.mHScrollbar->GetContent()->AsElement();
}
if (result.mVScrollbar) {
result.mVScrollbar->SetScrollbarMediatorContent(GetContent());
result.mVScrollbarContent = result.mVScrollbar->GetContent()->AsElement();
}
}
return result;
}
void nsTreeBodyFrame::UpdateScrollbars(const ScrollParts& aParts) {
nscoord rowHeightAsPixels = nsPresContext::AppUnitsToIntCSSPixels(mRowHeight);
AutoWeakFrame weakFrame(this);
if (aParts.mVScrollbar) {
nsAutoString curPos;
curPos.AppendInt(mTopRowIndex * rowHeightAsPixels);
aParts.mVScrollbarContent->SetAttr(kNameSpaceID_None, nsGkAtoms::curpos,
curPos, true);
// 'this' might be deleted here
}
if (weakFrame.IsAlive() && aParts.mHScrollbar) {
nsAutoString curPos;
curPos.AppendInt(mHorzPosition);
aParts.mHScrollbarContent->SetAttr(kNameSpaceID_None, nsGkAtoms::curpos,
curPos, true);
// 'this' might be deleted here
}
if (weakFrame.IsAlive() && mScrollbarActivity) {
mScrollbarActivity->ActivityOccurred();
}
}
void nsTreeBodyFrame::CheckOverflow(const ScrollParts& aParts) {
bool verticalOverflowChanged = false;
bool horizontalOverflowChanged = false;
if (!mVerticalOverflow && mRowCount > mPageLength) {
mVerticalOverflow = true;
verticalOverflowChanged = true;
} else if (mVerticalOverflow && mRowCount <= mPageLength) {
mVerticalOverflow = false;
verticalOverflowChanged = true;
}
if (aParts.mColumnsFrame) {
nsRect bounds = aParts.mColumnsFrame->GetRect();
if (bounds.width != 0) {
/* Ignore overflows that are less than half a pixel. Yes these happen
all over the place when flex boxes are compressed real small.
Probably a result of a rounding errors somewhere in the layout code. */
bounds.width += nsPresContext::CSSPixelsToAppUnits(0.5f);
if (!mHorizontalOverflow && bounds.width < mHorzWidth) {
mHorizontalOverflow = true;
horizontalOverflowChanged = true;
} else if (mHorizontalOverflow && bounds.width >= mHorzWidth) {
mHorizontalOverflow = false;
horizontalOverflowChanged = true;
}
}
}
if (!horizontalOverflowChanged && !verticalOverflowChanged) {
return;
}
AutoWeakFrame weakFrame(this);
RefPtr<nsPresContext> presContext = PresContext();
RefPtr<mozilla::PresShell> presShell = presContext->GetPresShell();
nsCOMPtr<nsIContent> content = mContent;
if (verticalOverflowChanged) {
InternalScrollPortEvent event(
true, mVerticalOverflow ? eScrollPortOverflow : eScrollPortUnderflow,
nullptr);
event.mOrient = InternalScrollPortEvent::eVertical;
EventDispatcher::Dispatch(content, presContext, &event);
}
if (horizontalOverflowChanged) {
InternalScrollPortEvent event(
true, mHorizontalOverflow ? eScrollPortOverflow : eScrollPortUnderflow,
nullptr);
event.mOrient = InternalScrollPortEvent::eHorizontal;
EventDispatcher::Dispatch(content, presContext, &event);
}
// The synchronous event dispatch above can trigger reflow notifications.
// Flush those explicitly now, so that we can guard against potential infinite
// recursion. See bug 905909.
if (!weakFrame.IsAlive()) {
return;
}
NS_ASSERTION(!mCheckingOverflow,
"mCheckingOverflow should not already be set");
// Don't use AutoRestore since we want to not touch mCheckingOverflow if we
// fail the weakFrame.IsAlive() check below
mCheckingOverflow = true;
presShell->FlushPendingNotifications(FlushType::Layout);
if (!weakFrame.IsAlive()) {
return;
}
mCheckingOverflow = false;
}
void nsTreeBodyFrame::InvalidateScrollbars(const ScrollParts& aParts,
AutoWeakFrame& aWeakColumnsFrame) {
if (mUpdateBatchNest || !mView) return;
AutoWeakFrame weakFrame(this);
if (aParts.mVScrollbar) {
// Do Vertical Scrollbar
nsAutoString maxposStr;
nscoord rowHeightAsPixels =
nsPresContext::AppUnitsToIntCSSPixels(mRowHeight);
int32_t size = rowHeightAsPixels *
(mRowCount > mPageLength ? mRowCount - mPageLength : 0);
maxposStr.AppendInt(size);
aParts.mVScrollbarContent->SetAttr(kNameSpaceID_None, nsGkAtoms::maxpos,
maxposStr, true);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
// Also set our page increment and decrement.
nscoord pageincrement = mPageLength * rowHeightAsPixels;
nsAutoString pageStr;
pageStr.AppendInt(pageincrement);
aParts.mVScrollbarContent->SetAttr(kNameSpaceID_None,
nsGkAtoms::pageincrement, pageStr, true);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
}
if (aParts.mHScrollbar && aParts.mColumnsFrame &&
aWeakColumnsFrame.IsAlive()) {
// And now Horizontal scrollbar
nsRect bounds = aParts.mColumnsFrame->GetRect();
nsAutoString maxposStr;
maxposStr.AppendInt(mHorzWidth > bounds.width ? mHorzWidth - bounds.width
: 0);
aParts.mHScrollbarContent->SetAttr(kNameSpaceID_None, nsGkAtoms::maxpos,
maxposStr, true);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
nsAutoString pageStr;
pageStr.AppendInt(bounds.width);
aParts.mHScrollbarContent->SetAttr(kNameSpaceID_None,
nsGkAtoms::pageincrement, pageStr, true);
NS_ENSURE_TRUE_VOID(weakFrame.IsAlive());
pageStr.Truncate();
pageStr.AppendInt(nsPresContext::CSSPixelsToAppUnits(16));
aParts.mHScrollbarContent->SetAttr(kNameSpaceID_None, nsGkAtoms::increment,
pageStr, true);
}
if (weakFrame.IsAlive() && mScrollbarActivity) {
mScrollbarActivity->ActivityOccurred();
}
}
// Takes client x/y in pixels, converts them to appunits, and converts into
// values relative to this nsTreeBodyFrame frame.
nsPoint nsTreeBodyFrame::AdjustClientCoordsToBoxCoordSpace(int32_t aX,
int32_t aY) {
nsPoint point(nsPresContext::CSSPixelsToAppUnits(aX),
nsPresContext::CSSPixelsToAppUnits(aY));
nsPresContext* presContext = PresContext();
point -= GetOffsetTo(presContext->GetPresShell()->GetRootFrame());
// Adjust by the inner box coords, so that we're in the inner box's
// coordinate space.
point -= mInnerBox.TopLeft();
return point;
} // AdjustClientCoordsToBoxCoordSpace
int32_t nsTreeBodyFrame::GetRowAt(int32_t aX, int32_t aY) {
if (!mView) {
return 0;
}
nsPoint point = AdjustClientCoordsToBoxCoordSpace(aX, aY);
// Check if the coordinates are above our visible space.
if (point.y < 0) {
return -1;
}
return GetRowAtInternal(point.x, point.y);
}
nsresult nsTreeBodyFrame::GetCellAt(int32_t aX, int32_t aY, int32_t* aRow,
nsTreeColumn** aCol,
nsACString& aChildElt) {
if (!mView) return NS_OK;
nsPoint point = AdjustClientCoordsToBoxCoordSpace(aX, aY);
// Check if the coordinates are above our visible space.
if (point.y < 0) {
*aRow = -1;
return NS_OK;
}
nsTreeColumn* col;
nsCSSAnonBoxPseudoStaticAtom* child;
GetCellAt(point.x, point.y, aRow, &col, &child);
if (col) {
NS_ADDREF(*aCol = col);
if (child == nsCSSAnonBoxes::mozTreeCell())
aChildElt.AssignLiteral("cell");
else if (child == nsCSSAnonBoxes::mozTreeTwisty())
aChildElt.AssignLiteral("twisty");
else if (child == nsCSSAnonBoxes::mozTreeImage())
aChildElt.AssignLiteral("image");
else if (child == nsCSSAnonBoxes::mozTreeCellText())
aChildElt.AssignLiteral("text");
}
return NS_OK;
}
//
// GetCoordsForCellItem
//
// Find the x/y location and width/height (all in PIXELS) of the given object
// in the given column.
//
// XXX IMPORTANT XXX:
// Hyatt says in the bug for this, that the following needs to be done:
// (1) You need to deal with overflow when computing cell rects. See other
// column iteration examples... if you don't deal with this, you'll mistakenly
// extend the cell into the scrollbar's rect.
//
// (2) You are adjusting the cell rect by the *row" border padding. That's
// wrong. You need to first adjust a row rect by its border/padding, and then
// the cell rect fits inside the adjusted row rect. It also can have
// border/padding as well as margins. The vertical direction isn't that
// important, but you need to get the horizontal direction right.
//
// (3) GetImageSize() does not include margins (but it does include
// border/padding). You need to make sure to add in the image's margins as well.
//
nsresult nsTreeBodyFrame::GetCoordsForCellItem(int32_t aRow, nsTreeColumn* aCol,
const nsACString& aElement,
int32_t* aX, int32_t* aY,
int32_t* aWidth,
int32_t* aHeight) {
*aX = 0;
*aY = 0;
*aWidth = 0;
*aHeight = 0;
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
nscoord currX = mInnerBox.x - mHorzPosition;
// The Rect for the requested item.
nsRect theRect;
nsPresContext* presContext = PresContext();
nsCOMPtr<nsITreeView> view = GetExistingView();
for (nsTreeColumn* currCol = mColumns->GetFirstColumn(); currCol;
currCol = currCol->GetNext()) {
// The Rect for the current cell.
nscoord colWidth;
#ifdef DEBUG
nsresult rv =
#endif
currCol->GetWidthInTwips(this, &colWidth);
NS_ASSERTION(NS_SUCCEEDED(rv), "invalid column");
nsRect cellRect(currX, mInnerBox.y + mRowHeight * (aRow - mTopRowIndex),
colWidth, mRowHeight);
// Check the ID of the current column to see if it matches. If it doesn't
// increment the current X value and continue to the next column.
if (currCol != aCol) {
currX += cellRect.width;
continue;
}
// Now obtain the properties for our cell.
PrefillPropertyArray(aRow, currCol);
nsAutoString properties;
view->GetCellProperties(aRow, currCol, properties);
nsTreeUtils::TokenizeProperties(properties, mScratchArray);
ComputedStyle* rowContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeRow());
// We don't want to consider any of the decorations that may be present
// on the current row, so we have to deflate the rect by the border and
// padding and offset its left and top coordinates appropriately.
AdjustForBorderPadding(rowContext, cellRect);
ComputedStyle* cellContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCell());
constexpr auto cell = "cell"_ns;
if (currCol->IsCycler() || cell.Equals(aElement)) {
// If the current Column is a Cycler, then the Rect is just the cell - the
// margins. Similarly, if we're just being asked for the cell rect,
// provide it.
theRect = cellRect;
nsMargin cellMargin;
cellContext->StyleMargin()->GetMargin(cellMargin);
theRect.Deflate(cellMargin);
break;
}
// Since we're not looking for the cell, and since the cell isn't a cycler,
// we're looking for some subcomponent, and now we need to subtract the
// borders and padding of the cell from cellRect so this does not
// interfere with our computations.
AdjustForBorderPadding(cellContext, cellRect);
UniquePtr<gfxContext> rc =
presContext->PresShell()->CreateReferenceRenderingContext();
// Now we'll start making our way across the cell, starting at the edge of
// the cell and proceeding until we hit the right edge. |cellX| is the
// working X value that we will increment as we crawl from left to right.
nscoord cellX = cellRect.x;
nscoord remainWidth = cellRect.width;
if (currCol->IsPrimary()) {
// If the current Column is a Primary, then we need to take into account
// the indentation and possibly a twisty.
// The amount of indentation is the indentation width (|mIndentation|) by
// the level.
int32_t level;
view->GetLevel(aRow, &level);
if (!isRTL) cellX += mIndentation * level;
remainWidth -= mIndentation * level;
// Find the twisty rect by computing its size.
nsRect imageRect;
nsRect twistyRect(cellRect);
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
GetTwistyRect(aRow, currCol, imageRect, twistyRect, presContext,
twistyContext);
if ("twisty"_ns.Equals(aElement)) {
// If we're looking for the twisty Rect, just return the size
theRect = twistyRect;
break;
}
// Now we need to add in the margins of the twisty element, so that we
// can find the offset of the next element in the cell.
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Inflate(twistyMargin);
// Adjust our working X value with the twisty width (image size, margins,
// borders, padding.
if (!isRTL) cellX += twistyRect.width;
}
// Cell Image
ComputedStyle* imageContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeImage());
nsRect imageSize = GetImageSize(aRow, currCol, false, imageContext);
if ("image"_ns.Equals(aElement)) {
theRect = imageSize;
theRect.x = cellX;
theRect.y = cellRect.y;
break;
}
// Add in the margins of the cell image.
nsMargin imageMargin;
imageContext->StyleMargin()->GetMargin(imageMargin);
imageSize.Inflate(imageMargin);
// Increment cellX by the image width
if (!isRTL) cellX += imageSize.width;
// Cell Text
nsAutoString cellText;
view->GetCellText(aRow, currCol, cellText);
// We're going to measure this text so we need to ensure bidi is enabled if
// necessary
CheckTextForBidi(cellText);
// Create a scratch rect to represent the text rectangle, with the current
// X and Y coords, and a guess at the width and height. The width is the
// remaining width we have left to traverse in the cell, which will be the
// widest possible value for the text rect, and the row height.
nsRect textRect(cellX, cellRect.y, remainWidth, cellRect.height);
// Measure the width of the text. If the width of the text is greater than
// the remaining width available, then we just assume that the text has
// been cropped and use the remaining rect as the text Rect. Otherwise,
// we add in borders and padding to the text dimension and give that back.
ComputedStyle* textContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCellText());
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetFontMetricsForComputedStyle(textContext, presContext);
nscoord height = fm->MaxHeight();
nsMargin textMargin;
textContext->StyleMargin()->GetMargin(textMargin);
textRect.Deflate(textMargin);
// Center the text. XXX Obey vertical-align style prop?
if (height < textRect.height) {
textRect.y += (textRect.height - height) / 2;
textRect.height = height;
}
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(textContext, bp);
textRect.height += bp.top + bp.bottom;
AdjustForCellText(cellText, aRow, currCol, *rc, *fm, textRect);
theRect = textRect;
}
if (isRTL) theRect.x = mInnerBox.width - theRect.x - theRect.width;
*aX = nsPresContext::AppUnitsToIntCSSPixels(theRect.x);
*aY = nsPresContext::AppUnitsToIntCSSPixels(theRect.y);
*aWidth = nsPresContext::AppUnitsToIntCSSPixels(theRect.width);
*aHeight = nsPresContext::AppUnitsToIntCSSPixels(theRect.height);
return NS_OK;
}
int32_t nsTreeBodyFrame::GetRowAtInternal(nscoord aX, nscoord aY) {
if (mRowHeight <= 0) return -1;
// Now just mod by our total inner box height and add to our top row index.
int32_t row = (aY / mRowHeight) + mTopRowIndex;
// Check if the coordinates are below our visible space (or within our visible
// space but below any row).
if (row > mTopRowIndex + mPageLength || row >= mRowCount) return -1;
return row;
}
void nsTreeBodyFrame::CheckTextForBidi(nsAutoString& aText) {
// We could check to see whether the prescontext already has bidi enabled,
// but usually it won't, so it's probably faster to avoid the call to
// GetPresContext() when it's not needed.
if (HasRTLChars(aText)) {
PresContext()->SetBidiEnabled();
}
}
void nsTreeBodyFrame::AdjustForCellText(nsAutoString& aText, int32_t aRowIndex,
nsTreeColumn* aColumn,
gfxContext& aRenderingContext,
nsFontMetrics& aFontMetrics,
nsRect& aTextRect) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
nscoord maxWidth = aTextRect.width;
bool widthIsGreater = nsLayoutUtils::StringWidthIsGreaterThan(
aText, aFontMetrics, drawTarget, maxWidth);
nsCOMPtr<nsITreeView> view = GetExistingView();
if (aColumn->Overflow()) {
DebugOnly<nsresult> rv;
nsTreeColumn* nextColumn = aColumn->GetNext();
while (nextColumn && widthIsGreater) {
while (nextColumn) {
nscoord width;
rv = nextColumn->GetWidthInTwips(this, &width);
NS_ASSERTION(NS_SUCCEEDED(rv), "nextColumn is invalid");
if (width != 0) {
break;
}
nextColumn = nextColumn->GetNext();
}
if (nextColumn) {
nsAutoString nextText;
view->GetCellText(aRowIndex, nextColumn, nextText);
// We don't measure or draw this text so no need to check it for
// bidi-ness
if (nextText.Length() == 0) {
nscoord width;
rv = nextColumn->GetWidthInTwips(this, &width);
NS_ASSERTION(NS_SUCCEEDED(rv), "nextColumn is invalid");
maxWidth += width;
widthIsGreater = nsLayoutUtils::StringWidthIsGreaterThan(
aText, aFontMetrics, drawTarget, maxWidth);
nextColumn = nextColumn->GetNext();
} else {
nextColumn = nullptr;
}
}
}
}
CroppingStyle cropType = CroppingStyle::CropRight;
if (aColumn->GetCropStyle() == 1) {
cropType = CroppingStyle::CropCenter;
} else if (aColumn->GetCropStyle() == 2) {
cropType = CroppingStyle::CropLeft;
}
CropStringForWidth(aText, aRenderingContext, aFontMetrics, maxWidth,
cropType);
nscoord width = nsLayoutUtils::AppUnitWidthOfStringBidi(
aText, this, aFontMetrics, aRenderingContext);
switch (aColumn->GetTextAlignment()) {
case mozilla::StyleTextAlign::Right:
aTextRect.x += aTextRect.width - width;
break;
case mozilla::StyleTextAlign::Center:
aTextRect.x += (aTextRect.width - width) / 2;
break;
default:
break;
}
aTextRect.width = width;
}
nsCSSAnonBoxPseudoStaticAtom* nsTreeBodyFrame::GetItemWithinCellAt(
nscoord aX, const nsRect& aCellRect, int32_t aRowIndex,
nsTreeColumn* aColumn) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
// Obtain the properties for our cell.
PrefillPropertyArray(aRowIndex, aColumn);
nsAutoString properties;
nsCOMPtr<nsITreeView> view = GetExistingView();
view->GetCellProperties(aRowIndex, aColumn, properties);
nsTreeUtils::TokenizeProperties(properties, mScratchArray);
// Resolve style for the cell.
ComputedStyle* cellContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCell());
// Obtain the margins for the cell and then deflate our rect by that
// amount. The cell is assumed to be contained within the deflated rect.
nsRect cellRect(aCellRect);
nsMargin cellMargin;
cellContext->StyleMargin()->GetMargin(cellMargin);
cellRect.Deflate(cellMargin);
// Adjust the rect for its border and padding.
AdjustForBorderPadding(cellContext, cellRect);
if (aX < cellRect.x || aX >= cellRect.x + cellRect.width) {
// The user clicked within the cell's margins/borders/padding. This
// constitutes a click on the cell.
return nsCSSAnonBoxes::mozTreeCell();
}
nscoord currX = cellRect.x;
nscoord remainingWidth = cellRect.width;
// Handle right alignment hit testing.
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
nsPresContext* presContext = PresContext();
UniquePtr<gfxContext> rc =
presContext->PresShell()->CreateReferenceRenderingContext();
if (aColumn->IsPrimary()) {
// If we're the primary column, we have indentation and a twisty.
int32_t level;
view->GetLevel(aRowIndex, &level);
if (!isRTL) currX += mIndentation * level;
remainingWidth -= mIndentation * level;
if ((isRTL && aX > currX + remainingWidth) || (!isRTL && aX < currX)) {
// The user clicked within the indentation.
return nsCSSAnonBoxes::mozTreeCell();
}
// Always leave space for the twisty.
nsRect twistyRect(currX, cellRect.y, remainingWidth, cellRect.height);
bool hasTwisty = false;
bool isContainer = false;
view->IsContainer(aRowIndex, &isContainer);
if (isContainer) {
bool isContainerEmpty = false;
view->IsContainerEmpty(aRowIndex, &isContainerEmpty);
if (!isContainerEmpty) hasTwisty = true;
}
// Resolve style for the twisty.
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
nsRect imageSize;
GetTwistyRect(aRowIndex, aColumn, imageSize, twistyRect, presContext,
twistyContext);
// We will treat a click as hitting the twisty if it happens on the margins,
// borders, padding, or content of the twisty object. By allowing a "slop"
// into the margin, we make it a little bit easier for a user to hit the
// twisty. (We don't want to be too picky here.)
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Inflate(twistyMargin);
if (isRTL) twistyRect.x = currX + remainingWidth - twistyRect.width;
// Now we test to see if aX is actually within the twistyRect. If it is,
// and if the item should have a twisty, then we return "twisty". If it is
// within the rect but we shouldn't have a twisty, then we return "cell".
if (aX >= twistyRect.x && aX < twistyRect.x + twistyRect.width) {
if (hasTwisty)
return nsCSSAnonBoxes::mozTreeTwisty();
else
return nsCSSAnonBoxes::mozTreeCell();
}
if (!isRTL) currX += twistyRect.width;
remainingWidth -= twistyRect.width;
}
// Now test to see if the user hit the icon for the cell.
nsRect iconRect(currX, cellRect.y, remainingWidth, cellRect.height);
// Resolve style for the image.
ComputedStyle* imageContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeImage());
nsRect iconSize = GetImageSize(aRowIndex, aColumn, false, imageContext);
nsMargin imageMargin;
imageContext->StyleMargin()->GetMargin(imageMargin);
iconSize.Inflate(imageMargin);
iconRect.width = iconSize.width;
if (isRTL) iconRect.x = currX + remainingWidth - iconRect.width;
if (aX >= iconRect.x && aX < iconRect.x + iconRect.width) {
// The user clicked on the image.
return nsCSSAnonBoxes::mozTreeImage();
}
if (!isRTL) currX += iconRect.width;
remainingWidth -= iconRect.width;
nsAutoString cellText;
view->GetCellText(aRowIndex, aColumn, cellText);
// We're going to measure this text so we need to ensure bidi is enabled if
// necessary
CheckTextForBidi(cellText);
nsRect textRect(currX, cellRect.y, remainingWidth, cellRect.height);
ComputedStyle* textContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCellText());
nsMargin textMargin;
textContext->StyleMargin()->GetMargin(textMargin);
textRect.Deflate(textMargin);
AdjustForBorderPadding(textContext, textRect);
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetFontMetricsForComputedStyle(textContext, presContext);
AdjustForCellText(cellText, aRowIndex, aColumn, *rc, *fm, textRect);
if (aX >= textRect.x && aX < textRect.x + textRect.width)
return nsCSSAnonBoxes::mozTreeCellText();
else
return nsCSSAnonBoxes::mozTreeCell();
}
void nsTreeBodyFrame::GetCellAt(nscoord aX, nscoord aY, int32_t* aRow,
nsTreeColumn** aCol,
nsCSSAnonBoxPseudoStaticAtom** aChildElt) {
*aCol = nullptr;
*aChildElt = nullptr;
*aRow = GetRowAtInternal(aX, aY);
if (*aRow < 0) return;
// Determine the column hit.
for (nsTreeColumn* currCol = mColumns->GetFirstColumn(); currCol;
currCol = currCol->GetNext()) {
nsRect cellRect;
nsresult rv = currCol->GetRect(
this, mInnerBox.y + mRowHeight * (*aRow - mTopRowIndex), mRowHeight,
&cellRect);
if (NS_FAILED(rv)) {
MOZ_ASSERT_UNREACHABLE("column has no frame");
continue;
}
if (!OffsetForHorzScroll(cellRect, false)) continue;
if (aX >= cellRect.x && aX < cellRect.x + cellRect.width) {
// We know the column hit now.
*aCol = currCol;
if (currCol->IsCycler())
// Cyclers contain only images. Fill this in immediately and return.
*aChildElt = nsCSSAnonBoxes::mozTreeImage();
else
*aChildElt = GetItemWithinCellAt(aX, cellRect, *aRow, currCol);
break;
}
}
}
nsresult nsTreeBodyFrame::GetCellWidth(int32_t aRow, nsTreeColumn* aCol,
gfxContext* aRenderingContext,
nscoord& aDesiredSize,
nscoord& aCurrentSize) {
MOZ_ASSERT(aCol, "aCol must not be null");
MOZ_ASSERT(aRenderingContext, "aRenderingContext must not be null");
// The rect for the current cell.
nscoord colWidth;
nsresult rv = aCol->GetWidthInTwips(this, &colWidth);
NS_ENSURE_SUCCESS(rv, rv);
nsRect cellRect(0, 0, colWidth, mRowHeight);
int32_t overflow =
cellRect.x + cellRect.width - (mInnerBox.x + mInnerBox.width);
if (overflow > 0) cellRect.width -= overflow;
// Adjust borders and padding for the cell.
ComputedStyle* cellContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCell());
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(cellContext, bp);
aCurrentSize = cellRect.width;
aDesiredSize = bp.left + bp.right;
nsCOMPtr<nsITreeView> view = GetExistingView();
if (aCol->IsPrimary()) {
// If the current Column is a Primary, then we need to take into account
// the indentation and possibly a twisty.
// The amount of indentation is the indentation width (|mIndentation|) by
// the level.
int32_t level;
view->GetLevel(aRow, &level);
aDesiredSize += mIndentation * level;
// Find the twisty rect by computing its size.
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
nsRect imageSize;
nsRect twistyRect(cellRect);
GetTwistyRect(aRow, aCol, imageSize, twistyRect, PresContext(),
twistyContext);
// Add in the margins of the twisty element.
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Inflate(twistyMargin);
aDesiredSize += twistyRect.width;
}
ComputedStyle* imageContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeImage());
// Account for the width of the cell image.
nsRect imageSize = GetImageSize(aRow, aCol, false, imageContext);
// Add in the margins of the cell image.
nsMargin imageMargin;
imageContext->StyleMargin()->GetMargin(imageMargin);
imageSize.Inflate(imageMargin);
aDesiredSize += imageSize.width;
// Get the cell text.
nsAutoString cellText;
view->GetCellText(aRow, aCol, cellText);
// We're going to measure this text so we need to ensure bidi is enabled if
// necessary
CheckTextForBidi(cellText);
ComputedStyle* textContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCellText());
// Get the borders and padding for the text.
GetBorderPadding(textContext, bp);
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetFontMetricsForComputedStyle(textContext, PresContext());
// Get the width of the text itself
nscoord width = nsLayoutUtils::AppUnitWidthOfStringBidi(cellText, this, *fm,
*aRenderingContext);
nscoord totalTextWidth = width + bp.left + bp.right;
aDesiredSize += totalTextWidth;
return NS_OK;
}
nsresult nsTreeBodyFrame::IsCellCropped(int32_t aRow, nsTreeColumn* aCol,
bool* _retval) {
nscoord currentSize, desiredSize;
nsresult rv;
if (!aCol) return NS_ERROR_INVALID_ARG;
UniquePtr<gfxContext> rc = PresShell()->CreateReferenceRenderingContext();
rv = GetCellWidth(aRow, aCol, rc.get(), desiredSize, currentSize);
NS_ENSURE_SUCCESS(rv, rv);
*_retval = desiredSize > currentSize;
return NS_OK;
}
nsresult nsTreeBodyFrame::CreateTimer(const LookAndFeel::IntID aID,
nsTimerCallbackFunc aFunc, int32_t aType,
nsITimer** aTimer, const char* aName) {
// Get the delay from the look and feel service.
int32_t delay = LookAndFeel::GetInt(aID, 0);
nsCOMPtr<nsITimer> timer;
// Create a new timer only if the delay is greater than zero.
// Zero value means that this feature is completely disabled.
if (delay > 0) {
MOZ_TRY_VAR(timer,
NS_NewTimerWithFuncCallback(aFunc, this, delay, aType, aName,
GetMainThreadSerialEventTarget()));
}
timer.forget(aTimer);
return NS_OK;
}
nsresult nsTreeBodyFrame::RowCountChanged(int32_t aIndex, int32_t aCount) {
if (aCount == 0 || !mView) {
return NS_OK; // Nothing to do.
}
#ifdef ACCESSIBILITY
if (GetAccService()) {
FireRowCountChangedEvent(aIndex, aCount);
}
#endif // #ifdef ACCESSIBILITY
AutoWeakFrame weakFrame(this);
// Adjust our selection.
if (nsCOMPtr<nsITreeSelection> sel = GetSelection()) {
sel->AdjustSelection(aIndex, aCount);
}
NS_ENSURE_STATE(weakFrame.IsAlive());
if (mUpdateBatchNest) return NS_OK;
mRowCount += aCount;
#ifdef DEBUG
int32_t rowCount = mRowCount;
mView->GetRowCount(&rowCount);
NS_ASSERTION(
rowCount == mRowCount,
"row count did not change by the amount suggested, check caller");
#endif
int32_t count = Abs(aCount);
int32_t last = LastVisibleRow();
if (aIndex >= mTopRowIndex && aIndex <= last) InvalidateRange(aIndex, last);
ScrollParts parts = GetScrollParts();
if (mTopRowIndex == 0) {
// Just update the scrollbar and return.
FullScrollbarsUpdate(false);
return NS_OK;
}
bool needsInvalidation = false;
// Adjust our top row index.
if (aCount > 0) {
if (mTopRowIndex > aIndex) {
// Rows came in above us. Augment the top row index.
mTopRowIndex += aCount;
}
} else if (aCount < 0) {
if (mTopRowIndex > aIndex + count - 1) {
// No need to invalidate. The remove happened
// completely above us (offscreen).
mTopRowIndex -= count;
} else if (mTopRowIndex >= aIndex) {
// This is a full-blown invalidate.
if (mTopRowIndex + mPageLength > mRowCount - 1) {
mTopRowIndex = std::max(0, mRowCount - 1 - mPageLength);
}
needsInvalidation = true;
}
}
FullScrollbarsUpdate(needsInvalidation);
return NS_OK;
}
nsresult nsTreeBodyFrame::BeginUpdateBatch() {
++mUpdateBatchNest;
return NS_OK;
}
nsresult nsTreeBodyFrame::EndUpdateBatch() {
NS_ASSERTION(mUpdateBatchNest > 0, "badly nested update batch");
if (--mUpdateBatchNest != 0) {
return NS_OK;
}
nsCOMPtr<nsITreeView> view = GetExistingView();
if (!view) {
return NS_OK;
}
Invalidate();
int32_t countBeforeUpdate = mRowCount;
view->GetRowCount(&mRowCount);
if (countBeforeUpdate != mRowCount) {
if (mTopRowIndex + mPageLength > mRowCount - 1) {
mTopRowIndex = std::max(0, mRowCount - 1 - mPageLength);
}
FullScrollbarsUpdate(false);
}
return NS_OK;
}
void nsTreeBodyFrame::PrefillPropertyArray(int32_t aRowIndex,
nsTreeColumn* aCol) {
MOZ_ASSERT(!aCol || aCol->GetFrame(), "invalid column passed");
mScratchArray.Clear();
// focus
if (mFocused)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::focus);
else
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::blur);
// sort
bool sorted = false;
mView->IsSorted(&sorted);
if (sorted) mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::sorted);
// drag session
if (mSlots && mSlots->mIsDragging)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::dragSession);
if (aRowIndex != -1) {
if (aRowIndex == mMouseOverRow)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::hover);
nsCOMPtr<nsITreeSelection> selection = GetSelection();
if (selection) {
// selected
bool isSelected;
selection->IsSelected(aRowIndex, &isSelected);
if (isSelected)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::selected);
// current
int32_t currentIndex;
selection->GetCurrentIndex(¤tIndex);
if (aRowIndex == currentIndex)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::current);
}
// container or leaf
bool isContainer = false;
mView->IsContainer(aRowIndex, &isContainer);
if (isContainer) {
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::container);
// open or closed
bool isOpen = false;
mView->IsContainerOpen(aRowIndex, &isOpen);
if (isOpen)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::open);
else
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::closed);
} else {
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::leaf);
}
// drop orientation
if (mSlots && mSlots->mDropAllowed && mSlots->mDropRow == aRowIndex) {
if (mSlots->mDropOrient == nsITreeView::DROP_BEFORE)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::dropBefore);
else if (mSlots->mDropOrient == nsITreeView::DROP_ON)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::dropOn);
else if (mSlots->mDropOrient == nsITreeView::DROP_AFTER)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::dropAfter);
}
// odd or even
if (aRowIndex % 2)
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::odd);
else
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::even);
XULTreeElement* tree = GetBaseElement();
if (tree && tree->HasAttr(nsGkAtoms::editing)) {
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::editing);
}
// multiple columns
if (mColumns->GetColumnAt(1))
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::multicol);
}
if (aCol) {
mScratchArray.AppendElement(aCol->GetAtom());
if (aCol->IsPrimary())
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::primary);
if (aCol->GetType() == TreeColumn_Binding::TYPE_CHECKBOX) {
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::checkbox);
if (aRowIndex != -1) {
nsAutoString value;
mView->GetCellValue(aRowIndex, aCol, value);
if (value.EqualsLiteral("true"))
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::checked);
}
}
// Read special properties from attributes on the column content node
if (aCol->mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::insertbefore,
nsGkAtoms::_true, eCaseMatters))
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::insertbefore);
if (aCol->mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::insertafter,
nsGkAtoms::_true, eCaseMatters))
mScratchArray.AppendElement((nsStaticAtom*)nsGkAtoms::insertafter);
}
}
nsITheme* nsTreeBodyFrame::GetTwistyRect(int32_t aRowIndex,
nsTreeColumn* aColumn,
nsRect& aImageRect,
nsRect& aTwistyRect,
nsPresContext* aPresContext,
ComputedStyle* aTwistyContext) {
// The twisty rect extends all the way to the end of the cell. This is
// incorrect. We need to determine the twisty rect's true width. This is
// done by examining the ComputedStyle for a width first. If it has one, we
// use that. If it doesn't, we use the image's natural width. If the image
// hasn't loaded and if no width is specified, then we just bail. If there is
// a -moz-appearance involved, adjust the rect by the minimum widget size
// provided by the theme implementation.
aImageRect = GetImageSize(aRowIndex, aColumn, true, aTwistyContext);
if (aImageRect.height > aTwistyRect.height)
aImageRect.height = aTwistyRect.height;
if (aImageRect.width > aTwistyRect.width)
aImageRect.width = aTwistyRect.width;
else
aTwistyRect.width = aImageRect.width;
bool useTheme = false;
nsITheme* theme = nullptr;
StyleAppearance appearance =
aTwistyContext->StyleDisplay()->EffectiveAppearance();
if (appearance != StyleAppearance::None) {
theme = aPresContext->Theme();
if (theme->ThemeSupportsWidget(aPresContext, nullptr, appearance))
useTheme = true;
}
if (useTheme) {
LayoutDeviceIntSize minTwistySizePx =
theme->GetMinimumWidgetSize(aPresContext, this, appearance);
// GMWS() returns size in pixels, we need to convert it back to app units
nsSize minTwistySize;
minTwistySize.width =
aPresContext->DevPixelsToAppUnits(minTwistySizePx.width);
minTwistySize.height =
aPresContext->DevPixelsToAppUnits(minTwistySizePx.height);
if (aTwistyRect.width < minTwistySize.width) {
aTwistyRect.width = minTwistySize.width;
}
}
return useTheme ? theme : nullptr;
}
nsresult nsTreeBodyFrame::GetImage(int32_t aRowIndex, nsTreeColumn* aCol,
bool aUseContext,
ComputedStyle* aComputedStyle,
imgIContainer** aResult) {
*aResult = nullptr;
nsAutoString imageSrc;
mView->GetImageSrc(aRowIndex, aCol, imageSrc);
RefPtr<imgRequestProxy> styleRequest;
if (aUseContext || imageSrc.IsEmpty()) {
// Obtain the URL from the ComputedStyle.
styleRequest =
aComputedStyle->StyleList()->mListStyleImage.GetImageRequest();
if (!styleRequest) return NS_OK;
nsCOMPtr<nsIURI> uri;
styleRequest->GetURI(getter_AddRefs(uri));
nsAutoCString spec;
nsresult rv = uri->GetSpec(spec);
NS_ENSURE_SUCCESS(rv, rv);
CopyUTF8toUTF16(spec, imageSrc);
}
// Look the image up in our cache.
nsTreeImageCacheEntry entry;
if (mImageCache.Get(imageSrc, &entry)) {
// Find out if the image has loaded.
uint32_t status;
imgIRequest* imgReq = entry.request;
imgReq->GetImageStatus(&status);
imgReq->GetImage(aResult); // We hand back the image here. The GetImage
// call addrefs *aResult.
bool animated = true; // Assuming animated is the safe option
// We can only call GetAnimated if we're decoded
if (*aResult && (status & imgIRequest::STATUS_DECODE_COMPLETE))
(*aResult)->GetAnimated(&animated);
if ((!(status & imgIRequest::STATUS_LOAD_COMPLETE)) || animated) {
// We either aren't done loading, or we're animating. Add our row as a
// listener for invalidations.
nsCOMPtr<imgINotificationObserver> obs;
imgReq->GetNotificationObserver(getter_AddRefs(obs));
if (obs) {
static_cast<nsTreeImageListener*>(obs.get())->AddCell(aRowIndex, aCol);
}
return NS_OK;
}
}
if (!*aResult) {
// Create a new nsTreeImageListener object and pass it our row and column
// information.
nsTreeImageListener* listener = new nsTreeImageListener(this);
if (!listener) return NS_ERROR_OUT_OF_MEMORY;
mCreatedListeners.Insert(listener);
listener->AddCell(aRowIndex, aCol);
nsCOMPtr<imgINotificationObserver> imgNotificationObserver = listener;
Document* doc = mContent->GetComposedDoc();
if (!doc)
// The page is currently being torn down. Why bother.
return NS_ERROR_FAILURE;
RefPtr<imgRequestProxy> imageRequest;
if (styleRequest) {
styleRequest->SyncClone(imgNotificationObserver, doc,
getter_AddRefs(imageRequest));
} else {
nsCOMPtr<nsIURI> srcURI;
nsContentUtils::NewURIWithDocumentCharset(
getter_AddRefs(srcURI), imageSrc, doc, mContent->GetBaseURI());
if (!srcURI) return NS_ERROR_FAILURE;
auto referrerInfo = MakeRefPtr<mozilla::dom::ReferrerInfo>(*doc);
// XXXbz what's the origin principal for this stuff that comes from our
// view? I guess we should assume that it's the node's principal...
nsresult rv = nsContentUtils::LoadImage(
srcURI, mContent, doc, mContent->NodePrincipal(), 0, referrerInfo,
imgNotificationObserver, nsIRequest::LOAD_NORMAL, u""_ns,
getter_AddRefs(imageRequest));
NS_ENSURE_SUCCESS(rv, rv);
// NOTE(heycam): If it's an SVG image, and we need to want the image to
// able to respond to media query changes, it needs to be added to the
// document's ImageTracker. For now, assume we don't need this.
}
listener->UnsuppressInvalidation();
if (!imageRequest) return NS_ERROR_FAILURE;
// We don't want discarding/decode-on-draw for xul images
imageRequest->StartDecoding(imgIContainer::FLAG_ASYNC_NOTIFY);
imageRequest->LockImage();
// In a case it was already cached.
imageRequest->GetImage(aResult);
nsTreeImageCacheEntry cacheEntry(imageRequest, imgNotificationObserver);
mImageCache.InsertOrUpdate(imageSrc, cacheEntry);
}
return NS_OK;
}
nsRect nsTreeBodyFrame::GetImageSize(int32_t aRowIndex, nsTreeColumn* aCol,
bool aUseContext,
ComputedStyle* aComputedStyle) {
// XXX We should respond to visibility rules for collapsed vs. hidden.
// This method returns the width of the twisty INCLUDING borders and padding.
// It first checks the ComputedStyle for a width. If none is found, it tries
// to use the default image width for the twisty. If no image is found, it
// defaults to border+padding.
nsRect r(0, 0, 0, 0);
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(aComputedStyle, bp);
r.Inflate(bp);
// Now r contains our border+padding info. We now need to get our width and
// height.
bool needWidth = false;
bool needHeight = false;
// We have to load image even though we already have a size.
// Don't change this, otherwise things start to go awry.
nsCOMPtr<imgIContainer> image;
GetImage(aRowIndex, aCol, aUseContext, aComputedStyle, getter_AddRefs(image));
const nsStylePosition* myPosition = aComputedStyle->StylePosition();
if (myPosition->mWidth.ConvertsToLength()) {
int32_t val = myPosition->mWidth.ToLength();
r.width += val;
} else {
needWidth = true;
}
if (myPosition->mHeight.ConvertsToLength()) {
int32_t val = myPosition->mHeight.ToLength();
r.height += val;
} else {
needHeight = true;
}
if (image) {
if (needWidth || needHeight) {
// Get the natural image size.
if (needWidth) {
// Get the size from the image.
nscoord width;
image->GetWidth(&width);
r.width += nsPresContext::CSSPixelsToAppUnits(width);
}
if (needHeight) {
nscoord height;
image->GetHeight(&height);
r.height += nsPresContext::CSSPixelsToAppUnits(height);
}
}
}
return r;
}
// GetImageDestSize returns the destination size of the image.
// The width and height do not include borders and padding.
// The width and height have not been adjusted to fit in the row height
// or cell width.
// The width and height reflect the destination size specified in CSS,
// or the image region specified in CSS, or the natural size of the
// image.
// If only the destination width has been specified in CSS, the height is
// calculated to maintain the aspect ratio of the image.
// If only the destination height has been specified in CSS, the width is
// calculated to maintain the aspect ratio of the image.
nsSize nsTreeBodyFrame::GetImageDestSize(ComputedStyle* aComputedStyle,
imgIContainer* image) {
nsSize size(0, 0);
// We need to get the width and height.
bool needWidth = false;
bool needHeight = false;
// Get the style position to see if the CSS has specified the
// destination width/height.
const nsStylePosition* myPosition = aComputedStyle->StylePosition();
if (myPosition->mWidth.ConvertsToLength()) {
// CSS has specified the destination width.
size.width = myPosition->mWidth.ToLength();
} else {
// We'll need to get the width of the image/region.
needWidth = true;
}
if (myPosition->mHeight.ConvertsToLength()) {
// CSS has specified the destination height.
size.height = myPosition->mHeight.ToLength();
} else {
// We'll need to get the height of the image/region.
needHeight = true;
}
if (needWidth || needHeight) {
// We need to get the size of the image/region.
nsSize imageSize(0, 0);
if (image) {
nscoord width;
image->GetWidth(&width);
imageSize.width = nsPresContext::CSSPixelsToAppUnits(width);
nscoord height;
image->GetHeight(&height);
imageSize.height = nsPresContext::CSSPixelsToAppUnits(height);
}
if (needWidth) {
if (!needHeight && imageSize.height != 0) {
// The CSS specified the destination height, but not the destination
// width. We need to calculate the width so that we maintain the
// image's aspect ratio.
size.width = imageSize.width * size.height / imageSize.height;
} else {
size.width = imageSize.width;
}
}
if (needHeight) {
if (!needWidth && imageSize.width != 0) {
// The CSS specified the destination width, but not the destination
// height. We need to calculate the height so that we maintain the
// image's aspect ratio.
size.height = imageSize.height * size.width / imageSize.width;
} else {
size.height = imageSize.height;
}
}
}
return size;
}
// GetImageSourceRect returns the source rectangle of the image to be
// displayed.
// The width and height reflect the image region specified in CSS, or
// the natural size of the image.
// The width and height do not include borders and padding.
// The width and height do not reflect the destination size specified
// in CSS.
nsRect nsTreeBodyFrame::GetImageSourceRect(ComputedStyle* aComputedStyle,
imgIContainer* image) {
if (!image) {
return nsRect();
}
nsRect r;
// Use the actual image size.
nscoord coord;
if (NS_SUCCEEDED(image->GetWidth(&coord))) {
r.width = nsPresContext::CSSPixelsToAppUnits(coord);
}
if (NS_SUCCEEDED(image->GetHeight(&coord))) {
r.height = nsPresContext::CSSPixelsToAppUnits(coord);
}
return r;
}
int32_t nsTreeBodyFrame::GetRowHeight() {
// Look up the correct height. It is equal to the specified height
// + the specified margins.
mScratchArray.Clear();
ComputedStyle* rowContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeRow());
if (rowContext) {
const nsStylePosition* myPosition = rowContext->StylePosition();
nscoord minHeight = 0;
if (myPosition->mMinHeight.ConvertsToLength()) {
minHeight = myPosition->mMinHeight.ToLength();
}
nscoord height = 0;
if (myPosition->mHeight.ConvertsToLength()) {
height = myPosition->mHeight.ToLength();
}
if (height < minHeight) height = minHeight;
if (height > 0) {
height = nsPresContext::AppUnitsToIntCSSPixels(height);
height += height % 2;
height = nsPresContext::CSSPixelsToAppUnits(height);
// XXX Check box-sizing to determine if border/padding should augment the
// height Inflate the height by our margins.
nsRect rowRect(0, 0, 0, height);
nsMargin rowMargin;
rowContext->StyleMargin()->GetMargin(rowMargin);
rowRect.Inflate(rowMargin);
height = rowRect.height;
return height;
}
}
return nsPresContext::CSSPixelsToAppUnits(18); // As good a default as any.
}
int32_t nsTreeBodyFrame::GetIndentation() {
// Look up the correct indentation. It is equal to the specified indentation
// width.
mScratchArray.Clear();
ComputedStyle* indentContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeIndentation());
if (indentContext) {
const nsStylePosition* myPosition = indentContext->StylePosition();
if (myPosition->mWidth.ConvertsToLength()) {
return myPosition->mWidth.ToLength();
}
}
return nsPresContext::CSSPixelsToAppUnits(16); // As good a default as any.
}
void nsTreeBodyFrame::CalcInnerBox() {
mInnerBox.SetRect(0, 0, mRect.width, mRect.height);
AdjustForBorderPadding(mComputedStyle, mInnerBox);
}
nscoord nsTreeBodyFrame::CalcHorzWidth(const ScrollParts& aParts) {
// Compute the adjustment to the last column. This varies depending on the
// visibility of the columnpicker and the scrollbar.
if (aParts.mColumnsFrame)
mAdjustWidth = mRect.width - aParts.mColumnsFrame->GetRect().width;
else
mAdjustWidth = 0;
nscoord width = 0;
// We calculate this from the scrollable frame, so that it
// properly covers all contingencies of what could be
// scrollable (columns, body, etc...)
if (aParts.mColumnsScrollFrame) {
width = aParts.mColumnsScrollFrame->GetScrollRange().width +
aParts.mColumnsScrollFrame->GetScrollPortRect().width;
}
// If no horz scrolling periphery is present, then just return our width
if (width == 0) width = mRect.width;
return width;
}
nsIFrame::Cursor nsTreeBodyFrame::GetCursor(const nsPoint& aPoint) {
// Check the GetScriptHandlingObject so we don't end up running code when
// the document is a zombie.
bool dummy;
if (mView && GetContent()->GetComposedDoc()->GetScriptHandlingObject(dummy)) {
int32_t row;
nsTreeColumn* col;
nsCSSAnonBoxPseudoStaticAtom* child;
GetCellAt(aPoint.x, aPoint.y, &row, &col, &child);
if (child) {
// Our scratch array is already prefilled.
RefPtr<ComputedStyle> childContext = GetPseudoComputedStyle(child);
StyleCursorKind kind = childContext->StyleUI()->Cursor().keyword;
if (kind == StyleCursorKind::Auto) {
kind = StyleCursorKind::Default;
}
return Cursor{kind, AllowCustomCursorImage::Yes, std::move(childContext)};
}
}
return SimpleXULLeafFrame::GetCursor(aPoint);
}
static uint32_t GetDropEffect(WidgetGUIEvent* aEvent) {
NS_ASSERTION(aEvent->mClass == eDragEventClass, "wrong event type");
WidgetDragEvent* dragEvent = aEvent->AsDragEvent();
nsContentUtils::SetDataTransferInEvent(dragEvent);
uint32_t action = 0;
if (dragEvent->mDataTransfer) {
action = dragEvent->mDataTransfer->DropEffectInt();
}
return action;
}
nsresult nsTreeBodyFrame::HandleEvent(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
if (aEvent->mMessage == eMouseOver || aEvent->mMessage == eMouseMove) {
nsPoint pt =
nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, RelativeTo{this});
int32_t xTwips = pt.x - mInnerBox.x;
int32_t yTwips = pt.y - mInnerBox.y;
int32_t newrow = GetRowAtInternal(xTwips, yTwips);
if (mMouseOverRow != newrow) {
// redraw the old and the new row
if (mMouseOverRow != -1) InvalidateRow(mMouseOverRow);
mMouseOverRow = newrow;
if (mMouseOverRow != -1) InvalidateRow(mMouseOverRow);
}
} else if (aEvent->mMessage == eMouseOut) {
if (mMouseOverRow != -1) {
InvalidateRow(mMouseOverRow);
mMouseOverRow = -1;
}
} else if (aEvent->mMessage == eDragEnter) {
if (!mSlots) {
mSlots = MakeUnique<Slots>();
}
// Cache several things we'll need throughout the course of our work. These
// will all get released on a drag exit.
if (mSlots->mTimer) {
mSlots->mTimer->Cancel();
mSlots->mTimer = nullptr;
}
// Cache the drag session.
mSlots->mIsDragging = true;
mSlots->mDropRow = -1;
mSlots->mDropOrient = -1;
mSlots->mDragAction = GetDropEffect(aEvent);
} else if (aEvent->mMessage == eDragOver) {
// The mouse is hovering over this tree. If we determine things are
// different from the last time, invalidate the drop feedback at the old
// position, query the view to see if the current location is droppable,
// and then invalidate the drop feedback at the new location if it is.
// The mouse may or may not have changed position from the last time
// we were called, so optimize out a lot of the extra notifications by
// checking if anything changed first. For drop feedback we use drop,
// dropBefore and dropAfter property.
if (!mView || !mSlots) {
return NS_OK;
}
// Save last values, we will need them.
int32_t lastDropRow = mSlots->mDropRow;
int16_t lastDropOrient = mSlots->mDropOrient;
#ifndef XP_MACOSX
int16_t lastScrollLines = mSlots->mScrollLines;
#endif
// Find out the current drag action
uint32_t lastDragAction = mSlots->mDragAction;
mSlots->mDragAction = GetDropEffect(aEvent);
// Compute the row mouse is over and the above/below/on state.
// Below we'll use this to see if anything changed.
// Also check if we want to auto-scroll.
ComputeDropPosition(aEvent, &mSlots->mDropRow, &mSlots->mDropOrient,
&mSlots->mScrollLines);
// While we're here, handle tracking of scrolling during a drag.
if (mSlots->mScrollLines) {
if (mSlots->mDropAllowed) {
// Invalidate primary cell at old location.
mSlots->mDropAllowed = false;
InvalidateDropFeedback(lastDropRow, lastDropOrient);
}
#ifdef XP_MACOSX
ScrollByLines(mSlots->mScrollLines);
#else
if (!lastScrollLines) {
// Cancel any previously initialized timer.
if (mSlots->mTimer) {
mSlots->mTimer->Cancel();
mSlots->mTimer = nullptr;
}
// Set a timer to trigger the tree scrolling.
CreateTimer(LookAndFeel::IntID::TreeLazyScrollDelay, LazyScrollCallback,
nsITimer::TYPE_ONE_SHOT, getter_AddRefs(mSlots->mTimer),
"nsTreeBodyFrame::LazyScrollCallback");
}
#endif
// Bail out to prevent spring loaded timer and feedback line settings.
return NS_OK;
}
// If changed from last time, invalidate primary cell at the old location
// and if allowed, invalidate primary cell at the new location. If nothing
// changed, just bail.
if (mSlots->mDropRow != lastDropRow ||
mSlots->mDropOrient != lastDropOrient ||
mSlots->mDragAction != lastDragAction) {
// Invalidate row at the old location.
if (mSlots->mDropAllowed) {
mSlots->mDropAllowed = false;
InvalidateDropFeedback(lastDropRow, lastDropOrient);
}
if (mSlots->mTimer) {
// Timer is active but for a different row than the current one, kill
// it.
mSlots->mTimer->Cancel();
mSlots->mTimer = nullptr;
}
if (mSlots->mDropRow >= 0) {
if (!mSlots->mTimer && mSlots->mDropOrient == nsITreeView::DROP_ON) {
// Either there wasn't a timer running or it was just killed above.
// If over a folder, start up a timer to open the folder.
bool isContainer = false;
mView->IsContainer(mSlots->mDropRow, &isContainer);
if (isContainer) {
bool isOpen = false;
mView->IsContainerOpen(mSlots->mDropRow, &isOpen);
if (!isOpen) {
// This node isn't expanded, set a timer to expand it.
CreateTimer(LookAndFeel::IntID::TreeOpenDelay, OpenCallback,
nsITimer::TYPE_ONE_SHOT,
getter_AddRefs(mSlots->mTimer),
"nsTreeBodyFrame::OpenCallback");
}
}
}
// The dataTransfer was initialized by the call to GetDropEffect above.
bool canDropAtNewLocation = false;
mView->CanDrop(mSlots->mDropRow, mSlots->mDropOrient,
aEvent->AsDragEvent()->mDataTransfer,
&canDropAtNewLocation);
if (canDropAtNewLocation) {
// Invalidate row at the new location.
mSlots->mDropAllowed = canDropAtNewLocation;
InvalidateDropFeedback(mSlots->mDropRow, mSlots->mDropOrient);
}
}
}
// Indicate that the drop is allowed by preventing the default behaviour.
if (mSlots->mDropAllowed) *aEventStatus = nsEventStatus_eConsumeNoDefault;
} else if (aEvent->mMessage == eDrop) {
// this event was meant for another frame, so ignore it
if (!mSlots) return NS_OK;
// Tell the view where the drop happened.
// Remove the drop folder and all its parents from the array.
int32_t parentIndex;
nsresult rv = mView->GetParentIndex(mSlots->mDropRow, &parentIndex);
while (NS_SUCCEEDED(rv) && parentIndex >= 0) {
mSlots->mArray.RemoveElement(parentIndex);
rv = mView->GetParentIndex(parentIndex, &parentIndex);
}
NS_ASSERTION(aEvent->mClass == eDragEventClass, "wrong event type");
WidgetDragEvent* dragEvent = aEvent->AsDragEvent();
nsContentUtils::SetDataTransferInEvent(dragEvent);
mView->Drop(mSlots->mDropRow, mSlots->mDropOrient,
dragEvent->mDataTransfer);
mSlots->mDropRow = -1;
mSlots->mDropOrient = -1;
mSlots->mIsDragging = false;
*aEventStatus =
nsEventStatus_eConsumeNoDefault; // already handled the drop
} else if (aEvent->mMessage == eDragExit) {
// this event was meant for another frame, so ignore it
if (!mSlots) return NS_OK;
// Clear out all our tracking vars.
if (mSlots->mDropAllowed) {
mSlots->mDropAllowed = false;
InvalidateDropFeedback(mSlots->mDropRow, mSlots->mDropOrient);
} else
mSlots->mDropAllowed = false;
mSlots->mIsDragging = false;
mSlots->mScrollLines = 0;
// If a drop is occuring, the exit event will fire just before the drop
// event, so don't reset mDropRow or mDropOrient as these fields are used
// by the drop event.
if (mSlots->mTimer) {
mSlots->mTimer->Cancel();
mSlots->mTimer = nullptr;
}
if (!mSlots->mArray.IsEmpty()) {
// Close all spring loaded folders except the drop folder.
CreateTimer(LookAndFeel::IntID::TreeCloseDelay, CloseCallback,
nsITimer::TYPE_ONE_SHOT, getter_AddRefs(mSlots->mTimer),
"nsTreeBodyFrame::CloseCallback");
}
}
return NS_OK;
}
namespace mozilla {
class nsDisplayTreeBody final : public nsPaintedDisplayItem {
public:
nsDisplayTreeBody(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
: nsPaintedDisplayItem(aBuilder, aFrame) {
MOZ_COUNT_CTOR(nsDisplayTreeBody);
}
MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTreeBody)
nsDisplayItemGeometry* AllocateGeometry(
nsDisplayListBuilder* aBuilder) override {
return new nsDisplayTreeBodyGeometry(this, aBuilder, IsWindowActive());
}
void Destroy(nsDisplayListBuilder* aBuilder) override {
aBuilder->UnregisterThemeGeometry(this);
nsPaintedDisplayItem::Destroy(aBuilder);
}
bool IsWindowActive() const {
return !mFrame->PresContext()->Document()->IsTopLevelWindowInactive();
}
void ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const override {
auto geometry = static_cast<const nsDisplayTreeBodyGeometry*>(aGeometry);
if (IsWindowActive() != geometry->mWindowIsActive) {
bool snap;
aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
}
nsPaintedDisplayItem::ComputeInvalidationRegion(aBuilder, aGeometry,
aInvalidRegion);
}
void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override {
MOZ_ASSERT(aBuilder);
Unused << static_cast<nsTreeBodyFrame*>(mFrame)->PaintTreeBody(
*aCtx, GetPaintRect(aBuilder, aCtx), ToReferenceFrame(), aBuilder);
}
NS_DISPLAY_DECL_NAME("XULTreeBody", TYPE_XUL_TREE_BODY)
nsRect GetComponentAlphaBounds(
nsDisplayListBuilder* aBuilder) const override {
bool snap;
return GetBounds(aBuilder, &snap);
}
};
} // namespace mozilla
// Painting routines
void nsTreeBodyFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
// REVIEW: why did we paint if we were collapsed? that makes no sense!
if (!IsVisibleForPainting()) return; // We're invisible. Don't paint.
// Handles painting our background, border, and outline.
SimpleXULLeafFrame::BuildDisplayList(aBuilder, aLists);
// Bail out now if there's no view or we can't run script because the
// document is a zombie
if (!mView || !GetContent()->GetComposedDoc()->GetWindow()) return;
nsDisplayItem* item = MakeDisplayItem<nsDisplayTreeBody>(aBuilder, this);
aLists.Content()->AppendToTop(item);
}
ImgDrawResult nsTreeBodyFrame::PaintTreeBody(gfxContext& aRenderingContext,
const nsRect& aDirtyRect,
nsPoint aPt,
nsDisplayListBuilder* aBuilder) {
// Update our available height and our page count.
CalcInnerBox();
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
aRenderingContext.Save();
aRenderingContext.Clip(NSRectToSnappedRect(
mInnerBox + aPt, PresContext()->AppUnitsPerDevPixel(), *drawTarget));
int32_t oldPageCount = mPageLength;
if (!mHasFixedRowCount) {
mPageLength =
(mRowHeight > 0) ? (mInnerBox.height / mRowHeight) : mRowCount;
}
if (oldPageCount != mPageLength ||
mHorzWidth != CalcHorzWidth(GetScrollParts())) {
// Schedule a ResizeReflow that will update our info properly.
PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
NS_FRAME_IS_DIRTY);
}
#ifdef DEBUG
int32_t rowCount = mRowCount;
mView->GetRowCount(&rowCount);
NS_WARNING_ASSERTION(mRowCount == rowCount, "row count changed unexpectedly");
#endif
ImgDrawResult result = ImgDrawResult::SUCCESS;
// Loop through our columns and paint them (e.g., for sorting). This is only
// relevant when painting backgrounds, since columns contain no content.
// Content is contained in the rows.
for (nsTreeColumn* currCol = mColumns->GetFirstColumn(); currCol;
currCol = currCol->GetNext()) {
nsRect colRect;
nsresult rv =
currCol->GetRect(this, mInnerBox.y, mInnerBox.height, &colRect);
// Don't paint hidden columns.
if (NS_FAILED(rv) || colRect.width == 0) continue;
if (OffsetForHorzScroll(colRect, false)) {
nsRect dirtyRect;
colRect += aPt;
if (dirtyRect.IntersectRect(aDirtyRect, colRect)) {
result &= PaintColumn(currCol, colRect, PresContext(),
aRenderingContext, aDirtyRect);
}
}
}
// Loop through our on-screen rows.
for (int32_t i = mTopRowIndex;
i < mRowCount && i <= mTopRowIndex + mPageLength; i++) {
nsRect rowRect(mInnerBox.x, mInnerBox.y + mRowHeight * (i - mTopRowIndex),
mInnerBox.width, mRowHeight);
nsRect dirtyRect;
if (dirtyRect.IntersectRect(aDirtyRect, rowRect + aPt) &&
rowRect.y < (mInnerBox.y + mInnerBox.height)) {
result &= PaintRow(i, rowRect + aPt, PresContext(), aRenderingContext,
aDirtyRect, aPt, aBuilder);
}
}
if (mSlots && mSlots->mDropAllowed &&
(mSlots->mDropOrient == nsITreeView::DROP_BEFORE ||
mSlots->mDropOrient == nsITreeView::DROP_AFTER)) {
nscoord yPos = mInnerBox.y +
mRowHeight * (mSlots->mDropRow - mTopRowIndex) -
mRowHeight / 2;
nsRect feedbackRect(mInnerBox.x, yPos, mInnerBox.width, mRowHeight);
if (mSlots->mDropOrient == nsITreeView::DROP_AFTER)
feedbackRect.y += mRowHeight;
nsRect dirtyRect;
feedbackRect += aPt;
if (dirtyRect.IntersectRect(aDirtyRect, feedbackRect)) {
result &= PaintDropFeedback(feedbackRect, PresContext(),
aRenderingContext, aDirtyRect, aPt);
}
}
aRenderingContext.Restore();
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintColumn(nsTreeColumn* aColumn,
const nsRect& aColumnRect,
nsPresContext* aPresContext,
gfxContext& aRenderingContext,
const nsRect& aDirtyRect) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
// Now obtain the properties for our cell.
PrefillPropertyArray(-1, aColumn);
nsAutoString properties;
nsCOMPtr<nsITreeView> view = GetExistingView();
view->GetColumnProperties(aColumn, properties);
nsTreeUtils::TokenizeProperties(properties, mScratchArray);
// Resolve style for the column. It contains all the info we need to lay
// ourselves out and to paint.
ComputedStyle* colContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeColumn());
// Obtain the margins for the cell and then deflate our rect by that
// amount. The cell is assumed to be contained within the deflated rect.
nsRect colRect(aColumnRect);
nsMargin colMargin;
colContext->StyleMargin()->GetMargin(colMargin);
colRect.Deflate(colMargin);
return PaintBackgroundLayer(colContext, aPresContext, aRenderingContext,
colRect, aDirtyRect);
}
ImgDrawResult nsTreeBodyFrame::PaintRow(int32_t aRowIndex,
const nsRect& aRowRect,
nsPresContext* aPresContext,
gfxContext& aRenderingContext,
const nsRect& aDirtyRect, nsPoint aPt,
nsDisplayListBuilder* aBuilder) {
// We have been given a rect for our row. We treat this row like a full-blown
// frame, meaning that it can have borders, margins, padding, and a
// background.
// Without a view, we have no data. Check for this up front.
nsCOMPtr<nsITreeView> view = GetExistingView();
if (!view) {
return ImgDrawResult::SUCCESS;
}
nsresult rv;
// Now obtain the properties for our row.
// XXX Automatically fill in the following props: open, closed, container,
// leaf, selected, focused
PrefillPropertyArray(aRowIndex, nullptr);
nsAutoString properties;
view->GetRowProperties(aRowIndex, properties);
nsTreeUtils::TokenizeProperties(properties, mScratchArray);
// Resolve style for the row. It contains all the info we need to lay
// ourselves out and to paint.
ComputedStyle* rowContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeRow());
// Obtain the margins for the row and then deflate our rect by that
// amount. The row is assumed to be contained within the deflated rect.
nsRect rowRect(aRowRect);
nsMargin rowMargin;
rowContext->StyleMargin()->GetMargin(rowMargin);
rowRect.Deflate(rowMargin);
ImgDrawResult result = ImgDrawResult::SUCCESS;
// Paint our borders and background for our row rect.
nsITheme* theme = nullptr;
auto appearance = rowContext->StyleDisplay()->EffectiveAppearance();
if (appearance != StyleAppearance::None) {
theme = aPresContext->Theme();
}
if (theme && theme->ThemeSupportsWidget(aPresContext, nullptr, appearance)) {
nsRect dirty;
dirty.IntersectRect(rowRect, aDirtyRect);
theme->DrawWidgetBackground(&aRenderingContext, this, appearance, rowRect,
dirty);
} else {
result &= PaintBackgroundLayer(rowContext, aPresContext, aRenderingContext,
rowRect, aDirtyRect);
}
// Adjust the rect for its border and padding.
nsRect originalRowRect = rowRect;
AdjustForBorderPadding(rowContext, rowRect);
bool isSeparator = false;
view->IsSeparator(aRowIndex, &isSeparator);
if (isSeparator) {
// The row is a separator.
nscoord primaryX = rowRect.x;
nsTreeColumn* primaryCol = mColumns->GetPrimaryColumn();
if (primaryCol) {
// Paint the primary cell.
nsRect cellRect;
rv = primaryCol->GetRect(this, rowRect.y, rowRect.height, &cellRect);
if (NS_FAILED(rv)) {
MOZ_ASSERT_UNREACHABLE("primary column is invalid");
return result;
}
if (OffsetForHorzScroll(cellRect, false)) {
cellRect.x += aPt.x;
nsRect dirtyRect;
nsRect checkRect(cellRect.x, originalRowRect.y, cellRect.width,
originalRowRect.height);
if (dirtyRect.IntersectRect(aDirtyRect, checkRect)) {
result &=
PaintCell(aRowIndex, primaryCol, cellRect, aPresContext,
aRenderingContext, aDirtyRect, primaryX, aPt, aBuilder);
}
}
// Paint the left side of the separator.
nscoord currX;
nsTreeColumn* previousCol = primaryCol->GetPrevious();
if (previousCol) {
nsRect prevColRect;
rv = previousCol->GetRect(this, 0, 0, &prevColRect);
if (NS_SUCCEEDED(rv)) {
currX = (prevColRect.x - mHorzPosition) + prevColRect.width + aPt.x;
} else {
MOZ_ASSERT_UNREACHABLE(
"The column before the primary column is "
"invalid");
currX = rowRect.x;
}
} else {
currX = rowRect.x;
}
int32_t level;
view->GetLevel(aRowIndex, &level);
if (level == 0) currX += mIndentation;
if (currX > rowRect.x) {
nsRect separatorRect(rowRect);
separatorRect.width -= rowRect.x + rowRect.width - currX;
result &= PaintSeparator(aRowIndex, separatorRect, aPresContext,
aRenderingContext, aDirtyRect);
}
}
// Paint the right side (whole) separator.
nsRect separatorRect(rowRect);
if (primaryX > rowRect.x) {
separatorRect.width -= primaryX - rowRect.x;
separatorRect.x += primaryX - rowRect.x;
}
result &= PaintSeparator(aRowIndex, separatorRect, aPresContext,
aRenderingContext, aDirtyRect);
} else {
// Now loop over our cells. Only paint a cell if it intersects with our
// dirty rect.
for (nsTreeColumn* currCol = mColumns->GetFirstColumn(); currCol;
currCol = currCol->GetNext()) {
nsRect cellRect;
rv = currCol->GetRect(this, rowRect.y, rowRect.height, &cellRect);
// Don't paint cells in hidden columns.
if (NS_FAILED(rv) || cellRect.width == 0) continue;
if (OffsetForHorzScroll(cellRect, false)) {
cellRect.x += aPt.x;
// for primary columns, use the row's vertical size so that the
// lines get drawn properly
nsRect checkRect = cellRect;
if (currCol->IsPrimary())
checkRect = nsRect(cellRect.x, originalRowRect.y, cellRect.width,
originalRowRect.height);
nsRect dirtyRect;
nscoord dummy;
if (dirtyRect.IntersectRect(aDirtyRect, checkRect))
result &=
PaintCell(aRowIndex, currCol, cellRect, aPresContext,
aRenderingContext, aDirtyRect, dummy, aPt, aBuilder);
}
}
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintSeparator(int32_t aRowIndex,
const nsRect& aSeparatorRect,
nsPresContext* aPresContext,
gfxContext& aRenderingContext,
const nsRect& aDirtyRect) {
// Resolve style for the separator.
ComputedStyle* separatorContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeSeparator());
bool useTheme = false;
nsITheme* theme = nullptr;
StyleAppearance appearance =
separatorContext->StyleDisplay()->EffectiveAppearance();
if (appearance != StyleAppearance::None) {
theme = aPresContext->Theme();
if (theme->ThemeSupportsWidget(aPresContext, nullptr, appearance))
useTheme = true;
}
ImgDrawResult result = ImgDrawResult::SUCCESS;
// use -moz-appearance if provided.
if (useTheme) {
nsRect dirty;
dirty.IntersectRect(aSeparatorRect, aDirtyRect);
theme->DrawWidgetBackground(&aRenderingContext, this, appearance,
aSeparatorRect, dirty);
} else {
const nsStylePosition* stylePosition = separatorContext->StylePosition();
// Obtain the height for the separator or use the default value.
nscoord height;
if (stylePosition->mHeight.ConvertsToLength()) {
height = stylePosition->mHeight.ToLength();
} else {
// Use default height 2px.
height = nsPresContext::CSSPixelsToAppUnits(2);
}
// Obtain the margins for the separator and then deflate our rect by that
// amount. The separator is assumed to be contained within the deflated
// rect.
nsRect separatorRect(aSeparatorRect.x, aSeparatorRect.y,
aSeparatorRect.width, height);
nsMargin separatorMargin;
separatorContext->StyleMargin()->GetMargin(separatorMargin);
separatorRect.Deflate(separatorMargin);
// Center the separator.
separatorRect.y += (aSeparatorRect.height - height) / 2;
result &=
PaintBackgroundLayer(separatorContext, aPresContext, aRenderingContext,
separatorRect, aDirtyRect);
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintCell(
int32_t aRowIndex, nsTreeColumn* aColumn, const nsRect& aCellRect,
nsPresContext* aPresContext, gfxContext& aRenderingContext,
const nsRect& aDirtyRect, nscoord& aCurrX, nsPoint aPt,
nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
// Now obtain the properties for our cell.
// XXX Automatically fill in the following props: open, closed, container,
// leaf, selected, focused, and the col ID.
PrefillPropertyArray(aRowIndex, aColumn);
nsAutoString properties;
nsCOMPtr<nsITreeView> view = GetExistingView();
view->GetCellProperties(aRowIndex, aColumn, properties);
nsTreeUtils::TokenizeProperties(properties, mScratchArray);
// Resolve style for the cell. It contains all the info we need to lay
// ourselves out and to paint.
ComputedStyle* cellContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCell());
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
// Obtain the margins for the cell and then deflate our rect by that
// amount. The cell is assumed to be contained within the deflated rect.
nsRect cellRect(aCellRect);
nsMargin cellMargin;
cellContext->StyleMargin()->GetMargin(cellMargin);
cellRect.Deflate(cellMargin);
// Paint our borders and background for our row rect.
ImgDrawResult result = PaintBackgroundLayer(
cellContext, aPresContext, aRenderingContext, cellRect, aDirtyRect);
// Adjust the rect for its border and padding.
AdjustForBorderPadding(cellContext, cellRect);
nscoord currX = cellRect.x;
nscoord remainingWidth = cellRect.width;
// Now we paint the contents of the cells.
// Directionality of the tree determines the order in which we paint.
// StyleDirection::Ltr means paint from left to right.
// StyleDirection::Rtl means paint from right to left.
if (aColumn->IsPrimary()) {
// If we're the primary column, we need to indent and paint the twisty and
// any connecting lines between siblings.
int32_t level;
view->GetLevel(aRowIndex, &level);
if (!isRTL) currX += mIndentation * level;
remainingWidth -= mIndentation * level;
// Resolve the style to use for the connecting lines.
ComputedStyle* lineContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeLine());
if (mIndentation && level &&
lineContext->StyleVisibility()->IsVisibleOrCollapsed()) {
// Paint the thread lines.
// Get the size of the twisty. We don't want to paint the twisty
// before painting of connecting lines since it would paint lines over
// the twisty. But we need to leave a place for it.
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
nsRect imageSize;
nsRect twistyRect(aCellRect);
GetTwistyRect(aRowIndex, aColumn, imageSize, twistyRect, aPresContext,
twistyContext);
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Inflate(twistyMargin);
const nsStyleBorder* borderStyle = lineContext->StyleBorder();
// Resolve currentcolor values against the treeline context
nscolor color = borderStyle->mBorderLeftColor.CalcColor(*lineContext);
ColorPattern colorPatt(ToDeviceColor(color));
StyleBorderStyle style = borderStyle->GetBorderStyle(eSideLeft);
StrokeOptions strokeOptions;
nsLayoutUtils::InitDashPattern(strokeOptions, style);
nscoord srcX = currX + twistyRect.width - mIndentation / 2;
nscoord lineY = (aRowIndex - mTopRowIndex) * mRowHeight + aPt.y;
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
nsPresContext* pc = PresContext();
// Don't paint off our cell.
if (srcX <= cellRect.x + cellRect.width) {
nscoord destX = currX + twistyRect.width;
if (destX > cellRect.x + cellRect.width)
destX = cellRect.x + cellRect.width;
if (isRTL) {
srcX = currX + remainingWidth - (srcX - cellRect.x);
destX = currX + remainingWidth - (destX - cellRect.x);
}
Point p1(pc->AppUnitsToGfxUnits(srcX),
pc->AppUnitsToGfxUnits(lineY + mRowHeight / 2));
Point p2(pc->AppUnitsToGfxUnits(destX),
pc->AppUnitsToGfxUnits(lineY + mRowHeight / 2));
SnapLineToDevicePixelsForStroking(p1, p2, *drawTarget,
strokeOptions.mLineWidth);
drawTarget->StrokeLine(p1, p2, colorPatt, strokeOptions);
}
int32_t currentParent = aRowIndex;
for (int32_t i = level; i > 0; i--) {
if (srcX <= cellRect.x + cellRect.width) {
// Paint full vertical line only if we have next sibling.
bool hasNextSibling;
view->HasNextSibling(currentParent, aRowIndex, &hasNextSibling);
if (hasNextSibling || i == level) {
Point p1(pc->AppUnitsToGfxUnits(srcX),
pc->AppUnitsToGfxUnits(lineY));
Point p2;
p2.x = pc->AppUnitsToGfxUnits(srcX);
if (hasNextSibling)
p2.y = pc->AppUnitsToGfxUnits(lineY + mRowHeight);
else if (i == level)
p2.y = pc->AppUnitsToGfxUnits(lineY + mRowHeight / 2);
SnapLineToDevicePixelsForStroking(p1, p2, *drawTarget,
strokeOptions.mLineWidth);
drawTarget->StrokeLine(p1, p2, colorPatt, strokeOptions);
}
}
int32_t parent;
if (NS_FAILED(view->GetParentIndex(currentParent, &parent)) ||
parent < 0)
break;
currentParent = parent;
srcX -= mIndentation;
}
}
// Always leave space for the twisty.
nsRect twistyRect(currX, cellRect.y, remainingWidth, cellRect.height);
result &= PaintTwisty(aRowIndex, aColumn, twistyRect, aPresContext,
aRenderingContext, aDirtyRect, remainingWidth, currX);
}
// Now paint the icon for our cell.
nsRect iconRect(currX, cellRect.y, remainingWidth, cellRect.height);
nsRect dirtyRect;
if (dirtyRect.IntersectRect(aDirtyRect, iconRect)) {
result &= PaintImage(aRowIndex, aColumn, iconRect, aPresContext,
aRenderingContext, aDirtyRect, remainingWidth, currX,
aBuilder);
}
// Now paint our element, but only if we aren't a cycler column.
// XXX until we have the ability to load images, allow the view to
// insert text into cycler columns...
if (!aColumn->IsCycler()) {
nsRect elementRect(currX, cellRect.y, remainingWidth, cellRect.height);
nsRect dirtyRect;
if (dirtyRect.IntersectRect(aDirtyRect, elementRect)) {
switch (aColumn->GetType()) {
case TreeColumn_Binding::TYPE_TEXT:
result &= PaintText(aRowIndex, aColumn, elementRect, aPresContext,
aRenderingContext, aDirtyRect, currX);
break;
case TreeColumn_Binding::TYPE_CHECKBOX:
result &= PaintCheckbox(aRowIndex, aColumn, elementRect, aPresContext,
aRenderingContext, aDirtyRect);
break;
}
}
}
aCurrX = currX;
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintTwisty(
int32_t aRowIndex, nsTreeColumn* aColumn, const nsRect& aTwistyRect,
nsPresContext* aPresContext, gfxContext& aRenderingContext,
const nsRect& aDirtyRect, nscoord& aRemainingWidth, nscoord& aCurrX) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
nscoord rightEdge = aCurrX + aRemainingWidth;
// Paint the twisty, but only if we are a non-empty container.
bool shouldPaint = false;
bool isContainer = false;
nsCOMPtr<nsITreeView> view = GetExistingView();
view->IsContainer(aRowIndex, &isContainer);
if (isContainer) {
bool isContainerEmpty = false;
view->IsContainerEmpty(aRowIndex, &isContainerEmpty);
if (!isContainerEmpty) shouldPaint = true;
}
// Resolve style for the twisty.
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
// Obtain the margins for the twisty and then deflate our rect by that
// amount. The twisty is assumed to be contained within the deflated rect.
nsRect twistyRect(aTwistyRect);
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Deflate(twistyMargin);
nsRect imageSize;
nsITheme* theme = GetTwistyRect(aRowIndex, aColumn, imageSize, twistyRect,
aPresContext, twistyContext);
// Subtract out the remaining width. This is done even when we don't actually
// paint a twisty in this cell, so that cells in different rows still line up.
nsRect copyRect(twistyRect);
copyRect.Inflate(twistyMargin);
aRemainingWidth -= copyRect.width;
if (!isRTL) aCurrX += copyRect.width;
ImgDrawResult result = ImgDrawResult::SUCCESS;
if (shouldPaint) {
// Paint our borders and background for our image rect.
result &= PaintBackgroundLayer(twistyContext, aPresContext,
aRenderingContext, twistyRect, aDirtyRect);
if (theme) {
if (isRTL) twistyRect.x = rightEdge - twistyRect.width;
// yeah, I know it says we're drawing a background, but a twisty is really
// a fg object since it doesn't have anything that gecko would want to
// draw over it. Besides, we have to prevent imagelib from drawing it.
nsRect dirty;
dirty.IntersectRect(twistyRect, aDirtyRect);
theme->DrawWidgetBackground(
&aRenderingContext, this,
twistyContext->StyleDisplay()->EffectiveAppearance(), twistyRect,
dirty);
} else {
// Time to paint the twisty.
// Adjust the rect for its border and padding.
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(twistyContext, bp);
twistyRect.Deflate(bp);
if (isRTL) twistyRect.x = rightEdge - twistyRect.width;
imageSize.Deflate(bp);
// Get the image for drawing.
nsCOMPtr<imgIContainer> image;
GetImage(aRowIndex, aColumn, true, twistyContext, getter_AddRefs(image));
if (image) {
nsPoint anchorPoint = twistyRect.TopLeft();
// Center the image. XXX Obey vertical-align style prop?
if (imageSize.height < twistyRect.height) {
anchorPoint.y += (twistyRect.height - imageSize.height) / 2;
}
// Apply context paint if applicable
SVGImageContext svgContext;
SVGImageContext::MaybeStoreContextPaint(svgContext, *aPresContext,
*twistyContext, image);
// Paint the image.
result &= nsLayoutUtils::DrawSingleUnscaledImage(
aRenderingContext, aPresContext, image, SamplingFilter::POINT,
anchorPoint, &aDirtyRect, svgContext, imgIContainer::FLAG_NONE,
&imageSize);
}
}
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintImage(
int32_t aRowIndex, nsTreeColumn* aColumn, const nsRect& aImageRect,
nsPresContext* aPresContext, gfxContext& aRenderingContext,
const nsRect& aDirtyRect, nscoord& aRemainingWidth, nscoord& aCurrX,
nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
nscoord rightEdge = aCurrX + aRemainingWidth;
// Resolve style for the image.
ComputedStyle* imageContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeImage());
// Obtain the margins for the image and then deflate our rect by that
// amount. The image is assumed to be contained within the deflated rect.
nsRect imageRect(aImageRect);
nsMargin imageMargin;
imageContext->StyleMargin()->GetMargin(imageMargin);
imageRect.Deflate(imageMargin);
// Get the image.
nsCOMPtr<imgIContainer> image;
GetImage(aRowIndex, aColumn, false, imageContext, getter_AddRefs(image));
// Get the image destination size.
nsSize imageDestSize = GetImageDestSize(imageContext, image);
if (!imageDestSize.width || !imageDestSize.height) {
return ImgDrawResult::SUCCESS;
}
// Get the borders and padding.
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(imageContext, bp);
// destRect will be passed as the aDestRect argument in the DrawImage method.
// Start with the imageDestSize width and height.
nsRect destRect(0, 0, imageDestSize.width, imageDestSize.height);
// Inflate destRect for borders and padding so that we can compare/adjust
// with respect to imageRect.
destRect.Inflate(bp);
// The destRect width and height have not been adjusted to fit within the
// cell width and height.
// We must adjust the width even if image is null, because the width is used
// to update the aRemainingWidth and aCurrX values.
// Since the height isn't used unless the image is not null, we will adjust
// the height inside the if (image) block below.
if (destRect.width > imageRect.width) {
// The destRect is too wide to fit within the cell width.
// Adjust destRect width to fit within the cell width.
destRect.width = imageRect.width;
} else {
// The cell is wider than the destRect.
// In a cycler column, the image is centered horizontally.
if (!aColumn->IsCycler()) {
// If this column is not a cycler, we won't center the image horizontally.
// We adjust the imageRect width so that the image is placed at the start
// of the cell.
imageRect.width = destRect.width;
}
}
ImgDrawResult result = ImgDrawResult::SUCCESS;
if (image) {
if (isRTL) imageRect.x = rightEdge - imageRect.width;
// Paint our borders and background for our image rect
result &= PaintBackgroundLayer(imageContext, aPresContext,
aRenderingContext, imageRect, aDirtyRect);
// The destRect x and y have not been set yet. Let's do that now.
// Initially, we use the imageRect x and y.
destRect.x = imageRect.x;
destRect.y = imageRect.y;
if (destRect.width < imageRect.width) {
// The destRect width is smaller than the cell width.
// Center the image horizontally in the cell.
// Adjust the destRect x accordingly.
destRect.x += (imageRect.width - destRect.width) / 2;
}
// Now it's time to adjust the destRect height to fit within the cell
// height.
if (destRect.height > imageRect.height) {
// The destRect height is larger than the cell height.
// Adjust destRect height to fit within the cell height.
destRect.height = imageRect.height;
} else if (destRect.height < imageRect.height) {
// The destRect height is smaller than the cell height.
// Center the image vertically in the cell.
// Adjust the destRect y accordingly.
destRect.y += (imageRect.height - destRect.height) / 2;
}
// It's almost time to paint the image.
// Deflate destRect for the border and padding.
destRect.Deflate(bp);
// Compute the area where our whole image would be mapped, to get the
// desired subregion onto our actual destRect:
nsRect wholeImageDest;
CSSIntSize rawImageCSSIntSize;
if (NS_SUCCEEDED(image->GetWidth(&rawImageCSSIntSize.width)) &&
NS_SUCCEEDED(image->GetHeight(&rawImageCSSIntSize.height))) {
// Get the image source rectangle - the rectangle containing the part of
// the image that we are going to display. sourceRect will be passed as
// the aSrcRect argument in the DrawImage method.
nsRect sourceRect = GetImageSourceRect(imageContext, image);
// Let's say that the image is 100 pixels tall and that the CSS has
// specified that the destination height should be 50 pixels tall. Let's
// say that the cell height is only 20 pixels. So, in those 20 visible
// pixels, we want to see the top 20/50ths of the image. So, the
// sourceRect.height should be 100 * 20 / 50, which is 40 pixels.
// Essentially, we are scaling the image as dictated by the CSS
// destination height and width, and we are then clipping the scaled
// image by the cell width and height.
nsSize rawImageSize(CSSPixel::ToAppUnits(rawImageCSSIntSize));
wholeImageDest = nsLayoutUtils::GetWholeImageDestination(
rawImageSize, sourceRect, nsRect(destRect.TopLeft(), imageDestSize));
} else {
// GetWidth/GetHeight failed, so we can't easily map a subregion of the
// source image onto the destination area.
// * If this happens with a RasterImage, it probably means the image is
// in an error state, and we shouldn't draw anything. Hence, we leave
// wholeImageDest as an empty rect (its initial state).
// * If this happens with a VectorImage, it probably means the image has
// no explicit width or height attribute -- but we can still proceed and
// just treat the destination area as our whole SVG image area. Hence, we
// set wholeImageDest to the full destRect.
if (image->GetType() == imgIContainer::TYPE_VECTOR) {
wholeImageDest = destRect;
}
}
const auto* styleEffects = imageContext->StyleEffects();
gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&aRenderingContext);
if (!styleEffects->IsOpaque()) {
autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA,
styleEffects->mOpacity);
}
uint32_t drawFlags = aBuilder && aBuilder->UseHighQualityScaling()
? imgIContainer::FLAG_HIGH_QUALITY_SCALING
: imgIContainer::FLAG_NONE;
result &= nsLayoutUtils::DrawImage(
aRenderingContext, imageContext, aPresContext, image,
nsLayoutUtils::GetSamplingFilterForFrame(this), wholeImageDest,
destRect, destRect.TopLeft(), aDirtyRect, drawFlags);
}
// Update the aRemainingWidth and aCurrX values.
imageRect.Inflate(imageMargin);
aRemainingWidth -= imageRect.width;
if (!isRTL) {
aCurrX += imageRect.width;
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintText(
int32_t aRowIndex, nsTreeColumn* aColumn, const nsRect& aTextRect,
nsPresContext* aPresContext, gfxContext& aRenderingContext,
const nsRect& aDirtyRect, nscoord& aCurrX) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
bool isRTL = StyleVisibility()->mDirection == StyleDirection::Rtl;
// Now obtain the text for our cell.
nsAutoString text;
nsCOMPtr<nsITreeView> view = GetExistingView();
view->GetCellText(aRowIndex, aColumn, text);
// We're going to paint this text so we need to ensure bidi is enabled if
// necessary
CheckTextForBidi(text);
ImgDrawResult result = ImgDrawResult::SUCCESS;
if (text.Length() == 0) {
// Don't paint an empty string. XXX What about background/borders? Still
// paint?
return result;
}
int32_t appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
// Resolve style for the text. It contains all the info we need to lay
// ourselves out and to paint.
ComputedStyle* textContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCellText());
// Obtain the margins for the text and then deflate our rect by that
// amount. The text is assumed to be contained within the deflated rect.
nsRect textRect(aTextRect);
nsMargin textMargin;
textContext->StyleMargin()->GetMargin(textMargin);
textRect.Deflate(textMargin);
// Adjust the rect for its border and padding.
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(textContext, bp);
textRect.Deflate(bp);
// Compute our text size.
RefPtr<nsFontMetrics> fontMet =
nsLayoutUtils::GetFontMetricsForComputedStyle(textContext, PresContext());
nscoord height = fontMet->MaxHeight();
nscoord baseline = fontMet->MaxAscent();
// Center the text. XXX Obey vertical-align style prop?
if (height < textRect.height) {
textRect.y += (textRect.height - height) / 2;
textRect.height = height;
}
// Set our font.
AdjustForCellText(text, aRowIndex, aColumn, aRenderingContext, *fontMet,
textRect);
textRect.Inflate(bp);
// Subtract out the remaining width.
if (!isRTL) aCurrX += textRect.width + textMargin.LeftRight();
result &= PaintBackgroundLayer(textContext, aPresContext, aRenderingContext,
textRect, aDirtyRect);
// Time to paint our text.
textRect.Deflate(bp);
// Set our color.
ColorPattern color(ToDeviceColor(textContext->StyleText()->mColor));
// Draw decorations.
StyleTextDecorationLine decorations =
textContext->StyleTextReset()->mTextDecorationLine;
nscoord offset;
nscoord size;
if (decorations & (StyleTextDecorationLine::OVERLINE |
StyleTextDecorationLine::UNDERLINE)) {
fontMet->GetUnderline(offset, size);
if (decorations & StyleTextDecorationLine::OVERLINE) {
nsRect r(textRect.x, textRect.y, textRect.width, size);
Rect devPxRect = NSRectToSnappedRect(r, appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(devPxRect, color);
}
if (decorations & StyleTextDecorationLine::UNDERLINE) {
nsRect r(textRect.x, textRect.y + baseline - offset, textRect.width,
size);
Rect devPxRect = NSRectToSnappedRect(r, appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(devPxRect, color);
}
}
if (decorations & StyleTextDecorationLine::LINE_THROUGH) {
fontMet->GetStrikeout(offset, size);
nsRect r(textRect.x, textRect.y + baseline - offset, textRect.width, size);
Rect devPxRect = NSRectToSnappedRect(r, appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(devPxRect, color);
}
ComputedStyle* cellContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCell());
const auto* styleEffects = textContext->StyleEffects();
gfxGroupForBlendAutoSaveRestore autoGroupForBlend(&aRenderingContext);
if (!styleEffects->IsOpaque()) {
autoGroupForBlend.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA,
styleEffects->mOpacity);
}
aRenderingContext.SetColor(
sRGBColor::FromABGR(textContext->StyleText()->mColor.ToColor()));
nsLayoutUtils::DrawString(
this, *fontMet, &aRenderingContext, text.get(), text.Length(),
textRect.TopLeft() + nsPoint(0, baseline), cellContext);
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintCheckbox(int32_t aRowIndex,
nsTreeColumn* aColumn,
const nsRect& aCheckboxRect,
nsPresContext* aPresContext,
gfxContext& aRenderingContext,
const nsRect& aDirtyRect) {
MOZ_ASSERT(aColumn && aColumn->GetFrame(), "invalid column passed");
// Resolve style for the checkbox.
ComputedStyle* checkboxContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeCheckbox());
nscoord rightEdge = aCheckboxRect.XMost();
// Obtain the margins for the checkbox and then deflate our rect by that
// amount. The checkbox is assumed to be contained within the deflated rect.
nsRect checkboxRect(aCheckboxRect);
nsMargin checkboxMargin;
checkboxContext->StyleMargin()->GetMargin(checkboxMargin);
checkboxRect.Deflate(checkboxMargin);
nsRect imageSize = GetImageSize(aRowIndex, aColumn, true, checkboxContext);
if (imageSize.height > checkboxRect.height) {
imageSize.height = checkboxRect.height;
}
if (imageSize.width > checkboxRect.width) {
imageSize.width = checkboxRect.width;
}
if (StyleVisibility()->mDirection == StyleDirection::Rtl) {
checkboxRect.x = rightEdge - checkboxRect.width;
}
// Paint our borders and background for our image rect.
ImgDrawResult result =
PaintBackgroundLayer(checkboxContext, aPresContext, aRenderingContext,
checkboxRect, aDirtyRect);
// Time to paint the checkbox.
// Adjust the rect for its border and padding.
nsMargin bp(0, 0, 0, 0);
GetBorderPadding(checkboxContext, bp);
checkboxRect.Deflate(bp);
// Get the image for drawing.
nsCOMPtr<imgIContainer> image;
GetImage(aRowIndex, aColumn, true, checkboxContext, getter_AddRefs(image));
if (image) {
nsPoint pt = checkboxRect.TopLeft();
if (imageSize.height < checkboxRect.height) {
pt.y += (checkboxRect.height - imageSize.height) / 2;
}
if (imageSize.width < checkboxRect.width) {
pt.x += (checkboxRect.width - imageSize.width) / 2;
}
// Apply context paint if applicable
SVGImageContext svgContext;
SVGImageContext::MaybeStoreContextPaint(svgContext, *aPresContext,
*checkboxContext, image);
// Paint the image.
result &= nsLayoutUtils::DrawSingleUnscaledImage(
aRenderingContext, aPresContext, image, SamplingFilter::POINT, pt,
&aDirtyRect, svgContext, imgIContainer::FLAG_NONE, &imageSize);
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintDropFeedback(
const nsRect& aDropFeedbackRect, nsPresContext* aPresContext,
gfxContext& aRenderingContext, const nsRect& aDirtyRect, nsPoint aPt) {
// Paint the drop feedback in between rows.
nscoord currX;
// Adjust for the primary cell.
nsTreeColumn* primaryCol = mColumns->GetPrimaryColumn();
if (primaryCol) {
#ifdef DEBUG
nsresult rv =
#endif
primaryCol->GetXInTwips(this, &currX);
NS_ASSERTION(NS_SUCCEEDED(rv), "primary column is invalid?");
currX += aPt.x - mHorzPosition;
} else {
currX = aDropFeedbackRect.x;
}
PrefillPropertyArray(mSlots->mDropRow, primaryCol);
// Resolve the style to use for the drop feedback.
ComputedStyle* feedbackContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeDropFeedback());
ImgDrawResult result = ImgDrawResult::SUCCESS;
// Paint only if it is visible.
nsCOMPtr<nsITreeView> view = GetExistingView();
if (feedbackContext->StyleVisibility()->IsVisibleOrCollapsed()) {
int32_t level;
view->GetLevel(mSlots->mDropRow, &level);
// If our previous or next row has greater level use that for
// correct visual indentation.
if (mSlots->mDropOrient == nsITreeView::DROP_BEFORE) {
if (mSlots->mDropRow > 0) {
int32_t previousLevel;
view->GetLevel(mSlots->mDropRow - 1, &previousLevel);
if (previousLevel > level) level = previousLevel;
}
} else {
if (mSlots->mDropRow < mRowCount - 1) {
int32_t nextLevel;
view->GetLevel(mSlots->mDropRow + 1, &nextLevel);
if (nextLevel > level) level = nextLevel;
}
}
currX += mIndentation * level;
if (primaryCol) {
ComputedStyle* twistyContext =
GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeTwisty());
nsRect imageSize;
nsRect twistyRect;
GetTwistyRect(mSlots->mDropRow, primaryCol, imageSize, twistyRect,
aPresContext, twistyContext);
nsMargin twistyMargin;
twistyContext->StyleMargin()->GetMargin(twistyMargin);
twistyRect.Inflate(twistyMargin);
currX += twistyRect.width;
}
const nsStylePosition* stylePosition = feedbackContext->StylePosition();
// Obtain the width for the drop feedback or use default value.
nscoord width;
if (stylePosition->mWidth.ConvertsToLength()) {
width = stylePosition->mWidth.ToLength();
} else {
// Use default width 50px.
width = nsPresContext::CSSPixelsToAppUnits(50);
}
// Obtain the height for the drop feedback or use default value.
nscoord height;
if (stylePosition->mHeight.ConvertsToLength()) {
height = stylePosition->mHeight.ToLength();
} else {
// Use default height 2px.
height = nsPresContext::CSSPixelsToAppUnits(2);
}
// Obtain the margins for the drop feedback and then deflate our rect
// by that amount.
nsRect feedbackRect(currX, aDropFeedbackRect.y, width, height);
nsMargin margin;
feedbackContext->StyleMargin()->GetMargin(margin);
feedbackRect.Deflate(margin);
feedbackRect.y += (aDropFeedbackRect.height - height) / 2;
// Finally paint the drop feedback.
result &= PaintBackgroundLayer(feedbackContext, aPresContext,
aRenderingContext, feedbackRect, aDirtyRect);
}
return result;
}
ImgDrawResult nsTreeBodyFrame::PaintBackgroundLayer(
ComputedStyle* aComputedStyle, nsPresContext* aPresContext,
gfxContext& aRenderingContext, const nsRect& aRect,
const nsRect& aDirtyRect) {
const nsStyleBorder* myBorder = aComputedStyle->StyleBorder();
nsCSSRendering::PaintBGParams params =
nsCSSRendering::PaintBGParams::ForAllLayers(
*aPresContext, aDirtyRect, aRect, this,
nsCSSRendering::PAINTBG_SYNC_DECODE_IMAGES);
ImgDrawResult result = nsCSSRendering::PaintStyleImageLayerWithSC(
params, aRenderingContext, aComputedStyle, *myBorder);
result &= nsCSSRendering::PaintBorderWithStyleBorder(
aPresContext, aRenderingContext, this, aDirtyRect, aRect, *myBorder,
mComputedStyle, PaintBorderFlags::SyncDecodeImages);
nsCSSRendering::PaintNonThemedOutline(aPresContext, aRenderingContext, this,
aDirtyRect, aRect, aComputedStyle);
return result;
}
// Scrolling
nsresult nsTreeBodyFrame::EnsureRowIsVisible(int32_t aRow) {
ScrollParts parts = GetScrollParts();
nsresult rv = EnsureRowIsVisibleInternal(parts, aRow);
NS_ENSURE_SUCCESS(rv, rv);
UpdateScrollbars(parts);
return rv;
}
nsresult nsTreeBodyFrame::EnsureRowIsVisibleInternal(const ScrollParts& aParts,
int32_t aRow) {
if (!mView || !mPageLength) {
return NS_OK;
}
if (mTopRowIndex <= aRow && mTopRowIndex + mPageLength > aRow) return NS_OK;
if (aRow < mTopRowIndex)
ScrollToRowInternal(aParts, aRow);
else {
// Bring it just on-screen.
int32_t distance = aRow - (mTopRowIndex + mPageLength) + 1;
ScrollToRowInternal(aParts, mTopRowIndex + distance);
}
return NS_OK;
}
nsresult nsTreeBodyFrame::EnsureCellIsVisible(int32_t aRow,
nsTreeColumn* aCol) {
if (!aCol) return NS_ERROR_INVALID_ARG;
ScrollParts parts = GetScrollParts();
nscoord result = -1;
nsresult rv;
nscoord columnPos;
rv = aCol->GetXInTwips(this, &columnPos);
if (NS_FAILED(rv)) return rv;
nscoord columnWidth;
rv = aCol->GetWidthInTwips(this, &columnWidth);
if (NS_FAILED(rv)) return rv;
// If the start of the column is before the
// start of the horizontal view, then scroll
if (columnPos < mHorzPosition) result = columnPos;
// If the end of the column is past the end of
// the horizontal view, then scroll
else if ((columnPos + columnWidth) > (mHorzPosition + mInnerBox.width))
result = ((columnPos + columnWidth) - (mHorzPosition + mInnerBox.width)) +
mHorzPosition;
if (result != -1) {
rv = ScrollHorzInternal(parts, result);
if (NS_FAILED(rv)) return rv;
}
rv = EnsureRowIsVisibleInternal(parts, aRow);
NS_ENSURE_SUCCESS(rv, rv);
UpdateScrollbars(parts);
return rv;
}
void nsTreeBodyFrame::ScrollToRow(int32_t aRow) {
ScrollParts parts = GetScrollParts();
ScrollToRowInternal(parts, aRow);
UpdateScrollbars(parts);
}
nsresult nsTreeBodyFrame::ScrollToRowInternal(const ScrollParts& aParts,
int32_t aRow) {
ScrollInternal(aParts, aRow);
return NS_OK;
}
void nsTreeBodyFrame::ScrollByLines(int32_t aNumLines) {
if (!mView) {
return;
}
int32_t newIndex = mTopRowIndex + aNumLines;
ScrollToRow(newIndex);
}
void nsTreeBodyFrame::ScrollByPages(int32_t aNumPages) {
if (!mView) {
return;
}
int32_t newIndex = mTopRowIndex + aNumPages * mPageLength;
ScrollToRow(newIndex);
}
nsresult nsTreeBodyFrame::ScrollInternal(const ScrollParts& aParts,
int32_t aRow) {
if (!mView) {
return NS_OK;
}
// Note that we may be "over scrolled" at this point; that is the
// current mTopRowIndex may be larger than mRowCount - mPageLength.
// This can happen when items are removed for example. (bug 1085050)
int32_t maxTopRowIndex = std::max(0, mRowCount - mPageLength);
aRow = mozilla::clamped(aRow, 0, maxTopRowIndex);
if (aRow == mTopRowIndex) {
return NS_OK;
}
mTopRowIndex = aRow;
Invalidate();
PostScrollEvent();
return NS_OK;
}
nsresult nsTreeBodyFrame::ScrollHorzInternal(const ScrollParts& aParts,
int32_t aPosition) {
if (!mView || !aParts.mColumnsScrollFrame || !aParts.mHScrollbar)
return NS_OK;
if (aPosition == mHorzPosition) return NS_OK;
if (aPosition < 0 || aPosition > mHorzWidth) return NS_OK;
nsRect bounds = aParts.mColumnsFrame->GetRect();
if (aPosition > (mHorzWidth - bounds.width))
aPosition = mHorzWidth - bounds.width;
mHorzPosition = aPosition;
Invalidate();
// Update the column scroll view
AutoWeakFrame weakFrame(this);
aParts.mColumnsScrollFrame->ScrollTo(nsPoint(mHorzPosition, 0),
ScrollMode::Instant);
if (!weakFrame.IsAlive()) {
return NS_ERROR_FAILURE;
}
// And fire off an event about it all
PostScrollEvent();
return NS_OK;
}
void nsTreeBodyFrame::ScrollByPage(nsScrollbarFrame* aScrollbar,
int32_t aDirection,
ScrollSnapFlags aSnapFlags) {
// CSS Scroll Snapping is not enabled for XUL, aSnap is ignored
MOZ_ASSERT(aScrollbar != nullptr);
ScrollByPages(aDirection);
}
void nsTreeBodyFrame::ScrollByWhole(nsScrollbarFrame* aScrollbar,
int32_t aDirection,
ScrollSnapFlags aSnapFlags) {
// CSS Scroll Snapping is not enabled for XUL, aSnap is ignored
MOZ_ASSERT(aScrollbar != nullptr);
int32_t newIndex = aDirection < 0 ? 0 : mTopRowIndex;
ScrollToRow(newIndex);
}
void nsTreeBodyFrame::ScrollByLine(nsScrollbarFrame* aScrollbar,
int32_t aDirection,
ScrollSnapFlags aSnapFlags) {
// CSS Scroll Snapping is not enabled for XUL, aSnap is ignored
MOZ_ASSERT(aScrollbar != nullptr);
ScrollByLines(aDirection);
}
void nsTreeBodyFrame::ScrollByUnit(
nsScrollbarFrame* aScrollbar, ScrollMode aMode, int32_t aDirection,
ScrollUnit aUnit, ScrollSnapFlags aSnapFlags /* = Disabled */) {
MOZ_ASSERT_UNREACHABLE("Can't get here, we pass false to MoveToNewPosition");
}
void nsTreeBodyFrame::RepeatButtonScroll(nsScrollbarFrame* aScrollbar) {
ScrollParts parts = GetScrollParts();
int32_t increment = aScrollbar->GetIncrement();
int32_t direction = 0;
if (increment < 0) {
direction = -1;
} else if (increment > 0) {
direction = 1;
}
bool isHorizontal = aScrollbar->IsHorizontal();
AutoWeakFrame weakFrame(this);
if (isHorizontal) {
int32_t curpos = aScrollbar->MoveToNewPosition(
nsScrollbarFrame::ImplementsScrollByUnit::No);
if (weakFrame.IsAlive()) {
ScrollHorzInternal(parts, curpos);
}
} else {
ScrollToRowInternal(parts, mTopRowIndex + direction);
}
if (weakFrame.IsAlive() && mScrollbarActivity) {
mScrollbarActivity->ActivityOccurred();
}
if (weakFrame.IsAlive()) {
UpdateScrollbars(parts);
}
}
void nsTreeBodyFrame::ThumbMoved(nsScrollbarFrame* aScrollbar, nscoord aOldPos,
nscoord aNewPos) {
ScrollParts parts = GetScrollParts();
if (aOldPos == aNewPos) return;
AutoWeakFrame weakFrame(this);
// Vertical Scrollbar
if (parts.mVScrollbar == aScrollbar) {
nscoord rh = nsPresContext::AppUnitsToIntCSSPixels(mRowHeight);
nscoord newIndex = nsPresContext::AppUnitsToIntCSSPixels(aNewPos);
nscoord newrow = (rh > 0) ? (newIndex / rh) : 0;
ScrollInternal(parts, newrow);
// Horizontal Scrollbar
} else if (parts.mHScrollbar == aScrollbar) {
int32_t newIndex = nsPresContext::AppUnitsToIntCSSPixels(aNewPos);
ScrollHorzInternal(parts, newIndex);
}
if (weakFrame.IsAlive()) {
UpdateScrollbars(parts);
}
}
// The style cache.
ComputedStyle* nsTreeBodyFrame::GetPseudoComputedStyle(
nsCSSAnonBoxPseudoStaticAtom* aPseudoElement) {
return mStyleCache.GetComputedStyle(PresContext(), mContent, mComputedStyle,
aPseudoElement, mScratchArray);
}
XULTreeElement* nsTreeBodyFrame::GetBaseElement() {
if (!mTree) {
nsIFrame* parent = GetParent();
while (parent) {
nsIContent* content = parent->GetContent();
if (content && content->IsXULElement(nsGkAtoms::tree)) {
mTree = XULTreeElement::FromNodeOrNull(content->AsElement());
break;
}
parent = parent->GetInFlowParent();
}
}
return mTree;
}
nsresult nsTreeBodyFrame::ClearStyleAndImageCaches() {
mStyleCache.Clear();
CancelImageRequests();
mImageCache.Clear();
return NS_OK;
}
void nsTreeBodyFrame::RemoveImageCacheEntry(int32_t aRowIndex,
nsTreeColumn* aCol) {
nsAutoString imageSrc;
nsCOMPtr<nsITreeView> view = GetExistingView();
if (NS_FAILED(view->GetImageSrc(aRowIndex, aCol, imageSrc))) {
return;
}
nsTreeImageCacheEntry entry;
if (!mImageCache.Get(imageSrc, &entry)) {
return;
}
nsLayoutUtils::DeregisterImageRequest(PresContext(), entry.request, nullptr);
entry.request->UnlockImage();
entry.request->CancelAndForgetObserver(NS_BINDING_ABORTED);
mImageCache.Remove(imageSrc);
}
/* virtual */
void nsTreeBodyFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
SimpleXULLeafFrame::DidSetComputedStyle(aOldComputedStyle);
// Clear the style cache; the pointers are no longer even valid
mStyleCache.Clear();
// XXX The following is hacky, but it's not incorrect,
// and appears to fix a few bugs with style changes, like text zoom and
// dpi changes
mIndentation = GetIndentation();
mRowHeight = GetRowHeight();
}
bool nsTreeBodyFrame::OffsetForHorzScroll(nsRect& rect, bool clip) {
rect.x -= mHorzPosition;
// Scrolled out before
if (rect.XMost() <= mInnerBox.x) return false;
// Scrolled out after
if (rect.x > mInnerBox.XMost()) return false;
if (clip) {
nscoord leftEdge = std::max(rect.x, mInnerBox.x);
nscoord rightEdge = std::min(rect.XMost(), mInnerBox.XMost());
rect.x = leftEdge;
rect.width = rightEdge - leftEdge;
// Should have returned false above
NS_ASSERTION(rect.width >= 0, "horz scroll code out of sync");
}
return true;
}
bool nsTreeBodyFrame::CanAutoScroll(int32_t aRowIndex) {
// Check first for partially visible last row.
if (aRowIndex == mRowCount - 1) {
nscoord y = mInnerBox.y + (aRowIndex - mTopRowIndex) * mRowHeight;
if (y < mInnerBox.height && y + mRowHeight > mInnerBox.height) return true;
}
if (aRowIndex > 0 && aRowIndex < mRowCount - 1) return true;
return false;
}
// Given a dom event, figure out which row in the tree the mouse is over,
// if we should drop before/after/on that row or we should auto-scroll.
// Doesn't query the content about if the drag is allowable, that's done
// elsewhere.
//
// For containers, we break up the vertical space of the row as follows: if in
// the topmost 25%, the drop is _before_ the row the mouse is over; if in the
// last 25%, _after_; in the middle 50%, we consider it a drop _on_ the
// container.
//
// For non-containers, if the mouse is in the top 50% of the row, the drop is
// _before_ and the bottom 50% _after_
void nsTreeBodyFrame::ComputeDropPosition(WidgetGUIEvent* aEvent, int32_t* aRow,
int16_t* aOrient,
int16_t* aScrollLines) {
*aOrient = -1;
*aScrollLines = 0;
// Convert the event's point to our coordinates. We want it in
// the coordinates of our inner box's coordinates.
nsPoint pt =
nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, RelativeTo{this});
int32_t xTwips = pt.x - mInnerBox.x;
int32_t yTwips = pt.y - mInnerBox.y;
nsCOMPtr<nsITreeView> view = GetExistingView();
*aRow = GetRowAtInternal(xTwips, yTwips);
if (*aRow >= 0) {
// Compute the top/bottom of the row in question.
int32_t yOffset = yTwips - mRowHeight * (*aRow - mTopRowIndex);
bool isContainer = false;
view->IsContainer(*aRow, &isContainer);
if (isContainer) {
// for a container, use a 25%/50%/25% breakdown
if (yOffset < mRowHeight / 4)
*aOrient = nsITreeView::DROP_BEFORE;
else if (yOffset > mRowHeight - (mRowHeight / 4))
*aOrient = nsITreeView::DROP_AFTER;
else
*aOrient = nsITreeView::DROP_ON;
} else {
// for a non-container use a 50%/50% breakdown
if (yOffset < mRowHeight / 2)
*aOrient = nsITreeView::DROP_BEFORE;
else
*aOrient = nsITreeView::DROP_AFTER;
}
}
if (CanAutoScroll(*aRow)) {
// Get the max value from the look and feel service.
int32_t scrollLinesMax =
LookAndFeel::GetInt(LookAndFeel::IntID::TreeScrollLinesMax, 0);
scrollLinesMax--;
if (scrollLinesMax < 0) scrollLinesMax = 0;
// Determine if we're w/in a margin of the top/bottom of the tree during a
// drag. This will ultimately cause us to scroll, but that's done elsewhere.
nscoord height = (3 * mRowHeight) / 4;
if (yTwips < height) {
// scroll up
*aScrollLines =
NSToIntRound(-scrollLinesMax * (1 - (float)yTwips / height) - 1);
} else if (yTwips > mRect.height - height) {
// scroll down
*aScrollLines = NSToIntRound(
scrollLinesMax * (1 - (float)(mRect.height - yTwips) / height) + 1);
}
}
} // ComputeDropPosition
void nsTreeBodyFrame::OpenCallback(nsITimer* aTimer, void* aClosure) {
auto* self = static_cast<nsTreeBodyFrame*>(aClosure);
if (!self) {
return;
}
aTimer->Cancel();
self->mSlots->mTimer = nullptr;
nsCOMPtr<nsITreeView> view = self->GetExistingView();
if (self->mSlots->mDropRow >= 0) {
self->mSlots->mArray.AppendElement(self->mSlots->mDropRow);
view->ToggleOpenState(self->mSlots->mDropRow);
}
}
void nsTreeBodyFrame::CloseCallback(nsITimer* aTimer, void* aClosure) {
auto* self = static_cast<nsTreeBodyFrame*>(aClosure);
if (!self) {
return;
}
aTimer->Cancel();
self->mSlots->mTimer = nullptr;
nsCOMPtr<nsITreeView> view = self->GetExistingView();
auto array = std::move(self->mSlots->mArray);
if (!view) {
return;
}
for (auto elem : Reversed(array)) {
view->ToggleOpenState(elem);
}
}
void nsTreeBodyFrame::LazyScrollCallback(nsITimer* aTimer, void* aClosure) {
nsTreeBodyFrame* self = static_cast<nsTreeBodyFrame*>(aClosure);
if (self) {
aTimer->Cancel();
self->mSlots->mTimer = nullptr;
if (self->mView) {
// Set a new timer to scroll the tree repeatedly.
self->CreateTimer(LookAndFeel::IntID::TreeScrollDelay, ScrollCallback,
nsITimer::TYPE_REPEATING_SLACK,
getter_AddRefs(self->mSlots->mTimer),
"nsTreeBodyFrame::ScrollCallback");
self->ScrollByLines(self->mSlots->mScrollLines);
// ScrollByLines may have deleted |self|.
}
}
}
void nsTreeBodyFrame::ScrollCallback(nsITimer* aTimer, void* aClosure) {
nsTreeBodyFrame* self = static_cast<nsTreeBodyFrame*>(aClosure);
if (self) {
// Don't scroll if we are already at the top or bottom of the view.
if (self->mView && self->CanAutoScroll(self->mSlots->mDropRow)) {
self->ScrollByLines(self->mSlots->mScrollLines);
} else {
aTimer->Cancel();
self->mSlots->mTimer = nullptr;
}
}
}
// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP nsTreeBodyFrame::ScrollEvent::Run() {
if (mInner) {
mInner->FireScrollEvent();
}
return NS_OK;
}
void nsTreeBodyFrame::FireScrollEvent() {
mScrollEvent.Forget();
WidgetGUIEvent event(true, eScroll, nullptr);
// scroll events fired at elements don't bubble
event.mFlags.mBubbles = false;
RefPtr<nsIContent> content = GetContent();
RefPtr<nsPresContext> presContext = PresContext();
EventDispatcher::Dispatch(content, presContext, &event);
}
void nsTreeBodyFrame::PostScrollEvent() {
if (mScrollEvent.IsPending()) return;
RefPtr<ScrollEvent> event = new ScrollEvent(this);
nsresult rv = mContent->OwnerDoc()->Dispatch(do_AddRef(event));
if (NS_FAILED(rv)) {
NS_WARNING("failed to dispatch ScrollEvent");
} else {
mScrollEvent = std::move(event);
}
}
void nsTreeBodyFrame::ScrollbarActivityStarted() const {
if (mScrollbarActivity) {
mScrollbarActivity->ActivityStarted();
}
}
void nsTreeBodyFrame::ScrollbarActivityStopped() const {
if (mScrollbarActivity) {
mScrollbarActivity->ActivityStopped();
}
}
void nsTreeBodyFrame::DetachImageListeners() { mCreatedListeners.Clear(); }
void nsTreeBodyFrame::RemoveTreeImageListener(nsTreeImageListener* aListener) {
if (aListener) {
mCreatedListeners.Remove(aListener);
}
}
#ifdef ACCESSIBILITY
static void InitCustomEvent(CustomEvent* aEvent, const nsAString& aType,
nsIWritablePropertyBag2* aDetail) {
AutoJSAPI jsapi;
if (!jsapi.Init(aEvent->GetParentObject())) {
return;
}
JSContext* cx = jsapi.cx();
JS::Rooted<JS::Value> detail(cx);
if (!ToJSValue(cx, aDetail, &detail)) {
jsapi.ClearException();
return;
}
aEvent->InitCustomEvent(cx, aType, /* aCanBubble = */ true,
/* aCancelable = */ false, detail);
}
void nsTreeBodyFrame::FireRowCountChangedEvent(int32_t aIndex, int32_t aCount) {
RefPtr<XULTreeElement> tree(GetBaseElement());
if (!tree) return;
RefPtr<Document> doc = tree->OwnerDoc();
MOZ_ASSERT(doc);
RefPtr<Event> event =
doc->CreateEvent(u"customevent"_ns, CallerType::System, IgnoreErrors());
CustomEvent* treeEvent = event->AsCustomEvent();
if (!treeEvent) {
return;
}
nsCOMPtr<nsIWritablePropertyBag2> propBag(
do_CreateInstance("@mozilla.org/hash-property-bag;1"));
if (!propBag) {
return;
}
// Set 'index' data - the row index rows are changed from.
propBag->SetPropertyAsInt32(u"index"_ns, aIndex);
// Set 'count' data - the number of changed rows.
propBag->SetPropertyAsInt32(u"count"_ns, aCount);
InitCustomEvent(treeEvent, u"TreeRowCountChanged"_ns, propBag);
event->SetTrusted(true);
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(tree, event.forget());
asyncDispatcher->PostDOMEvent();
}
void nsTreeBodyFrame::FireInvalidateEvent(int32_t aStartRowIdx,
int32_t aEndRowIdx,
nsTreeColumn* aStartCol,
nsTreeColumn* aEndCol) {
RefPtr<XULTreeElement> tree(GetBaseElement());
if (!tree) return;
RefPtr<Document> doc = tree->OwnerDoc();
RefPtr<Event> event =
doc->CreateEvent(u"customevent"_ns, CallerType::System, IgnoreErrors());
CustomEvent* treeEvent = event->AsCustomEvent();
if (!treeEvent) {
return;
}
nsCOMPtr<nsIWritablePropertyBag2> propBag(
do_CreateInstance("@mozilla.org/hash-property-bag;1"));
if (!propBag) {
return;
}
if (aStartRowIdx != -1 && aEndRowIdx != -1) {
// Set 'startrow' data - the start index of invalidated rows.
propBag->SetPropertyAsInt32(u"startrow"_ns, aStartRowIdx);
// Set 'endrow' data - the end index of invalidated rows.
propBag->SetPropertyAsInt32(u"endrow"_ns, aEndRowIdx);
}
if (aStartCol && aEndCol) {
// Set 'startcolumn' data - the start index of invalidated rows.
int32_t startColIdx = aStartCol->GetIndex();
propBag->SetPropertyAsInt32(u"startcolumn"_ns, startColIdx);
// Set 'endcolumn' data - the start index of invalidated rows.
int32_t endColIdx = aEndCol->GetIndex();
propBag->SetPropertyAsInt32(u"endcolumn"_ns, endColIdx);
}
InitCustomEvent(treeEvent, u"TreeInvalidated"_ns, propBag);
event->SetTrusted(true);
RefPtr<AsyncEventDispatcher> asyncDispatcher =
new AsyncEventDispatcher(tree, event.forget());
asyncDispatcher->PostDOMEvent();
}
#endif
class nsOverflowChecker : public Runnable {
public:
explicit nsOverflowChecker(nsTreeBodyFrame* aFrame)
: mozilla::Runnable("nsOverflowChecker"), mFrame(aFrame) {}
NS_IMETHOD Run() override {
if (mFrame.IsAlive()) {
nsTreeBodyFrame* tree = static_cast<nsTreeBodyFrame*>(mFrame.GetFrame());
nsTreeBodyFrame::ScrollParts parts = tree->GetScrollParts();
tree->CheckOverflow(parts);
}
return NS_OK;
}
private:
WeakFrame mFrame;
};
bool nsTreeBodyFrame::FullScrollbarsUpdate(bool aNeedsFullInvalidation) {
ScrollParts parts = GetScrollParts();
AutoWeakFrame weakFrame(this);
AutoWeakFrame weakColumnsFrame(parts.mColumnsFrame);
UpdateScrollbars(parts);
NS_ENSURE_TRUE(weakFrame.IsAlive(), false);
if (aNeedsFullInvalidation) {
Invalidate();
}
InvalidateScrollbars(parts, weakColumnsFrame);
NS_ENSURE_TRUE(weakFrame.IsAlive(), false);
// Overflow checking dispatches synchronous events, which can cause infinite
// recursion during reflow. Do the first overflow check synchronously, but
// force any nested checks to round-trip through the event loop. See bug
// 905909.
RefPtr<nsOverflowChecker> checker = new nsOverflowChecker(this);
if (!mCheckingOverflow) {
nsContentUtils::AddScriptRunner(checker);
} else {
mContent->OwnerDoc()->Dispatch(checker.forget());
}
return weakFrame.IsAlive();
}
void nsTreeBodyFrame::OnImageIsAnimated(imgIRequest* aRequest) {
nsLayoutUtils::RegisterImageRequest(PresContext(), aRequest, nullptr);
}
|