1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <svx/svdpage.hxx>
#include <editeng/brushitem.hxx>
#include <editeng/shaditem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/lspcitem.hxx>
#include <editeng/fhgtitem.hxx>
#include <sal/log.hxx>

#include <drawdoc.hxx>
#include <fmtornt.hxx>
#include <fmthdft.hxx>
#include <fmtfsize.hxx>
#include <fmtsrnd.hxx>
#include <docary.hxx>
#include <lineinfo.hxx>
#include <swmodule.hxx>
#include <pagefrm.hxx>
#include <colfrm.hxx>
#include <fesh.hxx>
#include <viewimp.hxx>
#include <viewopt.hxx>
#include <dflyobj.hxx>
#include <dcontact.hxx>
#include <frmatr.hxx>
#include <frmtool.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <ftnfrm.hxx>
#include <txtfrm.hxx>
#include <notxtfrm.hxx>
#include <flyfrms.hxx>
#include <layact.hxx>
#include <pagedesc.hxx>
#include <section.hxx>
#include <sectfrm.hxx>
#include <node2lay.hxx>
#include <ndole.hxx>
#include <hints.hxx>
#include "layhelp.hxx"
#include <laycache.hxx>
#include <rootfrm.hxx>
#include <paratr.hxx>
#include <redline.hxx>
#include <sortedobjs.hxx>
#include <objectformatter.hxx>
#include <calbck.hxx>
#include <ndtxt.hxx>
#include <undobj.hxx>
#include <DocumentSettingManager.hxx>
#include <IDocumentDrawModelAccess.hxx>
#include <IDocumentTimerAccess.hxx>
#include <IDocumentRedlineAccess.hxx>
#include <IDocumentFieldsAccess.hxx>
#include <IDocumentState.hxx>
#include <frameformats.hxx>
#include <boost/circular_buffer.hpp>
#include <svx/sdr/attribute/sdrallfillattributeshelper.hxx>

using namespace ::com::sun::star;

bool bObjsDirect = true;
bool bDontCreateObjects = false;
bool bSetCompletePaintOnInvalidate = false;

sal_uInt8 StackHack::nCnt = 0;
bool StackHack::bLocked = false;

SwFrameNotify::SwFrameNotify( SwFrame *pF ) :
    mpFrame( pF ),
    maFrame( pF->getFrameArea() ),
    maPrt( pF->getFramePrintArea() ),
    mbInvaKeep( false ),
    mbValidSize( pF->isFrameAreaSizeValid() )
{
    if ( pF->IsTextFrame() )
    {
        mnFlyAnchorOfst = static_cast<SwTextFrame*>(pF)->GetBaseOffsetForFly( true );
        mnFlyAnchorOfstNoWrap = static_cast<SwTextFrame*>(pF)->GetBaseOffsetForFly( false );
    }
    else
    {
        mnFlyAnchorOfst = 0;
        mnFlyAnchorOfstNoWrap = 0;
    }

    mbHadFollow = pF->IsContentFrame() && static_cast<SwContentFrame*>(pF)->GetFollow();
}

SwFrameNotify::~SwFrameNotify() COVERITY_NOEXCEPT_FALSE
{
    SwRectFnSet aRectFnSet(mpFrame);
    const bool bAbsP = aRectFnSet.PosDiff(maFrame, mpFrame->getFrameArea());
    const bool bChgWidth =
            aRectFnSet.GetWidth(maFrame) != aRectFnSet.GetWidth(mpFrame->getFrameArea());
    const bool bChgHeight =
            aRectFnSet.GetHeight(maFrame)!=aRectFnSet.GetHeight(mpFrame->getFrameArea());
    const bool bChgFlyBasePos = mpFrame->IsTextFrame() &&
       ( ( mnFlyAnchorOfst != static_cast<SwTextFrame*>(mpFrame)->GetBaseOffsetForFly( true ) ) ||
         ( mnFlyAnchorOfstNoWrap != static_cast<SwTextFrame*>(mpFrame)->GetBaseOffsetForFly( false ) ) );

    if ( mpFrame->IsFlowFrame() && !mpFrame->IsInFootnote() )
    {
        SwFlowFrame *pFlow = SwFlowFrame::CastFlowFrame( mpFrame );

        if ( !pFlow->IsFollow() )
        {
            if ( !mpFrame->GetIndPrev() )
            {
                if ( mbInvaKeep )
                {
                    SwFrame *pPre = mpFrame->FindPrev();
                    if ( pPre && pPre->IsFlowFrame() )
                    {
                        // 1. pPre wants to keep with me:
                        bool bInvalidPrePos = SwFlowFrame::CastFlowFrame(pPre)->IsKeep(pPre->GetAttrSet()->GetKeep(), pPre->GetBreakItem())
                            && pPre->GetIndPrev();

                        // 2. pPre is a table and the last row wants to keep with me:
                        if ( !bInvalidPrePos && pPre->IsTabFrame() )
                        {
                            SwTabFrame* pPreTab = static_cast<SwTabFrame*>(pPre);
                            if ( pPreTab->GetFormat()->GetDoc()->GetDocumentSettingManager().get(DocumentSettingId::TABLE_ROW_KEEP) )
                            {
                                SwRowFrame* pLastRow = static_cast<SwRowFrame*>(pPreTab->GetLastLower());
                                if ( pLastRow && pLastRow->ShouldRowKeepWithNext() )
                                    bInvalidPrePos = true;
                            }
                        }

                        if ( bInvalidPrePos )
                            pPre->InvalidatePos();
                    }
                }
            }
            else if ( !pFlow->HasFollow() )
            {
                long nOldHeight = aRectFnSet.GetHeight(maFrame);
                long nNewHeight = aRectFnSet.GetHeight(mpFrame->getFrameArea());
                if( (nOldHeight > nNewHeight) || (!nOldHeight && nNewHeight) )
                    pFlow->CheckKeep();
            }
        }
    }

    if ( bAbsP )
    {
        mpFrame->SetCompletePaint();

        SwFrame* pNxt = mpFrame->GetIndNext();
        // #121888# - skip empty section frames
        while ( pNxt &&
                pNxt->IsSctFrame() && !static_cast<SwSectionFrame*>(pNxt)->GetSection() )
        {
            pNxt = pNxt->GetIndNext();
        }

        if ( pNxt )
            pNxt->InvalidatePos();
        else
        {
            // #104100# - correct condition for setting retouche
            // flag for vertical layout.
            if( mpFrame->IsRetoucheFrame() &&
                aRectFnSet.TopDist( maFrame, aRectFnSet.GetTop(mpFrame->getFrameArea()) ) > 0 )
            {
                mpFrame->SetRetouche();
            }

            // A fresh follow frame does not have to be invalidated, because
            // it is already formatted:
            if ( mbHadFollow || !mpFrame->IsContentFrame() || !static_cast<SwContentFrame*>(mpFrame)->GetFollow() )
            {
                if ( !mpFrame->IsTabFrame() || !static_cast<SwTabFrame*>(mpFrame)->GetFollow() )
                    mpFrame->InvalidateNextPos();
            }
        }
    }

    //For each resize of the background graphics is a repaint necessary.
    const bool bPrtWidth =
            aRectFnSet.GetWidth(maPrt) != aRectFnSet.GetWidth(mpFrame->getFramePrintArea());
    const bool bPrtHeight =
            aRectFnSet.GetHeight(maPrt)!=aRectFnSet.GetHeight(mpFrame->getFramePrintArea());
    if ( bPrtWidth || bPrtHeight )
    {
        bool bUseNewFillProperties(false);
        if (mpFrame->supportsFullDrawingLayerFillAttributeSet())
        {
            drawinglayer::attribute::SdrAllFillAttributesHelperPtr aFillAttributes(mpFrame->getSdrAllFillAttributesHelper());
            if(aFillAttributes && aFillAttributes->isUsed())
            {
                bUseNewFillProperties = true;
                // use SetCompletePaint if needed
                if(aFillAttributes->needCompleteRepaint())
                {
                    mpFrame->SetCompletePaint();
                }
            }
        }
        if (!bUseNewFillProperties)
        {
            const SvxGraphicPosition ePos = mpFrame->GetAttrSet()->GetBackground().GetGraphicPos();
            if(GPOS_NONE != ePos && GPOS_TILED != ePos)
                mpFrame->SetCompletePaint();
        }
    }
    else
    {
        // #97597# - consider case that *only* margins between
        // frame and printing area has changed. Then, frame has to be repainted,
        // in order to force paint of the margin areas.
        if ( !bAbsP && (bChgWidth || bChgHeight) )
        {
            mpFrame->SetCompletePaint();
        }
    }

    const bool bPrtP = aRectFnSet.PosDiff( maPrt, mpFrame->getFramePrintArea() );
    if ( bAbsP || bPrtP || bChgWidth || bChgHeight ||
         bPrtWidth || bPrtHeight || bChgFlyBasePos )
    {
        if( mpFrame->IsAccessibleFrame() )
        {
            SwRootFrame *pRootFrame = mpFrame->getRootFrame();
            if( pRootFrame && pRootFrame->IsAnyShellAccessible() &&
                pRootFrame->GetCurrShell() )
            {
                pRootFrame->GetCurrShell()->Imp()->MoveAccessibleFrame( mpFrame, maFrame );
            }
        }

        // Notification of anchored objects
        if ( mpFrame->GetDrawObjs() )
        {
            const SwSortedObjs &rObjs = *mpFrame->GetDrawObjs();
            SwPageFrame* pPageFrame = nullptr;
            for (SwAnchoredObject* pObj : rObjs)
            {
                // OD 2004-03-31 #i26791# - no general distinction between
                // Writer fly frames and drawing objects
                bool bNotify = false;
                bool bNotifySize = false;
                SwContact* pContact = ::GetUserCall( pObj->GetDrawObj() );
                const bool bAnchoredAsChar = pContact->ObjAnchoredAsChar();
                if ( !bAnchoredAsChar )
                {
                    // Notify object, which aren't anchored as-character:

                    // always notify objects, if frame position has changed
                    // or if the object is to-page|to-fly anchored.
                    if ( bAbsP ||
                         pContact->ObjAnchoredAtPage() ||
                         pContact->ObjAnchoredAtFly() )
                    {
                        bNotify = true;

                        // assure that to-fly anchored Writer fly frames are
                        // registered at the correct page frame, if frame
                        // position has changed.
                        if ( bAbsP && pContact->ObjAnchoredAtFly() &&
                             dynamic_cast<const SwFlyFrame*>( pObj) !=  nullptr )
                        {
                            // determine to-fly anchored Writer fly frame
                            SwFlyFrame* pFlyFrame = static_cast<SwFlyFrame*>(pObj);
                            // determine page frame of to-fly anchored
                            // Writer fly frame
                            SwPageFrame* pFlyPageFrame = pFlyFrame->FindPageFrame();
                            // determine page frame, if needed.
                            if ( !pPageFrame )
                            {
                                pPageFrame = mpFrame->FindPageFrame();
                            }
                            if ( pPageFrame != pFlyPageFrame )
                            {
                                OSL_ENSURE( pFlyPageFrame, "~SwFrameNotify: Fly from Nowhere" );
                                if( pFlyPageFrame )
                                    pFlyPageFrame->MoveFly( pFlyFrame, pPageFrame );
                                else
                                    pPageFrame->AppendFlyToPage( pFlyFrame );
                            }
                        }
                    }
                    // otherwise the objects are notified in dependence to
                    // its positioning and alignment
                    else
                    {
                        const SwFormatVertOrient& rVert =
                                        pContact->GetFormat()->GetVertOrient();
                        if ( ( rVert.GetVertOrient() == text::VertOrientation::CENTER ||
                               rVert.GetVertOrient() == text::VertOrientation::BOTTOM ||
                               rVert.GetRelationOrient() == text::RelOrientation::PRINT_AREA ) &&
                             ( bChgHeight || bPrtHeight ) )
                        {
                            bNotify = true;
                        }
                        if ( !bNotify )
                        {
                            const SwFormatHoriOrient& rHori =
                                        pContact->GetFormat()->GetHoriOrient();
                            if ( ( rHori.GetHoriOrient() != text::HoriOrientation::NONE ||
                                   rHori.GetRelationOrient()== text::RelOrientation::PRINT_AREA ||
                                   rHori.GetRelationOrient()== text::RelOrientation::FRAME ) &&
                                 ( bChgWidth || bPrtWidth || bChgFlyBasePos ) )
                            {
                                bNotify = true;
                            }
                        }
                    }
                }
                else if ( bPrtWidth )
                {
                    // Notify as-character anchored objects, if printing area
                    // width has changed.
                    bNotify = true;
                    bNotifySize = true;
                }

                // perform notification via the corresponding invalidations
                if ( bNotify )
                {
                    if ( dynamic_cast<const SwFlyFrame*>( pObj) !=  nullptr )
                    {
                        SwFlyFrame* pFlyFrame = static_cast<SwFlyFrame*>(pObj);
                        if ( bNotifySize )
                            pFlyFrame->InvalidateSize_();
                        // #115759# - no invalidation of
                        // position for as-character anchored objects.
                        if ( !bAnchoredAsChar )
                        {
                            pFlyFrame->InvalidatePos_();
                        }
                        pFlyFrame->Invalidate_();
                    }
                    else if ( dynamic_cast<const SwAnchoredDrawObject*>( pObj) !=  nullptr )
                    {
                        // #115759# - no invalidation of
                        // position for as-character anchored objects.
                        if ( !bAnchoredAsChar )
                        {
                            pObj->InvalidateObjPos();
                        }
                    }
                    else
                    {
                        OSL_FAIL( "<SwContentNotify::~SwContentNotify()> - unknown anchored object type." );
                    }
                }
            }
        }
    }
    else if( mpFrame->IsTextFrame() && mbValidSize != mpFrame->isFrameAreaSizeValid() )
    {
        SwRootFrame *pRootFrame = mpFrame->getRootFrame();
        if( pRootFrame && pRootFrame->IsAnyShellAccessible() &&
            pRootFrame->GetCurrShell() )
        {
            pRootFrame->GetCurrShell()->Imp()->InvalidateAccessibleFrameContent( mpFrame );
        }
    }

    // #i9046# Automatic frame width
    SwFlyFrame* pFly = nullptr;
    // #i35879# Do not trust the inf flags. pFrame does not
    // necessarily have to have an upper!
    if ( !mpFrame->IsFlyFrame() && nullptr != ( pFly = mpFrame->ImplFindFlyFrame() ) )
    {
        // #i61999#
        // no invalidation of columned Writer fly frames, because automatic
        // width doesn't make sense for such Writer fly frames.
        if ( pFly->Lower() && !pFly->Lower()->IsColumnFrame() )
        {
            const SwFormatFrameSize &rFrameSz = pFly->GetFormat()->GetFrameSize();

            // This could be optimized. Basically the fly frame only has to
            // be invalidated, if the first line of pFrame (if pFrame is a content
            // frame, for other frame types it's the print area) has changed its
            // size and pFrame was responsible for the current width of pFly. On
            // the other hand, this is only rarely used and re-calculation of
            // the fly frame does not cause too much trouble. So we keep it this
            // way:
            if ( SwFrameSize::Fixed != rFrameSz.GetWidthSizeType() )
            {
                // #i50668#, #i50998# - invalidation of position
                // of as-character anchored fly frames not needed and can cause
                // layout loops
                if ( dynamic_cast<const SwFlyInContentFrame*>( pFly) ==  nullptr )
                {
                    pFly->InvalidatePos();
                }
                pFly->InvalidateSize();
            }
        }
    }
}

SwLayNotify::SwLayNotify( SwLayoutFrame *pLayFrame ) :
    SwFrameNotify( pLayFrame ),
    m_bLowersComplete( false )
{
}

// OD 2004-05-11 #i28701# - local method to invalidate the position of all
// frames inclusive its floating screen objects, which are lowers of the given
// layout frame
static void lcl_InvalidatePosOfLowers( SwLayoutFrame& _rLayoutFrame )
{
    if( _rLayoutFrame.IsFlyFrame() && _rLayoutFrame.GetDrawObjs() )
    {
        _rLayoutFrame.InvalidateObjs( false );
    }

    SwFrame* pLowerFrame = _rLayoutFrame.Lower();
    while ( pLowerFrame )
    {
        pLowerFrame->InvalidatePos();
        if ( pLowerFrame->IsTextFrame() )
        {
            static_cast<SwTextFrame*>(pLowerFrame)->Prepare( PrepareHint::FramePositionChanged );
        }
        else if ( pLowerFrame->IsTabFrame() )
        {
            pLowerFrame->InvalidatePrt();
        }

        pLowerFrame->InvalidateObjs( false );

        pLowerFrame = pLowerFrame->GetNext();
    }
}

