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
/* CTK - The GIMP Toolkit
 * ctktextlayout.c - calculate the layout of the text
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 2000 Red Hat, Inc.
 * Tk->Ctk port by Havoc Pennington
 * Pango support by Owen Taylor
 *
 * This file can be used under your choice of two licenses, the LGPL
 * and the original Tk license.
 *
 * LGPL:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.Free
 *
 * Original Tk license:
 *
 * This software is copyrighted by the Regents of the University of
 * California, Sun Microsystems, Inc., and other parties.  The
 * following terms apply to all files associated with the software
 * unless explicitly disclaimed in individual files.
 *
 * The authors hereby grant permission to use, copy, modify,
 * distribute, and license this software and its documentation for any
 * purpose, provided that existing copyright notices are retained in
 * all copies and that this notice is included verbatim in any
 * distributions. No written agreement, license, or royalty fee is
 * required for any of the authorized uses.  Modifications to this
 * software may be copyrighted by their authors and need not follow
 * the licensing terms described here, provided that the new terms are
 * clearly indicated on the first page of each file where they apply.
 *
 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY
 * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
 * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION,
 * OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
 * NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
 * AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * GOVERNMENT USE: If you are acquiring this software on behalf of the
 * U.S. government, the Government shall have only "Restricted Rights"
 * in the software and related documentation as defined in the Federal
 * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
 * are acquiring the software on behalf of the Department of Defense,
 * the software shall be classified as "Commercial Computer Software"
 * and the Government shall have only "Restricted Rights" as defined
 * in Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the
 * foregoing, the authors grant the U.S. Government and others acting
 * in its behalf permission to use and distribute the software in
 * accordance with the terms specified in this license.
 *
 */
/*
 * Modified by the CTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the CTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * CTK+ at ftp://ftp.ctk.org/pub/ctk/.
 */

#define CTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
#include "config.h"
#include "ctkmarshalers.h"
#include "ctktextlayout.h"
#include "ctktextbtree.h"
#include "ctktextbufferprivate.h"
#include "ctktextiterprivate.h"
#include "ctktextattributesprivate.h"
#include "ctktextutil.h"
#include "ctkintl.h"

#include <stdlib.h>
#include <string.h>

#define CTK_TEXT_LAYOUT_GET_PRIVATE(o)  ((CtkTextLayoutPrivate *) ctk_text_layout_get_instance_private ((o)))

typedef struct _CtkTextLayoutPrivate CtkTextLayoutPrivate;

struct _CtkTextLayoutPrivate
{
  /* Cache the line that the cursor is positioned on, as the keyboard
     direction only influences the direction of the cursor line.
  */
  CtkTextLine *cursor_line;
};

static CtkTextLineData *ctk_text_layout_real_wrap (CtkTextLayout *layout,
                                                   CtkTextLine *line,
                                                   /* may be NULL */
                                                   CtkTextLineData *line_data);

static void ctk_text_layout_invalidated     (CtkTextLayout     *layout);

static void ctk_text_layout_real_invalidate        (CtkTextLayout     *layout,
						    const CtkTextIter *start,
						    const CtkTextIter *end);
static void ctk_text_layout_real_invalidate_cursors(CtkTextLayout     *layout,
						    const CtkTextIter *start,
						    const CtkTextIter *end);
static void ctk_text_layout_invalidate_cache       (CtkTextLayout     *layout,
						    CtkTextLine       *line,
						    gboolean           cursors_only);
static void ctk_text_layout_invalidate_cursor_line (CtkTextLayout     *layout,
						    gboolean           cursors_only);
static void ctk_text_layout_real_free_line_data    (CtkTextLayout     *layout,
						    CtkTextLine       *line,
						    CtkTextLineData   *line_data);
static void ctk_text_layout_emit_changed           (CtkTextLayout     *layout,
						    gint               y,
						    gint               old_height,
						    gint               new_height);

static void ctk_text_layout_invalidate_all (CtkTextLayout *layout);

static PangoAttribute *ctk_text_attr_appearance_new (const CtkTextAppearance *appearance);

static void ctk_text_layout_mark_set_handler    (CtkTextBuffer     *buffer,
						 const CtkTextIter *location,
						 CtkTextMark       *mark,
						 gpointer           data);
static void ctk_text_layout_buffer_insert_text  (CtkTextBuffer     *textbuffer,
						 CtkTextIter       *iter,
						 gchar             *str,
						 gint               len,
						 gpointer           data);
static void ctk_text_layout_buffer_delete_range (CtkTextBuffer     *textbuffer,
						 CtkTextIter       *start,
						 CtkTextIter       *end,
						 gpointer           data);

static void ctk_text_layout_update_cursor_line (CtkTextLayout *layout);

static void line_display_index_to_iter (CtkTextLayout      *layout,
	                                CtkTextLineDisplay *display,
			                CtkTextIter        *iter,
                                        gint                index,
                                        gint                trailing);

static gint line_display_iter_to_index (CtkTextLayout      *layout,
                                        CtkTextLineDisplay *display,
                                        const CtkTextIter  *iter);

enum {
  INVALIDATED,
  CHANGED,
  ALLOCATE_CHILD,
  LAST_SIGNAL
};

enum {
  ARG_0,
  LAST_ARG
};

#define PIXEL_BOUND(d) (((d) + PANGO_SCALE - 1) / PANGO_SCALE)

static guint signals[LAST_SIGNAL] = { 0 };

PangoAttrType ctk_text_attr_appearance_type = 0;

G_DEFINE_TYPE_WITH_PRIVATE (CtkTextLayout, ctk_text_layout, G_TYPE_OBJECT)<--- There is an unknown macro here somewhere. Configuration is required. If G_DEFINE_TYPE_WITH_PRIVATE is a macro then please configure it.

static void
ctk_text_layout_dispose (GObject *object)
{
  CtkTextLayout *layout;

  layout = CTK_TEXT_LAYOUT (object);

  ctk_text_layout_set_buffer (layout, NULL);

  if (layout->default_style != NULL)
    {
      ctk_text_attributes_unref (layout->default_style);
      layout->default_style = NULL;
    }

  g_clear_object (&layout->ltr_context);
  g_clear_object (&layout->rtl_context);

  if (layout->one_display_cache)
    {
      CtkTextLineDisplay *tmp_display = layout->one_display_cache;
      layout->one_display_cache = NULL;
      ctk_text_layout_free_line_display (layout, tmp_display);
    }

  if (layout->preedit_attrs != NULL)
    {
      pango_attr_list_unref (layout->preedit_attrs);
      layout->preedit_attrs = NULL;
    }

  G_OBJECT_CLASS (ctk_text_layout_parent_class)->dispose (object);
}

static void
ctk_text_layout_finalize (GObject *object)
{
  CtkTextLayout *layout;

  layout = CTK_TEXT_LAYOUT (object);

  g_free (layout->preedit_string);

  G_OBJECT_CLASS (ctk_text_layout_parent_class)->finalize (object);
}

static void
ctk_text_layout_class_init (CtkTextLayoutClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->dispose = ctk_text_layout_dispose;
  object_class->finalize = ctk_text_layout_finalize;

  klass->wrap = ctk_text_layout_real_wrap;
  klass->invalidate = ctk_text_layout_real_invalidate;
  klass->invalidate_cursors = ctk_text_layout_real_invalidate_cursors;
  klass->free_line_data = ctk_text_layout_real_free_line_data;

  signals[INVALIDATED] =
    g_signal_new (I_("invalidated"),
                  G_OBJECT_CLASS_TYPE (object_class),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (CtkTextLayoutClass, invalidated),
                  NULL, NULL,
                  NULL,
                  G_TYPE_NONE,
                  0);

  signals[CHANGED] =
    g_signal_new (I_("changed"),
                  G_OBJECT_CLASS_TYPE (object_class),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (CtkTextLayoutClass, changed),
                  NULL, NULL,
                  _ctk_marshal_VOID__INT_INT_INT,
                  G_TYPE_NONE,
                  3,
                  G_TYPE_INT,
                  G_TYPE_INT,
                  G_TYPE_INT);
  g_signal_set_va_marshaller (signals[CHANGED], G_TYPE_FROM_CLASS (klass),
                              _ctk_marshal_VOID__INT_INT_INTv);

  signals[ALLOCATE_CHILD] =
    g_signal_new (I_("allocate-child"),
                  G_OBJECT_CLASS_TYPE (object_class),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (CtkTextLayoutClass, allocate_child),
                  NULL, NULL,
                  _ctk_marshal_VOID__OBJECT_INT_INT,
                  G_TYPE_NONE,
                  3,
                  G_TYPE_OBJECT,
                  G_TYPE_INT,
                  G_TYPE_INT);
}

static void
ctk_text_layout_init (CtkTextLayout *text_layout)
{
  text_layout->cursor_visible = TRUE;
}

CtkTextLayout*
ctk_text_layout_new (void)
{
  return g_object_new (CTK_TYPE_TEXT_LAYOUT, NULL);
}

static void
free_style_cache (CtkTextLayout *text_layout)
{
  if (text_layout->one_style_cache)
    {
      ctk_text_attributes_unref (text_layout->one_style_cache);
      text_layout->one_style_cache = NULL;
    }
}

/**
 * ctk_text_layout_set_buffer:
 * @buffer: (allow-none):
 */
void
ctk_text_layout_set_buffer (CtkTextLayout *layout,
                            CtkTextBuffer *buffer)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (buffer == NULL || CTK_IS_TEXT_BUFFER (buffer));

  if (layout->buffer == buffer)
    return;

  free_style_cache (layout);

  if (layout->buffer)
    {
      _ctk_text_btree_remove_view (_ctk_text_buffer_get_btree (layout->buffer),
                                  layout);

      g_signal_handlers_disconnect_by_func (layout->buffer, 
                                            G_CALLBACK (ctk_text_layout_mark_set_handler), 
                                            layout);
      g_signal_handlers_disconnect_by_func (layout->buffer, 
                                            G_CALLBACK (ctk_text_layout_buffer_insert_text), 
                                            layout);
      g_signal_handlers_disconnect_by_func (layout->buffer, 
                                            G_CALLBACK (ctk_text_layout_buffer_delete_range), 
                                            layout);

      g_object_unref (layout->buffer);
      layout->buffer = NULL;
    }

  if (buffer)
    {
      layout->buffer = buffer;

      g_object_ref (buffer);

      _ctk_text_btree_add_view (_ctk_text_buffer_get_btree (buffer), layout);

      /* Bind to all signals that move the insert mark. */
      g_signal_connect_after (layout->buffer, "mark-set",
                              G_CALLBACK (ctk_text_layout_mark_set_handler), layout);
      g_signal_connect_after (layout->buffer, "insert-text",
                              G_CALLBACK (ctk_text_layout_buffer_insert_text), layout);
      g_signal_connect_after (layout->buffer, "delete-range",
                              G_CALLBACK (ctk_text_layout_buffer_delete_range), layout);

      ctk_text_layout_update_cursor_line (layout);
    }
}

void
ctk_text_layout_default_style_changed (CtkTextLayout *layout)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));

  DV (g_print ("invalidating all due to default style change (%s)\n", G_STRLOC));
  ctk_text_layout_invalidate_all (layout);
}

void
ctk_text_layout_set_default_style (CtkTextLayout     *layout,
                                   CtkTextAttributes *values)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (values != NULL);

  if (values == layout->default_style)
    return;

  ctk_text_attributes_ref (values);

  if (layout->default_style)
    ctk_text_attributes_unref (layout->default_style);

  layout->default_style = values;

  ctk_text_layout_default_style_changed (layout);
}

void
ctk_text_layout_set_contexts (CtkTextLayout *layout,
                              PangoContext  *ltr_context,
                              PangoContext  *rtl_context)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));

  if (layout->ltr_context != ltr_context)
    {
      if (layout->ltr_context)
	g_object_unref (layout->ltr_context);

      layout->ltr_context = ltr_context;
      g_object_ref (layout->ltr_context);
    }

  if (layout->rtl_context != rtl_context)
    {
      if (layout->rtl_context)
	g_object_unref (layout->rtl_context);

      layout->rtl_context = rtl_context;
      g_object_ref (layout->rtl_context);
    }

  DV (g_print ("invalidating all due to new pango contexts (%s)\n", G_STRLOC));
  ctk_text_layout_invalidate_all (layout);
}

/**
 * ctk_text_layout_set_overwrite_mode:
 * @layout: a #CtkTextLayout
 * @overwrite: overwrite mode
 *
 * Sets overwrite mode
 */
void
ctk_text_layout_set_overwrite_mode (CtkTextLayout *layout,
				    gboolean       overwrite)
{
  overwrite = overwrite != 0;
  if (overwrite != layout->overwrite_mode)
    {
      layout->overwrite_mode = overwrite;
      ctk_text_layout_invalidate_cursor_line (layout, TRUE);
    }
}

/**
 * ctk_text_layout_set_cursor_direction:
 * @direction: the new direction(s) for which to draw cursors.
 *             %CTK_TEXT_DIR_NONE means draw cursors for both
 *             left-to-right insertion and right-to-left insertion.
 *             (The two cursors will be visually distinguished.)
 * 
 * Sets which text directions (left-to-right and/or right-to-left) for
 * which cursors will be drawn for the insertion point. The visual
 * point at which new text is inserted depends on whether the new
 * text is right-to-left or left-to-right, so it may be desired to
 * make the drawn position of the cursor depend on the keyboard state.
 */
void
ctk_text_layout_set_cursor_direction (CtkTextLayout   *layout,
				      CtkTextDirection direction)
{
  if (direction != layout->cursor_direction)
    {
      layout->cursor_direction = direction;
      ctk_text_layout_invalidate_cursor_line (layout, TRUE);
    }
}

/**
 * ctk_text_layout_set_keyboard_direction:
 * @keyboard_dir: the current direction of the keyboard.
 *
 * Sets the keyboard direction; this is used as for the bidirectional
 * base direction for the line with the cursor if the line contains
 * only neutral characters.
 */