SwLayNotify::~SwLayNotify()
{
    SwLayoutFrame *pLay = static_cast<SwLayoutFrame*>(mpFrame);
    SwRectFnSet aRectFnSet(pLay);
    bool bNotify = false;
    if ( pLay->getFramePrintArea().SSize() != maPrt.SSize() )
    {
        if ( !IsLowersComplete() )
        {
            bool bInvaPercent;

            if ( pLay->IsRowFrame() )
            {
                bInvaPercent = true;
                long nNew = aRectFnSet.GetHeight(pLay->getFramePrintArea());
                if( nNew != aRectFnSet.GetHeight(maPrt) )
                     static_cast<SwRowFrame*>(pLay)->AdjustCells( nNew, true);
                if( aRectFnSet.GetWidth(pLay->getFramePrintArea())
                    != aRectFnSet.GetWidth(maPrt) )
                     static_cast<SwRowFrame*>(pLay)->AdjustCells( 0, false );
            }
            else
            {
                //Proportional adoption of the internal.
                //1. If the formatted is no Fly
                //2. If he contains no columns
                //3. If the Fly has a fixed height and the columns
                //   are next to be.
                //   Hoehe danebenliegen.
                //4. Never at SectionFrames.
                bool bLow;
                if( pLay->IsFlyFrame() )
                {
                    if ( pLay->Lower() )
                    {
                        bLow = !pLay->Lower()->IsColumnFrame() ||
                            aRectFnSet.GetHeight(pLay->Lower()->getFrameArea())
                             != aRectFnSet.GetHeight(pLay->getFramePrintArea());
                    }
                    else
                        bLow = false;
                }
                else if( pLay->IsSctFrame() )
                {
                    if ( pLay->Lower() )
                    {
                        if( pLay->Lower()->IsColumnFrame() && pLay->Lower()->GetNext() )
                            bLow = pLay->Lower()->getFrameArea().Height() != pLay->getFramePrintArea().Height();
                        else
                            bLow = pLay->getFramePrintArea().Width() != maPrt.Width();
                    }
                    else
                        bLow = false;
                }
                else if( pLay->IsFooterFrame() && !pLay->HasFixSize() )
                    bLow = pLay->getFramePrintArea().Width() != maPrt.Width();
                else
                    bLow = true;
                bInvaPercent = bLow;
                if ( bLow )
                {
                    pLay->ChgLowersProp( maPrt.SSize() );
                }
                // If the PrtArea has been extended, it might be possible that the chain of parts
                // can take another frame. As a result, the "possible right one" needs to be
                // invalidated. This only pays off if this or its Uppers are moveable sections.
                // A PrtArea has been extended if width or height are larger than before.
                if ( (pLay->getFramePrintArea().Height() > maPrt.Height() ||
                      pLay->getFramePrintArea().Width()  > maPrt.Width()) &&
                     (pLay->IsMoveable() || pLay->IsFlyFrame()) )
                {
                    SwFrame *pTmpFrame = pLay->Lower();
                    if ( pTmpFrame && pTmpFrame->IsFlowFrame() )
                    {
                        while ( pTmpFrame->GetNext() )
                            pTmpFrame = pTmpFrame->GetNext();
                        pTmpFrame->InvalidateNextPos();
                    }
                }
            }
            bNotify = true;
            //EXPENSIVE!! But how we do it more elegant?
            if( bInvaPercent )
                pLay->InvaPercentLowers( pLay->getFramePrintArea().Height() - maPrt.Height() );
        }
        if ( pLay->IsTabFrame() )
            //So that _only_ the shadow is drawn while resizing.
            static_cast<SwTabFrame*>(pLay)->SetComplete();
        else
        {
            const SwViewShell *pSh = pLay->getRootFrame()->GetCurrShell();
            if( !( pSh && pSh->GetViewOptions()->getBrowseMode() ) ||
                  !(pLay->GetType() & (SwFrameType::Body | SwFrameType::Page)) )
            //Thereby the subordinates are retouched clean.
            //Example problem: Take the Flys with the handles and downsize.
            //Not for body and page, otherwise it flickers when loading HTML.
                pLay->SetCompletePaint();
        }
    }
    //Notify Lower if the position has changed.
    const bool bPrtPos = aRectFnSet.PosDiff( maPrt, pLay->getFramePrintArea() );
    const bool bPos = bPrtPos || aRectFnSet.PosDiff( maFrame, pLay->getFrameArea() );
    const bool bSize = pLay->getFrameArea().SSize() != maFrame.SSize();

    if ( bPos && pLay->Lower() && !IsLowersComplete() )
    {
        pLay->Lower()->InvalidatePos();
        SwFootnoteFrame* pFtnFrame = pLay->Lower()->IsFootnoteFrame() ?
            static_cast<SwFootnoteFrame*>(pLay->Lower()) : nullptr;
        SwFrame* pFtnLower = pFtnFrame ? pFtnFrame->Lower() : nullptr;
        if (pFtnLower)
            pFtnLower->InvalidatePos();
    }

    if ( bPrtPos )
        pLay->SetCompletePaint();

    //Inform the Follower if the SSize has changed.
    if ( bSize )
    {
        if( pLay->GetNext() )
        {
            if ( pLay->GetNext()->IsLayoutFrame() )
                pLay->GetNext()->InvalidatePos_();
            else
                pLay->GetNext()->InvalidatePos();
        }
        else if( pLay->IsSctFrame() )
            pLay->InvalidateNextPos();
    }
    if ( !IsLowersComplete() &&
         !(pLay->GetType()&(SwFrameType::Fly|SwFrameType::Section) &&
            pLay->Lower() && pLay->Lower()->IsColumnFrame()) &&
         (bPos || bNotify) &&
         !(pLay->GetType() & (SwFrameType::Row|SwFrameType::Tab|SwFrameType::FtnCont|SwFrameType::Page|SwFrameType::Root)))
    {
        // #i44016# - force unlock of position of lower objects.
        // #i43913# - no unlock of position of objects,
        // if <pLay> is a cell frame, and its table frame resp. its parent table
        // frame is locked.
        // #i47458# - force unlock of position of lower objects,
        // only if position of layout frame has changed.
        bool bUnlockPosOfObjs( bPos );
        if ( bUnlockPosOfObjs && pLay->IsCellFrame() )
        {
            SwTabFrame* pTabFrame( pLay->FindTabFrame() );
            if ( pTabFrame &&
                 ( pTabFrame->IsJoinLocked() ||
                   ( pTabFrame->IsFollow() &&
                     pTabFrame->FindMaster()->IsJoinLocked() ) ) )
            {
                bUnlockPosOfObjs = false;
            }
        }
        // #i49383# - check for footnote frame, if unlock
        // of position of lower objects is allowed.
        else if ( bUnlockPosOfObjs && pLay->IsFootnoteFrame() )
        {
            bUnlockPosOfObjs = static_cast<SwFootnoteFrame*>(pLay)->IsUnlockPosOfLowerObjs();
        }
        // #i51303# - no unlock of object positions for sections
        else if ( bUnlockPosOfObjs && pLay->IsSctFrame() )
        {
            bUnlockPosOfObjs = false;
        }
        pLay->NotifyLowerObjs( bUnlockPosOfObjs );
    }
    if ( bPos && pLay->IsFootnoteFrame() && pLay->Lower() )
    {
        // OD 2004-05-11 #i28701#
        ::lcl_InvalidatePosOfLowers( *pLay );
    }
    if( ( bPos || bSize ) && pLay->IsFlyFrame() && static_cast<SwFlyFrame*>(pLay)->GetAnchorFrame()
          && static_cast<SwFlyFrame*>(pLay)->GetAnchorFrame()->IsFlyFrame() )
        static_cast<SwFlyFrame*>(pLay)->AnchorFrame()->InvalidateSize();
}

SwFlyNotify::SwFlyNotify( SwFlyFrame *pFlyFrame ) :
    SwLayNotify( pFlyFrame ),
    // #115759# - keep correct page frame - the page frame
    // the Writer fly frame is currently registered at.
    pOldPage( pFlyFrame->GetPageFrame() ),
    aFrameAndSpace( pFlyFrame->GetObjRectWithSpaces() )
{
}

SwFlyNotify::~SwFlyNotify()
{
    SwFlyFrame *pFly = static_cast<SwFlyFrame*>(mpFrame);
    if ( pFly->IsNotifyBack() )
    {
        SwViewShell *pSh = pFly->getRootFrame()->GetCurrShell();
        SwViewShellImp *pImp = pSh ? pSh->Imp() : nullptr;
        if ( !pImp || !pImp->IsAction() || !pImp->GetLayAction().IsAgain() )
        {
            //If in the LayAction the IsAgain is set it can be
            //that the old page is destroyed in the meantime!
            ::Notify( pFly, pOldPage, aFrameAndSpace, &maPrt );
            // #i35640# - additional notify anchor text frame,
            // if Writer fly frame has changed its page
            if ( pFly->GetAnchorFrame()->IsTextFrame() &&
                 pFly->GetPageFrame() != pOldPage )
            {
                pFly->AnchorFrame()->Prepare( PrepareHint::FlyFrameLeave );
            }
        }
        pFly->ResetNotifyBack();
    }

    //Have the size or the position changed,
    //so should the view know this.
    SwRectFnSet aRectFnSet(pFly);
    const bool bPosChgd = aRectFnSet.PosDiff( maFrame, pFly->getFrameArea() );
    const bool bFrameChgd = pFly->getFrameArea().SSize() != maFrame.SSize();
    const bool bPrtChgd = maPrt != pFly->getFramePrintArea();
    if ( bPosChgd || bFrameChgd || bPrtChgd )
    {
        pFly->NotifyDrawObj();
    }
    if ( bPosChgd && maFrame.Pos().X() != FAR_AWAY )
    {
        // OD 2004-05-10 #i28701# - no direct move of lower Writer fly frames.
        // reason: New positioning and alignment (e.g. to-paragraph anchored,
        // but aligned at page) are introduced.
        // <SwLayNotify::~SwLayNotify()> takes care of invalidation of lower
        // floating screen objects by calling method <SwLayoutFrame::NotifyLowerObjs()>.

        if ( pFly->IsFlyAtContentFrame() )
        {
            SwFrame *pNxt = pFly->AnchorFrame()->FindNext();
            if ( pNxt )
            {
                pNxt->InvalidatePos();
            }
        }

        // #i26945# - notify anchor.
        // Needed for negative positioned Writer fly frames
        if ( pFly->GetAnchorFrame()->IsTextFrame() )
        {
            pFly->AnchorFrame()->Prepare( PrepareHint::FlyFrameLeave );
        }
    }

    // OD 2004-05-13 #i28701#
    // #i45180# - no adjustment of layout process flags and
    // further notifications/invalidations, if format is called by grow/shrink
    if ( pFly->ConsiderObjWrapInfluenceOnObjPos() &&
         ( dynamic_cast<const SwFlyFreeFrame*>( pFly) ==  nullptr ||
           !static_cast<SwFlyFreeFrame*>(pFly)->IsNoMoveOnCheckClip() ) )
    {
        // #i54138# - suppress restart of the layout process
        // on changed frame height.
        // Note: It doesn't seem to be necessary and can cause layout loops.
        if ( bPosChgd )
        {
            // indicate a restart of the layout process
            pFly->SetRestartLayoutProcess( true );
        }
        else
        {
            // lock position
            pFly->LockPosition();
        }

        if ( !pFly->ConsiderForTextWrap() )
        {
            // indicate that object has to be considered for text wrap
            pFly->SetConsiderForTextWrap( true );
            // invalidate 'background' in order to allow its 'background'
            // to wrap around it.
            pFly->NotifyBackground( pFly->GetPageFrame(),
                                    pFly->GetObjRectWithSpaces(),
                                    PrepareHint::FlyFrameArrive );
            // invalidate position of anchor frame in order to force
            // a re-format of the anchor frame, which also causes a
            // re-format of the invalid previous frames of the anchor frame.
            pFly->AnchorFrame()->InvalidatePos();
        }
    }
}

SwContentNotify::SwContentNotify( SwContentFrame *pContentFrame ) :
    SwFrameNotify( pContentFrame ),
    // OD 08.01.2004 #i11859#
    mbChkHeightOfLastLine( false ),
    mnHeightOfLastLine( 0 ),
    // OD 2004-02-26 #i25029#
    mbInvalidatePrevPrtArea( false ),
    mbBordersJoinedWithPrev( false )
{
    // OD 08.01.2004 #i11859#
    if ( pContentFrame->IsTextFrame() )
    {
        SwTextFrame* pTextFrame = static_cast<SwTextFrame*>(pContentFrame);
        if (!pTextFrame->GetDoc().getIDocumentSettingAccess().get(DocumentSettingId::OLD_LINE_SPACING))
        {
            const SvxLineSpacingItem &rSpace = pTextFrame->GetAttrSet()->GetLineSpacing();
            if ( rSpace.GetInterLineSpaceRule() == SvxInterLineSpaceRule::Prop )
            {
                mbChkHeightOfLastLine = true;
                mnHeightOfLastLine = pTextFrame->GetHeightOfLastLine();
            }
        }
    }
}

SwContentNotify::~SwContentNotify()
{
    SwContentFrame *pCnt = static_cast<SwContentFrame*>(mpFrame);
    if ( bSetCompletePaintOnInvalidate )
        pCnt->SetCompletePaint();

    SwRectFnSet aRectFnSet(pCnt);
    if ( pCnt->IsInTab() && ( aRectFnSet.PosDiff( pCnt->getFrameArea(), maFrame ) ||
                             pCnt->getFrameArea().SSize() != maFrame.SSize()))
    {
        SwLayoutFrame* pCell = pCnt->GetUpper();
        while( !pCell->IsCellFrame() && pCell->GetUpper() )
            pCell = pCell->GetUpper();
        OSL_ENSURE( pCell->IsCellFrame(), "Where's my cell?" );
        if ( text::VertOrientation::NONE != pCell->GetFormat()->GetVertOrient().GetVertOrient() )
            pCell->InvalidatePrt(); //for the vertical align.
    }

    // OD 2004-02-26 #i25029#
    if ( mbInvalidatePrevPrtArea && mbBordersJoinedWithPrev &&
         pCnt->IsTextFrame() &&
         !pCnt->IsFollow() && !pCnt->GetIndPrev() )
    {
        // determine previous frame
        SwFrame* pPrevFrame = pCnt->FindPrev();
        // skip empty section frames and hidden text frames
        {
            while ( pPrevFrame &&
                    ( ( pPrevFrame->IsSctFrame() &&
                        !static_cast<SwSectionFrame*>(pPrevFrame)->GetSection() ) ||
                      ( pPrevFrame->IsTextFrame() &&
                        static_cast<SwTextFrame*>(pPrevFrame)->IsHiddenNow() ) ) )
            {
                pPrevFrame = pPrevFrame->FindPrev();
            }
        }

        // Invalidate printing area of found previous frame
        if ( pPrevFrame )
        {
            if ( pPrevFrame->IsSctFrame() )
            {
                if ( pCnt->IsInSct() )
                {
                    // Note: found previous frame is a section frame and
                    //       <pCnt> is also inside a section.
                    //       Thus due to <mbBordersJoinedWithPrev>,
                    //       <pCnt> had joined its borders/shadow with the
                    //       last content of the found section.
                    // Invalidate printing area of last content in found section.
                    SwFrame* pLstContentOfSctFrame =
                            static_cast<SwSectionFrame*>(pPrevFrame)->FindLastContent();
                    if ( pLstContentOfSctFrame )
                    {
                        pLstContentOfSctFrame->InvalidatePrt();
                    }
                }
            }
            else
            {
                pPrevFrame->InvalidatePrt();
            }
        }
    }

    const bool bFirst = aRectFnSet.GetWidth(maFrame) == 0;

    if ( pCnt->IsNoTextFrame() )
    {
        //Active PlugIn's or OLE-Objects should know something of the change
        //thereby they move their window appropriate.
        SwViewShell *pSh  = pCnt->getRootFrame()->GetCurrShell();
        if ( pSh )
        {
            SwOLENode *const pNd(static_cast<SwNoTextFrame*>(pCnt)->GetNode()->GetOLENode());
            if (nullptr != pNd &&
                 (pNd->GetOLEObj().IsOleRef() ||
                  pNd->IsOLESizeInvalid()) )
            {
                const bool bNoTextFramePrtAreaChanged =
                        ( maPrt.SSize().Width() != 0 &&
                          maPrt.SSize().Height() != 0 ) &&
                        maPrt.SSize() != pCnt->getFramePrintArea().SSize();
                OSL_ENSURE( pCnt->IsInFly(), "OLE not in FlyFrame" );
                SwFlyFrame *pFly = pCnt->FindFlyFrame();
                svt::EmbeddedObjectRef& xObj = pNd->GetOLEObj().GetObject();
                SwFEShell *pFESh = nullptr;
                for(SwViewShell& rCurrentShell : pSh->GetRingContainer())
                {   if ( dynamic_cast<const SwCursorShell*>( &rCurrentShell) !=  nullptr )
                    {
                        pFESh = static_cast<SwFEShell*>(&rCurrentShell);
                        // #108369#: Here used to be the condition if (!bFirst).
                        // I think this should mean "do not call CalcAndSetScale"
                        // if the frame is formatted for the first time.
                        // Unfortunately this is not valid anymore since the
                        // SwNoTextFrame already gets a width during CalcLowerPreps.
                        // Nevertheless, the indention of !bFirst seemed to be
                        // to assure that the OLE objects have already been notified
                        // if necessary before calling CalcAndSetScale.
                        // So I replaced !bFirst by !IsOLESizeInvalid. There is
                        // one additional problem specific to the word import:
                        // The layout is calculated _before_ calling PrtOLENotify,
                        // and the OLE objects are not invalidated during import.
                        // Therefore I added the condition !IsUpdateExpField,
                        // have a look at the occurrence of CalcLayout in
                        // uiview/view.cxx.
                        if ( !pNd->IsOLESizeInvalid() &&
                             !pSh->GetDoc()->getIDocumentState().IsUpdateExpField() )
                            pFESh->CalcAndSetScale( xObj,
                                                    &pFly->getFramePrintArea(), &pFly->getFrameArea(),
                                                    bNoTextFramePrtAreaChanged );
                    }
                }

                if ( pFESh && pNd->IsOLESizeInvalid() )
                {
                    pNd->SetOLESizeInvalid( false );
                    pFESh->CalcAndSetScale( xObj ); // create client
                }
            }
            //dito animated graphics
            if ( getFrameArea().HasArea() && static_cast<SwNoTextFrame*>(pCnt)->HasAnimation() )
            {
                static_cast<SwNoTextFrame*>(pCnt)->StopAnimation();
                pSh->InvalidateWindows( getFrameArea() );
            }
        }
    }

    if ( bFirst )
    {
        pCnt->SetRetouche();    //fix(13870)

        SwDoc *const pDoc = pCnt->IsTextFrame()
            ? &static_cast<SwTextFrame*>(pCnt)->GetDoc()
            : static_cast<SwNoTextFrame*>(pCnt)->GetNode()->GetDoc();
        if ( !pDoc->GetSpzFrameFormats()->empty() &&
             pDoc->DoesContainAtPageObjWithContentAnchor() && !pDoc->getIDocumentState().IsNewDoc() )
        {
            // If certain import filters for foreign file format import
            // AT_PAGE anchored objects, the corresponding page number is
            // typically not known. In this case the content position is
            // stored at which the anchored object is found in the
            // imported document.
            // When this content is formatted it is the time at which
            // the page is known. Thus, this data can be corrected now.

            const SwPageFrame *pPage = nullptr;
            SwFrameFormats *pTable = pDoc->GetSpzFrameFormats();

            for ( size_t i = 0; i < pTable->size(); ++i )
            {
                SwFrameFormat *pFormat = (*pTable)[i];
                const SwFormatAnchor &rAnch = pFormat->GetAnchor();
                if ( RndStdIds::FLY_AT_PAGE != rAnch.GetAnchorId() ||
                     rAnch.GetContentAnchor() == nullptr )
                {
                    continue;
                }

                if (FrameContainsNode(*pCnt, rAnch.GetContentAnchor()->nNode.GetIndex()))
                {
                    OSL_FAIL( "<SwContentNotify::~SwContentNotify()> - to page anchored object with content position." );
                    if ( !pPage )
                    {
                        pPage = pCnt->FindPageFrame();
                    }
                    SwFormatAnchor aAnch( rAnch );
                    aAnch.SetAnchor( nullptr );
                    aAnch.SetPageNum( pPage->GetPhyPageNum() );
                    pFormat->SetFormatAttr( aAnch );
                    if ( RES_DRAWFRMFMT != pFormat->Which() )
                    {
                        pFormat->MakeFrames();
                    }
                }
            }
        }
    }

    // OD 12.01.2004 #i11859# - invalidate printing area of following frame,
    //  if height of last line has changed.
    if ( pCnt->IsTextFrame() && mbChkHeightOfLastLine )
    {
        if ( mnHeightOfLastLine != static_cast<SwTextFrame*>(pCnt)->GetHeightOfLastLine() )
        {
            pCnt->InvalidateNextPrtArea();
        }
    }

    // #i44049#
    if ( pCnt->IsTextFrame() && aRectFnSet.PosDiff( maFrame, pCnt->getFrameArea() ) )
    {
        pCnt->InvalidateObjs();
    }

    // #i43255# - move code to invalidate at-character
    // anchored objects due to a change of its anchor character from
    // method <SwTextFrame::Format(..)>.
    if ( pCnt->IsTextFrame() )
    {
        SwTextFrame* pMasterFrame = pCnt->IsFollow()
                               ? static_cast<SwTextFrame*>(pCnt)->FindMaster()
                               : static_cast<SwTextFrame*>(pCnt);
        if ( pMasterFrame && !pMasterFrame->IsFlyLock() &&
             pMasterFrame->GetDrawObjs() )
        {
            SwSortedObjs* pObjs = pMasterFrame->GetDrawObjs();
            for (SwAnchoredObject* pAnchoredObj : *pObjs)
            {
                if ( pAnchoredObj->GetFrameFormat().GetAnchor().GetAnchorId()
                        == RndStdIds::FLY_AT_CHAR )
                {
                    pAnchoredObj->CheckCharRectAndTopOfLine( !pMasterFrame->IsEmpty() );
                }
            }
        }
    }
}