void
ctk_text_layout_set_keyboard_direction (CtkTextLayout   *layout,
					CtkTextDirection keyboard_dir)
{
  if (keyboard_dir != layout->keyboard_direction)
    {
      layout->keyboard_direction = keyboard_dir;
      ctk_text_layout_invalidate_cursor_line (layout, TRUE);
    }
}

/**
 * ctk_text_layout_get_buffer:
 * @layout: a #CtkTextLayout
 *
 * Gets the text buffer used by the layout. See
 * ctk_text_layout_set_buffer().
 *
 * Returns: the text buffer used by the layout.
 */
CtkTextBuffer *
ctk_text_layout_get_buffer (CtkTextLayout *layout)
{
  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), NULL);

  return layout->buffer;
}

void
ctk_text_layout_set_screen_width (CtkTextLayout *layout, gint width)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (width >= 0);
  g_return_if_fail (layout->wrap_loop_count == 0);

  if (layout->screen_width == width)
    return;

  layout->screen_width = width;

  DV (g_print ("invalidating all due to new screen width (%s)\n", G_STRLOC));
  ctk_text_layout_invalidate_all (layout);
}

/**
 * ctk_text_layout_set_cursor_visible:
 * @layout: a #CtkTextLayout
 * @cursor_visible: If %FALSE, then the insertion cursor will not
 *   be shown, even if the text is editable.
 *
 * Sets whether the insertion cursor should be shown. Generally,
 * widgets using #CtkTextLayout will hide the cursor when the
 * widget does not have the input focus.
 */
void
ctk_text_layout_set_cursor_visible (CtkTextLayout *layout,
                                    gboolean       cursor_visible)
{
  cursor_visible = (cursor_visible != FALSE);

  if (layout->cursor_visible != cursor_visible)
    {
      CtkTextIter iter;
      gint y, height;

      layout->cursor_visible = cursor_visible;

      /* Now queue a redraw on the paragraph containing the cursor
       */
      ctk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
                                        ctk_text_buffer_get_insert (layout->buffer));

      ctk_text_layout_get_line_yrange (layout, &iter, &y, &height);
      ctk_text_layout_emit_changed (layout, y, height, height);

      ctk_text_layout_invalidate_cache (layout, _ctk_text_iter_get_text_line (&iter), TRUE);
    }
}

/**
 * ctk_text_layout_get_cursor_visible:
 * @layout: a #CtkTextLayout
 *
 * Returns whether the insertion cursor will be shown.
 *
 * Returns: if %FALSE, the insertion cursor will not be
 *     shown, even if the text is editable.
 */
gboolean
ctk_text_layout_get_cursor_visible (CtkTextLayout *layout)
{
  return layout->cursor_visible;
}

/**
 * ctk_text_layout_set_preedit_string:
 * @layout: a #PangoLayout
 * @preedit_string: a string to display at the insertion point
 * @preedit_attrs: a #PangoAttrList of attributes that apply to @preedit_string
 * @cursor_pos: position of cursor within preedit string in chars
 * 
 * Set the preedit string and attributes. The preedit string is a
 * string showing text that is currently being edited and not
 * yet committed into the buffer.
 */
void
ctk_text_layout_set_preedit_string (CtkTextLayout *layout,
				    const gchar   *preedit_string,
				    PangoAttrList *preedit_attrs,
				    gint           cursor_pos)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (preedit_attrs != NULL || preedit_string == NULL);

  g_free (layout->preedit_string);

  if (layout->preedit_attrs)
    pango_attr_list_unref (layout->preedit_attrs);

  if (preedit_string)
    {
      layout->preedit_string = g_strdup (preedit_string);
      layout->preedit_len = strlen (layout->preedit_string);
      pango_attr_list_ref (preedit_attrs);
      layout->preedit_attrs = preedit_attrs;

      cursor_pos = CLAMP (cursor_pos, 0, g_utf8_strlen (layout->preedit_string, -1));
      layout->preedit_cursor = g_utf8_offset_to_pointer (layout->preedit_string, cursor_pos) - layout->preedit_string;
    }
  else
    {
      layout->preedit_string = NULL;
      layout->preedit_len = 0;
      layout->preedit_attrs = NULL;
      layout->preedit_cursor = 0;
    }

  ctk_text_layout_invalidate_cursor_line (layout, FALSE);
}

void
ctk_text_layout_get_size (CtkTextLayout *layout,
                          gint *width,
                          gint *height)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));

  if (width)
    *width = layout->width;

  if (height)
    *height = layout->height;
}

static void
ctk_text_layout_invalidated (CtkTextLayout *layout)
{
  g_signal_emit (layout, signals[INVALIDATED], 0);
}

static void
ctk_text_layout_emit_changed (CtkTextLayout *layout,
			      gint           y,
			      gint           old_height,
			      gint           new_height)
{
  g_signal_emit (layout, signals[CHANGED], 0, y, old_height, new_height);
}

static void
text_layout_changed (CtkTextLayout *layout,
                     gint           y,
                     gint           old_height,
                     gint           new_height,
                     gboolean       cursors_only)
{
  /* Check if the range intersects our cached line display,
   * and invalidate the cached line if so.
   */
  if (layout->one_display_cache)
    {
      CtkTextLine *line = layout->one_display_cache->line;
      gint cache_y = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
						    line, layout);
      gint cache_height = layout->one_display_cache->height;

      if (cache_y + cache_height > y && cache_y < y + old_height)
	ctk_text_layout_invalidate_cache (layout, line, cursors_only);
    }

  ctk_text_layout_emit_changed (layout, y, old_height, new_height);
}

void
ctk_text_layout_changed (CtkTextLayout *layout,
                         gint           y,
                         gint           old_height,
                         gint           new_height)
{
  text_layout_changed (layout, y, old_height, new_height, FALSE);
}

void
ctk_text_layout_cursors_changed (CtkTextLayout *layout,
                                 gint           y,
				 gint           old_height,
				 gint           new_height)
{
  text_layout_changed (layout, y, old_height, new_height, TRUE);
}

void
ctk_text_layout_free_line_data (CtkTextLayout     *layout,
                                CtkTextLine       *line,
                                CtkTextLineData   *line_data)
{
  CTK_TEXT_LAYOUT_GET_CLASS (layout)->free_line_data (layout, line, line_data);
}

void
ctk_text_layout_invalidate (CtkTextLayout *layout,
                            const CtkTextIter *start_index,
                            const CtkTextIter *end_index)
{
  CTK_TEXT_LAYOUT_GET_CLASS (layout)->invalidate (layout, start_index, end_index);
}

void
ctk_text_layout_invalidate_cursors (CtkTextLayout *layout,
				    const CtkTextIter *start_index,
				    const CtkTextIter *end_index)
{
  CTK_TEXT_LAYOUT_GET_CLASS (layout)->invalidate_cursors (layout, start_index, end_index);
}

CtkTextLineData*
ctk_text_layout_wrap (CtkTextLayout *layout,
                      CtkTextLine  *line,
                      /* may be NULL */
                      CtkTextLineData *line_data)
{
  return CTK_TEXT_LAYOUT_GET_CLASS (layout)->wrap (layout, line, line_data);
}


/**
 * ctk_text_layout_get_lines:
 *
 * Returns: (element-type CtkTextLine) (transfer container):
 */
GSList*
ctk_text_layout_get_lines (CtkTextLayout *layout,
                           /* [top_y, bottom_y) */
                           gint top_y,
                           gint bottom_y,
                           gint *first_line_y)
{
  CtkTextLine *first_btree_line;
  CtkTextLine *last_btree_line;
  CtkTextLine *line;
  GSList *retval;

  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), NULL);
  g_return_val_if_fail (bottom_y > top_y, NULL);

  retval = NULL;

  first_btree_line =
    _ctk_text_btree_find_line_by_y (_ctk_text_buffer_get_btree (layout->buffer),
                                   layout, top_y, first_line_y);
  if (first_btree_line == NULL)
    {
      /* off the bottom */
      return NULL;
    }

  /* -1 since bottom_y is one past */
  last_btree_line =
    _ctk_text_btree_find_line_by_y (_ctk_text_buffer_get_btree (layout->buffer),
                                    layout, bottom_y - 1, NULL);

  if (!last_btree_line)
    last_btree_line =
      _ctk_text_btree_get_end_iter_line (_ctk_text_buffer_get_btree (layout->buffer));

  g_assert (last_btree_line != NULL);

  line = first_btree_line;
  while (TRUE)
    {
      retval = g_slist_prepend (retval, line);

      if (line == last_btree_line)
        break;

      line = _ctk_text_line_next_excluding_last (line);
    }

  retval = g_slist_reverse (retval);

  return retval;
}

static void
invalidate_cached_style (CtkTextLayout *layout)
{
  free_style_cache (layout);
}

/* These should be called around a loop which wraps a CONTIGUOUS bunch
 * of display lines. If the lines aren’t contiguous you can’t call
 * these.
 */
void
ctk_text_layout_wrap_loop_start (CtkTextLayout *layout)
{
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (layout->one_style_cache == NULL);

  layout->wrap_loop_count += 1;
}

void
ctk_text_layout_wrap_loop_end (CtkTextLayout *layout)
{
  g_return_if_fail (layout->wrap_loop_count > 0);

  layout->wrap_loop_count -= 1;

  if (layout->wrap_loop_count == 0)
    {
      /* We cache a some stuff if we're iterating over some lines wrapping
       * them. This cleans it up.
       */
      /* Nuke our cached style */
      invalidate_cached_style (layout);
      g_assert (layout->one_style_cache == NULL);
    }
}

static void
ctk_text_layout_invalidate_all (CtkTextLayout *layout)
{
  CtkTextIter start;
  CtkTextIter end;

  if (layout->buffer == NULL)
    return;

  ctk_text_buffer_get_bounds (layout->buffer, &start, &end);

  ctk_text_layout_invalidate (layout, &start, &end);
}

static void
ctk_text_layout_invalidate_cache (CtkTextLayout *layout,
                                  CtkTextLine   *line,
				  gboolean       cursors_only)
{
  if (layout->one_display_cache && line == layout->one_display_cache->line)
    {
      CtkTextLineDisplay *display = layout->one_display_cache;

      if (cursors_only)
	{
          if (display->cursors)
            g_array_free (display->cursors, TRUE);
	  display->cursors = NULL;
	  display->cursors_invalid = TRUE;
	  display->has_block_cursor = FALSE;
	}
      else
	{
	  layout->one_display_cache = NULL;
	  ctk_text_layout_free_line_display (layout, display);
	}
    }
}

/* Now invalidate the paragraph containing the cursor
 */
static void
ctk_text_layout_invalidate_cursor_line (CtkTextLayout *layout,
					gboolean cursors_only)
{
  CtkTextLayoutPrivate *priv = CTK_TEXT_LAYOUT_GET_PRIVATE (layout);
  CtkTextLineData *line_data;

  if (priv->cursor_line == NULL)
    return;

  line_data = _ctk_text_line_get_data (priv->cursor_line, layout);
  if (line_data)
    {
      if (cursors_only)
	  ctk_text_layout_invalidate_cache (layout, priv->cursor_line, TRUE);
      else
	{
	  ctk_text_layout_invalidate_cache (layout, priv->cursor_line, FALSE);
	  _ctk_text_line_invalidate_wrap (priv->cursor_line, line_data);
	}

      ctk_text_layout_invalidated (layout);
    }
}

static void
ctk_text_layout_update_cursor_line(CtkTextLayout *layout)
{
  CtkTextLayoutPrivate *priv = CTK_TEXT_LAYOUT_GET_PRIVATE (layout);
  CtkTextIter iter;

  ctk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
                                    ctk_text_buffer_get_insert (layout->buffer));

  priv->cursor_line = _ctk_text_iter_get_text_line (&iter);
}

static void
ctk_text_layout_real_invalidate (CtkTextLayout *layout,
                                 const CtkTextIter *start,
                                 const CtkTextIter *end)
{
  CtkTextLine *line;
  CtkTextLine *last_line;

  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (layout->wrap_loop_count == 0);

  /* Because we may be invalidating a mark, it's entirely possible
   * that ctk_text_iter_equal (start, end) in which case we
   * should still invalidate the line they are both on. i.e.
   * we always invalidate the line with "start" even
   * if there's an empty range.
   */
  
#if 0
  ctk_text_view_index_spew (start_index, "invalidate start");
  ctk_text_view_index_spew (end_index, "invalidate end");
#endif

  last_line = _ctk_text_iter_get_text_line (end);
  line = _ctk_text_iter_get_text_line (start);

  while (TRUE)
    {
      CtkTextLineData *line_data = _ctk_text_line_get_data (line, layout);

      ctk_text_layout_invalidate_cache (layout, line, FALSE);
      
      if (line_data)
        _ctk_text_line_invalidate_wrap (line, line_data);

      if (line == last_line)
        break;

      line = _ctk_text_line_next_excluding_last (line);
    }

  ctk_text_layout_invalidated (layout);
}

static void
ctk_text_layout_real_invalidate_cursors (CtkTextLayout     *layout,
					 const CtkTextIter *start,
					 const CtkTextIter *end)
{
  /* Check if the range intersects our cached line display,
   * and invalidate the cached line if so.
   */
  if (layout->one_display_cache)
    {
      CtkTextIter line_start, line_end;
      CtkTextLine *line = layout->one_display_cache->line;

      ctk_text_layout_get_iter_at_line (layout, &line_start, line, 0);

      line_end = line_start;
      if (!ctk_text_iter_ends_line (&line_end))
	ctk_text_iter_forward_to_line_end (&line_end);

      if (ctk_text_iter_compare (start, end) > 0)
	{
	  const CtkTextIter *tmp = start;
	  start = end;
	  end = tmp;
	}

      if (ctk_text_iter_compare (&line_start, end) <= 0 &&
	  ctk_text_iter_compare (start, &line_end) <= 0)
	{
	  ctk_text_layout_invalidate_cache (layout, line, TRUE);
	}
    }

  ctk_text_layout_invalidated (layout);
}