// note this *cannot* be static because it's a friend
void AppendObj(SwFrame *const pFrame, SwPageFrame *const pPage, SwFrameFormat *const pFormat, const SwFormatAnchor & rAnch)
{
            const bool bFlyAtFly = rAnch.GetAnchorId() == RndStdIds::FLY_AT_FLY; // LAYER_IMPL
            //Is a frame or a SdrObject described?
            const bool bSdrObj = RES_DRAWFRMFMT == pFormat->Which();
            // OD 23.06.2003 #108784# - append also drawing objects anchored
            // as character.
            const bool bDrawObjInContent = bSdrObj &&
                                         (rAnch.GetAnchorId() == RndStdIds::FLY_AS_CHAR);

            if( bFlyAtFly ||
                (rAnch.GetAnchorId() == RndStdIds::FLY_AT_PARA) ||
                (rAnch.GetAnchorId() == RndStdIds::FLY_AT_CHAR) ||
                bDrawObjInContent )
            {
                SdrObject* pSdrObj = nullptr;
                if ( bSdrObj && nullptr == (pSdrObj = pFormat->FindSdrObject()) )
                {
                    OSL_ENSURE( !bSdrObj, "DrawObject not found." );
                    pFormat->GetDoc()->DelFrameFormat( pFormat );
                    return;
                }
                if ( pSdrObj )
                {
                    if ( !pSdrObj->getSdrPageFromSdrObject() )
                    {
                        pFormat->getIDocumentDrawModelAccess().GetDrawModel()->GetPage(0)->
                                InsertObject(pSdrObj, pSdrObj->GetOrdNumDirect());
                    }

                    SwDrawContact* pNew =
                        static_cast<SwDrawContact*>(GetUserCall( pSdrObj ));
                    if ( !pNew->GetAnchorFrame() )
                    {
                        pFrame->AppendDrawObj( *(pNew->GetAnchoredObj( nullptr )) );
                    }
                    // OD 19.06.2003 #108784# - add 'virtual' drawing object,
                    // if necessary. But control objects have to be excluded.
                    else if ( !::CheckControlLayer( pSdrObj ) &&
                              pNew->GetAnchorFrame() != pFrame &&
                              !pNew->GetDrawObjectByAnchorFrame( *pFrame ) )
                    {
                        SwDrawVirtObj* pDrawVirtObj = pNew->AddVirtObj();
                        pFrame->AppendDrawObj( *(pNew->GetAnchoredObj( pDrawVirtObj )) );

                        pDrawVirtObj->ActionChanged();
                    }
                }
                else
                {
                    SwFlyFrame *pFly;
                    if( bFlyAtFly )
                        pFly = new SwFlyLayFrame( static_cast<SwFlyFrameFormat*>(pFormat), pFrame, pFrame );
                    else
                        pFly = new SwFlyAtContentFrame( static_cast<SwFlyFrameFormat*>(pFormat), pFrame, pFrame );
                    pFly->Lock();
                    pFrame->AppendFly( pFly );
                    pFly->Unlock();
                    if ( pPage )
                        ::RegistFlys( pPage, pFly );
                }
            }
}

static bool IsShown(sal_uLong const nIndex,
    const SwFormatAnchor & rAnch,
    std::vector<sw::Extent>::const_iterator const*const pIter,
    std::vector<sw::Extent>::const_iterator const*const pEnd,
    SwTextNode const*const pFirstNode, SwTextNode const*const pLastNode)
{
    assert(!pIter || *pIter == *pEnd || (*pIter)->pNode->GetIndex() == nIndex);
    SwPosition const& rAnchor(*rAnch.GetContentAnchor());
    if (rAnchor.nNode.GetIndex() != nIndex)
    {
        return false;
    }
    if (pIter && rAnch.GetAnchorId() != RndStdIds::FLY_AT_PARA)
    {
        // note: frames are not sorted by anchor position.
        assert(pEnd);
        assert(pFirstNode);
        assert(pLastNode);
        assert(rAnch.GetAnchorId() != RndStdIds::FLY_AT_FLY);
        for (auto iter = *pIter; iter != *pEnd; ++iter)
        {
            assert(iter->nStart != iter->nEnd); // TODO possible?
            assert(iter->pNode->GetIndex() == nIndex);
            if (rAnchor.nContent.GetIndex() < iter->nStart)
            {
                return false;
            }
            if (rAnch.GetAnchorId() == RndStdIds::FLY_AT_CHAR)
            {
                // if there is an extent then obviously the node was not
                // deleted fully...
                // show if start <= pos <= end
                // *or* if first-node/0  *and* not StartOfSection
                // *or* if last-node/Len *and* not EndOfSection

                // first determine the extent to compare to, then
                // construct start/end positions for the deletion *before* the
                // extent and compare once.
                // the interesting corner cases are on the edge of the extent!
                // no need to check for > the last extent because those
                // are never visible.
                if (rAnchor.nContent.GetIndex() <= iter->nEnd)
                {
                    if (iter->nStart == 0)
                    {
                        return true;
                    }
                    else
                    {
                        SwPosition const start(
                            const_cast<SwTextNode&>(
                                iter == *pIter
                                    ? *pFirstNode // simplification
                                    : *iter->pNode),
                            iter == *pIter // first extent?
                                ? iter->pNode == pFirstNode
                                    ? 0 // at start of 1st node
                                    : pFirstNode->Len() // previous node; simplification but should get right result
                                : (iter-1)->nEnd); // previous extent
                        SwPosition const end(*iter->pNode, iter->nStart);
                        return !IsDestroyFrameAnchoredAtChar(rAnchor, start, end);
                    }
                }
                else if (iter == *pEnd - 1) // special case: after last extent
                {
                    if (iter->nEnd == iter->pNode->Len())
                    {
                        return true; // special case: end of node
                    }
                    else
                    {
                        SwPosition const start(*iter->pNode, iter->nEnd);
                        SwPosition const end(
                            const_cast<SwTextNode&>(*pLastNode), // simplification
                            iter->pNode == pLastNode
                                ? iter->pNode->Len()
                                : 0);
                        return !IsDestroyFrameAnchoredAtChar(rAnchor, start, end);
                    }
                }
            }
            else
            {
                assert(rAnch.GetAnchorId() == RndStdIds::FLY_AS_CHAR);
                // for AS_CHAR obviously must be <
                if (rAnchor.nContent.GetIndex() < iter->nEnd)
                {
                    return true;
                }
            }
        }
        return false;
    }
    else
    {
        return true;
    }
}

void RemoveHiddenObjsOfNode(SwTextNode const& rNode,
    std::vector<sw::Extent>::const_iterator const*const pIter,
    std::vector<sw::Extent>::const_iterator const*const pEnd,
    SwTextNode const*const pFirstNode, SwTextNode const*const pLastNode)
{
    std::vector<SwFrameFormat*> const*const pFlys(rNode.GetAnchoredFlys());
    if (!pFlys)
    {
        return;
    }
    for (SwFrameFormat * pFrameFormat : *pFlys)
    {
        SwFormatAnchor const& rAnchor = pFrameFormat->GetAnchor();
        if (rAnchor.GetAnchorId() == RndStdIds::FLY_AT_CHAR
            || (rAnchor.GetAnchorId() == RndStdIds::FLY_AS_CHAR
                && RES_DRAWFRMFMT == pFrameFormat->Which()))
        {
            assert(rAnchor.GetContentAnchor()->nNode.GetIndex() == rNode.GetIndex());
            if (!IsShown(rNode.GetIndex(), rAnchor, pIter, pEnd, pFirstNode, pLastNode))
            {
                pFrameFormat->DelFrames();
            }
        }
    }
}

void AppendObjsOfNode(SwFrameFormats const*const pTable, sal_uLong const nIndex,
    SwFrame *const pFrame, SwPageFrame *const pPage, SwDoc *const pDoc,
    std::vector<sw::Extent>::const_iterator const*const pIter,
    std::vector<sw::Extent>::const_iterator const*const pEnd,
    SwTextNode const*const pFirstNode, SwTextNode const*const pLastNode)
{
#if OSL_DEBUG_LEVEL > 0
    std::vector<SwFrameFormat*> checkFormats;
    for ( size_t i = 0; i < pTable->size(); ++i )
    {
        SwFrameFormat *pFormat = (*pTable)[i];
        const SwFormatAnchor &rAnch = pFormat->GetAnchor();
        if ( rAnch.GetContentAnchor() &&
            IsShown(nIndex, rAnch, pIter, pEnd, pFirstNode, pLastNode))
        {
            checkFormats.push_back( pFormat );
        }
    }
#else
    (void)pTable;
#endif

    SwNode const& rNode(*pDoc->GetNodes()[nIndex]);
    std::vector<SwFrameFormat*> const*const pFlys(rNode.GetAnchoredFlys());
    for (size_t it = 0; pFlys && it != pFlys->size(); )
    {
        SwFrameFormat *const pFormat = (*pFlys)[it];
        const SwFormatAnchor &rAnch = pFormat->GetAnchor();
        if ( rAnch.GetContentAnchor() &&
            IsShown(nIndex, rAnch, pIter, pEnd, pFirstNode, pLastNode))
        {
#if OSL_DEBUG_LEVEL > 0
            std::vector<SwFrameFormat*>::iterator checkPos = std::find( checkFormats.begin(), checkFormats.end(), pFormat );
            assert( checkPos != checkFormats.end());
            checkFormats.erase( checkPos );
#endif
            AppendObj(pFrame, pPage, pFormat, rAnch);
        }
        ++it;
    }

#if OSL_DEBUG_LEVEL > 0
    assert( checkFormats.empty());
#endif
}


void AppendObjs(const SwFrameFormats *const pTable, sal_uLong const nIndex,
        SwFrame *const pFrame, SwPageFrame *const pPage, SwDoc *const pDoc)
{
    if (pFrame->IsTextFrame())
    {
        SwTextFrame const*const pTextFrame(static_cast<SwTextFrame const*>(pFrame));
        if (sw::MergedPara const*const pMerged = pTextFrame->GetMergedPara())
        {
            std::vector<sw::Extent>::const_iterator iterFirst(pMerged->extents.begin());
            std::vector<sw::Extent>::const_iterator iter(iterFirst);
            SwTextNode const* pNode(pMerged->pFirstNode);
            for ( ; ; ++iter)
            {
                if (iter == pMerged->extents.end()
                    || iter->pNode != pNode)
                {
                    AppendObjsOfNode(pTable, pNode->GetIndex(), pFrame, pPage, pDoc,
                        &iterFirst, &iter, pMerged->pFirstNode, pMerged->pLastNode);
                    sal_uLong const until = iter == pMerged->extents.end()
                        ? pMerged->pLastNode->GetIndex() + 1
                        : iter->pNode->GetIndex();
                    for (sal_uLong i = pNode->GetIndex() + 1; i < until; ++i)
                    {
                        // let's show at-para flys on nodes that contain start/end of
                        // redline too, even if there's no text there
                        SwNode const*const pTmp(pNode->GetNodes()[i]);
                        if (pTmp->GetRedlineMergeFlag() == SwNode::Merge::NonFirst)
                        {
                            AppendObjsOfNode(pTable, pTmp->GetIndex(), pFrame, pPage, pDoc, &iter, &iter, pMerged->pFirstNode, pMerged->pLastNode);
                        }
                    }
                    if (iter == pMerged->extents.end())
                    {
                        break;
                    }
                    pNode = iter->pNode;
                    iterFirst = iter;
                }
            }
        }
        else
        {
            return AppendObjsOfNode(pTable, nIndex, pFrame, pPage, pDoc, nullptr, nullptr, nullptr, nullptr);
        }
    }
    else
    {
        return AppendObjsOfNode(pTable, nIndex, pFrame, pPage, pDoc, nullptr, nullptr, nullptr, nullptr);
    }
}

bool IsAnchoredObjShown(SwTextFrame const& rFrame, SwFormatAnchor const& rAnchor)
{
    assert(rAnchor.GetAnchorId() == RndStdIds::FLY_AT_PARA ||
           rAnchor.GetAnchorId() == RndStdIds::FLY_AT_CHAR ||
           rAnchor.GetAnchorId() == RndStdIds::FLY_AS_CHAR);
    bool ret(true);
    if (auto const pMergedPara = rFrame.GetMergedPara())
    {
        ret = false;
        auto const pAnchor(rAnchor.GetContentAnchor());
        auto iterFirst(pMergedPara->extents.cbegin());
        auto iter(iterFirst);
        SwTextNode const* pNode(pMergedPara->pFirstNode);
        for ( ; ; ++iter)
        {
            if (iter == pMergedPara->extents.end()
                || iter->pNode != pNode)
            {
                assert(pNode->GetRedlineMergeFlag() != SwNode::Merge::Hidden);
                if (pNode == &pAnchor->nNode.GetNode())
                {
                    ret = IsShown(pNode->GetIndex(), rAnchor, &iterFirst, &iter,
                            pMergedPara->pFirstNode, pMergedPara->pLastNode);
                    break;
                }
                if (iter == pMergedPara->extents.end())
                {
                    break;
                }
                pNode = iter->pNode;
                if (pAnchor->nNode.GetIndex() < pNode->GetIndex())
                {
                    break;
                }
                iterFirst = iter;
            }
        }
    }
    return ret;
}

void AppendAllObjs(const SwFrameFormats* pTable, const SwFrame* pSib)
{
    //Connecting of all Objects, which are described in the SpzTable with the
    //layout.

    boost::circular_buffer<SwFrameFormat*> vFormatsToConnect(pTable->size());
    for(const auto& pFormat : *pTable)
    {
        const auto& rAnch = pFormat->GetAnchor();
        // Formats can still remain, because we neither use character bound
        // frames nor objects which are anchored to character bounds.
        if ((rAnch.GetAnchorId() != RndStdIds::FLY_AT_PAGE) && (rAnch.GetAnchorId() != RndStdIds::FLY_AS_CHAR))
        {
            auto pContentAnchor = rAnch.GetContentAnchor();
            // formats in header/footer have no dependencies
            if(pContentAnchor && pFormat->GetDoc()->IsInHeaderFooter(pContentAnchor->nNode))
                pFormat->MakeFrames();
            else
                vFormatsToConnect.push_back(pFormat);
        }
    }
    const SwRootFrame* pRoot = pSib ? pSib->getRootFrame() : nullptr;
    const SwFrameFormat* pFirstRequeued(nullptr);
    while(!vFormatsToConnect.empty())
    {
        auto& pFormat = vFormatsToConnect.front();
        bool isConnected(false);
        pFormat->CallSwClientNotify(sw::GetObjectConnectedHint(isConnected, pRoot));
        if(!isConnected)
        {
            pFormat->MakeFrames();
            pFormat->CallSwClientNotify(sw::GetObjectConnectedHint(isConnected, pRoot));
        }
        // do this *before* push_back! the circular_buffer can be "full"!
        vFormatsToConnect.pop_front();
        if (!isConnected)
        {
            if(pFirstRequeued == pFormat)
                // If nothing happens anymore we can stop.
                break;
            if(!pFirstRequeued)
                pFirstRequeued = pFormat;
            assert(!vFormatsToConnect.full());
            vFormatsToConnect.push_back(pFormat);
        }
        else
        {
            pFirstRequeued = nullptr;
        }
    }
}

namespace sw {

void RecreateStartTextFrames(SwTextNode & rNode)
{
    std::vector<SwTextFrame*> frames;
    SwIterator<SwTextFrame, SwTextNode, sw::IteratorMode::UnwrapMulti> aIter(rNode);
    for (SwTextFrame* pFrame = aIter.First(); pFrame; pFrame = aIter.Next())
    {
        if (pFrame->getRootFrame()->IsHideRedlines())
        {
            frames.push_back(pFrame);
        }
    }
    auto eMode(sw::FrameMode::Existing);
    for (SwTextFrame * pFrame : frames)
    {
        // SplitNode could have moved the original frame to the start node
        // & created a new one on end, or could have created new frame on
        // start node... grab start node's frame and recreate MergedPara.
        SwTextNode & rFirstNode(pFrame->GetMergedPara()
            ? *pFrame->GetMergedPara()->pFirstNode
            : rNode);
        assert(rFirstNode.GetIndex() <= rNode.GetIndex());
        pFrame->SetMergedPara(sw::CheckParaRedlineMerge(
                    *pFrame, rFirstNode, eMode));
        eMode = sw::FrameMode::New; // Existing is not idempotent!
        // note: this may or may not delete frames on the end node
    }
}

} // namespace sw

/** local method to set 'working' position for newly inserted frames

    OD 12.08.2003 #i17969#
*/
static void lcl_SetPos( SwFrame&             _rNewFrame,
                 const SwLayoutFrame& _rLayFrame )
{
    SwRectFnSet aRectFnSet(&_rLayFrame);
    SwFrameAreaDefinition::FrameAreaWriteAccess aFrm(_rNewFrame);
    aRectFnSet.SetPos( aFrm, aRectFnSet.GetPos(_rLayFrame.getFrameArea()) );

    // move position by one SwTwip in text flow direction in order to get
    // notifications for a new calculated position after its formatting.
    if ( aRectFnSet.IsVert() )
    {
        aFrm.Pos().AdjustX( -1 );
    }
    else
    {
        aFrm.Pos().AdjustY(1 );
    }
}

void InsertCnt_( SwLayoutFrame *pLay, SwDoc *pDoc,
                             sal_uLong nIndex, bool bPages, sal_uLong nEndIndex,
                             SwFrame *pPrv, sw::FrameMode const eMode )
{
    pDoc->getIDocumentTimerAccess().BlockIdling();
    SwRootFrame* pLayout = pLay->getRootFrame();
    const bool bOldCallbackActionEnabled = pLayout && pLayout->IsCallbackActionEnabled();
    if( bOldCallbackActionEnabled )
        pLayout->SetCallbackActionEnabled( false );

    //In the generation of the Layout bPages=true will be handed over.
    //Then will be new pages generated all x paragraphs already times in advance.
    //On breaks and/or pagedescriptorchanges the corresponding will be generated
    //immediately.
    //The advantage is, that on one hand already a nearly realistic number of
    //pages are created, but above all there are no almost endless long chain
    //of paragraphs, which must be moved expensively until it reaches a tolerable
    //reduced level.
    //We'd like to think that 20 Paragraphs fit on one page.
    //So that it does not become in extreme situations so violent we calculate depending
    //on the node something to it.
    //If in the DocStatistic a usable given pagenumber
    //(Will be cared for while writing), so it will be presumed that this will be
    //number of pages.
    const bool bStartPercent = bPages && !nEndIndex;

    SwPageFrame *pPage = pLay->FindPageFrame();
    const SwFrameFormats *pTable = pDoc->GetSpzFrameFormats();
    SwFrame       *pFrame = nullptr;
    std::unique_ptr<SwActualSection> pActualSection;
    std::unique_ptr<SwLayHelper> pPageMaker;

    //If the layout will be created (bPages == true) we do head on the progress
    //Flys and DrawObjects are not connected immediately, this
    //happens only at the end of the function.
    if ( bPages )
    {
        // Attention: the SwLayHelper class uses references to the content-,
        // page-, layout-frame etc. and may change them!
        pPageMaker.reset(new SwLayHelper( pDoc, pFrame, pPrv, pPage, pLay,
                pActualSection, nIndex, 0 == nEndIndex ));
        if( bStartPercent )
        {
            const sal_uLong nPageCount = pPageMaker->CalcPageCount();
            if( nPageCount )
                bObjsDirect = false;
        }
    }
    else
        pPageMaker = nullptr;

    if( pLay->IsInSct() &&
        ( pLay->IsSctFrame() || pLay->GetUpper() ) ) // Hereby will newbies
            // be intercepted, of which flags could not determined yet,
            // for e.g. while inserting a table
    {
        SwSectionFrame* pSct = pLay->FindSctFrame();
        // If content will be inserted in a footnote, which in a column area,
        // the column area it is not allowed to be broken up.
        // Only if in the inner of the footnote lies an area, is this a candidate
        // for pActualSection.
        // The same applies for areas in tables, if inside the table will be
        // something inserted, it's only allowed to break up areas, which
        // lies in the inside also.
        if( ( !pLay->IsInFootnote() || pSct->IsInFootnote() ) &&
            ( !pLay->IsInTab() || pSct->IsInTab() ) )
        {
            pActualSection.reset(new SwActualSection(nullptr, pSct, pSct->GetSection()->GetFormat()->GetSectionNode()));
            // tdf#132236 for SwUndoDelete: find outer sections whose start
            // nodes aren't contained in the range but whose end nodes are,
            // because section frames may need to be created for them
            SwActualSection * pUpperSection(pActualSection.get());
            while (pUpperSection->GetSectionNode()->EndOfSectionIndex() < nEndIndex)
            {
                SwStartNode *const pStart(pUpperSection->GetSectionNode()->StartOfSectionNode());
                if (!pStart->IsSectionNode())
                {
                    break;
                }
                // note: these don't have a section frame, check it in EndNode case!
                auto const pTmp(new SwActualSection(nullptr, nullptr, static_cast<SwSectionNode*>(pStart)));
                pUpperSection->SetUpper(pTmp);
                pUpperSection = pTmp;
            }
            OSL_ENSURE( !pLay->Lower() || !pLay->Lower()->IsColumnFrame(),
                "InsertCnt_: Wrong Call" );
        }
    }

    //If a section is "open", the pActualSection points to an SwActualSection.
    //If the page breaks, for "open" sections a follow will created.
    //For nested sections (which have, however, not a nested layout),
    //the SwActualSection class has a member, which points to an upper(section).
    //When the "inner" section finishes, the upper will used instead.

    // Do not consider the end node. The caller (Section/MakeFrames()) has to
    // ensure that the end of this range is positioned before EndIndex!
    for ( ; nEndIndex == 0 || nIndex < nEndIndex; ++nIndex)
    {
        SwNode *pNd = pDoc->GetNodes()[nIndex];
        if ( pNd->IsContentNode() )
        {
            SwContentNode* pNode = static_cast<SwContentNode*>(pNd);
            if (pLayout->IsHideRedlines() && !pNd->IsCreateFrameWhenHidingRedlines())
            {
                if (pNd->IsTextNode()
                    && pNd->GetRedlineMergeFlag() == SwNode::Merge::NonFirst)
                {   // must have a frame already
                    assert(static_cast<SwTextFrame*>(pNode->getLayoutFrame(pLayout))->GetMergedPara());
                }
                continue; // skip it
            }
            pFrame = pNode->IsTextNode()
                        ? sw::MakeTextFrame(*pNode->GetTextNode(), pLay, eMode)
                        : pNode->MakeFrame(pLay);
            if( pPageMaker )
                pPageMaker->CheckInsert( nIndex );

            pFrame->InsertBehind( pLay, pPrv );
            // #i27138#
            // notify accessibility paragraphs objects about changed
            // CONTENT_FLOWS_FROM/_TO relation.
            // Relation CONTENT_FLOWS_FROM for next paragraph will change
            // and relation CONTENT_FLOWS_TO for previous paragraph will change.
            if ( pFrame->IsTextFrame() )
            {
                SwViewShell* pViewShell( pFrame->getRootFrame()->GetCurrShell() );
                // no notification, if <SwViewShell> is in construction
                if ( pViewShell && !pViewShell->IsInConstructor() &&
                     pViewShell->GetLayout() &&
                     pViewShell->GetLayout()->IsAnyShellAccessible() &&
                     pFrame->FindPageFrame() != nullptr)
                {
                    pViewShell->InvalidateAccessibleParaFlowRelation(
                        dynamic_cast<SwTextFrame*>(pFrame->FindNextCnt( true )),
                        dynamic_cast<SwTextFrame*>(pFrame->FindPrevCnt()) );
                    // #i68958#
                    // The information flags of the text frame are validated
                    // in methods <FindNextCnt(..)> and <FindPrevCnt(..)>.
                    // The information flags have to be invalidated, because
                    // it is possible, that the one of its upper frames
                    // isn't inserted into the layout.
                    pFrame->InvalidateInfFlags();
                }
            }
            // OD 12.08.2003 #i17969# - consider horizontal/vertical layout
            // for setting position at newly inserted frame
            lcl_SetPos( *pFrame, *pLay );
            pPrv = pFrame;

            if ( !pTable->empty() && bObjsDirect && !bDontCreateObjects )
                AppendObjs( pTable, nIndex, pFrame, pPage, pDoc );
        }
        else if ( pNd->IsTableNode() )
        {   //Should we have encountered a table?
            SwTableNode *pTableNode = static_cast<SwTableNode*>(pNd);
            if (pLayout->IsHideRedlines())
            {
                // in the problematic case, there can be only 1 redline...
                SwPosition const tmp(*pNd);
                SwRangeRedline const*const pRedline(
                    pDoc->getIDocumentRedlineAccess().GetRedline(tmp, nullptr));
                // pathology: redline that starts on a TableNode; cannot
                // be created in UI but by import filters...
                if (pRedline
                    && pRedline->GetType() == RedlineType::Delete
                    && &pRedline->Start()->nNode.GetNode() == pNd)
                {
                    SAL_WARN("sw.pageframe", "skipping table frame creation on bizarre redline");
                    while (true)
                    {
                        pTableNode->GetNodes()[nIndex]->SetRedlineMergeFlag(SwNode::Merge::Hidden);
                        if (nIndex == pTableNode->EndOfSectionIndex())
                        {
                            break;
                        }
                        ++nIndex;
                    }
                    continue;
                }
            }
            if (pLayout->IsHideRedlines() && !pNd->IsCreateFrameWhenHidingRedlines())
            {
                assert(pNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden);
                nIndex = pTableNode->EndOfSectionIndex();
                continue; // skip it
            }

            // #108116# loading may produce table structures that GCLines
            // needs to clean up. To keep table formulas correct, change
            // all table formulas to internal (BOXPTR) representation.
            SwTableFormulaUpdate aMsgHint( &pTableNode->GetTable() );
            aMsgHint.m_eFlags = TBL_BOXPTR;
            pDoc->getIDocumentFieldsAccess().UpdateTableFields( &aMsgHint );
            pTableNode->GetTable().GCLines();

            pFrame = pTableNode->MakeFrame( pLay );

            if( pPageMaker )
                pPageMaker->CheckInsert( nIndex );

            pFrame->InsertBehind( pLay, pPrv );
            // #i27138#
            // notify accessibility paragraphs objects about changed
            // CONTENT_FLOWS_FROM/_TO relation.
            // Relation CONTENT_FLOWS_FROM for next paragraph will change
            // and relation CONTENT_FLOWS_TO for previous paragraph will change.
            {
                SwViewShell* pViewShell( pFrame->getRootFrame()->GetCurrShell() );
                // no notification, if <SwViewShell> is in construction
                if ( pViewShell && !pViewShell->IsInConstructor() &&
                     pViewShell->GetLayout() &&
                     pViewShell->GetLayout()->IsAnyShellAccessible() &&
                     pFrame->FindPageFrame() != nullptr)
                {
                    pViewShell->InvalidateAccessibleParaFlowRelation(
                            dynamic_cast<SwTextFrame*>(pFrame->FindNextCnt( true )),
                            dynamic_cast<SwTextFrame*>(pFrame->FindPrevCnt()) );
                }
            }
            if ( bObjsDirect && !pTable->empty() )
                static_cast<SwTabFrame*>(pFrame)->RegistFlys();
            // OD 12.08.2003 #i17969# - consider horizontal/vertical layout
            // for setting position at newly inserted frame
            lcl_SetPos( *pFrame, *pLay );

            pPrv = pFrame;
            //Set the index to the endnode of the table section.
            nIndex = pTableNode->EndOfSectionIndex();

            SwTabFrame* pTmpFrame = static_cast<SwTabFrame*>(pFrame);
            while ( pTmpFrame )
            {
                pTmpFrame->CheckDirChange();
                pTmpFrame = pTmpFrame->IsFollow() ? pTmpFrame->FindMaster() : nullptr;
            }

        }
        else if ( pNd->IsSectionNode() )
        {
            if (pLayout->IsHideRedlines() && !pNd->IsCreateFrameWhenHidingRedlines())
            {
                assert(pNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden);
                continue; // skip it
            }
            SwSectionNode *pNode = static_cast<SwSectionNode*>(pNd);
            if( pNode->GetSection().CalcHiddenFlag() )
                // is hidden, skip the area
                nIndex = pNode->EndOfSectionIndex();
            else
            {
                pFrame = pNode->MakeFrame( pLay );
                pActualSection.reset( new SwActualSection( pActualSection.release(),
                                                static_cast<SwSectionFrame*>(pFrame), pNode ) );
                if ( pActualSection->GetUpper() )<--- Null pointer dereference
                {
                    //Insert behind the Upper, the "Follow" of the Upper will be
                    //generated at the EndNode.
                    SwSectionFrame *pTmp = pActualSection->GetUpper()->GetSectionFrame();<--- Null pointer dereference
                    pFrame->InsertBehind( pTmp->GetUpper(), pTmp );
                    // OD 25.03.2003 #108339# - direct initialization of section
                    // after insertion in the layout
                    static_cast<SwSectionFrame*>(pFrame)->Init();
                }
                else
                {
                    pFrame->InsertBehind( pLay, pPrv );
                    // OD 25.03.2003 #108339# - direct initialization of section
                    // after insertion in the layout
                    static_cast<SwSectionFrame*>(pFrame)->Init();

                    // #i33963#
                    // Do not trust the IsInFootnote flag. If we are currently
                    // building up a table, the upper of pPrv may be a cell
                    // frame, but the cell frame does not have an upper yet.
                    if( pPrv && nullptr != pPrv->ImplFindFootnoteFrame() )
                    {
                        if( pPrv->IsSctFrame() )
                            pPrv = static_cast<SwSectionFrame*>(pPrv)->ContainsContent();
                        if( pPrv && pPrv->IsTextFrame() )
                            static_cast<SwTextFrame*>(pPrv)->Prepare( PrepareHint::QuoVadis, nullptr, false );
                    }
                }
                if (nIndex + 1 == nEndIndex)
                {   // tdf#131684 tdf#132236 fix upper of frame moved in
                    // SwUndoDelete; can't be done there unfortunately
                    // because empty section frames are deleted here
                    SwFrame *const pNext(
                        // if there's a parent section, it has been split
                        // into 2 SwSectionFrame already :(
                        (   pFrame->GetNext()->IsSctFrame()
                         && pActualSection->GetUpper()<--- Null pointer dereference
                         && pActualSection->GetUpper()->GetSectionNode() ==<--- Null pointer dereference
                             static_cast<SwSectionFrame const*>(pFrame->GetNext())->GetSection()->GetFormat()->GetSectionNode())
                        ? static_cast<SwSectionFrame *>(pFrame->GetNext())->ContainsContent()
                        : pFrame->GetNext());
                    if (pNext
                        && pNext->IsTextFrame()
                        && static_cast<SwTextFrame*>(pNext)->GetTextNodeFirst() == pDoc->GetNodes()[nEndIndex]
                        && (pNext->GetUpper() == pFrame->GetUpper()
                            || pFrame->GetNext()->IsSctFrame())) // checked above
                    {
                        pNext->Cut();
                        pNext->InvalidateInfFlags(); // mbInfSct changed
                        // could have columns
                        SwSectionFrame *const pSection(static_cast<SwSectionFrame*>(pFrame));
                        assert(!pSection->Lower() || pSection->Lower()->IsLayoutFrame());
                        SwLayoutFrame *const pParent(pSection->Lower() ? pSection->GetNextLayoutLeaf() : pSection);
                        assert(!pParent->Lower());
                        // paste invalidates, section could have indent...
                        pNext->Paste(pParent, nullptr);
                    }
                }
                // #i27138#
                // notify accessibility paragraphs objects about changed
                // CONTENT_FLOWS_FROM/_TO relation.
                // Relation CONTENT_FLOWS_FROM for next paragraph will change
                // and relation CONTENT_FLOWS_TO for previous paragraph will change.
                {
                    SwViewShell* pViewShell( pFrame->getRootFrame()->GetCurrShell() );
                    // no notification, if <SwViewShell> is in construction
                    if ( pViewShell && !pViewShell->IsInConstructor() &&
                         pViewShell->GetLayout() &&
                         pViewShell->GetLayout()->IsAnyShellAccessible() &&
                         pFrame->FindPageFrame() != nullptr)
                    {
                        pViewShell->InvalidateAccessibleParaFlowRelation(
                            dynamic_cast<SwTextFrame*>(pFrame->FindNextCnt( true )),
                            dynamic_cast<SwTextFrame*>(pFrame->FindPrevCnt()) );
                    }
                }
                pFrame->CheckDirChange();

                // OD 12.08.2003 #i17969# - consider horizontal/vertical layout
                // for setting position at newly inserted frame
                lcl_SetPos( *pFrame, *pLay );

                // OD 20.11.2002 #105405# - no page, no invalidate.
                if ( pPage )
                {
                    // OD 18.09.2002 #100522#
                    // invalidate page in order to force format and paint of
                    // inserted section frame
                    pFrame->InvalidatePage( pPage );

                    // FME 10.11.2003 #112243#
                    // Invalidate fly content flag:
                    if ( pFrame->IsInFly() )
                        pPage->InvalidateFlyContent();

                    // OD 14.11.2002 #104684# - invalidate page content in order to
                    // force format and paint of section content.
                    pPage->InvalidateContent();
                }

                pLay = static_cast<SwLayoutFrame*>(pFrame);
                if ( pLay->Lower() && pLay->Lower()->IsLayoutFrame() )
                    pLay = pLay->GetNextLayoutLeaf();
                pPrv = nullptr;
            }
        }
        else if ( pNd->IsEndNode() && pNd->StartOfSectionNode()->IsSectionNode() )
        {
            if (pLayout->IsHideRedlines() && !pNd->IsCreateFrameWhenHidingRedlines())
            {
                assert(pNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden);
                continue; // skip it
            }
            assert(pActualSection && "Section end without section start?");
            assert(pActualSection->GetSectionNode() == pNd->StartOfSectionNode());<--- Null pointer dereference

            //Close the section, where appropriate activate the surrounding
            //section again.
            pActualSection.reset(pActualSection->GetUpper());<--- Null pointer dereference
            pLay = pLay->FindSctFrame();
            if ( pActualSection )<--- Assuming that condition 'if(pActualSection)' is not redundant<--- Assuming that condition 'if(pActualSection)' is not redundant
            {
                //Could be, that the last SectionFrame remains empty.
                //Then now is the time to remove them.
                if ( !pLay->ContainsContent() )
                {
                    SwFrame *pTmpFrame = pLay;
                    pLay = pTmpFrame->GetUpper();
                    pPrv = pTmpFrame->GetPrev();
                    pTmpFrame->RemoveFromLayout();
                    SwFrame::DestroyFrame(pTmpFrame);
                }
                else
                {
                    pPrv = pLay;
                    pLay = pLay->GetUpper();
                }

                // new section frame
                pFrame = pActualSection->GetSectionNode()->MakeFrame( pLay );
                pFrame->InsertBehind( pLay, pPrv );
                static_cast<SwSectionFrame*>(pFrame)->Init();

                // OD 12.08.2003 #i17969# - consider horizontal/vertical layout
                // for setting position at newly inserted frame
                lcl_SetPos( *pFrame, *pLay );

                SwSectionFrame* pOuterSectionFrame = pActualSection->GetSectionFrame();

                // a follow has to be appended to the new section frame
                SwSectionFrame* pFollow = pOuterSectionFrame ? pOuterSectionFrame->GetFollow() : nullptr;
                if ( pFollow )
                {
                    pOuterSectionFrame->SetFollow( nullptr );
                    pOuterSectionFrame->InvalidateSize();
                    static_cast<SwSectionFrame*>(pFrame)->SetFollow( pFollow );
                }

                // We don't want to leave empty parts back.
                if (pOuterSectionFrame &&
                    ! pOuterSectionFrame->IsColLocked() &&
                    ! pOuterSectionFrame->ContainsContent() )
                {
                    pOuterSectionFrame->DelEmpty( true );
                    SwFrame::DestroyFrame(pOuterSectionFrame);
                }
                pActualSection->SetSectionFrame( static_cast<SwSectionFrame*>(pFrame) );

                pLay = static_cast<SwLayoutFrame*>(pFrame);
                if ( pLay->Lower() && pLay->Lower()->IsLayoutFrame() )
                    pLay = pLay->GetNextLayoutLeaf();
                pPrv = nullptr;
            }
            else
            {
                //Nothing more with sections, it goes on right behind
                //the SectionFrame.
                pPrv = pLay;
                pLay = pLay->GetUpper();
            }
        }
        else if( pNd->IsStartNode() &&
                 SwFlyStartNode == static_cast<SwStartNode*>(pNd)->GetStartNodeType() )
        {
            if (pLayout->IsHideRedlines() && !pNd->IsCreateFrameWhenHidingRedlines())
            {
                assert(pNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden);
                assert(false); // actually a fly-section can't be deleted?
                continue; // skip it
            }
            if ( !pTable->empty() && bObjsDirect && !bDontCreateObjects )
            {
                SwFlyFrame* pFly = pLay->FindFlyFrame();
                if( pFly )
                    AppendObjs( pTable, nIndex, pFly, pPage, pDoc );
            }
        }
        else
        {
            assert(!pLayout->IsHideRedlines()
                || pNd->GetRedlineMergeFlag() != SwNode::Merge::Hidden);
            // Neither Content nor table nor section, so we are done.
            break;
        }
    }

    if ( pActualSection )
    {
        // Might happen that an empty (Follow-)Section is left over.
        if ( !(pLay = pActualSection->GetSectionFrame())->ContainsContent() )
        {
            pLay->RemoveFromLayout();
            SwFrame::DestroyFrame(pLay);
        }
        pActualSection.reset();
    }

    if ( bPages ) // let the Flys connect to each other
    {
        if ( !bDontCreateObjects )
            AppendAllObjs( pTable, pLayout );
        bObjsDirect = true;
    }

    if( pPageMaker )
    {
        pPageMaker->CheckFlyCache( pPage );
        pPageMaker.reset();
        if( pDoc->GetLayoutCache() )
        {
#ifdef DBG_UTIL
            pDoc->GetLayoutCache()->CompareLayout( *pDoc );
#endif
            pDoc->GetLayoutCache()->ClearImpl();
        }
    }

    pDoc->getIDocumentTimerAccess().UnblockIdling();
    if( bOldCallbackActionEnabled )
        pLayout->SetCallbackActionEnabled( bOldCallbackActionEnabled );
}