static void
ctk_text_layout_real_free_line_data (CtkTextLayout     *layout,
                                     CtkTextLine       *line,
                                     CtkTextLineData   *line_data)
{
  ctk_text_layout_invalidate_cache (layout, line, FALSE);

  g_slice_free (CtkTextLineData, line_data);
}

/**
 * ctk_text_layout_is_valid:
 * @layout: a #CtkTextLayout
 *
 * Check if there are any invalid regions in a #CtkTextLayout’s buffer
 *
 * Returns: %TRUE if any invalid regions were found
 */
gboolean
ctk_text_layout_is_valid (CtkTextLayout *layout)
{
  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);

  return _ctk_text_btree_is_valid (_ctk_text_buffer_get_btree (layout->buffer),
                                  layout);
}

static void
update_layout_size (CtkTextLayout *layout)
{
  _ctk_text_btree_get_view_size (_ctk_text_buffer_get_btree (layout->buffer),
				layout,
				&layout->width, &layout->height);
}

/**
 * ctk_text_layout_validate_yrange:
 * @layout: a #CtkTextLayout
 * @anchor: iter pointing into a line that will be used as the
 *          coordinate origin
 * @y0_: offset from the top of the line pointed to by @anchor at
 *       which to begin validation. (The offset here is in pixels
 *       after validation.)
 * @y1_: offset from the top of the line pointed to by @anchor at
 *       which to end validation. (The offset here is in pixels
 *       after validation.)
 *
 * Ensure that a region of a #CtkTextLayout is valid. The ::changed
 * signal will be emitted if any lines are validated.
 */
void
ctk_text_layout_validate_yrange (CtkTextLayout *layout,
                                 CtkTextIter   *anchor,
                                 gint           y0,
                                 gint           y1)
{
  CtkTextLine *line;
  CtkTextLine *first_line = NULL;
  CtkTextLine *last_line = NULL;
  gint seen;
  gint delta_height = 0;
  gint first_line_y = 0;        /* Quiet GCC */
  gint last_line_y = 0;         /* Quiet GCC */

  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));

  if (y0 > 0)
    y0 = 0;
  if (y1 < 0)
    y1 = 0;
  
  /* Validate backwards from the anchor line to y0
   */
  line = _ctk_text_iter_get_text_line (anchor);
  line = _ctk_text_line_previous (line);
  seen = 0;
  while (line && seen < -y0)
    {
      CtkTextLineData *line_data = _ctk_text_line_get_data (line, layout);
      if (!line_data || !line_data->valid)
        {
          gint old_height, new_height;
          gint top_ink, bottom_ink;
	  
	  old_height = line_data ? line_data->height : 0;
          top_ink = line_data ? line_data->top_ink : 0;
          bottom_ink = line_data ? line_data->bottom_ink : 0;

          _ctk_text_btree_validate_line (_ctk_text_buffer_get_btree (layout->buffer),
                                         line, layout);
          line_data = _ctk_text_line_get_data (line, layout);

	  new_height = line_data ? line_data->height : 0;
          if (line_data)
            {
              top_ink = MAX (top_ink, line_data->top_ink);
              bottom_ink = MAX (bottom_ink, line_data->bottom_ink);
            }

          delta_height += new_height - old_height;
          
          first_line = line;
          first_line_y = -seen - new_height - top_ink;
          if (!last_line)
            {
              last_line = line;
              last_line_y = -seen + bottom_ink;
            }
        }

      seen += line_data ? line_data->height : 0;
      line = _ctk_text_line_previous (line);
    }

  /* Validate forwards to y1 */
  line = _ctk_text_iter_get_text_line (anchor);
  seen = 0;
  while (line && seen < y1)
    {
      CtkTextLineData *line_data = _ctk_text_line_get_data (line, layout);
      if (!line_data || !line_data->valid)
        {
          gint old_height, new_height;
          gint top_ink, bottom_ink;
	  
	  old_height = line_data ? line_data->height : 0;
          top_ink = line_data ? line_data->top_ink : 0;
          bottom_ink = line_data ? line_data->bottom_ink : 0;

          _ctk_text_btree_validate_line (_ctk_text_buffer_get_btree (layout->buffer),
                                         line, layout);
          line_data = _ctk_text_line_get_data (line, layout);
	  new_height = line_data ? line_data->height : 0;
          if (line_data)
            {
              top_ink = MAX (top_ink, line_data->top_ink);
              bottom_ink = MAX (bottom_ink, line_data->bottom_ink);
            }

          delta_height += new_height - old_height;
          
          if (!first_line)
            {
              first_line = line;
              first_line_y = seen - top_ink;
            }
          last_line = line;
          last_line_y = seen + new_height + bottom_ink;
        }

      seen += line_data ? line_data->height : 0;
      line = _ctk_text_line_next_excluding_last (line);
    }

  /* If we found and validated any invalid lines, update size and
   * emit the changed signal
   */
  if (first_line)
    {
      gint line_top;

      update_layout_size (layout);

      line_top = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
                                                first_line, layout);

      ctk_text_layout_emit_changed (layout,
				    line_top,
				    last_line_y - first_line_y - delta_height,
				    last_line_y - first_line_y);
    }
}

/**
 * ctk_text_layout_validate:
 * @tree: a #CtkTextLayout
 * @max_pixels: the maximum number of pixels to validate. (No more
 *              than one paragraph beyond this limit will be validated)
 *
 * Validate regions of a #CtkTextLayout. The ::changed signal will
 * be emitted for each region validated.
 **/
void
ctk_text_layout_validate (CtkTextLayout *layout,
                          gint           max_pixels)
{
  gint y, old_height, new_height;

  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));

  while (max_pixels > 0 &&
         _ctk_text_btree_validate (_ctk_text_buffer_get_btree (layout->buffer),
                                   layout,  max_pixels,
                                   &y, &old_height, &new_height))
    {
      max_pixels -= new_height;

      update_layout_size (layout);
      ctk_text_layout_emit_changed (layout, y, old_height, new_height);
    }
}

static CtkTextLineData*
ctk_text_layout_real_wrap (CtkTextLayout   *layout,
                           CtkTextLine     *line,
                           /* may be NULL */
                           CtkTextLineData *line_data)
{
  CtkTextLineDisplay *display;
  PangoRectangle ink_rect, logical_rect;

  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), NULL);
  g_return_val_if_fail (line != NULL, NULL);
  
  if (line_data == NULL)
    {
      line_data = _ctk_text_line_data_new (layout, line);
      _ctk_text_line_add_data (line, line_data);
    }

  display = ctk_text_layout_get_line_display (layout, line, TRUE);
  line_data->width = display->width;
  line_data->height = display->height;
  line_data->valid = TRUE;
  pango_layout_get_pixel_extents (display->layout, &ink_rect, &logical_rect);
  line_data->top_ink = MAX (0, logical_rect.x - ink_rect.x);
  line_data->bottom_ink = MAX (0, logical_rect.x + logical_rect.width - ink_rect.x - ink_rect.width);
  ctk_text_layout_free_line_display (layout, display);

  return line_data;
}

/*
 * Layout utility functions
 */

/* If you get the style with get_style () you need to call
   release_style () to free it. */
static CtkTextAttributes*
get_style (CtkTextLayout *layout,
	   GPtrArray     *tags)
{
  CtkTextAttributes *style;

  /* If we have the one-style cache, then it means
     that we haven't seen a toggle since we filled in the
     one-style cache.
  */
  if (layout->one_style_cache != NULL)
    {
      ctk_text_attributes_ref (layout->one_style_cache);
      return layout->one_style_cache;
    }

  g_assert (layout->one_style_cache == NULL);

  /* No tags, use default style */
  if (tags == NULL || tags->len == 0)
    {
      /* One ref for the return value, one ref for the
         layout->one_style_cache reference */
      ctk_text_attributes_ref (layout->default_style);
      ctk_text_attributes_ref (layout->default_style);
      layout->one_style_cache = layout->default_style;

      return layout->default_style;
    }

  style = ctk_text_attributes_new ();

  ctk_text_attributes_copy_values (layout->default_style,
                                   style);

  _ctk_text_attributes_fill_from_tags (style,
                                       (CtkTextTag**) tags->pdata,
                                       tags->len);

  g_assert (style->refcount == 1);

  /* Leave this style as the last one seen */
  g_assert (layout->one_style_cache == NULL);
  ctk_text_attributes_ref (style); /* ref held by layout->one_style_cache */
  layout->one_style_cache = style;

  /* Returning yet another refcount */
  return style;
}

static void
release_style (CtkTextLayout     *layout G_GNUC_UNUSED,
               CtkTextAttributes *style)
{
  g_return_if_fail (style != NULL);
  g_return_if_fail (style->refcount > 0);

  ctk_text_attributes_unref (style);
}

/*
 * Lines
 */

/* This function tries to optimize the case where a line
   is completely invisible */
static gboolean
totally_invisible_line (CtkTextLayout *layout,
                        CtkTextLine   *line,
                        CtkTextIter   *iter)
{
  CtkTextLineSegment *seg;
  int bytes = 0;

  /* Check if the first char is visible, if so we are partially visible.  
   * Note that we have to check this since we don't know the current 
   * invisible/noninvisible toggle state; this function can use the whole btree 
   * to get it right.
   */
  ctk_text_layout_get_iter_at_line (layout, iter, line, 0);
  if (!_ctk_text_btree_char_is_invisible (iter))
    return FALSE;

  bytes = 0;
  seg = line->segments;

  while (seg != NULL)
    {
      if (seg->byte_count > 0)
        bytes += seg->byte_count;

      /* Note that these two tests can cause us to bail out
       * when we shouldn't, because a higher-priority tag
       * may override these settings. However the important
       * thing is to only invisible really-invisible lines, rather
       * than to invisible all really-invisible lines.
       */

      else if (seg->type == &ctk_text_toggle_on_type)
        {
          invalidate_cached_style (layout);

          /* Bail out if an elision-unsetting tag begins */
          if (seg->body.toggle.info->tag->priv->invisible_set &&
              !seg->body.toggle.info->tag->priv->values->invisible)
            break;
        }
      else if (seg->type == &ctk_text_toggle_off_type)
        {
          invalidate_cached_style (layout);

          /* Bail out if an elision-setting tag ends */
          if (seg->body.toggle.info->tag->priv->invisible_set &&
              seg->body.toggle.info->tag->priv->values->invisible)
            break;
        }

      seg = seg->next;
    }

  if (seg != NULL)       /* didn't reach line end */
    return FALSE;

  return TRUE;
}

static void
set_para_values (CtkTextLayout      *layout,
                 PangoDirection      base_dir,
                 CtkTextAttributes  *style,
                 CtkTextLineDisplay *display)
{
  PangoAlignment pango_align = PANGO_ALIGN_LEFT;
  PangoWrapMode pango_wrap = PANGO_WRAP_WORD;
  gint h_margin;
  gint h_padding;

  switch (base_dir)
    {
    /* If no base direction was found, then use the style direction */
    case PANGO_DIRECTION_NEUTRAL :
      display->direction = style->direction;

      /* Override the base direction */
      if (display->direction == CTK_TEXT_DIR_RTL)
        base_dir = PANGO_DIRECTION_RTL;
      else
        base_dir = PANGO_DIRECTION_LTR;
      
      break;
    case PANGO_DIRECTION_RTL :
      display->direction = CTK_TEXT_DIR_RTL;
      break;
    default:
      display->direction = CTK_TEXT_DIR_LTR;
      break;
    }
  
  if (display->direction == CTK_TEXT_DIR_RTL)
    display->layout = pango_layout_new (layout->rtl_context);
  else
    display->layout = pango_layout_new (layout->ltr_context);

  switch (style->justification)
    {
    case CTK_JUSTIFY_LEFT:
      pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
      break;
    case CTK_JUSTIFY_RIGHT:
      pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
      break;
    case CTK_JUSTIFY_CENTER:
      pango_align = PANGO_ALIGN_CENTER;
      break;
    case CTK_JUSTIFY_FILL:
      pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
      pango_layout_set_justify (display->layout, TRUE);
      break;
    default:
      g_assert_not_reached ();
      break;
    }

  pango_layout_set_alignment (display->layout, pango_align);
  pango_layout_set_spacing (display->layout,
                            style->pixels_inside_wrap * PANGO_SCALE);

  if (style->tabs)
    pango_layout_set_tabs (display->layout, style->tabs);

  display->top_margin = style->pixels_above_lines;
  display->height = style->pixels_above_lines + style->pixels_below_lines;
  display->bottom_margin = style->pixels_below_lines;
  display->left_margin = style->left_margin;
  display->right_margin = style->right_margin;
  
  display->x_offset = display->left_margin;

  pango_layout_set_indent (display->layout,
                           style->indent * PANGO_SCALE);

  switch (style->wrap_mode)
    {
    case CTK_WRAP_CHAR:
      pango_wrap = PANGO_WRAP_CHAR;
      break;
    case CTK_WRAP_WORD:
      pango_wrap = PANGO_WRAP_WORD;
      break;

    case CTK_WRAP_WORD_CHAR:
      pango_wrap = PANGO_WRAP_WORD_CHAR;
      break;

    case CTK_WRAP_NONE:
      break;
    }

  h_margin = display->left_margin + display->right_margin;
  h_padding = layout->left_padding + layout->right_padding;

  if (style->wrap_mode != CTK_WRAP_NONE)
    {
      int layout_width = (layout->screen_width - h_margin - h_padding);
      pango_layout_set_width (display->layout, layout_width * PANGO_SCALE);
      pango_layout_set_wrap (display->layout, pango_wrap);
    }
  display->total_width = MAX (layout->screen_width, layout->width) - h_margin - h_padding;
  
  if (style->pg_bg_color)
    display->pg_bg_color = cdk_color_copy (style->pg_bg_color);
  else
    display->pg_bg_color = NULL;

  if (style->pg_bg_rgba)
    display->pg_bg_rgba = cdk_rgba_copy (style->pg_bg_rgba);
  else
    display->pg_bg_rgba = NULL;
}

static PangoAttribute *
ctk_text_attr_appearance_copy (const PangoAttribute *attr)
{
  const CtkTextAttrAppearance *appearance_attr = (const CtkTextAttrAppearance *)attr;

  return ctk_text_attr_appearance_new (&appearance_attr->appearance);
}

static void
ctk_text_attr_appearance_destroy (PangoAttribute *attr)
{
  CtkTextAttrAppearance *appearance_attr = (CtkTextAttrAppearance *)attr;

  if (appearance_attr->appearance.rgba[0])
    cdk_rgba_free (appearance_attr->appearance.rgba[0]);

  if (appearance_attr->appearance.rgba[1])
    cdk_rgba_free (appearance_attr->appearance.rgba[1]);

  g_slice_free (CtkTextAttrAppearance, appearance_attr);
}

static gboolean 
rgba_equal (const CdkRGBA *rgba1, const CdkRGBA *rgba2)
{
  if (rgba1 && rgba2)
    return cdk_rgba_equal (rgba1, rgba2);
  
  if (rgba1 || rgba2)
    return FALSE;

  return TRUE;
}

static gboolean
underline_equal (const CtkTextAppearance *appearance1,
                 const CtkTextAppearance *appearance2)
{
  CdkRGBA c1;
  CdkRGBA c2;

  CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA (appearance1, &c1);
  CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA (appearance2, &c2);

  return ((appearance1->underline == appearance2->underline) &&
          (CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA_SET (appearance1) ==
           CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA_SET (appearance2)) &&
          cdk_rgba_equal (&c1, &c2));
}

static gboolean
strikethrough_equal (const CtkTextAppearance *appearance1,
                     const CtkTextAppearance *appearance2)
{
  CdkRGBA c1;
  CdkRGBA c2;

  CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA (appearance1, &c1);
  CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA (appearance2, &c2);

  return ((appearance1->strikethrough == appearance2->strikethrough) &&
          (CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA_SET (appearance1) ==
           CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA_SET (appearance2)) &&
          cdk_rgba_equal (&c1, &c2));
}

static gboolean
ctk_text_attr_appearance_compare (const PangoAttribute *attr1,
                                  const PangoAttribute *attr2)
{
  const CtkTextAppearance *appearance1 = &((const CtkTextAttrAppearance *)attr1)->appearance;
  const CtkTextAppearance *appearance2 = &((const CtkTextAttrAppearance *)attr2)->appearance;

  return (rgba_equal (appearance1->rgba[0], appearance2->rgba[0]) &&
          rgba_equal (appearance1->rgba[1], appearance2->rgba[1]) &&
          appearance1->draw_bg == appearance2->draw_bg &&
          strikethrough_equal (appearance1, appearance2) &&
          underline_equal (appearance1, appearance2));
}

/*
 * ctk_text_attr_appearance_new:
 * @desc:
 *
 * Create a new font description attribute. (This attribute
 * allows setting family, style, weight, variant, stretch,
 * and size simultaneously.)
 *
 * Returns:
 */
static PangoAttribute *
ctk_text_attr_appearance_new (const CtkTextAppearance *appearance)
{
  static PangoAttrClass klass = {
    0,
    ctk_text_attr_appearance_copy,
    ctk_text_attr_appearance_destroy,
    ctk_text_attr_appearance_compare
  };

  CtkTextAttrAppearance *result;

  if (!klass.type)
    klass.type = ctk_text_attr_appearance_type =
      pango_attr_type_register ("CtkTextAttrAppearance");

  result = g_slice_new (CtkTextAttrAppearance);
  result->attr.klass = &klass;

  result->appearance = *appearance;

  if (appearance->rgba[0])
    result->appearance.rgba[0] = cdk_rgba_copy (appearance->rgba[0]);

  if (appearance->rgba[1])
    result->appearance.rgba[1] = cdk_rgba_copy (appearance->rgba[1]);

  return (PangoAttribute *)result;
}

static void
add_generic_attrs (CtkTextLayout      *layout G_GNUC_UNUSED,
                   CtkTextAppearance  *appearance,
                   gint                byte_count,
                   PangoAttrList      *attrs,
                   gint                start,
                   gboolean            size_only,
                   gboolean            is_text)
{
  PangoAttribute *attr;

  if (appearance->underline != PANGO_UNDERLINE_NONE)
    {
      attr = pango_attr_underline_new (appearance->underline);
      
      attr->start_index = start;
      attr->end_index = start + byte_count;
      
      pango_attr_list_insert (attrs, attr);
    }

  if (CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA_SET (appearance))
    {
      CdkRGBA rgba;

      CTK_TEXT_APPEARANCE_GET_UNDERLINE_RGBA (appearance, &rgba);

      attr = pango_attr_underline_color_new (rgba.red * 65535,
                                             rgba.green * 65535,
                                             rgba.blue * 65535);

      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }

  if (appearance->strikethrough)
    {
      attr = pango_attr_strikethrough_new (appearance->strikethrough);
      
      attr->start_index = start;
      attr->end_index = start + byte_count;
      
      pango_attr_list_insert (attrs, attr);
    }

  if (CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA_SET (appearance))
    {
      CdkRGBA rgba;

      CTK_TEXT_APPEARANCE_GET_STRIKETHROUGH_RGBA (appearance, &rgba);

      attr = pango_attr_strikethrough_color_new (rgba.red * 65535,
                                                 rgba.green * 65535,
                                                 rgba.blue * 65535);

      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }

  if (appearance->rise != 0)
    {
      attr = pango_attr_rise_new (appearance->rise);
      
      attr->start_index = start;
      attr->end_index = start + byte_count;
      
      pango_attr_list_insert (attrs, attr);
    }
  
  if (!size_only)
    {
      attr = ctk_text_attr_appearance_new (appearance);
      
      attr->start_index = start;
      attr->end_index = start + byte_count;

      ((CtkTextAttrAppearance *)attr)->appearance.is_text = is_text;
      
      pango_attr_list_insert (attrs, attr);
    }
}

static void
add_text_attrs (CtkTextLayout      *layout G_GNUC_UNUSED,
                CtkTextAttributes  *style,
                gint                byte_count,
                PangoAttrList      *attrs,
                gint                start,
                gboolean            size_only G_GNUC_UNUSED)
{
  PangoAttribute *attr;

  attr = pango_attr_font_desc_new (style->font);
  attr->start_index = start;
  attr->end_index = start + byte_count;

  pango_attr_list_insert (attrs, attr);

  if (style->font_scale != 1.0)
    {
      attr = pango_attr_scale_new (style->font_scale);
      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }

  if (style->no_fallback)
    {
      attr = pango_attr_fallback_new (!style->no_fallback);
      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }

  if (style->letter_spacing != 0)
    {
      attr = pango_attr_letter_spacing_new (style->letter_spacing);
      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }

  if (style->font_features)
    {
      attr = pango_attr_font_features_new (style->font_features);
      attr->start_index = start;
      attr->end_index = start + byte_count;

      pango_attr_list_insert (attrs, attr);
    }
}

static void
add_pixbuf_attrs (CtkTextLayout      *layout G_GNUC_UNUSED,
                  CtkTextLineDisplay *display G_GNUC_UNUSED,
                  CtkTextAttributes  *style G_GNUC_UNUSED,
                  CtkTextLineSegment *seg,
                  PangoAttrList      *attrs,
                  gint                start)
{
  PangoAttribute *attr;
  PangoRectangle logical_rect;
  CtkTextPixbuf *pixbuf = &seg->body.pixbuf;
  gint width, height;

  width = gdk_pixbuf_get_width (pixbuf->pixbuf);
  height = gdk_pixbuf_get_height (pixbuf->pixbuf);

  logical_rect.x = 0;
  logical_rect.y = -height * PANGO_SCALE;
  logical_rect.width = width * PANGO_SCALE;
  logical_rect.height = height * PANGO_SCALE;

  attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
					 pixbuf->pixbuf, NULL, NULL);
  attr->start_index = start;
  attr->end_index = start + seg->byte_count;
  pango_attr_list_insert (attrs, attr);
}

static void
add_child_attrs (CtkTextLayout      *layout,
                 CtkTextLineDisplay *display G_GNUC_UNUSED,
                 CtkTextAttributes  *style G_GNUC_UNUSED,
                 CtkTextLineSegment *seg,
                 PangoAttrList      *attrs,
                 gint                start)
{
  PangoAttribute *attr;
  PangoRectangle logical_rect;
  gint width, height;
  GSList *tmp_list;
  CtkWidget *widget = NULL;

  width = 1;
  height = 1;
  
  tmp_list = seg->body.child.widgets;
  while (tmp_list != NULL)
    {
      CtkWidget *child = tmp_list->data;

      if (_ctk_anchored_child_get_layout (child) == layout)
        {
          /* Found it */
          CtkRequisition req;

          ctk_widget_get_preferred_size (child, &req, NULL);

          width = req.width;
          height = req.height;

	  widget = child;
          
          break;
        }
      
      tmp_list = tmp_list->next;
    }

  if (tmp_list == NULL)
    {
      /* If tmp_list == NULL then there is no widget at this anchor in
       * this display; not an error. We make up an arbitrary size
       * to use, just so the programmer can see the blank spot.
       * We also put a NULL in the shaped objects list, to keep
       * the correspondence between the list and the shaped chars in
       * the layout. A bad hack, yes.
       */

      width = 30;
      height = 20;

      widget = NULL;
    }

  logical_rect.x = 0;
  logical_rect.y = -height * PANGO_SCALE;
  logical_rect.width = width * PANGO_SCALE;
  logical_rect.height = height * PANGO_SCALE;

  attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
					 widget, NULL, NULL);
  attr->start_index = start;
  attr->end_index = start + seg->byte_count;
  pango_attr_list_insert (attrs, attr);
}

/*
 * get_block_cursor:
 * @layout: a #CtkTextLayout
 * @display: a #CtkTextLineDisplay
 * @insert_iter: iter pointing to the cursor location
 * @insert_index: cursor offset in the @display’s layout, it may
 * be different from @insert_iter’s offset in case when preedit
 * string is present.
 * @pos: location to store cursor position
 * @cursor_at_line_end: whether cursor is at the end of line
 *
 * Checks whether layout should display block cursor at given position.
 * For this layout must be in overwrite mode and text at @insert_iter 
 * must be editable.
 */
static gboolean
get_block_cursor (CtkTextLayout      *layout,
		  CtkTextLineDisplay *display,
		  const CtkTextIter  *insert_iter,
		  gint                insert_index,
		  CdkRectangle       *pos,
		  gboolean           *cursor_at_line_end)
{
  PangoRectangle pango_pos;

  if (layout->overwrite_mode &&
      ctk_text_iter_editable (insert_iter, TRUE) &&
      _ctk_text_util_get_block_cursor_location (display->layout,
						insert_index,
						&pango_pos,
    					        cursor_at_line_end))
    {
      if (pos)
	{
	  pos->x = PANGO_PIXELS (pango_pos.x);
	  pos->y = PANGO_PIXELS (pango_pos.y);
	  pos->width = PANGO_PIXELS (pango_pos.width);
	  pos->height = PANGO_PIXELS (pango_pos.height);
	}

      return TRUE;
    }
  else
    return FALSE;
}

static void
add_cursor (CtkTextLayout      *layout,
            CtkTextLineDisplay *display,
            CtkTextLineSegment *seg,
            gint                start)
{
  /* Hide insertion cursor when we have a selection or the layout
   * user has hidden the cursor.
   */
  if (_ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
                                     seg->body.mark.obj) &&
      (!layout->cursor_visible ||
       ctk_text_buffer_get_selection_bounds (layout->buffer, NULL, NULL)))
    return;

  if (layout->overwrite_mode &&
      _ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
				      seg->body.mark.obj))
    {
      CtkTextIter iter;
      gboolean cursor_at_line_end;

      _ctk_text_btree_get_iter_at_mark (_ctk_text_buffer_get_btree (layout->buffer),
					&iter, seg->body.mark.obj);

      if (get_block_cursor (layout, display, &iter, start,
			    &display->block_cursor,
			    &cursor_at_line_end))
	{
	  display->has_block_cursor = TRUE;
	  display->cursor_at_line_end = cursor_at_line_end;
	  return;
	}
    }

  if (!display->cursors)
    display->cursors = g_array_new (FALSE, FALSE, sizeof(int));

  display->cursors = g_array_append_val (display->cursors, start);
}

static gboolean
is_shape (PangoLayoutRun *run)
{
  GSList *tmp_list = run->item->analysis.extra_attrs;
    
  while (tmp_list)
    {
      PangoAttribute *attr = tmp_list->data;

      if (attr->klass->type == PANGO_ATTR_SHAPE)
        return TRUE;

      tmp_list = tmp_list->next;
    }

  return FALSE;
}