void MakeFrames( SwDoc *pDoc, const SwNodeIndex &rSttIdx,
               const SwNodeIndex &rEndIdx )
{
    bObjsDirect = false;

    SwNodeIndex aTmp( rSttIdx );
    sal_uLong nEndIdx = rEndIdx.GetIndex();
    SwNode* pNd = pDoc->GetNodes().FindPrvNxtFrameNode( aTmp,
                                            pDoc->GetNodes()[ nEndIdx-1 ]);
    if ( pNd )
    {
        bool bApres = aTmp < rSttIdx;
        SwNode2Layout aNode2Layout( *pNd, rSttIdx.GetIndex() );
        SwFrame* pFrame;
        sw::FrameMode eMode = sw::FrameMode::Existing;
        while( nullptr != (pFrame = aNode2Layout.NextFrame()) )
        {
            SwLayoutFrame *pUpper = pFrame->GetUpper();
            SwFootnoteFrame* pFootnoteFrame = pUpper->FindFootnoteFrame();
            bool bOldLock, bOldFootnote;
            if( pFootnoteFrame )
            {
                bOldFootnote = pFootnoteFrame->IsColLocked();
                pFootnoteFrame->ColLock();
            }
            else
                bOldFootnote = true;
            SwSectionFrame* pSct = pUpper->FindSctFrame();
            // Inside of footnotes only those areas are interesting that are inside of them. But
            // not the ones (e.g. column areas) in which are the footnote containers positioned.
            // #109767# Table frame is in section, insert section in cell frame.
            if( pSct && ((pFootnoteFrame && !pSct->IsInFootnote()) || pUpper->IsCellFrame()) )
                pSct = nullptr;
            if( pSct )
            {   // to prevent pTmp->MoveFwd from destroying the SectionFrame
                bOldLock = pSct->IsColLocked();
                pSct->ColLock();
            }
            else
                bOldLock = true;

            // If pFrame cannot be moved, it is not possible to move it to the next page. This applies
            // also for frames (in the first column of a frame pFrame is moveable) and column
            // sections of tables (also here pFrame is moveable).
            bool bMoveNext = nEndIdx - rSttIdx.GetIndex() > 120;
            bool bAllowMove = !pFrame->IsInFly() && pFrame->IsMoveable() &&
                 (!pFrame->IsInTab() || pFrame->IsTabFrame() );
            if ( bMoveNext && bAllowMove )
            {
                SwFrame *pMove = pFrame;
                SwFrame *pPrev = pFrame->GetPrev();
                SwFlowFrame *pTmp = SwFlowFrame::CastFlowFrame( pMove );
                assert(pTmp);

                if ( bApres )
                {
                    // The rest of this page should be empty. Thus, the following one has to move to
                    // the next page (it might also be located in the following column).
                    assert(!pTmp->HasFollow() && "prev. node's frame is not last");
                    pPrev = pFrame;
                    // If the surrounding SectionFrame has a "next" one,
                    // so this one needs to be moved as well.
                    pMove = pFrame->GetIndNext();
                    SwColumnFrame* pCol = static_cast<SwColumnFrame*>(pFrame->FindColFrame());
                    if( pCol )
                        pCol = static_cast<SwColumnFrame*>(pCol->GetNext());
                    do
                    {
                        if( pCol && !pMove )
                        {   // No successor so far, look into the next column
                            pMove = pCol->ContainsAny();
                            if( pCol->GetNext() )
                                pCol = static_cast<SwColumnFrame*>(pCol->GetNext());
                            else if( pCol->IsInSct() )
                            {   // If there is no following column but we are in a column frame,
                                // there might be (page) columns outside of it.
                                pCol = static_cast<SwColumnFrame*>(pCol->FindSctFrame()->FindColFrame());
                                if( pCol )
                                    pCol = static_cast<SwColumnFrame*>(pCol->GetNext());
                            }
                            else
                                pCol = nullptr;
                        }
                        // skip invalid SectionFrames
                        while( pMove && pMove->IsSctFrame() &&
                               !static_cast<SwSectionFrame*>(pMove)->GetSection() )
                            pMove = pMove->GetNext();
                    } while( !pMove && pCol );

                    if( pMove )
                    {
                        if ( pMove->IsContentFrame() )
                            pTmp = static_cast<SwContentFrame*>(pMove);
                        else if ( pMove->IsTabFrame() )
                            pTmp = static_cast<SwTabFrame*>(pMove);
                        else if ( pMove->IsSctFrame() )
                        {
                            pMove = static_cast<SwSectionFrame*>(pMove)->ContainsAny();
                            if( pMove )
                                pTmp = SwFlowFrame::CastFlowFrame( pMove );
                            else
                                pTmp = nullptr;
                        }
                    }
                    else
                        pTmp = nullptr;
                }
                else
                {
                    assert(!pTmp->IsFollow() && "next node's frame is not master");
                    // move the _content_ of a section frame
                    if( pMove->IsSctFrame() )
                    {
                        while( pMove && pMove->IsSctFrame() &&
                               !static_cast<SwSectionFrame*>(pMove)->GetSection() )
                            pMove = pMove->GetNext();
                        if( pMove && pMove->IsSctFrame() )
                            pMove = static_cast<SwSectionFrame*>(pMove)->ContainsAny();
                        if( pMove )
                            pTmp = SwFlowFrame::CastFlowFrame( pMove );
                        else
                            pTmp = nullptr;
                    }
                }

                if( pTmp )
                {
                    SwFrame* pOldUp = pTmp->GetFrame().GetUpper();
                    // MoveFwd==true means that we are still on the same page.
                    // But since we want to move if possible!
                    bool bTmpOldLock = pTmp->IsJoinLocked();
                    pTmp->LockJoin();
                    while( pTmp->MoveFwd( true, false, true ) )
                    {
                        if( pOldUp == pTmp->GetFrame().GetUpper() )
                            break;
                        pOldUp = pTmp->GetFrame().GetUpper();
                    }
                    if( !bTmpOldLock )
                        pTmp->UnlockJoin();
                }
                ::InsertCnt_( pUpper, pDoc, rSttIdx.GetIndex(),
                              pFrame->IsInDocBody(), nEndIdx, pPrev, eMode );
            }
            else
            {
                bool bSplit;
                SwFrame* pPrv = bApres ? pFrame : pFrame->GetPrev();
                // If the section frame is inserted into another one, it must be split.
                if( pSct && rSttIdx.GetNode().IsSectionNode() )
                {
                    bSplit = pSct->SplitSect( pFrame, bApres );
                    if( !bSplit && !bApres )
                    {
                        pUpper = pSct->GetUpper();
                        pPrv = pSct->GetPrev();
                    }
                }
                else
                    bSplit = false;

                ::InsertCnt_( pUpper, pDoc, rSttIdx.GetIndex(), false,
                              nEndIdx, pPrv, eMode );
                // OD 23.06.2003 #108784# - correction: append objects doesn't
                // depend on value of <bAllowMove>
                if( !bDontCreateObjects )
                {
                    const SwFrameFormats *pTable = pDoc->GetSpzFrameFormats();
                    if( !pTable->empty() )
                        AppendAllObjs( pTable, pUpper );
                }

                // If nothing was added (e.g. a hidden section), the split must be reversed.
                if( bSplit && pSct && pSct->GetNext()
                    && pSct->GetNext()->IsSctFrame() )
                    pSct->MergeNext( static_cast<SwSectionFrame*>(pSct->GetNext()) );
                if( pFrame->IsInFly() )
                    pFrame->FindFlyFrame()->Invalidate_();
                if( pFrame->IsInTab() )
                    pFrame->InvalidateSize();
            }

            SwPageFrame *pPage = pUpper->FindPageFrame();
            SwFrame::CheckPageDescs( pPage, false );
            if( !bOldFootnote )
                pFootnoteFrame->ColUnlock();
            if( !bOldLock )
            {
                pSct->ColUnlock();
                // pSct might be empty (e.g. when inserting linked section containing further
                // sections) and can be destroyed in such cases.
                if( !pSct->ContainsContent() )
                {
                    pSct->DelEmpty( true );
                    pUpper->getRootFrame()->RemoveFromList( pSct );
                    SwFrame::DestroyFrame(pSct);
                }
            }
            eMode = sw::FrameMode::New; // use Existing only once!
        }
    }

    bObjsDirect = true;
}

SwBorderAttrs::SwBorderAttrs(const SwModify *pMod, const SwFrame *pConstructor)
    : SwCacheObj(pMod)
    , m_rAttrSet(pConstructor->IsContentFrame()
                    ? pConstructor->IsTextFrame()
                        ? static_cast<const SwTextFrame*>(pConstructor)->GetTextNodeForParaProps()->GetSwAttrSet()
                        : static_cast<const SwNoTextFrame*>(pConstructor)->GetNode()->GetSwAttrSet()
                    : static_cast<const SwLayoutFrame*>(pConstructor)->GetFormat()->GetAttrSet())
    , m_rUL(m_rAttrSet.GetULSpace())
    // #i96772#
    // LRSpaceItem is copied due to the possibility that it is adjusted - see below
    , m_rLR(m_rAttrSet.GetLRSpace().Clone())
    , m_rBox(m_rAttrSet.GetBox())
    , m_rShadow(m_rAttrSet.GetShadow())
    , m_aFrameSize(m_rAttrSet.GetFrameSize().GetSize())
    , m_bIsLine(false)
    , m_bJoinedWithPrev(false)
    , m_bJoinedWithNext(false)
    , m_nTopLine(0)
    , m_nBottomLine(0)
    , m_nLeftLine(0)
    , m_nRightLine(0)
    , m_nTop(0)
    , m_nBottom(0)
    , m_nGetTopLine(0)
    , m_nGetBottomLine(0)
    , m_nLineSpacing(0)
{
    // #i96772#
    const SwTextFrame* pTextFrame = dynamic_cast<const SwTextFrame*>(pConstructor);
    if ( pTextFrame )
    {
        pTextFrame->GetTextNodeForParaProps()->ClearLRSpaceItemDueToListLevelIndents( m_rLR );
    }
    else if ( pConstructor->IsNoTextFrame() )
    {
        m_rLR = std::make_shared<SvxLRSpaceItem>(RES_LR_SPACE);
    }

    // Caution: The USHORTs for the cached values are not initialized by intention!

    // everything needs to be calculated at least once:
    m_bTopLine = m_bBottomLine = m_bLeftLine = m_bRightLine =
    m_bTop     = m_bBottom     = m_bLine   = true;

    // except this one: calculate line spacing before cell border only for text frames
    m_bLineSpacing = bool(pTextFrame);

    m_bCacheGetLine = m_bCachedGetTopLine = m_bCachedGetBottomLine = false;
    // OD 21.05.2003 #108789# - init cache status for values <m_bJoinedWithPrev>
    // and <m_bJoinedWithNext>, which aren't initialized by default.
    m_bCachedJoinedWithPrev = false;
    m_bCachedJoinedWithNext = false;
}

SwBorderAttrs::~SwBorderAttrs()
{
    const_cast<SwModify *>(static_cast<SwModify const *>(m_pOwner))->SetInCache( false );
}

/* All calc methods calculate a safety distance in addition to the values given by the attributes.
 * This safety distance is only added when working with borders and/or shadows to prevent that
 * e.g. borders are painted over.
 */

void SwBorderAttrs::CalcTop_()
{
    m_nTop = CalcTopLine() + m_rUL.GetUpper();
    m_bTop = false;
}

void SwBorderAttrs::CalcBottom_()
{
    m_nBottom = CalcBottomLine() + m_rUL.GetLower();
    m_bBottom = false;
}

long SwBorderAttrs::CalcRight( const SwFrame* pCaller ) const
{
    long nRight=0;

    if (!pCaller->IsTextFrame() || !static_cast<const SwTextFrame*>(pCaller)->GetDoc().GetDocumentSettingManager().get(DocumentSettingId::INVERT_BORDER_SPACING)) {
    // OD 23.01.2003 #106895# - for cell frame in R2L text direction the left
    // and right border are painted on the right respectively left.
    if ( pCaller->IsCellFrame() && pCaller->IsRightToLeft() )
        nRight = CalcLeftLine();
    else
        nRight = CalcRightLine();

    }
    // for paragraphs, "left" is "before text" and "right" is "after text"
    if ( pCaller->IsTextFrame() && pCaller->IsRightToLeft() )
        nRight += m_rLR->GetLeft();
    else
        nRight += m_rLR->GetRight();

    // correction: retrieve left margin for numbering in R2L-layout
    if ( pCaller->IsTextFrame() && pCaller->IsRightToLeft() )
    {
        nRight += static_cast<const SwTextFrame*>(pCaller)->GetTextNodeForParaProps()->GetLeftMarginWithNum();
    }

    return nRight;
}

/// Tries to detect if this paragraph has a floating table attached.
static bool lcl_hasTabFrame(const SwTextFrame* pTextFrame)
{
    if (pTextFrame->GetDrawObjs())
    {
        const SwSortedObjs* pSortedObjs = pTextFrame->GetDrawObjs();
        if (pSortedObjs->size() > 0)
        {
            SwAnchoredObject* pObject = (*pSortedObjs)[0];
            if (dynamic_cast<const SwFlyFrame*>(pObject) !=  nullptr)
            {
                SwFlyFrame* pFly = static_cast<SwFlyFrame*>(pObject);
                if (pFly->Lower() && pFly->Lower()->IsTabFrame())
                    return true;
            }
        }
    }
    return false;
}

long SwBorderAttrs::CalcLeft( const SwFrame *pCaller ) const
{
    long nLeft=0;

    if (!pCaller->IsTextFrame() || !static_cast<const SwTextFrame*>(pCaller)->GetDoc().GetDocumentSettingManager().get(DocumentSettingId::INVERT_BORDER_SPACING))
    {
    // OD 23.01.2003 #106895# - for cell frame in R2L text direction the left
    // and right border are painted on the right respectively left.
    if ( pCaller->IsCellFrame() && pCaller->IsRightToLeft() )
        nLeft = CalcRightLine();
    else
        nLeft = CalcLeftLine();
    }

    // for paragraphs, "left" is "before text" and "right" is "after text"
    if ( pCaller->IsTextFrame() && pCaller->IsRightToLeft() )
        nLeft += m_rLR->GetRight();
    else
    {
        bool bIgnoreMargin = false;
        if (pCaller->IsTextFrame())
        {
            const SwTextFrame* pTextFrame = static_cast<const SwTextFrame*>(pCaller);
            if (pTextFrame->GetDoc().GetDocumentSettingManager().get(DocumentSettingId::FLOATTABLE_NOMARGINS))
            {
                // If this is explicitly requested, ignore the margins next to the floating table.
                if (lcl_hasTabFrame(pTextFrame))
                    bIgnoreMargin = true;
                // TODO here we only handle the first two paragraphs, would be nice to generalize this.
                else if (pTextFrame->FindPrev() && pTextFrame->FindPrev()->IsTextFrame() && lcl_hasTabFrame(static_cast<const SwTextFrame*>(pTextFrame->FindPrev())))
                    bIgnoreMargin = true;
            }
        }
        if (!bIgnoreMargin)
            nLeft += m_rLR->GetLeft();
    }

    // correction: do not retrieve left margin for numbering in R2L-layout
    if ( pCaller->IsTextFrame() && !pCaller->IsRightToLeft() )
    {
        nLeft += static_cast<const SwTextFrame*>(pCaller)->GetTextNodeForParaProps()->GetLeftMarginWithNum();
    }

    return nLeft;
}

/* Calculated values for borders and shadows.
 * It might be that a distance is wanted even without lines. This will be
 * considered here and not by the attribute (e.g. bBorderDist for cells).
 */

void SwBorderAttrs::CalcTopLine_()
{
    m_nTopLine = m_rBox.CalcLineSpace( SvxBoxItemLine::TOP, /*bEvenIfNoLine*/true );
    m_nTopLine = m_nTopLine + m_rShadow.CalcShadowSpace(SvxShadowItemSide::TOP);
    m_bTopLine = false;
}

void SwBorderAttrs::CalcBottomLine_()
{
    m_nBottomLine = m_rBox.CalcLineSpace( SvxBoxItemLine::BOTTOM, true );
    m_nBottomLine = m_nBottomLine + m_rShadow.CalcShadowSpace(SvxShadowItemSide::BOTTOM);
    m_bBottomLine = false;
}

void SwBorderAttrs::CalcLeftLine_()
{
    m_nLeftLine = m_rBox.CalcLineSpace( SvxBoxItemLine::LEFT, true);
    m_nLeftLine = m_nLeftLine + m_rShadow.CalcShadowSpace(SvxShadowItemSide::LEFT);
    m_bLeftLine = false;
}

void SwBorderAttrs::CalcRightLine_()
{
    m_nRightLine = m_rBox.CalcLineSpace( SvxBoxItemLine::RIGHT, true );
    m_nRightLine = m_nRightLine + m_rShadow.CalcShadowSpace(SvxShadowItemSide::RIGHT);
    m_bRightLine = false;
}

void SwBorderAttrs::IsLine_()
{
    m_bIsLine = m_rBox.GetTop() || m_rBox.GetBottom() ||
              m_rBox.GetLeft()|| m_rBox.GetRight();
    m_bLine = false;
}

/* The borders of neighboring paragraphs are condensed by following algorithm:
 *
 * 1. No top border if the predecessor has the same top border and (3) applies.
 *    In addition, the paragraph needs to have a border at least one side (left/right/bottom).
 * 2. No bottom border if the successor has the same bottom border and (3) applies.
 *    In addition, the paragraph needs to have a border at least one side (left/right/top).
 * 3. The borders on the left and right side are identical between the current and the
 *    pre-/succeeding paragraph.
 */

static bool CmpLines( const editeng::SvxBorderLine *pL1, const editeng::SvxBorderLine *pL2 )
{
    return ( ((pL1 && pL2) && (*pL1 == *pL2)) || (!pL1 && !pL2) );
}

// OD 21.05.2003 #108789# - change name of 1st parameter - "rAttrs" -> "rCmpAttrs"
// OD 21.05.2003 #108789# - compare <CalcRight()> and <rCmpAttrs.CalcRight()>
//          instead of only the right LR-spacing, because R2L-layout has to be
//          considered.
bool SwBorderAttrs::CmpLeftRight( const SwBorderAttrs &rCmpAttrs,
                                  const SwFrame *pCaller,
                                  const SwFrame *pCmp ) const
{
    return ( CmpLines( rCmpAttrs.GetBox().GetLeft(), GetBox().GetLeft()  ) &&
             CmpLines( rCmpAttrs.GetBox().GetRight(),GetBox().GetRight() ) &&
             CalcLeft( pCaller ) == rCmpAttrs.CalcLeft( pCmp ) &&
             // OD 21.05.2003 #108789# - compare <CalcRight> with <rCmpAttrs.CalcRight>.
             CalcRight( pCaller ) == rCmpAttrs.CalcRight( pCmp ) );
}

bool SwBorderAttrs::JoinWithCmp( const SwFrame& _rCallerFrame,
                                  const SwFrame& _rCmpFrame ) const
{
    bool bReturnVal = false;

    SwBorderAttrAccess aCmpAccess( SwFrame::GetCache(), &_rCmpFrame );
    const SwBorderAttrs &rCmpAttrs = *aCmpAccess.Get();
    if ( m_rShadow == rCmpAttrs.GetShadow() &&
         CmpLines( m_rBox.GetTop(), rCmpAttrs.GetBox().GetTop() ) &&
         CmpLines( m_rBox.GetBottom(), rCmpAttrs.GetBox().GetBottom() ) &&
         CmpLeftRight( rCmpAttrs, &_rCallerFrame, &_rCmpFrame )
       )
    {
        bReturnVal = true;
    }

    return bReturnVal;
}