static void
allocate_child_widgets (CtkTextLayout      *text_layout,
                        CtkTextLineDisplay *display)
{
  PangoLayout *layout = display->layout;
  PangoLayoutIter *run_iter;

  run_iter = pango_layout_get_iter (layout);
  do
    {
      PangoLayoutRun *run = pango_layout_iter_get_run_readonly (run_iter);

      if (run && is_shape (run))
        {
          gint byte_index;
          CtkTextIter text_iter;
          CtkTextChildAnchor *anchor = NULL;
          GList *widgets = NULL;
          GList *l;

          /* The pango iterator iterates in visual order.
           * We use the byte index to find the child widget.
           */
          byte_index = pango_layout_iter_get_index (run_iter);
          line_display_index_to_iter (text_layout, display, &text_iter, byte_index, 0);
          anchor = ctk_text_iter_get_child_anchor (&text_iter);
	  if (anchor)
            widgets = ctk_text_child_anchor_get_widgets (anchor);

          for (l = widgets; l; l = l->next)
            {
              PangoRectangle extents;
              CtkWidget *child = l->data;

              if (_ctk_anchored_child_get_layout (child) == text_layout)
                {

                  /* We emit "allocate_child" with the x,y of
                   * the widget with respect to the top of the line
                   * and the left side of the buffer
                   */
                  pango_layout_iter_get_run_extents (run_iter,
                                                     NULL,
                                                     &extents);

                  g_signal_emit (text_layout,
                                 signals[ALLOCATE_CHILD],
                                 0,
                                 child,
                                 PANGO_PIXELS (extents.x) + display->x_offset,
                                 PANGO_PIXELS (extents.y) + display->top_margin);
                }
            }

          g_list_free (widgets);
        }
    }
  while (pango_layout_iter_next_run (run_iter));

  pango_layout_iter_free (run_iter);
}

static void
convert_color (CdkRGBA        *result,
	       PangoAttrColor *attr)
{
  result->red = attr->color.red / 65535.;
  result->blue = attr->color.blue / 65535.;
  result->green = attr->color.green / 65535.;
  result->alpha = 1;
}

/* This function is used to convert the preedit string attributes, which are
 * standard PangoAttributes, into the custom attributes used by the text
 * widget and insert them into a attr list with a given offset.
 */
static void
add_preedit_attrs (CtkTextLayout     *layout,
		   CtkTextAttributes *style,
		   PangoAttrList     *attrs,
		   gint               offset,
		   gboolean           size_only)
{
  PangoAttrIterator *iter = pango_attr_list_get_iterator (layout->preedit_attrs);

  do
    {
      CtkTextAppearance appearance = style->appearance;
      PangoFontDescription *font_desc = pango_font_description_copy_static (style->font);
      PangoAttribute *insert_attr;
      GSList *extra_attrs = NULL;
      GSList *tmp_list;
      PangoLanguage *language;
      gint start, end;

      pango_attr_iterator_range (iter, &start, &end);

      if (end == G_MAXINT)
	end = layout->preedit_len;
      
      if (end == start)
	continue;

      pango_attr_iterator_get_font (iter, font_desc, &language, &extra_attrs);

      if (appearance.rgba[0])
	appearance.rgba[0] = cdk_rgba_copy (appearance.rgba[0]);
      if (appearance.rgba[1])
	appearance.rgba[1] = cdk_rgba_copy (appearance.rgba[1]);
      
      tmp_list = extra_attrs;
      while (tmp_list)
	{
	  PangoAttribute *attr = tmp_list->data;
	  CdkRGBA rgba;
	  
	  switch (attr->klass->type)
	    {
	    case PANGO_ATTR_FOREGROUND:
	      convert_color (&rgba, (PangoAttrColor *)attr);
	      if (appearance.rgba[1])
		cdk_rgba_free (appearance.rgba[1]);
	      appearance.rgba[1] = cdk_rgba_copy (&rgba);
	      break;
	    case PANGO_ATTR_BACKGROUND:
	      convert_color (&rgba, (PangoAttrColor *)attr);
	      if (appearance.rgba[0])
		cdk_rgba_free (appearance.rgba[0]);
	      appearance.rgba[0] = cdk_rgba_copy (&rgba);
	      appearance.draw_bg = TRUE;
	      break;
	    case PANGO_ATTR_UNDERLINE:
	      appearance.underline = ((PangoAttrInt *)attr)->value;
	      break;
            case PANGO_ATTR_UNDERLINE_COLOR:
              convert_color (&rgba, (PangoAttrColor*)attr);
              CTK_TEXT_APPEARANCE_SET_UNDERLINE_RGBA_SET (&appearance, TRUE);
              CTK_TEXT_APPEARANCE_SET_UNDERLINE_RGBA (&appearance, &rgba);
	      break;
	    case PANGO_ATTR_STRIKETHROUGH:
	      appearance.strikethrough = ((PangoAttrInt *)attr)->value;
	      break;
            case PANGO_ATTR_STRIKETHROUGH_COLOR:
              convert_color (&rgba, (PangoAttrColor*)attr);
              CTK_TEXT_APPEARANCE_SET_STRIKETHROUGH_RGBA_SET (&appearance, TRUE);
              CTK_TEXT_APPEARANCE_SET_STRIKETHROUGH_RGBA (&appearance, &rgba);
            case PANGO_ATTR_RISE:
              appearance.rise = ((PangoAttrInt *)attr)->value;
              break;
	    default:
	      break;
	    }
	  
	  pango_attribute_destroy (attr);
	  tmp_list = tmp_list->next;
	}
      
      g_slist_free (extra_attrs);
      
      insert_attr = pango_attr_font_desc_new (font_desc);
      insert_attr->start_index = start + offset;
      insert_attr->end_index = end + offset;
      
      pango_attr_list_insert (attrs, insert_attr);

      if (language)
	{
	  insert_attr = pango_attr_language_new (language);
	  insert_attr->start_index = start + offset;
	  insert_attr->end_index = end + offset;
	  
	  pango_attr_list_insert (attrs, insert_attr);
	}

      add_generic_attrs (layout, &appearance, end - start,
                         attrs, start + offset,
                         size_only, TRUE);
      
      if (appearance.rgba[0])
	cdk_rgba_free (appearance.rgba[0]);
      if (appearance.rgba[1])
	cdk_rgba_free (appearance.rgba[1]);

      pango_font_description_free (font_desc);
    }
  while (pango_attr_iterator_next (iter));

  pango_attr_iterator_destroy (iter);
}

/* Iterate over the line and fill in display->cursors.
 * It’s a stripped copy of ctk_text_layout_get_line_display() */
static void
update_text_display_cursors (CtkTextLayout      *layout,
			     CtkTextLine        *line,
			     CtkTextLineDisplay *display)
{
  CtkTextLineSegment *seg;
  CtkTextIter iter;
  gint layout_byte_offset, buffer_byte_offset;
  GSList *cursor_byte_offsets = NULL;
  GSList *cursor_segs = NULL;
  GSList *tmp_list1, *tmp_list2;

  if (!display->cursors_invalid)
    return;

  display->cursors_invalid = FALSE;

  /* Special-case optimization for completely
   * invisible lines; makes it faster to deal
   * with sequences of invisible lines.
   */
  if (totally_invisible_line (layout, line, &iter))
    return;

  /* Iterate over segments */
  layout_byte_offset = 0; /* position in the layout text (includes preedit, does not include invisible text) */
  buffer_byte_offset = 0; /* position in the buffer line */
  seg = _ctk_text_iter_get_any_segment (&iter);
  while (seg != NULL)
    {
      /* Displayable segments */
      if (seg->type == &ctk_text_char_type ||
          seg->type == &ctk_text_pixbuf_type ||
          seg->type == &ctk_text_child_type)
        {
          ctk_text_layout_get_iter_at_line (layout, &iter, line,
                                            buffer_byte_offset);

          if (!_ctk_text_btree_char_is_invisible (&iter))
            layout_byte_offset += seg->byte_count;

	  buffer_byte_offset += seg->byte_count;
        }

      /* Marks */
      else if (seg->type == &ctk_text_right_mark_type ||
               seg->type == &ctk_text_left_mark_type)
        {
	  gint cursor_offset = 0;

	  /* At the insertion point, add the preedit string, if any */

	  if (_ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
					      seg->body.mark.obj))
	    {
	      display->insert_index = layout_byte_offset;

	      if (layout->preedit_len > 0)
		{
		  layout_byte_offset += layout->preedit_len;
                  /* DO NOT increment the buffer byte offset for preedit */
		  cursor_offset = layout->preedit_cursor - layout->preedit_len;
		}
	    }

          /* Display visible marks */

          if (seg->body.mark.visible)
            {
              cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
                                                     GINT_TO_POINTER (layout_byte_offset + cursor_offset));
              cursor_segs = g_slist_prepend (cursor_segs, seg);
            }
        }

      /* Toggles */
      else if (seg->type == &ctk_text_toggle_on_type ||
               seg->type == &ctk_text_toggle_off_type)
        {
        }

      else
        g_error ("Unknown segment type: %s", seg->type->name);

      seg = seg->next;
    }

  tmp_list1 = cursor_byte_offsets;
  tmp_list2 = cursor_segs;
  while (tmp_list1)
    {
      add_cursor (layout, display, tmp_list2->data,
                  GPOINTER_TO_INT (tmp_list1->data));
      tmp_list1 = tmp_list1->next;
      tmp_list2 = tmp_list2->next;
    }
  g_slist_free (cursor_byte_offsets);
  g_slist_free (cursor_segs);
}

/* Same as _ctk_text_btree_get_tags(), except it returns GPtrArray,
 * to be used in ctk_text_layout_get_line_display(). */
static GPtrArray *
get_tags_array_at_iter (CtkTextIter *iter)
{
  CtkTextTag **tags;
  GPtrArray *array = NULL;
  gint n_tags;

  tags = _ctk_text_btree_get_tags (iter, &n_tags);

  if (n_tags > 0)
    {
      array = g_ptr_array_sized_new (n_tags);
      g_ptr_array_set_size (array, n_tags);
      memcpy (array->pdata, tags, n_tags * sizeof (CtkTextTag*));
    }

  g_free (tags);
  return array;
}

/* Add the tag to the array if it's not there already, and remove
 * it otherwise. It keeps the array sorted by tags priority. */
static GPtrArray *
tags_array_toggle_tag (GPtrArray  *array,
		       CtkTextTag *tag)
{
  gint pos;
  CtkTextTag **tags;

  if (array == NULL)
    array = g_ptr_array_new ();

  tags = (CtkTextTag**) array->pdata;

  for (pos = 0; pos < array->len && tags[pos]->priv->priority < tag->priv->priority; pos++) ;

  if (pos < array->len && tags[pos] == tag)
    g_ptr_array_remove_index (array, pos);
  else
    {
      g_ptr_array_set_size (array, array->len + 1);
      if (pos < array->len - 1)
	memmove (array->pdata + pos + 1, array->pdata + pos,
		 (array->len - pos - 1) * sizeof (CtkTextTag*));
      array->pdata[pos] = tag;
    }

  return array;
}

CtkTextLineDisplay *
ctk_text_layout_get_line_display (CtkTextLayout *layout,
                                  CtkTextLine   *line,
                                  gboolean       size_only)
{
  CtkTextLayoutPrivate *priv = CTK_TEXT_LAYOUT_GET_PRIVATE (layout);
  CtkTextLineDisplay *display;
  CtkTextLineSegment *seg;
  CtkTextIter iter;
  CtkTextAttributes *style;
  gchar *text;
  gint text_pixel_width;
  PangoAttrList *attrs;
  gint text_allocated, layout_byte_offset, buffer_byte_offset;
  PangoRectangle extents;
  gboolean para_values_set = FALSE;
  GSList *cursor_byte_offsets = NULL;
  GSList *cursor_segs = NULL;
  GSList *tmp_list1, *tmp_list2;
  gboolean saw_widget = FALSE;
  PangoDirection base_dir;
  GPtrArray *tags;
  gboolean initial_toggle_segments;
  gint h_margin;
  gint h_padding;
  
  g_return_val_if_fail (line != NULL, NULL);

  if (layout->one_display_cache)
    {
      if (line == layout->one_display_cache->line &&
          (size_only || !layout->one_display_cache->size_only))
	{
	  if (!size_only)
            update_text_display_cursors (layout, line, layout->one_display_cache);
	  return layout->one_display_cache;
	}
      else
        {
          CtkTextLineDisplay *tmp_display = layout->one_display_cache;
          layout->one_display_cache = NULL;
          ctk_text_layout_free_line_display (layout, tmp_display);
        }
    }

  DV (g_print ("creating one line display cache (%s)\n", G_STRLOC));

  display = g_slice_new0 (CtkTextLineDisplay);

  display->size_only = size_only;
  display->line = line;
  display->insert_index = -1;

  /* Special-case optimization for completely
   * invisible lines; makes it faster to deal
   * with sequences of invisible lines.
   */
  if (totally_invisible_line (layout, line, &iter))
    {
      if (display->direction == CTK_TEXT_DIR_RTL)
	display->layout = pango_layout_new (layout->rtl_context);
      else
	display->layout = pango_layout_new (layout->ltr_context);
      
      return display;
    }

  /* Find the bidi base direction */
  base_dir = line->dir_propagated_forward;
  if (base_dir == PANGO_DIRECTION_NEUTRAL)
    base_dir = line->dir_propagated_back;

  if (line == priv->cursor_line &&
      line->dir_strong == PANGO_DIRECTION_NEUTRAL)
    {
      base_dir = (layout->keyboard_direction == CTK_TEXT_DIR_LTR) ?
	 PANGO_DIRECTION_LTR : PANGO_DIRECTION_RTL;
    }
  
  /* Allocate space for flat text for buffer
   */
  text_allocated = _ctk_text_line_byte_count (line);
  text = g_malloc (text_allocated);

  attrs = pango_attr_list_new ();

  /* Iterate over segments, creating display chunks for them, and updating the tags array. */
  layout_byte_offset = 0; /* current length of layout text (includes preedit, does not include invisible text) */
  buffer_byte_offset = 0; /* position in the buffer line */
  seg = _ctk_text_iter_get_any_segment (&iter);
  tags = get_tags_array_at_iter (&iter);
  initial_toggle_segments = TRUE;
  while (seg != NULL)
    {
      /* Displayable segments */
      if (seg->type == &ctk_text_char_type ||
          seg->type == &ctk_text_pixbuf_type ||
          seg->type == &ctk_text_child_type)
        {
          style = get_style (layout, tags);
	  initial_toggle_segments = FALSE;

          /* We have to delay setting the paragraph values until we
           * hit the first pixbuf or text segment because toggles at
           * the beginning of the paragraph should affect the
           * paragraph-global values
           */
          if (!para_values_set)
            {
              set_para_values (layout, base_dir, style, display);
              para_values_set = TRUE;
            }

          /* First see if the chunk is invisible, and ignore it if so. Tk
           * looked at tabs, wrap mode, etc. before doing this, but
           * that made no sense to me, so I am just skipping the
           * invisible chunks
           */
          if (!style->invisible)
            {
              if (seg->type == &ctk_text_char_type)
                {
                  /* We don't want to split segments because of marks,
                   * so we scan forward for more segments only
                   * separated from us by marks. In theory, we should
                   * also merge segments with identical styles, even
                   * if there are toggles in-between
                   */

                  gint bytes = 0;
 		  CtkTextLineSegment *prev_seg = NULL;
  
 		  while (seg)
                    {
                      if (seg->type == &ctk_text_char_type)
                        {
                          memcpy (text + layout_byte_offset, seg->body.chars, seg->byte_count);
                          layout_byte_offset += seg->byte_count;
                          buffer_byte_offset += seg->byte_count;
                          bytes += seg->byte_count;
                        }
 		      else if (seg->type == &ctk_text_right_mark_type ||
 			       seg->type == &ctk_text_left_mark_type)
                        {
 			  /* If we have preedit string, break out of this loop - we'll almost
 			   * certainly have different attributes on the preedit string
 			   */

 			  if (layout->preedit_len > 0 &&
 			      _ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
 							     seg->body.mark.obj))
			    break;

 			  if (seg->body.mark.visible)
 			    {
			      cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets, GINT_TO_POINTER (layout_byte_offset));
			      cursor_segs = g_slist_prepend (cursor_segs, seg);
			      if (_ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
								  seg->body.mark.obj))
				display->insert_index = layout_byte_offset;
			    }
                        }
		      else
			break;

 		      prev_seg = seg;
                      seg = seg->next;
                    }

 		  seg = prev_seg; /* Back up one */
                  add_generic_attrs (layout, &style->appearance,
                                     bytes,
                                     attrs, layout_byte_offset - bytes,
                                     size_only, TRUE);
                  add_text_attrs (layout, style, bytes, attrs,
                                  layout_byte_offset - bytes, size_only);
                }
              else if (seg->type == &ctk_text_pixbuf_type)
                {
                  add_generic_attrs (layout,
                                     &style->appearance,
                                     seg->byte_count,
                                     attrs, layout_byte_offset,
                                     size_only, FALSE);
                  add_pixbuf_attrs (layout, display, style,
                                    seg, attrs, layout_byte_offset);
                  memcpy (text + layout_byte_offset, _ctk_text_unknown_char_utf8,
                          seg->byte_count);
                  layout_byte_offset += seg->byte_count;
                  buffer_byte_offset += seg->byte_count;
                }
              else if (seg->type == &ctk_text_child_type)
                {
                  saw_widget = TRUE;
                  
                  add_generic_attrs (layout, &style->appearance,
                                     seg->byte_count,
                                     attrs, layout_byte_offset,
                                     size_only, FALSE);
                  add_child_attrs (layout, display, style,
                                   seg, attrs, layout_byte_offset);
                  memcpy (text + layout_byte_offset, _ctk_text_unknown_char_utf8,
                          seg->byte_count);
                  layout_byte_offset += seg->byte_count;
                  buffer_byte_offset += seg->byte_count;
                }
              else
                {
                  /* We don't know this segment type */
                  g_assert_not_reached ();
                }
              
            } /* if (segment was visible) */
          else
            {
              /* Invisible segment */
              buffer_byte_offset += seg->byte_count;
            }

          release_style (layout, style);
        }

      /* Toggles */
      else if (seg->type == &ctk_text_toggle_on_type ||
               seg->type == &ctk_text_toggle_off_type)
        {
          /* Style may have changed, drop our
             current cached style */
          invalidate_cached_style (layout);
	  /* Add the tag only after we have seen some non-toggle non-mark segment,
	   * otherwise the tag is already accounted for by _ctk_text_btree_get_tags(). */
	  if (!initial_toggle_segments)
	    tags = tags_array_toggle_tag (tags, seg->body.toggle.info->tag);
        }

      /* Marks */
      else if (seg->type == &ctk_text_right_mark_type ||
               seg->type == &ctk_text_left_mark_type)
        {
	  gint cursor_offset = 0;
 	  
	  /* At the insertion point, add the preedit string, if any */
	  
	  if (_ctk_text_btree_mark_is_insert (_ctk_text_buffer_get_btree (layout->buffer),
					     seg->body.mark.obj))
	    {
	      display->insert_index = layout_byte_offset;
	      
	      if (layout->preedit_len > 0)
		{
		  text_allocated += layout->preedit_len;
		  text = g_realloc (text, text_allocated);

		  style = get_style (layout, tags);
		  add_preedit_attrs (layout, style, attrs, layout_byte_offset, size_only);
		  release_style (layout, style);
                  
		  memcpy (text + layout_byte_offset, layout->preedit_string, layout->preedit_len);
		  layout_byte_offset += layout->preedit_len;
                  /* DO NOT increment the buffer byte offset for preedit */
                  
		  cursor_offset = layout->preedit_cursor - layout->preedit_len;
		}
	    }
	  

          /* Display visible marks */

          if (seg->body.mark.visible)
            {
              cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
                                                     GINT_TO_POINTER (layout_byte_offset + cursor_offset));
              cursor_segs = g_slist_prepend (cursor_segs, seg);
            }
        }

      else
        g_error ("Unknown segment type: %s", seg->type->name);

      seg = seg->next;
    }
  
  if (!para_values_set)
    {
      style = get_style (layout, tags);
      set_para_values (layout, base_dir, style, display);
      release_style (layout, style);
    }
  
  /* Pango doesn't want the trailing paragraph delimiters */

  {
    /* Only one character has type G_UNICODE_PARAGRAPH_SEPARATOR in
     * Unicode 3.0; update this if that changes.
     */
#define PARAGRAPH_SEPARATOR 0x2029
    gunichar ch = 0;

    if (layout_byte_offset > 0)
      {
        const char *prev = g_utf8_prev_char (text + layout_byte_offset);
        ch = g_utf8_get_char (prev);
        if (ch == PARAGRAPH_SEPARATOR || ch == '\r' || ch == '\n')
          layout_byte_offset = prev - text; /* chop off */

        if (ch == '\n' && layout_byte_offset > 0)
          {
            /* Possibly chop a CR as well */
            prev = g_utf8_prev_char (text + layout_byte_offset);
            if (*prev == '\r')
              --layout_byte_offset;
          }
      }
  }
  
  pango_layout_set_text (display->layout, text, layout_byte_offset);
  pango_layout_set_attributes (display->layout, attrs);

  tmp_list1 = cursor_byte_offsets;
  tmp_list2 = cursor_segs;
  while (tmp_list1)
    {
      add_cursor (layout, display, tmp_list2->data,
                  GPOINTER_TO_INT (tmp_list1->data));
      tmp_list1 = tmp_list1->next;
      tmp_list2 = tmp_list2->next;
    }
  g_slist_free (cursor_byte_offsets);
  g_slist_free (cursor_segs);

  pango_layout_get_extents (display->layout, NULL, &extents);

  text_pixel_width = PIXEL_BOUND (extents.width);
  display->width = text_pixel_width + display->left_margin + display->right_margin;

  h_margin = display->left_margin + display->right_margin;
  h_padding = layout->left_padding + layout->right_padding;

  display->width = text_pixel_width + h_margin + h_padding;
  display->height += PANGO_PIXELS (extents.height);

  /* If we aren't wrapping, we need to do the alignment of each
   * paragraph ourselves.
   */
  if (pango_layout_get_width (display->layout) < 0)
    {
      gint excess = display->total_width - text_pixel_width;

      switch (pango_layout_get_alignment (display->layout))
	{
	case PANGO_ALIGN_LEFT:
	  break;
	case PANGO_ALIGN_CENTER:
	  display->x_offset += excess / 2;
	  break;
	case PANGO_ALIGN_RIGHT:
	  display->x_offset += excess;
	  break;
	}
    }
  
  /* Free this if we aren't in a loop */
  if (layout->wrap_loop_count == 0)
    invalidate_cached_style (layout);

  g_free (text);
  pango_attr_list_unref (attrs);
  if (tags != NULL)
    g_ptr_array_free (tags, TRUE);

  layout->one_display_cache = display;

  if (saw_widget)
    allocate_child_widgets (layout, display);
  
  return display;
}

void
ctk_text_layout_free_line_display (CtkTextLayout      *layout,
                                   CtkTextLineDisplay *display)
{
  if (display != layout->one_display_cache)
    {
      if (display->layout)
        g_object_unref (display->layout);

      if (display->cursors)
        g_array_free (display->cursors, TRUE);

      if (display->pg_bg_color)
        cdk_color_free (display->pg_bg_color);

      if (display->pg_bg_rgba)
        cdk_rgba_free (display->pg_bg_rgba);

      g_slice_free (CtkTextLineDisplay, display);
    }
}

/* Functions to convert iter <=> index for the line of a CtkTextLineDisplay
 * taking into account the preedit string and invisible text if necessary.
 */
static gint
line_display_iter_to_index (CtkTextLayout      *layout,
			    CtkTextLineDisplay *display,
			    const CtkTextIter  *iter)
{
  gint index;

  g_return_val_if_fail (_ctk_text_iter_get_text_line (iter) == display->line, 0);

  index = ctk_text_iter_get_visible_line_index (iter);
  
  if (layout->preedit_len > 0 && display->insert_index >= 0)
    {
      if (index >= display->insert_index)
	index += layout->preedit_len;
    }

  return index;
}

static void
line_display_index_to_iter (CtkTextLayout      *layout,
			    CtkTextLineDisplay *display,
			    CtkTextIter        *iter,
			    gint                index,
			    gint                trailing)
{
  g_return_if_fail (!_ctk_text_line_is_last (display->line,
                                             _ctk_text_buffer_get_btree (layout->buffer)));
  
  if (layout->preedit_len > 0 && display->insert_index >= 0)
    {
      if (index >= display->insert_index + layout->preedit_len)
	index -= layout->preedit_len;
      else if (index > display->insert_index)
	{
	  index = display->insert_index;
	  trailing = 0;
	}
    }

  ctk_text_layout_get_iter_at_line (layout, iter, display->line, 0);

  ctk_text_iter_set_visible_line_index (iter, index);
  
  if (_ctk_text_iter_get_text_line (iter) != display->line)
    {
      /* Clamp to end of line - really this clamping should have been done
       * before here, maybe in Pango, this is a broken band-aid I think
       */
      ctk_text_layout_get_iter_at_line (layout, iter, display->line, 0);
      if (!ctk_text_iter_ends_line (iter))
        ctk_text_iter_forward_to_line_end (iter);
    }
  
  ctk_text_iter_forward_chars (iter, trailing);
}

static void
get_line_at_y (CtkTextLayout *layout,
               gint           y,
               CtkTextLine  **line,
               gint          *line_top)
{
  if (y < 0)
    y = 0;
  if (y > layout->height)
    y = layout->height;

  *line = _ctk_text_btree_find_line_by_y (_ctk_text_buffer_get_btree (layout->buffer),
                                         layout, y, line_top);
  if (*line == NULL)
    {
      *line = _ctk_text_btree_get_end_iter_line (_ctk_text_buffer_get_btree (layout->buffer));
      
      if (line_top)
        *line_top =
          _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
                                        *line, layout);
    }
}

/**
 * ctk_text_layout_get_line_at_y:
 * @layout: a #CtkLayout
 * @target_iter: the iterator in which the result is stored
 * @y: the y positition
 * @line_top: location to store the y coordinate of the
 *            top of the line. (Can by %NULL)
 *
 * Get the iter at the beginning of the line which is displayed
 * at the given y.
 */
void
ctk_text_layout_get_line_at_y (CtkTextLayout *layout,
                               CtkTextIter   *target_iter,
                               gint           y,
                               gint          *line_top)
{
  CtkTextLine *line;

  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (target_iter != NULL);

  get_line_at_y (layout, y, &line, line_top);
  ctk_text_layout_get_iter_at_line (layout, target_iter, line, 0);
}

gboolean
ctk_text_layout_get_iter_at_pixel (CtkTextLayout *layout,
                                   CtkTextIter   *target_iter,
                                   gint           x,
                                   gint           y)
{
  gint trailing;
  gboolean inside;

  inside = ctk_text_layout_get_iter_at_position (layout, target_iter, &trailing, x, y);

  ctk_text_iter_forward_chars (target_iter, trailing);

  return inside;
}

gboolean
ctk_text_layout_get_iter_at_position (CtkTextLayout *layout,
                                      CtkTextIter   *target_iter,
                                      gint          *trailing,
                                      gint           x,
                                      gint           y)
{
  CtkTextLine *line;
  gint byte_index;
  gint line_top;
  CtkTextLineDisplay *display;
  gboolean inside;

  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);
  g_return_val_if_fail (target_iter != NULL, FALSE);

  get_line_at_y (layout, y, &line, &line_top);

  display = ctk_text_layout_get_line_display (layout, line, FALSE);

  x -= display->x_offset;
  y -= line_top + display->top_margin;

  /* If we are below the layout, position the cursor at the last character
   * of the line.
   */
  if (y > display->height - display->top_margin - display->bottom_margin)
    {
      byte_index = _ctk_text_line_byte_count (line);
      if (trailing)
        *trailing = 0;

      inside = FALSE;
    }
  else
    {
       /* Ignore the "outside" return value from pango. Pango is doing
        * the right thing even if we are outside the layout in the
        * x-direction.
        */
      inside = pango_layout_xy_to_index (display->layout, x * PANGO_SCALE, y * PANGO_SCALE,
                                         &byte_index, trailing);
    }

  line_display_index_to_iter (layout, display, target_iter, byte_index, 0);

  ctk_text_layout_free_line_display (layout, display);

  return inside;
}