// OD 21.05.2003 #108789# - method to determine, if borders are joined with
// previous frame. Calculated value saved in cached value <m_bJoinedWithPrev>
// OD 2004-02-26 #i25029# - add 2nd parameter <_pPrevFrame>
void SwBorderAttrs::CalcJoinedWithPrev( const SwFrame& _rFrame,
                                         const SwFrame* _pPrevFrame )
{
    // set default
    m_bJoinedWithPrev = false;

    if ( _rFrame.IsTextFrame() )
    {
        // text frame can potentially join with previous text frame, if
        // corresponding attribute set is set at previous text frame.
        // OD 2004-02-26 #i25029# - If parameter <_pPrevFrame> is set, take this
        // one as previous frame.
        const SwFrame* pPrevFrame = _pPrevFrame ? _pPrevFrame : _rFrame.GetPrev();
        // OD 2004-02-13 #i25029# - skip hidden text frames.
        while ( pPrevFrame && pPrevFrame->IsTextFrame() &&
                static_cast<const SwTextFrame*>(pPrevFrame)->IsHiddenNow() )
        {
            pPrevFrame = pPrevFrame->GetPrev();
        }
        if ( pPrevFrame && pPrevFrame->IsTextFrame() &&
             pPrevFrame->GetAttrSet()->GetParaConnectBorder().GetValue()
           )
        {
            m_bJoinedWithPrev = JoinWithCmp( _rFrame, *pPrevFrame );
        }
    }

    // valid cache status, if demanded
    // OD 2004-02-26 #i25029# - Do not validate cache, if parameter <_pPrevFrame>
    // is set.
    m_bCachedJoinedWithPrev = m_bCacheGetLine && !_pPrevFrame;
}

// OD 21.05.2003 #108789# - method to determine, if borders are joined with
// next frame. Calculated value saved in cached value <m_bJoinedWithNext>
void SwBorderAttrs::CalcJoinedWithNext( const SwFrame& _rFrame )
{
    // set default
    m_bJoinedWithNext = false;

    if ( _rFrame.IsTextFrame() )
    {
        // text frame can potentially join with next text frame, if
        // corresponding attribute set is set at current text frame.
        // OD 2004-02-13 #i25029# - get next frame, but skip hidden text frames.
        const SwFrame* pNextFrame = _rFrame.GetNext();
        while ( pNextFrame && pNextFrame->IsTextFrame() &&
                static_cast<const SwTextFrame*>(pNextFrame)->IsHiddenNow() )
        {
            pNextFrame = pNextFrame->GetNext();
        }
        if ( pNextFrame && pNextFrame->IsTextFrame() &&
             _rFrame.GetAttrSet()->GetParaConnectBorder().GetValue()
           )
        {
            m_bJoinedWithNext = JoinWithCmp( _rFrame, *pNextFrame );
        }
    }

    // valid cache status, if demanded
    m_bCachedJoinedWithNext = m_bCacheGetLine;
}

// OD 21.05.2003 #108789# - accessor for cached values <m_bJoinedWithPrev>
// OD 2004-02-26 #i25029# - add 2nd parameter <_pPrevFrame>, which is passed to
// method <_CalcJoindWithPrev(..)>.
bool SwBorderAttrs::JoinedWithPrev( const SwFrame& _rFrame,
                                    const SwFrame* _pPrevFrame ) const
{
    if ( !m_bCachedJoinedWithPrev || _pPrevFrame )
    {
        // OD 2004-02-26 #i25029# - pass <_pPrevFrame> as 2nd parameter
        const_cast<SwBorderAttrs*>(this)->CalcJoinedWithPrev( _rFrame, _pPrevFrame );
    }

    return m_bJoinedWithPrev;
}

bool SwBorderAttrs::JoinedWithNext( const SwFrame& _rFrame ) const
{
    if ( !m_bCachedJoinedWithNext )
    {
        const_cast<SwBorderAttrs*>(this)->CalcJoinedWithNext( _rFrame );
    }

    return m_bJoinedWithNext;
}

// OD 2004-02-26 #i25029# - added 2nd parameter <_pPrevFrame>, which is passed to
// method <JoinedWithPrev>
void SwBorderAttrs::GetTopLine_( const SwFrame& _rFrame,
                                 const SwFrame* _pPrevFrame )
{
    sal_uInt16 nRet = CalcTopLine();

    // OD 21.05.2003 #108789# - use new method <JoinWithPrev()>
    // OD 2004-02-26 #i25029# - add 2nd parameter
    if ( JoinedWithPrev( _rFrame, _pPrevFrame ) )
    {
        nRet = 0;
    }

    m_bCachedGetTopLine = m_bCacheGetLine;

    m_nGetTopLine = nRet;
}

void SwBorderAttrs::GetBottomLine_( const SwFrame& _rFrame )
{
    sal_uInt16 nRet = CalcBottomLine();

    // OD 21.05.2003 #108789# - use new method <JoinWithPrev()>
    if ( JoinedWithNext( _rFrame ) )
    {
        nRet = 0;
    }

    m_bCachedGetBottomLine = m_bCacheGetLine;

    m_nGetBottomLine = nRet;
}

void SwBorderAttrs::CalcLineSpacing_()
{
    // tdf#125300 compatibility option AddParaSpacingToTableCells needs also line spacing
    const SvxLineSpacingItem &rSpace = m_rAttrSet.GetLineSpacing();
    if ( rSpace.GetInterLineSpaceRule() == SvxInterLineSpaceRule::Prop && rSpace.GetPropLineSpace() > 100 )
    {
        sal_Int32 nFontSize = m_rAttrSet.Get(RES_CHRATR_FONTSIZE).GetHeight();
        m_nLineSpacing = nFontSize * (rSpace.GetPropLineSpace() - 100) * 1.15 / 100;
    }
    m_bLineSpacing = false;
}

static SwModify const* GetCacheOwner(SwFrame const& rFrame)
{
    return rFrame.IsContentFrame()
        ? static_cast<SwModify const*>(rFrame.IsTextFrame()
        // sw_redlinehide: presumably this caches the border attrs at the model level and can be shared across different layouts so we want the ParaProps node here
            ? static_cast<const SwTextFrame&>(rFrame).GetTextNodeForParaProps()
            : static_cast<const SwNoTextFrame&>(rFrame).GetNode())
        : static_cast<SwModify const*>(static_cast<const SwLayoutFrame&>(rFrame).GetFormat());
}

SwBorderAttrAccess::SwBorderAttrAccess( SwCache &rCach, const SwFrame *pFrame ) :
    SwCacheAccess( rCach,
        static_cast<void const *>(GetCacheOwner(*pFrame)),
        GetCacheOwner(*pFrame)->IsInCache()),
    m_pConstructor( pFrame )
{
}

SwCacheObj *SwBorderAttrAccess::NewObj()
{
    const_cast<SwModify *>(static_cast<SwModify const *>(m_pOwner))->SetInCache( true );
    return new SwBorderAttrs( static_cast<SwModify const *>(m_pOwner), m_pConstructor );
}

SwBorderAttrs *SwBorderAttrAccess::Get()
{
    return static_cast<SwBorderAttrs*>(SwCacheAccess::Get());
}

SwOrderIter::SwOrderIter( const SwPageFrame *pPg ) :
    m_pPage( pPg ),
    m_pCurrent( nullptr )
{
}

void SwOrderIter::Top()
{
    m_pCurrent = nullptr;
    if ( m_pPage->GetSortedObjs() )
    {
        const SwSortedObjs *pObjs = m_pPage->GetSortedObjs();
        if ( pObjs->size() )
        {
            sal_uInt32 nTopOrd = 0;
            (*pObjs)[0]->GetDrawObj()->GetOrdNum();  // force updating
            for (SwAnchoredObject* i : *pObjs)
            {
                const SdrObject* pObj = i->GetDrawObj();
                if ( dynamic_cast<const SwVirtFlyDrawObj*>( pObj) ==  nullptr )
                    continue;
                sal_uInt32 nTmp = pObj->GetOrdNumDirect();
                if ( nTmp >= nTopOrd )
                {
                    nTopOrd = nTmp;
                    m_pCurrent = pObj;
                }
            }
        }
    }
}

const SdrObject *SwOrderIter::Bottom()
{
    m_pCurrent = nullptr;
    if ( m_pPage->GetSortedObjs() )
    {
        sal_uInt32 nBotOrd = USHRT_MAX;
        const SwSortedObjs *pObjs = m_pPage->GetSortedObjs();
        if ( pObjs->size() )
        {
            (*pObjs)[0]->GetDrawObj()->GetOrdNum();  // force updating
            for (SwAnchoredObject* i : *pObjs)
            {
                const SdrObject* pObj = i->GetDrawObj();
                if ( dynamic_cast<const SwVirtFlyDrawObj*>( pObj) ==  nullptr )
                    continue;
                sal_uInt32 nTmp = pObj->GetOrdNumDirect();
                if ( nTmp < nBotOrd )
                {
                    nBotOrd = nTmp;
                    m_pCurrent = pObj;
                }
            }
        }
    }
    return m_pCurrent;
}

const SdrObject *SwOrderIter::Next()
{
    const sal_uInt32 nCurOrd = m_pCurrent ? m_pCurrent->GetOrdNumDirect() : 0;
    m_pCurrent = nullptr;
    if ( m_pPage->GetSortedObjs() )
    {
        sal_uInt32 nOrd = USHRT_MAX;
        const SwSortedObjs *pObjs = m_pPage->GetSortedObjs();
        if ( pObjs->size() )
        {
            (*pObjs)[0]->GetDrawObj()->GetOrdNum();  // force updating
            for (SwAnchoredObject* i : *pObjs)
            {
                const SdrObject* pObj = i->GetDrawObj();
                if ( dynamic_cast<const SwVirtFlyDrawObj*>( pObj) ==  nullptr )
                    continue;
                sal_uInt32 nTmp = pObj->GetOrdNumDirect();
                if ( nTmp > nCurOrd && nTmp < nOrd )
                {
                    nOrd = nTmp;
                    m_pCurrent = pObj;
                }
            }
        }
    }
    return m_pCurrent;
}

void SwOrderIter::Prev()
{
    const sal_uInt32 nCurOrd = m_pCurrent ? m_pCurrent->GetOrdNumDirect() : 0;
    m_pCurrent = nullptr;
    if ( m_pPage->GetSortedObjs() )
    {
        const SwSortedObjs *pObjs = m_pPage->GetSortedObjs();
        if ( pObjs->size() )
        {
            sal_uInt32 nOrd = 0;
            (*pObjs)[0]->GetDrawObj()->GetOrdNum();  // force updating
            for (SwAnchoredObject* i : *pObjs)
            {
                const SdrObject* pObj = i->GetDrawObj();
                if ( dynamic_cast<const SwVirtFlyDrawObj*>( pObj) ==  nullptr )
                    continue;
                sal_uInt32 nTmp = pObj->GetOrdNumDirect();
                if ( nTmp < nCurOrd && nTmp >= nOrd )
                {
                    nOrd = nTmp;
                    m_pCurrent = pObj;
                }
            }
        }
    }
}

/// Keep and restore the substructure of a layout frame for an action.
// New algorithm:
//   Do not look at each neighbor one by one to set all pointers correctly.
//   It is sufficient to detach a part of a chain and check if another chain needs to be added
//   when attaching it again. Only the pointers necessary for the chain connection need to be
//   adjusted. The correction happens in RestoreContent(). In between all access is restricted.
//   During this action, the Flys are detached from the page.

// #115759# - 'remove' also drawing object from page and
// at-fly anchored objects from page
static void lcl_RemoveObjsFromPage( SwFrame* _pFrame )
{
    OSL_ENSURE( _pFrame->GetDrawObjs(), "no DrawObjs in lcl_RemoveObjsFromPage." );
    SwSortedObjs &rObjs = *_pFrame->GetDrawObjs();<--- Variable 'rObjs' can be declared with const
    for (SwAnchoredObject* pObj : rObjs)
    {
        // #115759# - reset member, at which the anchored
        // object orients its vertical position
        pObj->ClearVertPosOrientFrame();
        // #i43913#
        pObj->ResetLayoutProcessBools();
        // #115759# - remove also lower objects of as-character
        // anchored Writer fly frames from page
        if ( dynamic_cast<const SwFlyFrame*>( pObj) !=  nullptr )
        {
            SwFlyFrame* pFlyFrame = static_cast<SwFlyFrame*>(pObj);

            // #115759# - remove also direct lowers of Writer
            // fly frame from page
            if ( pFlyFrame->GetDrawObjs() )
            {
                ::lcl_RemoveObjsFromPage( pFlyFrame );
            }

            SwContentFrame* pCnt = pFlyFrame->ContainsContent();
            while ( pCnt )
            {
                if ( pCnt->GetDrawObjs() )
                    ::lcl_RemoveObjsFromPage( pCnt );
                pCnt = pCnt->GetNextContentFrame();
            }
            if ( pFlyFrame->IsFlyFreeFrame() )
            {
                // #i28701# - use new method <GetPageFrame()>
                if (SwPageFrame *pPg = pFlyFrame->GetPageFrame())
                    pPg->RemoveFlyFromPage(pFlyFrame);
            }
        }
        // #115759# - remove also drawing objects from page
        else if ( dynamic_cast<const SwAnchoredDrawObject*>( pObj) !=  nullptr )
        {
            if (pObj->GetFrameFormat().GetAnchor().GetAnchorId() != RndStdIds::FLY_AS_CHAR)
            {
                if (SwPageFrame *pPg = pObj->GetPageFrame())
                    pPg->RemoveDrawObjFromPage(
                                *static_cast<SwAnchoredDrawObject*>(pObj) );
            }
        }
    }
}

SwFrame *SaveContent( SwLayoutFrame *pLay, SwFrame *pStart )
{
    if( pLay->IsSctFrame() && pLay->Lower() && pLay->Lower()->IsColumnFrame() )
        sw_RemoveFootnotes( static_cast<SwColumnFrame*>(pLay->Lower()), true, true );

    SwFrame *pSav = pLay->ContainsAny();
    if ( nullptr == pSav )
        return nullptr;

    if( pSav->IsInFootnote() && !pLay->IsInFootnote() )
    {
        do
            pSav = pSav->FindNext();
        while( pSav && pSav->IsInFootnote() );
        if( !pSav || !pLay->IsAnLower( pSav ) )
            return nullptr;
    }

    // Tables should be saved as a whole, exception:
    // The contents of a section or a cell inside a table should be saved
    if ( pSav->IsInTab() && !( ( pLay->IsSctFrame() || pLay->IsCellFrame() ) && pLay->IsInTab() ) )
        while ( !pSav->IsTabFrame() )
            pSav = pSav->GetUpper();

    if( pSav->IsInSct() )
    { // search the upmost section inside of pLay
        SwFrame* pSect = pLay->FindSctFrame();
        SwFrame *pTmp = pSav;
        do
        {
            pSav = pTmp;
            pTmp = (pSav && pSav->GetUpper()) ? pSav->GetUpper()->FindSctFrame() : nullptr;
        } while ( pTmp != pSect );
    }

    SwFrame *pFloat = pSav;
    if( !pStart )
        pStart = pSav;
    bool bGo = pStart == pSav;
    do
    {
        if( bGo )
            pFloat->GetUpper()->m_pLower = nullptr; // detach the chain part

        // search the end of the chain part, remove Flys on the way
        do
        {
            if( bGo )
            {
                if ( pFloat->IsContentFrame() )
                {
                    if ( pFloat->GetDrawObjs() )
                        ::lcl_RemoveObjsFromPage( static_cast<SwContentFrame*>(pFloat) );
                }
                else if ( pFloat->IsTabFrame() || pFloat->IsSctFrame() )
                {
                    SwContentFrame *pCnt = static_cast<SwLayoutFrame*>(pFloat)->ContainsContent();
                    if( pCnt )
                    {
                        do
                        {   if ( pCnt->GetDrawObjs() )
                                ::lcl_RemoveObjsFromPage( pCnt );
                            pCnt = pCnt->GetNextContentFrame();
                        } while ( pCnt && static_cast<SwLayoutFrame*>(pFloat)->IsAnLower( pCnt ) );
                    }
                }
                else {
                    OSL_ENSURE( !pFloat, "new FloatFrame?" );
                }
            }
            if ( pFloat->GetNext()  )
            {
                if( bGo )
                    pFloat->mpUpper = nullptr;
                pFloat = pFloat->GetNext();
                if( !bGo && pFloat == pStart )
                {
                    bGo = true;
                    pFloat->mpPrev->mpNext = nullptr;
                    pFloat->mpPrev = nullptr;
                }
            }
            else
                break;

        } while ( pFloat );

        // search next chain part and connect both chains
        SwFrame *pTmp = pFloat->FindNext();
        if( bGo )
            pFloat->mpUpper = nullptr;

        if( !pLay->IsInFootnote() )
            while( pTmp && pTmp->IsInFootnote() )
                pTmp = pTmp->FindNext();

        if ( !pLay->IsAnLower( pTmp ) )
            pTmp = nullptr;

        if ( pTmp && bGo )
        {
            pFloat->mpNext = pTmp; // connect both chains
            pFloat->mpNext->mpPrev = pFloat;
        }
        pFloat = pTmp;
        bGo = bGo || ( pStart == pFloat );
    }  while ( pFloat );

    return bGo ? pStart : nullptr;
}

// #115759# - add also drawing objects to page and at-fly
// anchored objects to page
static void lcl_AddObjsToPage( SwFrame* _pFrame, SwPageFrame* _pPage )
{
    OSL_ENSURE( _pFrame->GetDrawObjs(), "no DrawObjs in lcl_AddObjsToPage." );
    SwSortedObjs &rObjs = *_pFrame->GetDrawObjs();<--- Variable 'rObjs' can be declared with const
    for (SwAnchoredObject* pObj : rObjs)
    {
        // #115759# - unlock position of anchored object
        // in order to get the object's position calculated.
        pObj->UnlockPosition();
        // #115759# - add also lower objects of as-character
        // anchored Writer fly frames from page
        if ( dynamic_cast<const SwFlyFrame*>( pObj) !=  nullptr )
        {
            SwFlyFrame* pFlyFrame = static_cast<SwFlyFrame*>(pObj);
            if ( dynamic_cast<const SwFlyFreeFrame*>( pObj) !=  nullptr )
            {
                _pPage->AppendFlyToPage( pFlyFrame );
            }
            pFlyFrame->InvalidatePos_();
            pFlyFrame->InvalidateSize_();
            pFlyFrame->InvalidatePage( _pPage );

            // #115759# - add also at-fly anchored objects
            // to page
            if ( pFlyFrame->GetDrawObjs() )
            {
                ::lcl_AddObjsToPage( pFlyFrame, _pPage );
            }

            SwContentFrame *pCnt = pFlyFrame->ContainsContent();
            while ( pCnt )
            {
                if ( pCnt->GetDrawObjs() )
                    ::lcl_AddObjsToPage( pCnt, _pPage );
                pCnt = pCnt->GetNextContentFrame();
            }
        }
        // #115759# - remove also drawing objects from page
        else if ( dynamic_cast<const SwAnchoredDrawObject*>( pObj) !=  nullptr )
        {
            if (pObj->GetFrameFormat().GetAnchor().GetAnchorId() != RndStdIds::FLY_AS_CHAR)
            {
                pObj->InvalidateObjPos();
                _pPage->AppendDrawObjToPage(
                                *static_cast<SwAnchoredDrawObject*>(pObj) );
            }
        }
    }
}