/**
 * ctk_text_layout_get_cursor_locations:
 * @layout: a #CtkTextLayout
 * @iter: a #CtkTextIter
 * @strong_pos: (out) (optional): location to store the strong cursor position, or %NULL
 * @weak_pos: (out) (optional): location to store the weak cursor position, or %NULL
 *
 * Given an iterator within a text layout, determine the positions of the
 * strong and weak cursors if the insertion point is at that
 * iterator. The position of each cursor is stored as a zero-width
 * rectangle. The strong cursor location is the location where
 * characters of the directionality equal to the base direction of the
 * paragraph are inserted.  The weak cursor location is the location
 * where characters of the directionality opposite to the base
 * direction of the paragraph are inserted.
 **/
void
ctk_text_layout_get_cursor_locations (CtkTextLayout  *layout,
                                      CtkTextIter    *iter,
                                      CdkRectangle   *strong_pos,
                                      CdkRectangle   *weak_pos)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_top;
  gint index;
  CtkTextIter insert_iter;

  PangoRectangle pango_strong_pos;
  PangoRectangle pango_weak_pos;

  g_return_if_fail (layout != NULL);
  g_return_if_fail (iter != NULL);

  line = _ctk_text_iter_get_text_line (iter);
  display = ctk_text_layout_get_line_display (layout, line, FALSE);
  index = line_display_iter_to_index (layout, display, iter);
  
  line_top = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
                                           line, layout);
  
  ctk_text_buffer_get_iter_at_mark (layout->buffer, &insert_iter,
                                    ctk_text_buffer_get_insert (layout->buffer));

  if (ctk_text_iter_equal (iter, &insert_iter))
    index += layout->preedit_cursor - layout->preedit_len;
  
  pango_layout_get_cursor_pos (display->layout, index,
			       strong_pos ? &pango_strong_pos : NULL,
			       weak_pos ? &pango_weak_pos : NULL);

  if (strong_pos)
    {
      strong_pos->x = display->x_offset + pango_strong_pos.x / PANGO_SCALE;
      strong_pos->y = line_top + display->top_margin + pango_strong_pos.y / PANGO_SCALE;
      strong_pos->width = 0;
      strong_pos->height = pango_strong_pos.height / PANGO_SCALE;
    }

  if (weak_pos)
    {
      weak_pos->x = display->x_offset + pango_weak_pos.x / PANGO_SCALE;
      weak_pos->y = line_top + display->top_margin + pango_weak_pos.y / PANGO_SCALE;
      weak_pos->width = 0;
      weak_pos->height = pango_weak_pos.height / PANGO_SCALE;
    }

  ctk_text_layout_free_line_display (layout, display);
}

/**
 * _ctk_text_layout_get_block_cursor:
 * @layout: a #CtkTextLayout
 * @pos: a #CdkRectangle to store block cursor position
 *
 * If layout is to display a block cursor, calculates its position
 * and returns %TRUE. Otherwise it returns %FALSE. In case when
 * cursor is visible, it simply returns the position stored in
 * the line display, otherwise it has to compute the position
 * (see get_block_cursor()).
 **/
gboolean
_ctk_text_layout_get_block_cursor (CtkTextLayout *layout,
				   CdkRectangle  *pos)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  CtkTextIter iter;
  CdkRectangle rect;
  gboolean block = FALSE;

  g_return_val_if_fail (layout != NULL, FALSE);

  ctk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
                                    ctk_text_buffer_get_insert (layout->buffer));
  line = _ctk_text_iter_get_text_line (&iter);
  display = ctk_text_layout_get_line_display (layout, line, FALSE);

  if (display->has_block_cursor)
    {
      block = TRUE;
      rect = display->block_cursor;
    }
  else
    {
      gint index = display->insert_index;

      if (index < 0)
        index = ctk_text_iter_get_line_index (&iter);

      if (get_block_cursor (layout, display, &iter, index, &rect, NULL))
	block = TRUE;
    }

  if (block && pos)
    {
      gint line_top;

      line_top = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
						line, layout);

      *pos = rect;
      pos->x += display->x_offset;
      pos->y += line_top + display->top_margin;
    }

  ctk_text_layout_free_line_display (layout, display);
  return block;
}

/**
 * ctk_text_layout_get_line_yrange:
 * @layout: a #CtkTextLayout
 * @iter:   a #CtkTextIter
 * @y:      location to store the top of the paragraph in pixels,
 *          or %NULL.
 * @height  location to store the height of the paragraph in pixels,
 *          or %NULL.
 *
 * Find the range of y coordinates for the paragraph containing
 * the given iter.
 **/
void
ctk_text_layout_get_line_yrange (CtkTextLayout     *layout,
                                 const CtkTextIter *iter,
                                 gint              *y,
                                 gint              *height)
{
  CtkTextLine *line;

  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (_ctk_text_iter_get_btree (iter) == _ctk_text_buffer_get_btree (layout->buffer));

  line = _ctk_text_iter_get_text_line (iter);

  if (y)
    *y = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
                                       line, layout);
  if (height)
    {
      CtkTextLineData *line_data = _ctk_text_line_get_data (line, layout);
      if (line_data)
        *height = line_data->height;
      else
        *height = 0;
    }
}

void
ctk_text_layout_get_iter_location (CtkTextLayout     *layout,
                                   const CtkTextIter *iter,
                                   CdkRectangle      *rect)
{
  PangoRectangle pango_rect;
  CtkTextLine *line;
  CtkTextBTree *tree;
  CtkTextLineDisplay *display;
  gint byte_index;
  gint x_offset;
  
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (_ctk_text_iter_get_btree (iter) == _ctk_text_buffer_get_btree (layout->buffer));
  g_return_if_fail (rect != NULL);

  tree = _ctk_text_iter_get_btree (iter);
  line = _ctk_text_iter_get_text_line (iter);

  display = ctk_text_layout_get_line_display (layout, line, FALSE);

  rect->y = _ctk_text_btree_find_line_top (tree, line, layout);

  x_offset = display->x_offset * PANGO_SCALE;

  byte_index = ctk_text_iter_get_line_index (iter);
  
  pango_layout_index_to_pos (display->layout, byte_index, &pango_rect);
  
  rect->x = PANGO_PIXELS (x_offset + pango_rect.x);
  rect->y += PANGO_PIXELS (pango_rect.y) + display->top_margin;
  rect->width = PANGO_PIXELS (pango_rect.width);
  rect->height = PANGO_PIXELS (pango_rect.height);

  ctk_text_layout_free_line_display (layout, display);
}

/* FFIXX */

/* Find the iter for the logical beginning of the first display line whose
 * top y is >= y. If none exists, move the iter to the logical beginning
 * of the last line in the buffer.
 */
static void
find_display_line_below (CtkTextLayout *layout,
                         CtkTextIter   *iter,
                         gint           y)
{
  CtkTextLine *line, *next;
  CtkTextLine *found_line = NULL;
  gint line_top;
  gint found_byte = 0;

  line = _ctk_text_btree_find_line_by_y (_ctk_text_buffer_get_btree (layout->buffer),
                                        layout, y, &line_top);
  if (!line)
    {
      line =
        _ctk_text_btree_get_end_iter_line (_ctk_text_buffer_get_btree (layout->buffer));

      line_top =
        _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer),
                                      line, layout);
    }

  while (line && !found_line)
    {
      CtkTextLineDisplay *display = ctk_text_layout_get_line_display (layout, line, FALSE);
      PangoLayoutIter *layout_iter;

      layout_iter = pango_layout_get_iter (display->layout);

      line_top += display->top_margin;

      do
        {
          gint first_y, last_y;
          PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);

          found_byte = layout_line->start_index;
          
          if (line_top >= y)
            {
              found_line = line;
              break;
            }

          pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
          line_top += (last_y - first_y) / PANGO_SCALE;
        }
      while (pango_layout_iter_next_line (layout_iter));

      pango_layout_iter_free (layout_iter);
      
      line_top += display->bottom_margin;
      ctk_text_layout_free_line_display (layout, display);

      next = _ctk_text_line_next_excluding_last (line);
      if (!next)
        found_line = line;

      line = next;
    }

  ctk_text_layout_get_iter_at_line (layout, iter, found_line, found_byte);
}

/* Find the iter for the logical beginning of the last display line whose
 * top y is >= y. If none exists, move the iter to the logical beginning
 * of the first line in the buffer.
 */
static void
find_display_line_above (CtkTextLayout *layout,
                         CtkTextIter   *iter,
                         gint           y)
{
  CtkTextLine *line;
  CtkTextLine *found_line = NULL;
  gint line_top;
  gint found_byte = 0;

  line = _ctk_text_btree_find_line_by_y (_ctk_text_buffer_get_btree (layout->buffer), layout, y, &line_top);
  if (!line)
    {
      line = _ctk_text_btree_get_end_iter_line (_ctk_text_buffer_get_btree (layout->buffer));
      
      line_top = _ctk_text_btree_find_line_top (_ctk_text_buffer_get_btree (layout->buffer), line, layout);
    }

  while (line && !found_line)
    {
      CtkTextLineDisplay *display = ctk_text_layout_get_line_display (layout, line, FALSE);
      PangoRectangle logical_rect;
      PangoLayoutIter *layout_iter;
      gint tmp_top;

      layout_iter = pango_layout_get_iter (display->layout);
      
      line_top -= display->top_margin + display->bottom_margin;
      pango_layout_iter_get_layout_extents (layout_iter, NULL, &logical_rect);
      line_top -= logical_rect.height / PANGO_SCALE;

      tmp_top = line_top + display->top_margin;

      do
        {
          gint first_y, last_y;
          PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);

          found_byte = layout_line->start_index;

          pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
          
          tmp_top -= (last_y - first_y) / PANGO_SCALE;

          if (tmp_top < y)
            {
              found_line = line;
	      pango_layout_iter_free (layout_iter);
              goto done;
            }
        }
      while (pango_layout_iter_next_line (layout_iter));

      pango_layout_iter_free (layout_iter);
      
      ctk_text_layout_free_line_display (layout, display);

      line = _ctk_text_line_previous (line);
    }

 done:

  if (found_line)
    ctk_text_layout_get_iter_at_line (layout, iter, found_line, found_byte);
  else
    ctk_text_buffer_get_iter_at_offset (layout->buffer, iter, 0);
}

/**
 * ctk_text_layout_clamp_iter_to_vrange:
 * @layout: a #CtkTextLayout
 * @iter:   a #CtkTextIter
 * @top:    the top of the range
 * @bottom: the bottom the range
 *
 * If the iterator is not fully in the range @top <= y < @bottom,
 * then, if possible, move it the minimum distance so that the
 * iterator in this range.
 *
 * Returns: %TRUE if the iterator was moved, otherwise %FALSE.
 **/
gboolean
ctk_text_layout_clamp_iter_to_vrange (CtkTextLayout *layout,
                                      CtkTextIter   *iter,
                                      gint           top,
                                      gint           bottom)
{
  CdkRectangle iter_rect;

  ctk_text_layout_get_iter_location (layout, iter, &iter_rect);

  /* If the iter is at least partially above the range, put the iter
   * at the first fully visible line after the range.
   */
  if (iter_rect.y < top)
    {
      find_display_line_below (layout, iter, top);

      return TRUE;
    }
  /* Otherwise, if the iter is at least partially below the screen, put the
   * iter on the last logical position of the last completely visible
   * line on screen
   */
  else if (iter_rect.y + iter_rect.height > bottom)
    {
      find_display_line_above (layout, iter, bottom);

      return TRUE;
    }
  else
    return FALSE;
}

/**
 * ctk_text_layout_move_iter_to_previous_line:
 * @layout: a #CtkLayout
 * @iter:   a #CtkTextIter
 *
 * Move the iterator to the beginning of the previous line. The lines
 * of a wrapped paragraph are treated as distinct for this operation.
 **/
gboolean
ctk_text_layout_move_iter_to_previous_line (CtkTextLayout *layout,
                                            CtkTextIter   *iter)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_byte;
  GSList *tmp_list;
  PangoLayoutLine *layout_line;
  CtkTextIter orig;
  gboolean update_byte = FALSE;
  
  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  orig = *iter;


  line = _ctk_text_iter_get_text_line (iter);
  display = ctk_text_layout_get_line_display (layout, line, FALSE);
  line_byte = line_display_iter_to_index (layout, display, iter);

  /* If display->height == 0 then the line is invisible, so don't
   * move onto it.
   */
  while (display->height == 0)
    {
      CtkTextLine *prev_line;

      prev_line = _ctk_text_line_previous (line);

      if (prev_line == NULL)
        {
          line_display_index_to_iter (layout, display, iter, 0, 0);
          goto out;
        }

      ctk_text_layout_free_line_display (layout, display);

      line = prev_line;
      display = ctk_text_layout_get_line_display (layout, prev_line, FALSE);
      update_byte = TRUE;
    }
  
  tmp_list = pango_layout_get_lines_readonly (display->layout);
  layout_line = tmp_list->data;

  if (update_byte)
    {
      line_byte = layout_line->start_index + layout_line->length;
    }

  if (line_byte < layout_line->length || !tmp_list->next) /* first line of paragraph */
    {
      CtkTextLine *prev_line;

      prev_line = _ctk_text_line_previous (line);

      /* first line of the whole buffer, do not move the iter and return FALSE */
      if (prev_line == NULL)
        goto out;

      while (prev_line)
        {
          ctk_text_layout_free_line_display (layout, display);

          display = ctk_text_layout_get_line_display (layout, prev_line, FALSE);

          if (display->height > 0)
            {
              tmp_list = g_slist_last (pango_layout_get_lines_readonly (display->layout));
              layout_line = tmp_list->data;

              line_display_index_to_iter (layout, display, iter,
                                          layout_line->start_index + layout_line->length, 0);
              break;
            }

          prev_line = _ctk_text_line_previous (prev_line);
        }
    }
  else
    {
      gint prev_offset = layout_line->start_index;

      tmp_list = tmp_list->next;
      while (tmp_list)
        {
          layout_line = tmp_list->data;

          if (line_byte < layout_line->start_index + layout_line->length ||
              !tmp_list->next)
            {
 	      line_display_index_to_iter (layout, display, iter, prev_offset, 0);
              break;
            }

          prev_offset = layout_line->start_index;
          tmp_list = tmp_list->next;
        }
    }

 out:
  
  ctk_text_layout_free_line_display (layout, display);

  return
    !ctk_text_iter_equal (iter, &orig) &&
    !ctk_text_iter_is_end (iter);
}