void RestoreContent( SwFrame *pSav, SwLayoutFrame *pParent, SwFrame *pSibling )
{
    OSL_ENSURE( pSav && pParent, "no Save or Parent provided for RestoreContent." );
    SwRectFnSet aRectFnSet(pParent);

    // If there are already FlowFrames below the new parent, so add the chain (starting with pSav)
    // after the last one. The parts are inserted and invalidated if needed.
    // On the way, the Flys of the ContentFrames are registered at the page.

    SwPageFrame *pPage = pParent->FindPageFrame();

    if ( pPage )
        pPage->InvalidatePage( pPage );

    // determine predecessor and establish connection or initialize
    pSav->mpPrev = pSibling;
    SwFrame* pNxt;
    if ( pSibling )
    {
        pNxt = pSibling->mpNext;
        pSibling->mpNext = pSav;
        pSibling->InvalidatePrt_();
        pSibling->InvalidatePage( pPage );
        SwFlowFrame *pFlowFrame = dynamic_cast<SwFlowFrame*>(pSibling);
        if (pFlowFrame && pFlowFrame->GetFollow())
            pSibling->Prepare( PrepareHint::Clear, nullptr, false );
    }
    else
    {   pNxt = pParent->m_pLower;
        pParent->m_pLower = pSav;
        pSav->mpUpper = pParent; // set here already, so that it is explicit when invalidating

        if ( pSav->IsContentFrame() )
            static_cast<SwContentFrame*>(pSav)->InvalidatePage( pPage );
        else
        {   // pSav might be an empty SectFrame
            SwContentFrame* pCnt = pParent->ContainsContent();
            if( pCnt )
                pCnt->InvalidatePage( pPage );
        }
    }

    // the parent needs to grow appropriately
    SwTwips nGrowVal = 0;
    SwFrame* pLast;
    do
    {   pSav->mpUpper = pParent;
        nGrowVal += aRectFnSet.GetHeight(pSav->getFrameArea());
        pSav->InvalidateAll_();

        // register Flys, if TextFrames than also invalidate appropriately
        if ( pSav->IsContentFrame() )
        {
            if ( pSav->IsTextFrame() &&
                 static_cast<SwTextFrame*>(pSav)->GetCacheIdx() != USHRT_MAX )
                static_cast<SwTextFrame*>(pSav)->Init();  // I am its friend

            if ( pPage && pSav->GetDrawObjs() )
                ::lcl_AddObjsToPage( static_cast<SwContentFrame*>(pSav), pPage );
        }
        else
        {   SwContentFrame *pBlub = static_cast<SwLayoutFrame*>(pSav)->ContainsContent();
            if( pBlub )
            {
                do
                {   if ( pPage && pBlub->GetDrawObjs() )
                        ::lcl_AddObjsToPage( pBlub, pPage );
                    if( pBlub->IsTextFrame() && static_cast<SwTextFrame*>(pBlub)->HasFootnote() &&
                         static_cast<SwTextFrame*>(pBlub)->GetCacheIdx() != USHRT_MAX )
                        static_cast<SwTextFrame*>(pBlub)->Init(); // I am its friend
                    pBlub = pBlub->GetNextContentFrame();
                } while ( pBlub && static_cast<SwLayoutFrame*>(pSav)->IsAnLower( pBlub ));
            }
        }
        pLast = pSav;
        pSav = pSav->GetNext();

    } while ( pSav );

    if( pNxt )
    {
        pLast->mpNext = pNxt;
        pNxt->mpPrev = pLast;
    }

    pParent->Grow( nGrowVal );
}

namespace sw {

bool IsRightPageByNumber(SwRootFrame const& rLayout, sal_uInt16 const nPageNum)
{
    assert(rLayout.GetLower());
    // unfortunately can only get SwPageDesc, not SwFormatPageDesc here...
    auto const nFirstVirtPageNum(rLayout.GetLower()->GetVirtPageNum());
    bool const isFirstPageOfLayoutOdd(nFirstVirtPageNum % 2 == 1);
    return ((nPageNum % 2) == 1) == isFirstPageOfLayoutOdd;
}

} // namespace sw

SwPageFrame * InsertNewPage( SwPageDesc &rDesc, SwFrame *pUpper,
        bool const isRightPage, bool const bFirst, bool bInsertEmpty,
        bool const bFootnote,
                          SwFrame *pSibling )
{
    assert(pUpper);
    assert(pUpper->IsRootFrame());
    assert(!pSibling || static_cast<SwLayoutFrame const*>(pUpper)->Lower() != pSibling); // currently no insert before 1st page
    SwPageFrame *pRet;
    SwDoc *pDoc = static_cast<SwLayoutFrame*>(pUpper)->GetFormat()->GetDoc();
    if (bFirst)
    {
        if (rDesc.IsFirstShared())
        {
            // We need to fallback to left or right page format, decide it now.
            // FIXME: is this still needed?
            if (isRightPage)
            {
                rDesc.GetFirstMaster().SetFormatAttr( rDesc.GetMaster().GetHeader() );
                rDesc.GetFirstMaster().SetFormatAttr( rDesc.GetMaster().GetFooter() );
                // fdo#60250 copy margins for mirrored pages
                rDesc.GetFirstMaster().SetFormatAttr( rDesc.GetMaster().GetLRSpace() );
            }
            else
            {
                rDesc.GetFirstLeft().SetFormatAttr( rDesc.GetLeft().GetHeader() );
                rDesc.GetFirstLeft().SetFormatAttr( rDesc.GetLeft().GetFooter() );
                rDesc.GetFirstLeft().SetFormatAttr( rDesc.GetLeft().GetLRSpace() );
            }
        }
    }
    SwFrameFormat *pFormat(isRightPage ? rDesc.GetRightFormat(bFirst) : rDesc.GetLeftFormat(bFirst));
    // If there is no FrameFormat for this page, add an empty page
    if ( !pFormat )
    {
        pFormat = isRightPage ? rDesc.GetLeftFormat() : rDesc.GetRightFormat();
        OSL_ENSURE( pFormat, "Descriptor without any format?!" );
        bInsertEmpty = !bInsertEmpty;
    }
    if( bInsertEmpty )
    {
        SwPageDesc *pTmpDesc = pSibling && pSibling->GetPrev() ?
                static_cast<SwPageFrame*>(pSibling->GetPrev())->GetPageDesc() : &rDesc;
        pRet = new SwPageFrame( pDoc->GetEmptyPageFormat(), pUpper, pTmpDesc );
        SAL_INFO( "sw.pageframe", "InsertNewPage - insert empty p: " << pRet << " d: " << pTmpDesc );
        pRet->Paste( pUpper, pSibling );
        pRet->PreparePage( bFootnote );
    }
    pRet = new SwPageFrame( pFormat, pUpper, &rDesc );
    SAL_INFO( "sw.pageframe", "InsertNewPage p: " << pRet << " d: " << &rDesc << " f: " << pFormat );
    pRet->Paste( pUpper, pSibling );
    pRet->PreparePage( bFootnote );
    if ( pRet->GetNext() )
        SwRootFrame::AssertPageFlys( pRet );
    return pRet;
}

/* The following two methods search the layout structure recursively and
 * register all Flys at the page that have a Frame in this structure as an anchor.
 */

static void lcl_Regist( SwPageFrame *pPage, const SwFrame *pAnch )
{
    SwSortedObjs *pObjs = const_cast<SwSortedObjs*>(pAnch->GetDrawObjs());
    for (SwAnchoredObject* pObj : *pObjs)
    {
        if (SwFlyFrame* pFly = dynamic_cast<SwFlyFrame*>(pObj))
        {
            // register (not if already known)
            // #i28701# - use new method <GetPageFrame()>
            SwPageFrame *pPg = pFly->IsFlyFreeFrame()
                             ? pFly->GetPageFrame() : pFly->FindPageFrame();
            if ( pPg != pPage )
            {
                if ( pPg )
                    pPg->RemoveFlyFromPage( pFly );
                pPage->AppendFlyToPage( pFly );
            }
            ::RegistFlys( pPage, pFly );
        }
        else
        {
            // #i87493#
            if ( pPage != pObj->GetPageFrame() )
            {
                // #i28701#
                if (SwPageFrame *pPg = pObj->GetPageFrame())
                    pPg->RemoveDrawObjFromPage( *pObj );
                pPage->AppendDrawObjToPage( *pObj );
            }
        }

        const SwFlyFrame* pFly = pAnch->FindFlyFrame();
        if ( pFly &&
             pObj->GetDrawObj()->GetOrdNum() < pFly->GetVirtDrawObj()->GetOrdNum() &&
             pObj->GetDrawObj()->getSdrPageFromSdrObject() )
        {
            //#i119945# set pFly's OrdNum to pObj's. So when pFly is removed by Undo, the original OrdNum will not be changed.
            pObj->DrawObj()->getSdrPageFromSdrObject()->SetObjectOrdNum( pFly->GetVirtDrawObj()->GetOrdNumDirect(),
                                                         pObj->GetDrawObj()->GetOrdNumDirect() );
        }
    }
}

void RegistFlys( SwPageFrame *pPage, const SwLayoutFrame *pLay )
{
    if ( pLay->GetDrawObjs() )
        ::lcl_Regist( pPage, pLay );
    const SwFrame *pFrame = pLay->Lower();
    while ( pFrame )
    {
        if ( pFrame->IsLayoutFrame() )
            ::RegistFlys( pPage, static_cast<const SwLayoutFrame*>(pFrame) );
        else if ( pFrame->GetDrawObjs() )
            ::lcl_Regist( pPage, pFrame );
        pFrame = pFrame->GetNext();
    }
}

/// Notify the background based on the difference between old and new rectangle
void Notify( SwFlyFrame *pFly, SwPageFrame *pOld, const SwRect &rOld,
             const SwRect* pOldPrt )
{
    const SwRect aFrame( pFly->GetObjRectWithSpaces() );
    if ( rOld.Pos() != aFrame.Pos() )
    {   // changed position, invalidate old and new area
        if ( rOld.HasArea() &&
             rOld.Left()+pFly->GetFormat()->GetLRSpace().GetLeft() < FAR_AWAY )
        {
            pFly->NotifyBackground( pOld, rOld, PrepareHint::FlyFrameLeave );
        }
        pFly->NotifyBackground( pFly->FindPageFrame(), aFrame, PrepareHint::FlyFrameArrive );
    }
    else if ( rOld.SSize() != aFrame.SSize() )
    {   // changed size, invalidate the area that was left or is now overlapped
        // For simplicity, we purposely invalidate a Twip even if not needed.

        SwViewShell *pSh = pFly->getRootFrame()->GetCurrShell();
        if( pSh && rOld.HasArea() )
            pSh->InvalidateWindows( rOld );

        // #i51941# - consider case that fly frame isn't
        // registered at the old page <pOld>
        SwPageFrame* pPageFrame = pFly->FindPageFrame();
        if ( pOld != pPageFrame )
        {
            pFly->NotifyBackground( pPageFrame, aFrame, PrepareHint::FlyFrameArrive );
        }

        if ( rOld.Left() != aFrame.Left() )
        {
            SwRect aTmp( rOld );
            aTmp.Union( aFrame );
            aTmp.Left(  std::min(aFrame.Left(), rOld.Left()) );
            aTmp.Right( std::max(aFrame.Left(), rOld.Left()) );
            pFly->NotifyBackground( pOld, aTmp, PrepareHint::FlyFrameSizeChanged );
        }
        SwTwips nOld = rOld.Right();
        SwTwips nNew = aFrame.Right();
        if ( nOld != nNew )
        {
            SwRect aTmp( rOld );
            aTmp.Union( aFrame );
            aTmp.Left(  std::min(nNew, nOld) );
            aTmp.Right( std::max(nNew, nOld) );
            pFly->NotifyBackground( pOld, aTmp, PrepareHint::FlyFrameSizeChanged );
        }
        if ( rOld.Top() != aFrame.Top() )
        {
            SwRect aTmp( rOld );
            aTmp.Union( aFrame );
            aTmp.Top(    std::min(aFrame.Top(), rOld.Top()) );
            aTmp.Bottom( std::max(aFrame.Top(), rOld.Top()) );
            pFly->NotifyBackground( pOld, aTmp, PrepareHint::FlyFrameSizeChanged );
        }
        nOld = rOld.Bottom();
        nNew = aFrame.Bottom();
        if ( nOld != nNew )
        {
            SwRect aTmp( rOld );
            aTmp.Union( aFrame );
            aTmp.Top(    std::min(nNew, nOld) );
            aTmp.Bottom( std::max(nNew, nOld) );
            pFly->NotifyBackground( pOld, aTmp, PrepareHint::FlyFrameSizeChanged );
        }
    }
    else if(pOldPrt && *pOldPrt != pFly->getFramePrintArea())
    {
        bool bNotifyBackground(pFly->GetFormat()->GetSurround().IsContour());

        if(!bNotifyBackground &&
            pFly->IsFlyFreeFrame() &&
            static_cast< const SwFlyFreeFrame* >(pFly)->supportsAutoContour())
        {
            // RotateFlyFrame3: Also notify for FlyFrames which allow AutoContour
            bNotifyBackground = true;
        }

        if(bNotifyBackground)
        {
            // #i24097#
            pFly->NotifyBackground( pFly->FindPageFrame(), aFrame, PrepareHint::FlyFrameArrive );
        }
    }
}

static void lcl_CheckFlowBack( SwFrame* pFrame, const SwRect &rRect )
{
    SwTwips nBottom = rRect.Bottom();
    while( pFrame )
    {
        if( pFrame->IsLayoutFrame() )
        {
            if( rRect.IsOver( pFrame->getFrameArea() ) )
                lcl_CheckFlowBack( static_cast<SwLayoutFrame*>(pFrame)->Lower(), rRect );
        }
        else if( !pFrame->GetNext() && nBottom > pFrame->getFrameArea().Bottom() )
        {
            if( pFrame->IsContentFrame() && static_cast<SwContentFrame*>(pFrame)->HasFollow() )
                pFrame->InvalidateSize();
            else
                pFrame->InvalidateNextPos();
        }
        pFrame = pFrame->GetNext();
    }
}

static void lcl_NotifyContent( const SdrObject *pThis, SwContentFrame *pCnt,
    const SwRect &rRect, const PrepareHint eHint )
{
    if ( pCnt->IsTextFrame() )
    {
        SwRect aCntPrt( pCnt->getFramePrintArea() );
        aCntPrt.Pos() += pCnt->getFrameArea().Pos();
        if ( eHint == PrepareHint::FlyFrameAttributesChanged )
        {
            // #i35640# - use given rectangle <rRect> instead
            // of current bound rectangle
            if ( aCntPrt.IsOver( rRect ) )
                pCnt->Prepare( PrepareHint::FlyFrameAttributesChanged );
        }
        // #i23129# - only invalidate, if the text frame
        // printing area overlaps with the given rectangle.
        else if ( aCntPrt.IsOver( rRect ) )
            pCnt->Prepare( eHint, static_cast<void*>(&aCntPrt.Intersection_( rRect )) );
        if ( pCnt->GetDrawObjs() )
        {
            const SwSortedObjs &rObjs = *pCnt->GetDrawObjs();
            for (SwAnchoredObject* pObj : rObjs)
            {
                if ( dynamic_cast<const SwFlyFrame*>( pObj) !=  nullptr )
                {
                    SwFlyFrame *pFly = static_cast<SwFlyFrame*>(pObj);
                    if ( pFly->IsFlyInContentFrame() )
                    {
                        SwContentFrame *pContent = pFly->ContainsContent();
                        while ( pContent )
                        {
                            ::lcl_NotifyContent( pThis, pContent, rRect, eHint );
                            pContent = pContent->GetNextContentFrame();
                        }
                    }
                }
            }
        }
    }
}

void Notify_Background( const SdrObject* pObj,
                        SwPageFrame* pPage,
                        const SwRect& rRect,
                        const PrepareHint eHint,
                        const bool bInva )
{
    // If the frame was positioned correctly for the first time, do not inform the old area
    if ( eHint == PrepareHint::FlyFrameLeave && rRect.Top() == FAR_AWAY )
         return;

    SwLayoutFrame* pArea;
    SwFlyFrame *pFlyFrame = nullptr;
    SwFrame* pAnchor;
    if( auto pVirtFlyDrawObj = dynamic_cast<const SwVirtFlyDrawObj*>( pObj) )
    {
        pFlyFrame = const_cast<SwVirtFlyDrawObj*>(pVirtFlyDrawObj)->GetFlyFrame();
        pAnchor = pFlyFrame->AnchorFrame();
    }
    else
    {
        pFlyFrame = nullptr;
        pAnchor = const_cast<SwFrame*>(
                    GetUserCall(pObj)->GetAnchoredObj( pObj )->GetAnchorFrame() );
    }
    if( PrepareHint::FlyFrameLeave != eHint && pAnchor->IsInFly() )
        pArea = pAnchor->FindFlyFrame();
    else
        pArea = pPage;
    SwContentFrame *pCnt = nullptr;
    if ( pArea )
    {
        if( PrepareHint::FlyFrameArrive != eHint )
            lcl_CheckFlowBack( pArea, rRect );

        // Only the Flys following this anchor are reacting. Thus, those do not
        // need to be processed.
        // An exception is LEAVE, since the Fly might come "from above".
        // If the anchor is positioned on the previous page, the whole page
        // needs to be processed (47722).
        // OD 2004-05-13 #i28701# - If the wrapping style has to be considered
        // on the object positioning, the complete area has to be processed,
        // because content frames before the anchor frame also have to consider
        // the object for the text wrapping.
        // #i3317# - The complete area has always been
        // processed.
        {
            pCnt = pArea->ContainsContent();
        }
    }
    SwFrame *pLastTab = nullptr;

    bool isValidTableBeforeAnchor(false);
    while ( pCnt && pArea && pArea->IsAnLower( pCnt ) )
    {
        ::lcl_NotifyContent( pObj, pCnt, rRect, eHint );
        if ( pCnt->IsInTab() )
        {
            SwTabFrame *pTab = pCnt->FindTabFrame();
            if ( pTab != pLastTab )
            {
                pLastTab = pTab;
                isValidTableBeforeAnchor = false;
                if (PrepareHint::FlyFrameArrive == eHint
                    && pFlyFrame // TODO: do it for draw objects too?
                    && pTab->IsFollow() // table starts on previous page?
                    // "through" means they will actually overlap anyway
                    && css::text::WrapTextMode_THROUGH != pFlyFrame->GetFormat()->GetSurround().GetSurround()
                    // if it's anchored in footer it can't move to other page
                    && !pAnchor->FindFooterOrHeader())
                {
                    SwFrame * pTmp(pAnchor->GetPrev());
                    while (pTmp)
                    {
                        if (pTmp == pTab)
                        {
                            // tdf#99460 the table shouldn't be moved by the fly
                            isValidTableBeforeAnchor = true;
                            break;
                        }
                        pTmp = pTmp->GetPrev();
                    }
                }
                // #i40606# - use <GetLastBoundRect()>
                // instead of <GetCurrentBoundRect()>, because a recalculation
                // of the bounding rectangle isn't intended here.
                if (!isValidTableBeforeAnchor
                    && (pTab->getFrameArea().IsOver(pObj->GetLastBoundRect()) ||
                        pTab->getFrameArea().IsOver(rRect)))
                {
                    if ( !pFlyFrame || !pFlyFrame->IsLowerOf( pTab ) )
                        pTab->InvalidatePrt();
                }
            }
            SwLayoutFrame* pCell = pCnt->GetUpper();
            // #i40606# - use <GetLastBoundRect()>
            // instead of <GetCurrentBoundRect()>, because a recalculation
            // of the bounding rectangle isn't intended here.
            if (!isValidTableBeforeAnchor && pCell->IsCellFrame() &&
                 ( pCell->getFrameArea().IsOver( pObj->GetLastBoundRect() ) ||
                   pCell->getFrameArea().IsOver( rRect ) ) )
            {
                const SwFormatVertOrient &rOri = pCell->GetFormat()->GetVertOrient();
                if ( text::VertOrientation::NONE != rOri.GetVertOrient() )
                    pCell->InvalidatePrt();
            }
        }
        pCnt = pCnt->GetNextContentFrame();
    }
    // #128702# - make code robust
    if ( pPage && pPage->GetSortedObjs() )
    {
        pObj->GetOrdNum();
        const SwSortedObjs &rObjs = *pPage->GetSortedObjs();
        for (SwAnchoredObject* pAnchoredObj : rObjs)
        {
            if ( dynamic_cast<const SwFlyFrame*>( pAnchoredObj) !=  nullptr )
            {
                if( pAnchoredObj->GetDrawObj() == pObj )
                    continue;
                SwFlyFrame *pFly = static_cast<SwFlyFrame*>(pAnchoredObj);
                if ( pFly->getFrameArea().Top() == FAR_AWAY )
                    continue;

                if ( !pFlyFrame ||
                        (!pFly->IsLowerOf( pFlyFrame ) &&
                        pFly->GetVirtDrawObj()->GetOrdNumDirect() < pObj->GetOrdNumDirect()))
                {
                    pCnt = pFly->ContainsContent();
                    while ( pCnt )
                    {
                        ::lcl_NotifyContent( pObj, pCnt, rRect, eHint );
                        pCnt = pCnt->GetNextContentFrame();
                    }
                }
                if( pFly->IsFlyLayFrame() )
                {
                    if( pFly->Lower() && pFly->Lower()->IsColumnFrame() &&
                        pFly->getFrameArea().Bottom() >= rRect.Top() &&
                        pFly->getFrameArea().Top() <= rRect.Bottom() &&
                        pFly->getFrameArea().Right() >= rRect.Left() &&
                        pFly->getFrameArea().Left() <= rRect.Right() )
                     {
                        pFly->InvalidateSize();
                     }
                }
                // Flys above myself might sidestep if they have an automatic
                // alignment. This happens independently of my attributes since
                // this might have been changed as well.
                else if ( pFly->IsFlyAtContentFrame() &&
                        pObj->GetOrdNumDirect() <
                        pFly->GetVirtDrawObj()->GetOrdNumDirect() &&
                        pFlyFrame && !pFly->IsLowerOf( pFlyFrame ) )
                {
                    const SwFormatHoriOrient &rH = pFly->GetFormat()->GetHoriOrient();
                    if ( text::HoriOrientation::NONE != rH.GetHoriOrient()  &&
                            text::HoriOrientation::CENTER != rH.GetHoriOrient()  &&
                            ( !pFly->IsAutoPos() || text::RelOrientation::CHAR != rH.GetRelationOrient() ) &&
                            (pFly->getFrameArea().Bottom() >= rRect.Top() &&
                            pFly->getFrameArea().Top() <= rRect.Bottom()) )
                        pFly->InvalidatePos();
                }
            }
        }
    }
    if ( pFlyFrame && pAnchor->GetUpper() && pAnchor->IsInTab() )//MA_FLY_HEIGHT
        pAnchor->GetUpper()->InvalidateSize();

    // #i82258# - make code robust
    SwViewShell* pSh = nullptr;
    if ( bInva && pPage &&
        nullptr != (pSh = pPage->getRootFrame()->GetCurrShell()) )
    {
        pSh->InvalidateWindows( rRect );
    }
}