/**
 * ctk_text_layout_move_iter_to_next_line:
 * @layout: a #CtkLayout
 * @iter:   a #CtkTextIter
 *
 * Move the iterator to the beginning of the next line. The
 * lines of a wrapped paragraph are treated as distinct for
 * this operation.
 **/
gboolean
ctk_text_layout_move_iter_to_next_line (CtkTextLayout *layout,
                                        CtkTextIter   *iter)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_byte;
  CtkTextIter orig;
  gboolean found = FALSE;
  gboolean found_after = FALSE;
  gboolean first = TRUE;

  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  orig = *iter;
  
  line = _ctk_text_iter_get_text_line (iter);

  while (line && !found_after)
    {
      GSList *tmp_list;

      display = ctk_text_layout_get_line_display (layout, line, FALSE);

      if (display->height == 0)
        goto next;
      
      if (first)
	{
	  line_byte = line_display_iter_to_index (layout, display, iter);
	  first = FALSE;
	}
      else
	line_byte = 0;
	
      tmp_list = pango_layout_get_lines_readonly (display->layout);
      while (tmp_list && !found_after)
        {
          PangoLayoutLine *layout_line = tmp_list->data;

          if (found)
            {
	      line_display_index_to_iter (layout, display, iter,
                                          layout_line->start_index, 0);
              found_after = TRUE;
            }
          else if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
            found = TRUE;
          
          tmp_list = tmp_list->next;
        }

    next:
      
      ctk_text_layout_free_line_display (layout, display);

      line = _ctk_text_line_next_excluding_last (line);
    }

  if (!found_after)
    ctk_text_buffer_get_end_iter (layout->buffer, iter);
  
  return
    !ctk_text_iter_equal (iter, &orig) &&
    !ctk_text_iter_is_end (iter);
}

/**
 * ctk_text_layout_move_iter_to_line_end:
 * @layout: a #CtkTextLayout
 * @direction: if negative, move to beginning of line, otherwise
               move to end of line.
 *
 * Move to the beginning or end of a display line.
 **/
gboolean
ctk_text_layout_move_iter_to_line_end (CtkTextLayout *layout,
                                       CtkTextIter   *iter,
                                       gint           direction)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_byte;
  GSList *tmp_list;
  CtkTextIter orig;
  
  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  orig = *iter;
  
  line = _ctk_text_iter_get_text_line (iter);
  display = ctk_text_layout_get_line_display (layout, line, FALSE);
  line_byte = line_display_iter_to_index (layout, display, iter);

  tmp_list = pango_layout_get_lines_readonly (display->layout);
  while (tmp_list)
    {
      PangoLayoutLine *layout_line = tmp_list->data;

      if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
        {
 	  line_display_index_to_iter (layout, display, iter,
 				      direction < 0 ? layout_line->start_index : layout_line->start_index + layout_line->length,
 				      0);

          /* FIXME: As a bad hack, we move back one position when we
	   * are inside a paragraph to avoid going to next line on a
	   * forced break not at whitespace. Real fix is to keep track
	   * of whether marks are at leading or trailing edge?  */
          if (direction > 0 && layout_line->length > 0 && 
	      !ctk_text_iter_ends_line (iter) && 
	      !_ctk_text_btree_char_is_invisible (iter))
            ctk_text_iter_backward_char (iter);
          break;
        }
      
      tmp_list = tmp_list->next;
    }

  ctk_text_layout_free_line_display (layout, display);

  return
    !ctk_text_iter_equal (iter, &orig) &&
    !ctk_text_iter_is_end (iter);
}


/**
 * ctk_text_layout_iter_starts_line:
 * @layout: a #CtkTextLayout
 * @iter: iterator to test
 *
 * Tests whether an iterator is at the start of a display line.
 **/
gboolean
ctk_text_layout_iter_starts_line (CtkTextLayout       *layout,
                                  const CtkTextIter   *iter)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_byte;
  GSList *tmp_list;
  
  g_return_val_if_fail (CTK_IS_TEXT_LAYOUT (layout), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  line = _ctk_text_iter_get_text_line (iter);
  display = ctk_text_layout_get_line_display (layout, line, FALSE);
  line_byte = line_display_iter_to_index (layout, display, iter);

  tmp_list = pango_layout_get_lines_readonly (display->layout);
  while (tmp_list)
    {
      PangoLayoutLine *layout_line = tmp_list->data;

      if (line_byte < layout_line->start_index + layout_line->length ||
          !tmp_list->next)
        {
          /* We're located on this line or the para delimiters before
           * it
           */
          ctk_text_layout_free_line_display (layout, display);
          
          if (line_byte == layout_line->start_index)
            return TRUE;
          else
            return FALSE;
        }
      
      tmp_list = tmp_list->next;
    }

  g_assert_not_reached ();
  return FALSE;
}

void
ctk_text_layout_get_iter_at_line (CtkTextLayout  *layout,
                                  CtkTextIter    *iter,
                                  CtkTextLine    *line,
                                  gint            byte_offset)
{
  _ctk_text_btree_get_iter_at_line (_ctk_text_buffer_get_btree (layout->buffer),
                                    iter, line, byte_offset);
}

/**
 * ctk_text_layout_move_iter_to_x:
 * @layout: a #CtkTextLayout
 * @iter:   a #CtkTextIter
 * @x:      X coordinate
 *
 * Keeping the iterator on the same line of the layout, move it to the
 * specified X coordinate. The lines of a wrapped paragraph are
 * treated as distinct for this operation.
 **/
void
ctk_text_layout_move_iter_to_x (CtkTextLayout *layout,
                                CtkTextIter   *iter,
                                gint           x)
{
  CtkTextLine *line;
  CtkTextLineDisplay *display;
  gint line_byte;
  PangoLayoutIter *layout_iter;
  
  g_return_if_fail (CTK_IS_TEXT_LAYOUT (layout));
  g_return_if_fail (iter != NULL);

  line = _ctk_text_iter_get_text_line (iter);

  display = ctk_text_layout_get_line_display (layout, line, FALSE);
  line_byte = line_display_iter_to_index (layout, display, iter);

  layout_iter = pango_layout_get_iter (display->layout);

  do
    {
      PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);

      if (line_byte < layout_line->start_index + layout_line->length ||
          pango_layout_iter_at_last_line (layout_iter))
        {
          PangoRectangle logical_rect;
          gint byte_index, trailing;
          gint x_offset = display->x_offset * PANGO_SCALE;

          pango_layout_iter_get_line_extents (layout_iter, NULL, &logical_rect);

          pango_layout_line_x_to_index (layout_line,
                                        x * PANGO_SCALE - x_offset - logical_rect.x,
                                        &byte_index, &trailing);

 	  line_display_index_to_iter (layout, display, iter, byte_index, trailing);

          break;
        }
    }
  while (pango_layout_iter_next_line (layout_iter));

  pango_layout_iter_free (layout_iter);
  
  ctk_text_layout_free_line_display (layout, display);
}

/**
 * ctk_text_layout_move_iter_visually:
 * @layout:  a #CtkTextLayout
 * @iter:    a #CtkTextIter
 * @count:   number of characters to move (negative moves left, positive moves right)
 *
 * Move the iterator a given number of characters visually, treating
 * it as the strong cursor position. If @count is positive, then the
 * new strong cursor position will be @count positions to the right of
 * the old cursor position. If @count is negative then the new strong
 * cursor position will be @count positions to the left of the old
 * cursor position.
 *
 * In the presence of bidirection text, the correspondence
 * between logical and visual order will depend on the direction
 * of the current run, and there may be jumps when the cursor
 * is moved off of the end of a run.
 **/

gboolean
ctk_text_layout_move_iter_visually (CtkTextLayout *layout,
                                    CtkTextIter   *iter,
                                    gint           count)
{
  CtkTextLineDisplay *display = NULL;
  CtkTextIter orig;
  CtkTextIter lineiter;
  
  g_return_val_if_fail (layout != NULL, FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  orig = *iter;
  
  while (count != 0)
    {
      CtkTextLine *line = _ctk_text_iter_get_text_line (iter);
      gint line_byte;
      gint extra_back = 0;
      gboolean strong;

      int byte_count = _ctk_text_line_byte_count (line);

      int new_index;
      int new_trailing;

      if (!display)
	display = ctk_text_layout_get_line_display (layout, line, FALSE);

      if (layout->cursor_direction == CTK_TEXT_DIR_NONE)
	strong = TRUE;
      else
	strong = display->direction == layout->cursor_direction;

      line_byte = line_display_iter_to_index (layout, display, iter);

      if (count > 0)
        {
          pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, 1, &new_index, &new_trailing);
          count--;
        }
      else
        {
          pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, -1, &new_index, &new_trailing);
          count++;
        }

      /* We need to handle the preedit string specially. Well, we don't really need to
       * handle it specially, since hopefully calling ctk_im_context_reset() will
       * remove the preedit string; but if we start off in front of the preedit
       * string (logically) and end up in or on the back edge of the preedit string,
       * we should move the iter one place farther.
       */
      if (layout->preedit_len > 0 && display->insert_index >= 0)
	{
	  if (line_byte == display->insert_index + layout->preedit_len &&
	      new_index < display->insert_index + layout->preedit_len)
	    {
	      line_byte = display->insert_index;
	      extra_back = 1;
	    }
	}
      
      if (new_index < 0 || (new_index == 0 && extra_back))
        {
          do
            {
              line = _ctk_text_line_previous (line);
              if (!line)
                goto done;
            }
          while (totally_invisible_line (layout, line, &lineiter));
          
 	  ctk_text_layout_free_line_display (layout, display);
 	  display = ctk_text_layout_get_line_display (layout, line, FALSE);
          ctk_text_iter_forward_to_line_end (&lineiter);
          new_index = ctk_text_iter_get_visible_line_index (&lineiter);
        }
      else if (new_index > byte_count)
        {
          do
            {
              line = _ctk_text_line_next_excluding_last (line);
              if (!line)
                goto done;
            }
          while (totally_invisible_line (layout, line, &lineiter));

 	  ctk_text_layout_free_line_display (layout, display);
 	  display = ctk_text_layout_get_line_display (layout, line, FALSE);
          new_index = 0;
        }
      
       line_display_index_to_iter (layout, display, iter, new_index, new_trailing);
       if (extra_back)
	 ctk_text_iter_backward_char (iter);
    }

  if (display)
    ctk_text_layout_free_line_display (layout, display);

 done:
  
  return
    !ctk_text_iter_equal (iter, &orig) &&
    !ctk_text_iter_is_end (iter);
}

void
ctk_text_layout_spew (CtkTextLayout *layout G_GNUC_UNUSED)
{
#if 0
  CtkTextDisplayLine *iter;
  guint wrapped = 0;
  guint paragraphs = 0;
  CtkTextLine *last_line = NULL;

  iter = layout->line_list;
  while (iter != NULL)
    {
      if (iter->line != last_line)
        {
          printf ("%5u  paragraph (%p)\n", paragraphs, iter->line);
          ++paragraphs;
          last_line = iter->line;
        }

      printf ("  %5u  y: %d len: %d start: %d bytes: %d\n",
              wrapped, iter->y, iter->length, iter->byte_offset,
              iter->byte_count);

      ++wrapped;
      iter = iter->next;
    }

  printf ("Layout %s recompute\n",
          layout->need_recompute ? "needs" : "doesn't need");

  printf ("Layout pars: %u lines: %u size: %d x %d Screen width: %d\n",
          paragraphs, wrapped, layout->width,
          layout->height, layout->screen_width);
#endif
}

/* Catch all situations that move the insertion point.
 */
static void
ctk_text_layout_mark_set_handler (CtkTextBuffer     *buffer,
                                  const CtkTextIter *location G_GNUC_UNUSED,
                                  CtkTextMark       *mark,
                                  gpointer           data)
{
  CtkTextLayout *layout = CTK_TEXT_LAYOUT (data);

  if (mark == ctk_text_buffer_get_insert (buffer))
    ctk_text_layout_update_cursor_line (layout);
}

static void
ctk_text_layout_buffer_insert_text (CtkTextBuffer *textbuffer G_GNUC_UNUSED,
				    CtkTextIter   *iter G_GNUC_UNUSED,
				    gchar         *str G_GNUC_UNUSED,
				    gint           len G_GNUC_UNUSED,
				    gpointer       data)
{
  CtkTextLayout *layout = CTK_TEXT_LAYOUT (data);

  ctk_text_layout_update_cursor_line (layout);
}

static void
ctk_text_layout_buffer_delete_range (CtkTextBuffer *textbuffer G_GNUC_UNUSED,
				     CtkTextIter   *start G_GNUC_UNUSED,
				     CtkTextIter   *end G_GNUC_UNUSED,
				     gpointer       data)
{
  CtkTextLayout *layout = CTK_TEXT_LAYOUT (data);

  ctk_text_layout_update_cursor_line (layout);
}