/// Provides the Upper of an anchor in paragraph-bound objects. If the latter
/// is a chained border or a footnote, the "virtual" Upper might be returned.
const SwFrame* GetVirtualUpper( const SwFrame* pFrame, const Point& rPos )
{
    if( pFrame->IsTextFrame() )
    {
        pFrame = pFrame->GetUpper();
        if( !pFrame->getFrameArea().IsInside( rPos ) )
        {
            if( pFrame->IsFootnoteFrame() )
            {
                const SwFootnoteFrame* pTmp = static_cast<const SwFootnoteFrame*>(pFrame)->GetFollow();
                while( pTmp )
                {
                    if( pTmp->getFrameArea().IsInside( rPos ) )
                        return pTmp;
                    pTmp = pTmp->GetFollow();
                }
            }
            else
            {
                SwFlyFrame* pTmp = const_cast<SwFlyFrame*>(pFrame->FindFlyFrame());
                while( pTmp )
                {
                    if( pTmp->getFrameArea().IsInside( rPos ) )
                        return pTmp;
                    pTmp = pTmp->GetNextLink();
                }
            }
        }
    }
    return pFrame;
}

bool Is_Lower_Of(const SwFrame *pCurrFrame, const SdrObject* pObj)
{
    Point aPos;
    const SwFrame* pFrame;
    if (const SwVirtFlyDrawObj *pFlyDrawObj = dynamic_cast<const SwVirtFlyDrawObj*>(pObj))
    {
        const SwFlyFrame* pFly = pFlyDrawObj->GetFlyFrame();
        pFrame = pFly->GetAnchorFrame();
        aPos = pFly->getFrameArea().Pos();
    }
    else
    {
        pFrame = static_cast<SwDrawContact*>(GetUserCall(pObj))->GetAnchorFrame(pObj);
        aPos = pObj->GetCurrentBoundRect().TopLeft();
    }
    OSL_ENSURE( pFrame, "8-( Fly is lost in Space." );
    pFrame = GetVirtualUpper( pFrame, aPos );
    do
    {   if ( pFrame == pCurrFrame )
            return true;
        if( pFrame->IsFlyFrame() )
        {
            aPos = pFrame->getFrameArea().Pos();
            pFrame = GetVirtualUpper( static_cast<const SwFlyFrame*>(pFrame)->GetAnchorFrame(), aPos );
        }
        else
            pFrame = pFrame->GetUpper();
    } while ( pFrame );
    return false;
}

/// provides the area of a frame in that no Fly from another area can overlap
const SwFrame *FindContext( const SwFrame *pFrame, SwFrameType nAdditionalContextType )
{
    const SwFrameType nTyp = SwFrameType::Root | SwFrameType::Header   | SwFrameType::Footer | SwFrameType::FtnCont  |
                        SwFrameType::Ftn  | SwFrameType::Fly      |
                        SwFrameType::Tab  | SwFrameType::Row      | SwFrameType::Cell |
                        nAdditionalContextType;
    do
    {   if ( pFrame->GetType() & nTyp )
            break;
        pFrame = pFrame->GetUpper();
    } while( pFrame );
    return pFrame;
}

bool IsFrameInSameContext( const SwFrame *pInnerFrame, const SwFrame *pFrame )
{
    const SwFrame *pContext = FindContext( pInnerFrame, SwFrameType::None );

    const SwFrameType nTyp = SwFrameType::Root | SwFrameType::Header | SwFrameType::Footer | SwFrameType::FtnCont |
                        SwFrameType::Ftn  | SwFrameType::Fly      |
                        SwFrameType::Tab  | SwFrameType::Row      | SwFrameType::Cell;
    do
    {   if ( pFrame->GetType() & nTyp )
        {
            if( pFrame == pContext )
                return true;
            if( pFrame->IsCellFrame() )
                return false;
        }
        if( pFrame->IsFlyFrame() )
        {
            Point aPos( pFrame->getFrameArea().Pos() );
            pFrame = GetVirtualUpper( static_cast<const SwFlyFrame*>(pFrame)->GetAnchorFrame(), aPos );
        }
        else
            pFrame = pFrame->GetUpper();
    } while( pFrame );

    return false;
}

static SwTwips lcl_CalcCellRstHeight( SwLayoutFrame *pCell )
{
    SwFrame *pLow = pCell->Lower();
    if ( pLow && (pLow->IsContentFrame() || pLow->IsSctFrame()) )
    {
        long nHeight = 0, nFlyAdd = 0;
        do
        {
            long nLow = pLow->getFrameArea().Height();
            if( pLow->IsTextFrame() && static_cast<SwTextFrame*>(pLow)->IsUndersized() )
                nLow += static_cast<SwTextFrame*>(pLow)->GetParHeight()-pLow->getFramePrintArea().Height();
            else if( pLow->IsSctFrame() && static_cast<SwSectionFrame*>(pLow)->IsUndersized() )
                nLow += static_cast<SwSectionFrame*>(pLow)->Undersize();
            nFlyAdd = std::max( 0L, nFlyAdd - nLow );
            nFlyAdd = std::max( nFlyAdd, ::CalcHeightWithFlys( pLow ) );
            nHeight += nLow;
            pLow = pLow->GetNext();
        } while ( pLow );
        if ( nFlyAdd )
            nHeight += nFlyAdd;

        // The border cannot be calculated based on PrtArea and Frame, since both can be invalid.
        SwBorderAttrAccess aAccess( SwFrame::GetCache(), pCell );
        const SwBorderAttrs &rAttrs = *aAccess.Get();
        nHeight += rAttrs.CalcTop() + rAttrs.CalcBottom();

        return pCell->getFrameArea().Height() - nHeight;
    }
    else
    {
        long nRstHeight = 0;
        while (pLow && pLow->IsLayoutFrame())
        {
            nRstHeight += ::CalcRowRstHeight(static_cast<SwLayoutFrame*>(pLow));
            pLow = pLow->GetNext();
        }
        return nRstHeight;
    }
}

SwTwips CalcRowRstHeight( SwLayoutFrame *pRow )
{
    SwFrame *pLow = pRow->Lower();
    if (!(pLow && pLow->IsLayoutFrame()))
    {
        return 0;
    }
    SwTwips nRstHeight = LONG_MAX;
    while (pLow && pLow->IsLayoutFrame())
    {
        nRstHeight = std::min(nRstHeight, ::lcl_CalcCellRstHeight(static_cast<SwLayoutFrame*>(pLow)));
        pLow = pLow->GetNext();
    }
    return nRstHeight;
}

const SwFrame* FindPage( const SwRect &rRect, const SwFrame *pPage )
{
    if ( !rRect.IsOver( pPage->getFrameArea() ) )
    {
        const SwRootFrame* pRootFrame = static_cast<const SwRootFrame*>(pPage->GetUpper());
        const SwFrame* pTmpPage = pRootFrame ? pRootFrame->GetPageAtPos( rRect.TopLeft(), &rRect.SSize(), true ) : nullptr;
        if ( pTmpPage )
            pPage = pTmpPage;
    }

    return pPage;
}

namespace {

class SwFrameHolder : private SfxListener
{
    SwFrame* pFrame;
    bool bSet;
    virtual void Notify(  SfxBroadcaster& rBC, const SfxHint& rHint ) override;
public:
    SwFrameHolder() : pFrame(nullptr), bSet(false) {}
    void SetFrame( SwFrame* pHold );
    SwFrame* GetFrame() { return pFrame; }
    void Reset();
    bool IsSet() const { return bSet; }
};

}

void SwFrameHolder::SetFrame( SwFrame* pHold )
{
    bSet = true;
    if (pFrame != pHold)
    {
        if (pFrame)
            EndListening(*pFrame);
        StartListening(*pHold);
        pFrame = pHold;
    }
}

void SwFrameHolder::Reset()
{
    if (pFrame)
        EndListening(*pFrame);
    bSet = false;
    pFrame = nullptr;
}

void SwFrameHolder::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if ( rHint.GetId() == SfxHintId::Dying && &rBC == pFrame )
    {
        pFrame = nullptr;
    }
}

SwFrame* GetFrameOfModify(SwRootFrame const*const pLayout, SwModify const& rMod,
        SwFrameType const nFrameType, SwPosition const*const pPos,
        std::pair<Point, bool> const*const pViewPosAndCalcFrame)
{
    SwFrame *pMinFrame = nullptr, *pTmpFrame;
    SwFrameHolder aHolder;
    SwRect aCalcRect;
    bool bClientIterChanged = false;

    SwIterator<SwFrame, SwModify, sw::IteratorMode::UnwrapMulti> aIter(rMod);
    do {
        pMinFrame = nullptr;
        aHolder.Reset();
        sal_uInt64 nMinDist = 0;
        bClientIterChanged = false;

        for( pTmpFrame = aIter.First(); pTmpFrame; pTmpFrame = aIter.Next() )
        {
            if( pTmpFrame->GetType() & nFrameType &&
                ( !pLayout || pLayout == pTmpFrame->getRootFrame() ) &&
                (!pTmpFrame->IsFlowFrame() ||
                 !SwFlowFrame::CastFlowFrame( pTmpFrame )->IsFollow() ))
            {
                if (pViewPosAndCalcFrame)
                {
                    // watch for Frame being deleted
                    if ( pMinFrame )
                        aHolder.SetFrame( pMinFrame );
                    else
                        aHolder.Reset();

                    if (pViewPosAndCalcFrame->second)
                    {
                        // tdf#108118 prevent recursion
                        DisableCallbackAction a(*pTmpFrame->getRootFrame());
                        // - format parent Writer
                        // fly frame, if it isn't been formatted yet.
                        // Note: The Writer fly frame could be the frame itself.
                        SwFlyFrame* pFlyFrame( pTmpFrame->FindFlyFrame() );
                        if ( pFlyFrame &&
                             pFlyFrame->getFrameArea().Pos().X() == FAR_AWAY &&
                             pFlyFrame->getFrameArea().Pos().Y() == FAR_AWAY )
                        {
                            SwObjectFormatter::FormatObj( *pFlyFrame );
                        }
                        pTmpFrame->Calc(pLayout ? pLayout->GetCurrShell()->GetOut() : nullptr);
                    }

                    // aIter.IsChanged checks if the current pTmpFrame has been deleted while
                    // it is the current iterator
                    // FrameHolder watches for deletion of the current pMinFrame
                    if( aIter.IsChanged() || ( aHolder.IsSet() && !aHolder.GetFrame() ) )
                    {
                        // restart iteration
                        bClientIterChanged = true;
                        break;
                    }

                    // for Flys go via the parent if the Fly is not yet "formatted"
                    if (!pViewPosAndCalcFrame->second &&
                        pTmpFrame->GetType() & SwFrameType::Fly &&
                        static_cast<SwFlyFrame*>(pTmpFrame)->GetAnchorFrame() &&
                        FAR_AWAY == pTmpFrame->getFrameArea().Pos().getX() &&
                        FAR_AWAY == pTmpFrame->getFrameArea().Pos().getY() )
                        aCalcRect = static_cast<SwFlyFrame*>(pTmpFrame)->GetAnchorFrame()->getFrameArea();
                    else
                        aCalcRect = pTmpFrame->getFrameArea();

                    if (aCalcRect.IsInside(pViewPosAndCalcFrame->first))
                    {
                        pMinFrame = pTmpFrame;
                        break;
                    }

                    // Point not in rectangle. Compare distances:
                    const Point aCalcRectCenter = aCalcRect.Center();
                    const Point aDiff = aCalcRectCenter - pViewPosAndCalcFrame->first;
                    const sal_uInt64 nCurrentDist = sal_Int64(aDiff.getX()) * sal_Int64(aDiff.getX()) + sal_Int64(aDiff.getY()) * sal_Int64(aDiff.getY()); // opt: no sqrt
                    if ( !pMinFrame || nCurrentDist < nMinDist )
                    {
                        pMinFrame = pTmpFrame;
                        nMinDist = nCurrentDist;
                    }
                }
                else
                {
                    // if no pViewPosAndCalcFrame is provided, take the first one
                    pMinFrame = pTmpFrame;
                    break;
                }
            }
        }
    } while( bClientIterChanged );

    if( pPos && pMinFrame && pMinFrame->IsTextFrame() )
        return static_cast<SwTextFrame*>(pMinFrame)->GetFrameAtPos( *pPos );

    return pMinFrame;
}

bool IsExtraData( const SwDoc *pDoc )
{
    const SwLineNumberInfo &rInf = pDoc->GetLineNumberInfo();
    return rInf.IsPaintLineNumbers() ||
           rInf.IsCountInFlys() ||
           (static_cast<sal_Int16>(SW_MOD()->GetRedlineMarkPos()) != text::HoriOrientation::NONE &&
            !pDoc->getIDocumentRedlineAccess().GetRedlineTable().empty());
}

// OD 22.09.2003 #110978#
SwRect SwPageFrame::PrtWithoutHeaderAndFooter() const
{
    SwRect aPrtWithoutHeaderFooter( getFramePrintArea() );
    aPrtWithoutHeaderFooter.Pos() += getFrameArea().Pos();

    const SwFrame* pLowerFrame = Lower();
    while ( pLowerFrame )
    {
        // Note: independent on text direction page header and page footer are
        //       always at top respectively at bottom of the page frame.
        if ( pLowerFrame->IsHeaderFrame() )
        {
            aPrtWithoutHeaderFooter.AddTop( pLowerFrame->getFrameArea().Height() );
        }
        if ( pLowerFrame->IsFooterFrame() )
        {
            aPrtWithoutHeaderFooter.AddBottom( - pLowerFrame->getFrameArea().Height() );
        }

        pLowerFrame = pLowerFrame->GetNext();
    }

    return aPrtWithoutHeaderFooter;
}

/** method to determine the spacing values of a frame

    OD 2004-03-10 #i28701#
    OD 2009-08-28 #i102458#
    Add output parameter <obIsLineSpacingProportional>
*/
void GetSpacingValuesOfFrame( const SwFrame& rFrame,
                            SwTwips& onLowerSpacing,
                            SwTwips& onLineSpacing,
                            bool& obIsLineSpacingProportional )
{
    if ( !rFrame.IsFlowFrame() )
    {
        onLowerSpacing = 0;
        onLineSpacing = 0;
    }
    else
    {
        const SvxULSpaceItem& rULSpace = rFrame.GetAttrSet()->GetULSpace();
        onLowerSpacing = rULSpace.GetLower();

        onLineSpacing = 0;
        obIsLineSpacingProportional = false;
        if ( rFrame.IsTextFrame() )
        {
            onLineSpacing = static_cast<const SwTextFrame&>(rFrame).GetLineSpace();
            obIsLineSpacingProportional =
                onLineSpacing != 0 &&
                static_cast<const SwTextFrame&>(rFrame).GetLineSpace( true ) == 0;
        }

        OSL_ENSURE( onLowerSpacing >= 0 && onLineSpacing >= 0,
                "<GetSpacingValuesOfFrame(..)> - spacing values aren't positive!" );
    }
}

/// get the content of the table cell, skipping content from nested tables
const SwContentFrame* GetCellContent( const SwLayoutFrame& rCell )
{
    const SwContentFrame* pContent = rCell.ContainsContent();
    const SwTabFrame* pTab = rCell.FindTabFrame();

    while ( pContent && rCell.IsAnLower( pContent ) )
    {
        const SwTabFrame* pTmpTab = pContent->FindTabFrame();
        if ( pTmpTab != pTab )
        {
            SwFrame const*const pTmp = pTmpTab->FindLastContentOrTable();
            if (pTmp)
            {
                pContent = pTmp->FindNextCnt();
            }
            else
            {
                pContent = nullptr;
            }
        }
        else
            break;
    }
    return pContent;
}

SwDeletionChecker::SwDeletionChecker(const SwFrame* pFrame)
    : mpFrame( pFrame )
    , mpRegIn( pFrame
        ? pFrame->IsTextFrame()
            // sw_redlinehide: GetDep() may be a member of SwTextFrame!
            ? static_cast<SwTextFrame const*>(pFrame)->GetTextNodeFirst()
            : const_cast<SwFrame*>(pFrame)->GetDep()
        : nullptr )
{
}

/// Can be used to check if a frame has been deleted
bool SwDeletionChecker::HasBeenDeleted() const
{
    if ( !mpFrame || !mpRegIn )
        return false;

    SwIterator<SwFrame, SwModify, sw::IteratorMode::UnwrapMulti> aIter(*mpRegIn);
    SwFrame* pLast = aIter.First();
    while ( pLast )
    {
        if ( pLast == mpFrame )
            return false;
        pLast = aIter.Next();
    }

    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */