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
/* -*- 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 <sal/config.h>
#include <sal/log.hxx>

#include <anchoredobject.hxx>
#include <bodyfrm.hxx>
#include <hintids.hxx>
#include <editeng/keepitem.hxx>
#include <editeng/hyphenzoneitem.hxx>
#include <pagefrm.hxx>
#include <ndtxt.hxx>
#include <ftnfrm.hxx>
#include <txtftn.hxx>
#include <fmtftn.hxx>
#include <paratr.hxx>
#include <viewopt.hxx>
#include <viewsh.hxx>
#include <frmatr.hxx>
#include <pam.hxx>
#include <fmtanchr.hxx>
#include "itrform2.hxx"
#include "widorp.hxx"
#include "txtcache.hxx"
#include <sectfrm.hxx>
#include <rootfrm.hxx>
#include <frmfmt.hxx>
#include <sortedobjs.hxx>
#include <editeng/tstpitem.hxx>
#include <redline.hxx>
#include <comphelper/lok.hxx>

// Tolerance in formatting and text output
#define SLOPPY_TWIPS    5

namespace {

class FormatLevel
{
    static sal_uInt16 nLevel;
public:
    FormatLevel()  { ++nLevel; }
    ~FormatLevel() { --nLevel; }
    static sal_uInt16 GetLevel() { return nLevel; }
    static bool LastLevel() { return 10 < nLevel; }
};

}

sal_uInt16 FormatLevel::nLevel = 0;

void ValidateText( SwFrame *pFrame )     // Friend of frame
{
    if ( ( ! pFrame->IsVertical() &&
             pFrame->getFrameArea().Width() == pFrame->GetUpper()->getFramePrintArea().Width() ) ||
         (   pFrame->IsVertical() &&
             pFrame->getFrameArea().Height() == pFrame->GetUpper()->getFramePrintArea().Height() ) )
    {
        pFrame->setFrameAreaSizeValid(true);
    }
}

void SwTextFrame::ValidateFrame()
{
    vcl::RenderContext* pRenderContext = getRootFrame()->GetCurrShell()->GetOut();
    // Validate surroundings to avoid oscillation
    SwSwapIfSwapped swap( this );

    if ( !IsInFly() && !IsInTab() )
    {   // Only validate 'this' when inside a fly, the rest should actually only be
        // needed for footnotes, which do not exist in flys.
        SwSectionFrame* pSct = FindSctFrame();
        if( pSct )
        {
            if( !pSct->IsColLocked() )
                pSct->ColLock();
            else
                pSct = nullptr;
        }

        SwFrame *pUp = GetUpper();
        pUp->Calc(pRenderContext);
        if( pSct )
            pSct->ColUnlock();
    }
    ValidateText( this );

    // We at least have to save the MustFit flag!
    assert(HasPara() && "ResetPreps(), missing ParaPortion, SwCache bug?");
    SwParaPortion *pPara = GetPara();
    const bool bMustFit = pPara->IsPrepMustFit();
    ResetPreps();
    pPara->SetPrepMustFit( bMustFit );
}

// After a RemoveFootnote the BodyFrame and all Frames contained within it, need to be
// recalculated, so that the DeadLine is right.
// First we search outwards, on the way back we calculate everything.
static void ValidateBodyFrame_( SwFrame *pFrame )
{
    vcl::RenderContext* pRenderContext = pFrame ? pFrame->getRootFrame()->GetCurrShell()->GetOut() : nullptr;
    if( pFrame && !pFrame->IsCellFrame() )
    {
        if( !pFrame->IsBodyFrame() && pFrame->GetUpper() )
            ValidateBodyFrame_( pFrame->GetUpper() );
        if( !pFrame->IsSctFrame() )
            pFrame->Calc(pRenderContext);
        else
        {
            const bool bOld = static_cast<SwSectionFrame*>(pFrame)->IsContentLocked();
            static_cast<SwSectionFrame*>(pFrame)->SetContentLock( true );
            pFrame->Calc(pRenderContext);
            if( !bOld )
                static_cast<SwSectionFrame*>(pFrame)->SetContentLock( false );
        }
    }
}

void SwTextFrame::ValidateBodyFrame()
{
    SwSwapIfSwapped swap( this );

     // See comment in ValidateFrame()
    if ( !IsInFly() && !IsInTab() &&
         !( IsInSct() && FindSctFrame()->Lower()->IsColumnFrame() ) )
        ValidateBodyFrame_( GetUpper() );
}

bool SwTextFrame::GetDropRect_( SwRect &rRect ) const
{
    SwSwapIfNotSwapped swap(const_cast<SwTextFrame *>(this));

    OSL_ENSURE( HasPara(), "SwTextFrame::GetDropRect_: try again next year." );
    SwTextSizeInfo aInf( const_cast<SwTextFrame*>(this) );
    SwTextMargin aLine( const_cast<SwTextFrame*>(this), &aInf );
    if( aLine.GetDropLines() )
    {
        rRect.Top( aLine.Y() );
        rRect.Left( aLine.GetLineStart() );
        rRect.Height( aLine.GetDropHeight() );
        rRect.Width( aLine.GetDropLeft() );

        if ( IsRightToLeft() )
            SwitchLTRtoRTL( rRect );

        if ( IsVertical() )
            SwitchHorizontalToVertical( rRect );
        return true;
    }

    return false;
}

bool SwTextFrame::CalcFollow(TextFrameIndex const nTextOfst)
{
    vcl::RenderContext* pRenderContext = getRootFrame()->GetCurrShell()->GetOut();
    SwSwapIfSwapped swap( this );

    OSL_ENSURE( HasFollow(), "CalcFollow: missing Follow." );

    SwTextFrame* pMyFollow = GetFollow();

    SwParaPortion *pPara = GetPara();
    const bool bFollowField = pPara && pPara->IsFollowField();

    if( !pMyFollow->GetOffset() || pMyFollow->GetOffset() != nTextOfst ||
        bFollowField || pMyFollow->IsFieldFollow() ||
        ( pMyFollow->IsVertical() && !pMyFollow->getFramePrintArea().Width() ) ||
        ( ! pMyFollow->IsVertical() && !pMyFollow->getFramePrintArea().Height() ) )
    {
#if OSL_DEBUG_LEVEL > 0
        const SwFrame *pOldUp = GetUpper();
#endif

        SwRectFnSet aRectFnSet(this);
        SwTwips nOldBottom = aRectFnSet.GetBottom(GetUpper()->getFrameArea());
        SwTwips nMyPos = aRectFnSet.GetTop(getFrameArea());

        const SwPageFrame *pPage = nullptr;
        bool bOldInvaContent = true;
        if ( !IsInFly() && GetNext() )
        {
            pPage = FindPageFrame();
            // Minimize (reset if possible) invalidations: see below
            bOldInvaContent  = pPage->IsInvalidContent();
        }

        pMyFollow->SetOffset_( nTextOfst );
        pMyFollow->SetFieldFollow( bFollowField );
        if( HasFootnote() || pMyFollow->HasFootnote() )
        {
            ValidateFrame();
            ValidateBodyFrame();
            if( pPara )
            {
                pPara->GetReformat() = SwCharRange();
                pPara->GetDelta() = 0;
            }
        }

        // The footnote area must not get larger
        SwSaveFootnoteHeight aSave( FindFootnoteBossFrame( true ), LONG_MAX );

        pMyFollow->CalcFootnoteFlag();
        if ( !pMyFollow->GetNext() && !pMyFollow->HasFootnote() )
            nOldBottom =  aRectFnSet.IsVert() ? 0 : LONG_MAX;

        // tdf#122892 check flag:
        // 1. WidowsAndOrphans::FindWidows() determines follow is a widow
        // 2. SwTextFrame::PrepWidows() calls SetPrepWidows() on master;
        //    if it can spare lines, master truncates one line
        // 3. SwTextFrame::CalcPreps() on master (below);
        //    unless IsPrepMustFit(), if master hasn't shrunk via 2., it will SetWidow()
        // 4. loop must exit then, because the follow didn't grow so nothing will ever change
        while (!IsWidow())
        {
            if( !FormatLevel::LastLevel() )
            {
                // If the follow is contained within a column section or column
                // frame, we need to calculate that first. This is because the
                // FormatWidthCols() does not work if it is called from MakeAll
                // of the _locked_ follow.
                SwSectionFrame* pSct = pMyFollow->FindSctFrame();
                if( pSct && !pSct->IsAnLower( this ) )
                {
                    if( pSct->GetFollow() )
                        pSct->SimpleFormat();
                    else if( ( pSct->IsVertical() && !pSct->getFrameArea().Width() ) ||
                             ( ! pSct->IsVertical() && !pSct->getFrameArea().Height() ) )
                        break;
                }
                // i#11760 - Intrinsic format of follow is controlled.
                if ( FollowFormatAllowed() )
                {
                    // i#11760 - No nested format of follows, if
                    // text frame is contained in a column frame.
                    // Thus, forbid intrinsic format of follow.
                    {
                        bool bIsFollowInColumn = false;
                        SwFrame* pFollowUpper = pMyFollow->GetUpper();
                        while ( pFollowUpper )
                        {
                            if ( pFollowUpper->IsColumnFrame() )
                            {
                                bIsFollowInColumn = true;
                                break;
                            }
                            if ( pFollowUpper->IsPageFrame() ||
                                 pFollowUpper->IsFlyFrame() )
                            {
                                break;
                            }
                            pFollowUpper = pFollowUpper->GetUpper();
                        }
                        if ( bIsFollowInColumn )
                        {
                            pMyFollow->ForbidFollowFormat();
                        }
                    }

                    pMyFollow->Calc(pRenderContext);
                    // The Follow can tell from its getFrameArea().Height() that something went wrong
                    OSL_ENSURE( !pMyFollow->GetPrev(), "SwTextFrame::CalcFollow: cheesy follow" );
                    if( pMyFollow->GetPrev() )
                    {
                        pMyFollow->Prepare();
                        pMyFollow->Calc(pRenderContext);
                        OSL_ENSURE( !pMyFollow->GetPrev(), "SwTextFrame::CalcFollow: very cheesy follow" );
                    }

                    // i#11760 - Reset control flag for follow format.
                    pMyFollow->AllowFollowFormat();
                }

                // Make sure that the Follow gets painted
                pMyFollow->SetCompletePaint();
            }

            pPara = GetPara();
            // As long as the Follow requests lines due to Orphans, it is
            // passed these and is formatted again if possible
            if( pPara && pPara->IsPrepWidows() )
                CalcPreps();
            else
                break;
        }

        if( HasFootnote() || pMyFollow->HasFootnote() )
        {
            ValidateBodyFrame();
            ValidateFrame();
            if( pPara )
            {
                pPara->GetReformat() = SwCharRange();
                pPara->GetDelta() = 0;
            }
        }

        if ( pPage  && !bOldInvaContent )
            pPage->ValidateContent();

#if OSL_DEBUG_LEVEL > 0
        OSL_ENSURE( pOldUp == GetUpper(), "SwTextFrame::CalcFollow: heavy follow" );
#endif

        const long nRemaining =
                 - aRectFnSet.BottomDist( GetUpper()->getFrameArea(), nOldBottom );
        if (  nRemaining > 0 && !GetUpper()->IsSctFrame() &&
              nRemaining != ( aRectFnSet.IsVert() ?
                              nMyPos - getFrameArea().Right() :
                              getFrameArea().Top() - nMyPos ) )
        {
            return true;
        }
    }

    return false;
}

void SwTextFrame::MakePos()
{
    SwFrame::MakePos();
    // Inform LOK clients about change in position of redlines (if any)
    if(comphelper::LibreOfficeKit::isActive())
    {
        SwTextNode const* pTextNode = GetTextNodeFirst();
        const SwRedlineTable& rTable = pTextNode->getIDocumentRedlineAccess().GetRedlineTable();
        for (SwRedlineTable::size_type nRedlnPos = 0; nRedlnPos < rTable.size(); ++nRedlnPos)
        {
            SwRangeRedline* pRedln = rTable[nRedlnPos];
            if (pTextNode->GetIndex() == pRedln->GetPoint()->nNode.GetNode().GetIndex())
            {
                pRedln->MaybeNotifyRedlinePositionModification(getFrameArea().Top());
                if (GetMergedPara()
                    && pRedln->GetType() == RedlineType::Delete
                    && pRedln->GetPoint()->nNode != pRedln->GetMark()->nNode)
                {
                    pTextNode = pRedln->End()->nNode.GetNode().GetTextNode();
                }
            }
        }
    }
}

void SwTextFrame::AdjustFrame( const SwTwips nChgHght, bool bHasToFit )
{
    vcl::RenderContext* pRenderContext = getRootFrame()->GetCurrShell()->GetOut();
    if( IsUndersized() )
    {
        if( GetOffset() && !IsFollow() ) // A scrolled paragraph (undersized)
            return;
        SetUndersized( nChgHght == 0 || bHasToFit );
    }

    // AdjustFrame is called with a swapped frame during
    // formatting but the frame is not swapped during FormatEmpty
    SwSwapIfSwapped swap( this );
    SwRectFnSet aRectFnSet(this);

    // The Frame's size variable is incremented by Grow or decremented by Shrink.
    // If the size cannot change, nothing should happen!
    if( nChgHght >= 0)
    {
        SwTwips nChgHeight = nChgHght;
        if( nChgHght && !bHasToFit )
        {
            if( IsInFootnote() && !IsInSct() )
            {
                SwTwips nReal = Grow( nChgHght, true );
                if( nReal < nChgHght )
                {
                    SwTwips nBot = aRectFnSet.YInc( aRectFnSet.GetBottom(getFrameArea()),
                                                      nChgHght - nReal );
                    SwFrame* pCont = FindFootnoteFrame()->GetUpper();

                    if( aRectFnSet.BottomDist( pCont->getFrameArea(), nBot ) > 0 )
                    {
                        SwFrameAreaDefinition::FrameAreaWriteAccess aFrm(*this);
                        aRectFnSet.AddBottom( aFrm, nChgHght );

                        SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);

                        if( aRectFnSet.IsVert() )
                        {
                            aPrt.AddWidth(nChgHght );
                        }
                        else
                        {
                            aPrt.AddHeight(nChgHght );
                        }

                        return;
                    }
                }
            }

            Grow( nChgHght );

            if ( IsInFly() )
            {
                // If one of the Upper is a Fly, it's very likely that this fly changes its
                // position by the Grow. Therefore, my position has to be corrected also or
                // the check further down is not meaningful.
                // The predecessors need to be calculated, so that the position can be
                // calculated correctly.
                if ( GetPrev() )
                {
                    SwFrame *pPre = GetUpper()->Lower();
                    do
                    {   pPre->Calc(pRenderContext);
                        pPre = pPre->GetNext();
                    } while ( pPre && pPre != this );
                }
                const Point aOldPos( getFrameArea().Pos() );
                MakePos();
                if ( aOldPos != getFrameArea().Pos() )
                {
                    InvalidateObjs(false);
                }
            }
            nChgHeight = 0;
        }
        // A Grow() is always accepted by the Layout, even if the
        // FixSize of the surrounding layout frame should not allow it.
        // We text for this case and correct the values.
        // The Frame must NOT be shrunk further than its size permits
        // even in the case of an emergency.
        SwTwips nRstHeight;
        if ( IsVertical() )
        {
            OSL_ENSURE( ! IsSwapped(),"Swapped frame while calculating nRstHeight" );

            if ( IsVertLR() )
                    nRstHeight = GetUpper()->getFrameArea().Left()
                               + GetUpper()->getFramePrintArea().Left()
                               + GetUpper()->getFramePrintArea().Width()
                               - getFrameArea().Left();
            else
                nRstHeight = getFrameArea().Left() + getFrameArea().Width() -
                            ( GetUpper()->getFrameArea().Left() + GetUpper()->getFramePrintArea().Left() );
         }
        else
            nRstHeight = GetUpper()->getFrameArea().Top()
                       + GetUpper()->getFramePrintArea().Top()
                       + GetUpper()->getFramePrintArea().Height()
                       - getFrameArea().Top();

        // We can get a bit of space in table cells, because there could be some
        // left through a vertical alignment to the top.
        // Assure that first lower in upper is the current one or is valid.
        if ( IsInTab() &&
             ( GetUpper()->Lower() == this ||
               GetUpper()->Lower()->isFrameAreaDefinitionValid() ) )
        {
            long nAdd = aRectFnSet.YDiff( aRectFnSet.GetTop(GetUpper()->Lower()->getFrameArea()),
                                            aRectFnSet.GetPrtTop(*GetUpper()) );
            OSL_ENSURE( nAdd >= 0, "Ey" );
            nRstHeight += nAdd;
        }

        // nRstHeight < 0 means that the TextFrame is located completely outside of its Upper.
        // This can happen, if it's located within a FlyAtContentFrame, which changed sides by a
        // Grow(). In such a case, it's wrong to execute the following Grow().
        // In the case of a bug, we end up with an infinite loop.
        SwTwips nFrameHeight = aRectFnSet.GetHeight(getFrameArea());
        SwTwips nPrtHeight = aRectFnSet.GetHeight(getFramePrintArea());

        if( nRstHeight < nFrameHeight )
        {
            // It can be that I have the right size, but the Upper is too small and can get me some room
            if( ( nRstHeight >= 0 || ( IsInFootnote() && IsInSct() ) ) && !bHasToFit )
                nRstHeight += GetUpper()->Grow( nFrameHeight - nRstHeight );
            // In column sections we do not want to get too big or else more areas are created by
            // GetNextSctLeaf. Instead, we shrink and remember bUndersized, so that FormatWidthCols
            // can calculate the right column size.
            if ( nRstHeight < nFrameHeight )
            {
                if( bHasToFit || !IsMoveable() ||
                    ( IsInSct() && !FindSctFrame()->MoveAllowed(this) ) )
                {
                    SetUndersized( true );
                    Shrink( std::min( ( nFrameHeight - nRstHeight), nPrtHeight ) );
                }
                else
                    SetUndersized( false );
            }
        }
        else if( nChgHeight )
        {
            if( nRstHeight - nFrameHeight < nChgHeight )
                nChgHeight = nRstHeight - nFrameHeight;
            if( nChgHeight )
                Grow( nChgHeight );
        }
    }
    else
        Shrink( -nChgHght );
}

css::uno::Sequence< css::style::TabStop > SwTextFrame::GetTabStopInfo( SwTwips CurrentPos )
{
    css::uno::Sequence< css::style::TabStop > tabs(1);
    css::style::TabStop ts;

    SwTextFormatInfo     aInf( getRootFrame()->GetCurrShell()->GetOut(), this );
    SwTextFormatter      aLine( this, &aInf );
    SwTextCursor         TextCursor( this, &aInf );
    const Point aCharPos( TextCursor.GetTopLeft() );

    SwTwips nRight = aLine.Right();
    CurrentPos -= aCharPos.X();

    // get current tab stop information stored in the Frame
    const SvxTabStop *pTS = aLine.GetLineInfo().GetTabStop( CurrentPos, nRight );

    if( !pTS )
    {
        return css::uno::Sequence< css::style::TabStop >();
    }

    // copy tab stop information into a Sequence, which only contains one element.
    ts.Position = pTS->GetTabPos();
    ts.DecimalChar = pTS->GetDecimal();
    ts.FillChar = pTS->GetFill();
    switch( pTS->GetAdjustment() )
    {
    case SvxTabAdjust::Left   : ts.Alignment = css::style::TabAlign_LEFT; break;
    case SvxTabAdjust::Center : ts.Alignment = css::style::TabAlign_CENTER; break;
    case SvxTabAdjust::Right  : ts.Alignment = css::style::TabAlign_RIGHT; break;
    case SvxTabAdjust::Decimal: ts.Alignment = css::style::TabAlign_DECIMAL; break;
    case SvxTabAdjust::Default: ts.Alignment = css::style::TabAlign_DEFAULT; break;
    default: break; // prevent warning
    }

    tabs[0] = ts;
    return tabs;
}

// AdjustFollow expects the following situation:
// The SwTextIter points to the lower end of the Master, the Offset is set in the Follow.
// nOffset holds the Offset in the text string, from which the Master closes
// and the Follow starts.
// If it's 0, the FollowFrame is deleted.
void SwTextFrame::AdjustFollow_( SwTextFormatter &rLine,
                 const TextFrameIndex nOffset, const TextFrameIndex nEnd,
                             const sal_uInt8 nMode )
{
    SwFrameSwapper aSwapper( this, false );

    // We got the rest of the text mass: Delete all Follows
    // DummyPortions() are a special case.
    // Special cases are controlled by parameter <nMode>.
    if( HasFollow() && !(nMode & 1) && nOffset == nEnd )
    {
        while( GetFollow() )
        {
            if( GetFollow()->IsLocked() )
            {
                OSL_FAIL( "+SwTextFrame::JoinFrame: Follow is locked." );
                return;
            }
            if (GetFollow()->IsDeleteForbidden())
                return;
            JoinFrame();
        }

        return;
    }

    // Dancing on the volcano: We'll just format the last line quickly
    // for the QuoVadis stuff.
    // The Offset can move of course:
    const TextFrameIndex nNewOfst = (IsInFootnote() && (!GetIndNext() || HasFollow()))
        ? rLine.FormatQuoVadis(nOffset) : nOffset;

    if( !(nMode & 1) )
    {
        // We steal text mass from our Follows
        // It can happen that we have to join some of them
        while( GetFollow() && GetFollow()->GetFollow() &&
               nNewOfst >= GetFollow()->GetFollow()->GetOffset() )
        {
            JoinFrame();
        }
    }

    // The Offset moved
    if( GetFollow() )
    {
        if ( nMode )
            GetFollow()->ManipOfst(TextFrameIndex(0));

        if ( CalcFollow( nNewOfst ) )   // CalcFollow only at the end, we do a SetOffset there
            rLine.SetOnceMore( true );
    }
}

SwContentFrame *SwTextFrame::JoinFrame()
{
    OSL_ENSURE( GetFollow(), "+SwTextFrame::JoinFrame: no follow" );
    SwTextFrame  *pFoll = GetFollow();

    SwTextFrame *pNxt = pFoll->GetFollow();

    // All footnotes of the to-be-destroyed Follow are relocated to us
    TextFrameIndex nStart = pFoll->GetOffset();
    if ( pFoll->HasFootnote() )
    {
        SwFootnoteBossFrame *pFootnoteBoss = nullptr;
        SwFootnoteBossFrame *pEndBoss = nullptr;
        SwTextNode const* pNode(nullptr);
        sw::MergedAttrIter iter(*pFoll);
        for (SwTextAttr const* pHt = iter.NextAttr(&pNode); pHt; pHt = iter.NextAttr(&pNode))
        {
            if (RES_TXTATR_FTN == pHt->Which()
                && nStart <= pFoll->MapModelToView(pNode, pHt->GetStart()))
            {
                if (pHt->GetFootnote().IsEndNote())
                {
                    if (!pEndBoss)
                        pEndBoss = pFoll->FindFootnoteBossFrame();
                    SwFootnoteBossFrame::ChangeFootnoteRef( pFoll, static_cast<const SwTextFootnote*>(pHt), this );
                }
                else
                {
                    if (!pFootnoteBoss)
                        pFootnoteBoss = pFoll->FindFootnoteBossFrame( true );
                    SwFootnoteBossFrame::ChangeFootnoteRef( pFoll, static_cast<const SwTextFootnote*>(pHt), this );
                }
                SetFootnote( true );
            }
        }
    }

#ifdef DBG_UTIL
    else if ( pFoll->isFramePrintAreaValid() ||
              pFoll->isFrameAreaSizeValid() )
    {
        pFoll->CalcFootnoteFlag();
        OSL_ENSURE( !pFoll->HasFootnote(), "Missing FootnoteFlag." );
    }
#endif

    pFoll->MoveFlyInCnt( this, nStart, TextFrameIndex(COMPLETE_STRING) );
    pFoll->SetFootnote( false );
    // i#27138
    // Notify accessibility paragraphs objects about changed CONTENT_FLOWS_FROM/_TO relation.
    // Relation CONTENT_FLOWS_FROM for current next paragraph will change
    // and relation CONTENT_FLOWS_TO for current previous paragraph, which
    // is <this>, will change.
    {
        SwViewShell* pViewShell( pFoll->getRootFrame()->GetCurrShell() );
        if ( pViewShell && pViewShell->GetLayout() &&
             pViewShell->GetLayout()->IsAnyShellAccessible() )
        {
            pViewShell->InvalidateAccessibleParaFlowRelation(
                            dynamic_cast<SwTextFrame*>(pFoll->FindNextCnt( true )),
                            this );
        }
    }
    pFoll->Cut();
    SetFollow(pNxt);
    SwFrame::DestroyFrame(pFoll);
    return pNxt;
}

void SwTextFrame::SplitFrame(TextFrameIndex const nTextPos)
{
    SwSwapIfSwapped swap( this );

    // The Paste sends a Modify() to me
    // I lock myself, so that my data does not disappear
    TextFrameLockGuard aLock( this );
    SwTextFrame *const pNew = static_cast<SwTextFrame *>(GetTextNodeFirst()->MakeFrame(this));

    pNew->SetFollow( GetFollow() );
    SetFollow( pNew );

    pNew->Paste( GetUpper(), GetNext() );
    // i#27138
    // notify accessibility paragraphs objects about changed CONTENT_FLOWS_FROM/_TO relation.
    // Relation CONTENT_FLOWS_FROM for current next paragraph will change
    // and relation CONTENT_FLOWS_TO for current previous paragraph, which
    // is <this>, will change.
    {
        SwViewShell* pViewShell( pNew->getRootFrame()->GetCurrShell() );
        if ( pViewShell && pViewShell->GetLayout() &&
             pViewShell->GetLayout()->IsAnyShellAccessible() )
        {
            pViewShell->InvalidateAccessibleParaFlowRelation(
                            dynamic_cast<SwTextFrame*>(pNew->FindNextCnt( true )),
                            this );
        }
    }

    // If footnotes end up in pNew bz our actions, we need
    // to re-register them
    if ( HasFootnote() )
    {
        SwFootnoteBossFrame *pFootnoteBoss = nullptr;
        SwFootnoteBossFrame *pEndBoss = nullptr;
        SwTextNode const* pNode(nullptr);
        sw::MergedAttrIter iter(*this);
        for (SwTextAttr const* pHt = iter.NextAttr(&pNode); pHt; pHt = iter.NextAttr(&pNode))
        {
            if (RES_TXTATR_FTN == pHt->Which()
                && nTextPos <= MapModelToView(pNode, pHt->GetStart()))
            {
                if (pHt->GetFootnote().IsEndNote())
                {
                    if (!pEndBoss)
                        pEndBoss = FindFootnoteBossFrame();
                    SwFootnoteBossFrame::ChangeFootnoteRef( this, static_cast<const SwTextFootnote*>(pHt), pNew );
                }
                else
                {
                    if (!pFootnoteBoss)
                        pFootnoteBoss = FindFootnoteBossFrame( true );
                    SwFootnoteBossFrame::ChangeFootnoteRef( this, static_cast<const SwTextFootnote*>(pHt), pNew );
                }
                pNew->SetFootnote( true );
            }
        }
    }

#ifdef DBG_UTIL
    else
    {
        CalcFootnoteFlag( nTextPos - TextFrameIndex(1) );
        OSL_ENSURE( !HasFootnote(), "Missing FootnoteFlag." );
    }
#endif

    MoveFlyInCnt( pNew, nTextPos, TextFrameIndex(COMPLETE_STRING) );

    // No SetOffset or CalcFollow, because an AdjustFollow follows immediately anyways

    pNew->ManipOfst( nTextPos );
}

void SwTextFrame::SetOffset_(TextFrameIndex const nNewOfst)
{
    // We do not need to invalidate out Follow.
    // We are a Follow, get formatted right away and call
    // SetOffset() from there
    mnOffset = nNewOfst;
    SwParaPortion *pPara = GetPara();
    if( pPara )
    {
        SwCharRange &rReformat = pPara->GetReformat();
        rReformat.Start() = TextFrameIndex(0);
        rReformat.Len() = TextFrameIndex(GetText().getLength());
        pPara->GetDelta() = sal_Int32(rReformat.Len());
    }
    InvalidateSize();
}

bool SwTextFrame::CalcPreps()
{
    OSL_ENSURE( ! IsVertical() || ! IsSwapped(), "SwTextFrame::CalcPreps with swapped frame" );
    SwRectFnSet aRectFnSet(this);

    SwParaPortion *pPara = GetPara();
    if ( !pPara )
        return false;
    const bool bPrep = pPara->IsPrep();
    const bool bPrepWidows = pPara->IsPrepWidows();
    const bool bPrepAdjust = pPara->IsPrepAdjust();
    const bool bPrepMustFit = pPara->IsPrepMustFit();
    ResetPreps();

    bool bRet = false;
    if( bPrep && !pPara->GetReformat().Len() )
    {
        // PrepareHint::Widows means that the orphans rule got activated in the Follow.
        // In unfortunate cases we could also have a PrepAdjust!
        if( bPrepWidows )
        {
            if( !GetFollow() )
            {
                OSL_ENSURE( GetFollow(), "+SwTextFrame::CalcPreps: no credits" );
                return false;
            }

            // We need to prepare for two cases:
            // We were able to hand over a few lines to the Follow
            // -> we need to shrink
            // or we need to go on the next page
            // -> we let our Frame become too big

            SwTwips nChgHeight = GetParHeight();
            if( nChgHeight >= aRectFnSet.GetHeight(getFramePrintArea()) )
            {
                if( bPrepMustFit )
                {
                    GetFollow()->SetJustWidow( true );
                    GetFollow()->Prepare();
                }
                else if ( aRectFnSet.IsVert() )
                {
                    {
                        SwFrameAreaDefinition::FrameAreaWriteAccess aFrm(*this);
                        aFrm.Width( aFrm.Width() + aFrm.Left() );
                        aFrm.Left( 0 );
                    }

                    {
                        SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
                        aPrt.Width( aPrt.Width() + getFrameArea().Left() );
                    }

                    SetWidow( true );
                }
                else
                {
                    // nTmp should be very large, but not so large as to cause overflow later (e.g.,
                    // GetFrameOfModify in sw/source/core/layout/frmtool.cxx calculates nCurrentDist
                    // from, among others, the square of aDiff.getY(), which can be close to nTmp);
                    // the previously used value TWIPS_MAX/2 (i.e., (LONG_MAX - 1)/2) depended on
                    // the range of 'long', while the value (SAL_MAX_INT32 - 1)/2 (which matches the
                    // old value on platforms where 'long' is 'sal_Int32') is empirically shown to
                    // be large enough in practice even on platforms where 'long' is 'sal_Int64':
                    SwTwips const nTmp = sw::WIDOW_MAGIC - (getFrameArea().Top()+10000);
                    SwTwips nDiff = nTmp - getFrameArea().Height();

                    {
                        SwFrameAreaDefinition::FrameAreaWriteAccess aFrm(*this);
                        aFrm.Height( nTmp );
                    }

                    {
                        SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
                        aPrt.Height( aPrt.Height() + nDiff );
                    }

                    SetWidow( true );
                }
            }
            else
            {
                OSL_ENSURE( nChgHeight < aRectFnSet.GetHeight(getFramePrintArea()),
                        "+SwTextFrame::CalcPrep: want to shrink" );

                nChgHeight = aRectFnSet.GetHeight(getFramePrintArea()) - nChgHeight;

                GetFollow()->SetJustWidow( true );
                GetFollow()->Prepare();
                Shrink( nChgHeight );
                SwRect &rRepaint = pPara->GetRepaint();

                if ( aRectFnSet.IsVert() )
                {
                    SwRect aRepaint( getFrameArea().Pos() + getFramePrintArea().Pos(), getFramePrintArea().SSize() );
                    SwitchVerticalToHorizontal( aRepaint );
                    rRepaint.Chg( aRepaint.Pos(), aRepaint.SSize() );
                }
                else
                    rRepaint.Chg( getFrameArea().Pos() + getFramePrintArea().Pos(), getFramePrintArea().SSize() );

                if( 0 >= rRepaint.Width() )
                    rRepaint.Width(1);
            }
            bRet = true;
        }
        else if ( bPrepAdjust )
        {
            if ( HasFootnote() )
            {
                if( !CalcPrepFootnoteAdjust() )
                {
                    if( bPrepMustFit )
                    {
                        SwTextLineAccess aAccess( this );
                        aAccess.GetPara()->SetPrepMustFit(true);
                    }
                    return false;
                }
            }

            {
                SwSwapIfNotSwapped swap( this );

                SwTextFormatInfo aInf( getRootFrame()->GetCurrShell()->GetOut(), this );
                SwTextFormatter aLine( this, &aInf );

                WidowsAndOrphans aFrameBreak( this );
                // Whatever the attributes say: we split the paragraph in
                // MustFit case if necessary
                if( bPrepMustFit )
                {
                    aFrameBreak.SetKeep( false );
                    aFrameBreak.ClrOrphLines();
                }
                // Before calling FormatAdjust, we need to make sure
                // that the lines protruding at the bottom get indeed
                // truncated
                bool bBreak = aFrameBreak.IsBreakNowWidAndOrp( aLine );
                bRet = true;
                while( !bBreak && aLine.Next() )
                {
                    bBreak = aFrameBreak.IsBreakNowWidAndOrp( aLine );
                }
                if( bBreak )
                {
                    // We run into troubles: when TruncLines is called, the
                    // conditions in IsInside change immediately such that
                    // IsBreakNow can return different results.
                    // For this reason, we tell rFrameBreak that the
                    // end is reached at the location of rLine.
                    // Let's see if it works ...
                    aLine.TruncLines();
                    aFrameBreak.SetRstHeight( aLine );
                    FormatAdjust( aLine, aFrameBreak, TextFrameIndex(aInf.GetText().getLength()), aInf.IsStop() );
                }
                else
                {
                    if( !GetFollow() )
                    {
                        FormatAdjust( aLine, aFrameBreak,
                            TextFrameIndex(aInf.GetText().getLength()), aInf.IsStop() );
                    }
                    else if ( !aFrameBreak.IsKeepAlways() )
                    {
                        // We delete a line before the Master, because the Follow
                        // could hand over a line
                        const SwCharRange aFollowRg(GetFollow()->GetOffset(), TextFrameIndex(1));
                        pPara->GetReformat() += aFollowRg;
                        // We should continue!
                        bRet = false;
                    }
                }
            }

            // A final check, if FormatAdjust() didn't help we need to
            // truncate
            if( bPrepMustFit )
            {
                const SwTwips nMust = aRectFnSet.GetPrtBottom(*GetUpper());
                const SwTwips nIs   = aRectFnSet.GetBottom(getFrameArea());

                if( aRectFnSet.IsVert() && nIs < nMust )
                {
                    Shrink( nMust - nIs );

                    if( getFramePrintArea().Width() < 0 )
                    {
                        SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
                        aPrt.Width( 0 );
                    }

                    SetUndersized( true );
                }
                else if ( ! aRectFnSet.IsVert() && nIs > nMust )
                {
                    Shrink( nIs - nMust );

                    if( getFramePrintArea().Height() < 0 )
                    {
                        SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
                        aPrt.Height( 0 );
                    }

                    SetUndersized( true );
                }
            }
        }
    }
    pPara->SetPrepMustFit( bPrepMustFit );
    return bRet;
}

// We rewire the footnotes and the character bound objects
void SwTextFrame::ChangeOffset( SwTextFrame* pFrame, TextFrameIndex nNew )
{
    if( pFrame->GetOffset() < nNew )
        pFrame->MoveFlyInCnt( this, TextFrameIndex(0), nNew );
    else if( pFrame->GetOffset() > nNew )
        MoveFlyInCnt( pFrame, nNew, TextFrameIndex(COMPLETE_STRING) );
}

void SwTextFrame::FormatAdjust( SwTextFormatter &rLine,
                             WidowsAndOrphans &rFrameBreak,
                             TextFrameIndex const nStrLen,
                             const bool bDummy )
{
    SwSwapIfNotSwapped swap( this );

    SwParaPortion *pPara = rLine.GetInfo().GetParaPortion();

    TextFrameIndex nEnd = rLine.GetStart();

    const bool bHasToFit = pPara->IsPrepMustFit();

    // The StopFlag is set by footnotes which want to go onto the next page
    // Call base class method <SwTextFrameBreak::IsBreakNow(..)>
    // instead of method <WidowsAndOrphans::IsBreakNow(..)> to get a break,
    // even if due to widow rule no enough lines exists.
    sal_uInt8 nNew = ( !GetFollow() &&
                       nEnd < nStrLen &&
                       ( rLine.IsStop() ||
                         ( bHasToFit
                           ? ( rLine.GetLineNr() > 1 &&
                               !rFrameBreak.IsInside( rLine ) )
                           : rFrameBreak.IsBreakNow( rLine ) ) ) )
                     ? 1 : 0;
    // i#84870
    // no split of text frame, which only contains an as-character anchored object
    bool bOnlyContainsAsCharAnchoredObj =
            !IsFollow() && nStrLen == TextFrameIndex(1) &&
            GetDrawObjs() && GetDrawObjs()->size() == 1 &&
            (*GetDrawObjs())[0]->GetFrameFormat().GetAnchor().GetAnchorId() == RndStdIds::FLY_AS_CHAR;

    // Still try split text frame if we have columns.
    if (FindColFrame())
        bOnlyContainsAsCharAnchoredObj = false;

    if ( nNew && bOnlyContainsAsCharAnchoredObj )
    {
        nNew = 0;
    }

    if ( nNew )
    {
        SplitFrame( nEnd );
    }

    const SwFrame *pBodyFrame = FindBodyFrame();

    const long nBodyHeight = pBodyFrame ? ( IsVertical() ?
                                          pBodyFrame->getFrameArea().Width() :
                                          pBodyFrame->getFrameArea().Height() ) : 0;

    // If the current values have been calculated, show that they
    // are valid now
    pPara->GetReformat() = SwCharRange();
    bool bDelta = pPara->GetDelta() != 0;
    pPara->GetDelta() = 0;

    if( rLine.IsStop() )
    {
        rLine.TruncLines( true );
        nNew = 1;
    }

    // FindBreak truncates the last line
    if( !rFrameBreak.FindBreak( this, rLine, bHasToFit ) )
    {
        // If we're done formatting, we set nEnd to the end.
        // AdjustFollow might execute JoinFrame() because of this.
        // Else, nEnd is the end of the last line in the Master.
        TextFrameIndex nOld = nEnd;
        nEnd = rLine.GetEnd();
        if( GetFollow() )
        {
            if( nNew && nOld < nEnd )
                RemoveFootnote( nOld, nEnd - nOld );
            ChangeOffset( GetFollow(), nEnd );
            if( !bDelta )
                GetFollow()->ManipOfst( nEnd );
        }
    }
    else
    {   // If we pass over lines, we must not call Join in Follows, instead we even
        // need to create a Follow.
        // We also need to do this if the whole mass of text remains in the Master,
        // because a hard line break could necessitate another line (without text mass)!
        nEnd = rLine.GetEnd();
        if( GetFollow() )
        {
            // Another case for not joining the follow:
            // Text frame has no content, but a numbering. Then, do *not* join.
            // Example of this case: When an empty, but numbered paragraph
            // at the end of page is completely displaced by a fly frame.
            // Thus, the text frame introduced a follow by a
            // <SwTextFrame::SplitFrame(..)> - see below. The follow then shows
            // the numbering and must stay.
            if ( GetFollow()->GetOffset() != nEnd ||
                 GetFollow()->IsFieldFollow() ||
                 (nStrLen == TextFrameIndex(0) && GetTextNodeForParaProps()->GetNumRule()))
            {
                nNew |= 3;
            }
            else if (FindTabFrame() && nEnd > TextFrameIndex(0) &&
                rLine.GetInfo().GetChar(nEnd - TextFrameIndex(1)) == CH_BREAK)
            {
                // We are in a table, the paragraph has a follow and the text
                // ends with a hard line break. Don't join the follow just
                // because the follow would have no content, we may still need it
                // for the paragraph mark.
                nNew |= 1;
            }
            ChangeOffset( GetFollow(), nEnd );
            GetFollow()->ManipOfst( nEnd );
        }
        else
        {
            // Only split frame, if the frame contains
            // content or contains no content, but has a numbering.
            // i#84870 - No split, if text frame only contains one
            // as-character anchored object.
            if ( !bOnlyContainsAsCharAnchoredObj &&
                 (nStrLen > TextFrameIndex(0) ||
                   (nStrLen == TextFrameIndex(0) && GetTextNodeForParaProps()->GetNumRule()))
               )
            {
                SplitFrame( nEnd );
                nNew |= 3;
            }
        }
        // If the remaining height changed e.g by RemoveFootnote() we need to
        // fill up in order to avoid oscillation.
        if( bDummy && pBodyFrame &&
           nBodyHeight < ( IsVertical() ?
                           pBodyFrame->getFrameArea().Width() :
                           pBodyFrame->getFrameArea().Height() ) )
            rLine.MakeDummyLine();
    }

    // In AdjustFrame() we set ourselves via Grow/Shrink
    // In AdjustFollow() we set our FollowFrame

    const SwTwips nDocPrtTop = getFrameArea().Top() + getFramePrintArea().Top();
    const SwTwips nOldHeight = getFramePrintArea().SSize().Height();
    SwTwips nChg = rLine.CalcBottomLine() - nDocPrtTop - nOldHeight;

    //#i84870# - no shrink of text frame, if it only contains one as-character anchored object.
    if ( nChg < 0 && !bDelta && bOnlyContainsAsCharAnchoredObj )
    {
        nChg = 0;
    }

    // Vertical Formatting:
    // The (rotated) repaint rectangle's x coordinate refers to the frame.
    // If the frame grows (or shirks) the repaint rectangle cannot simply
    // be rotated back after formatting, because we use the upper left point
    // of the frame for rotation. This point changes when growing/shrinking.

    if ( IsVertical() && !IsVertLR() && nChg )
    {
        SwRect &rRepaint = pPara->GetRepaint();
        rRepaint.Left( rRepaint.Left() - nChg );
        rRepaint.Width( rRepaint.Width() - nChg );
    }

    AdjustFrame( nChg, bHasToFit );

    if( HasFollow() || IsInFootnote() )
        AdjustFollow_( rLine, nEnd, nStrLen, nNew );

    pPara->SetPrepMustFit( false );
}

// bPrev is set whether Reformat.Start() was called because of Prev().
// Else, wo don't know whether we can limit the repaint or not.
bool SwTextFrame::FormatLine( SwTextFormatter &rLine, const bool bPrev )
{
    OSL_ENSURE( ! IsVertical() || IsSwapped(),
            "SwTextFrame::FormatLine( rLine, bPrev) with unswapped frame" );
    SwParaPortion *pPara = rLine.GetInfo().GetParaPortion();
    const SwLineLayout *pOldCur = rLine.GetCurr();
    const TextFrameIndex nOldLen = pOldCur->GetLen();
    const sal_uInt16 nOldAscent = pOldCur->GetAscent();
    const sal_uInt16 nOldHeight = pOldCur->Height();
    const SwTwips nOldWidth = pOldCur->Width() + pOldCur->GetHangingMargin();
    const bool bOldHyph = pOldCur->IsEndHyph();
    SwTwips nOldTop = 0;
    SwTwips nOldBottom = 0;
    if( rLine.GetCurr()->IsClipping() )
        rLine.CalcUnclipped( nOldTop, nOldBottom );

    TextFrameIndex const nNewStart = rLine.FormatLine( rLine.GetStart() );

    OSL_ENSURE( getFrameArea().Pos().Y() + getFramePrintArea().Pos().Y() == rLine.GetFirstPos(),
            "SwTextFrame::FormatLine: frame leaves orbit." );
    OSL_ENSURE( rLine.GetCurr()->Height(),
            "SwTextFrame::FormatLine: line height is zero" );

    // The current line break object
    const SwLineLayout *pNew = rLine.GetCurr();

    bool bUnChg = nOldLen == pNew->GetLen() &&
                  bOldHyph == pNew->IsEndHyph();
    if ( bUnChg && !bPrev )
    {
        const long nWidthDiff = nOldWidth > pNew->Width()
                                ? nOldWidth - pNew->Width()
                                : pNew->Width() - nOldWidth;

        // we only declare a line as unchanged, if its main values have not
        // changed and it is not the last line (!paragraph end symbol!)
        bUnChg = nOldHeight == pNew->Height() &&
                 nOldAscent == pNew->GetAscent() &&
                 nWidthDiff <= SLOPPY_TWIPS &&
                 pOldCur->GetNext();
    }

    // Calculate rRepaint
    const SwTwips nBottom = rLine.Y() + rLine.GetLineHeight();
    SwRepaint &rRepaint = pPara->GetRepaint();
    if( bUnChg && rRepaint.Top() == rLine.Y()
               && (bPrev || nNewStart <= pPara->GetReformat().Start())
               && (nNewStart < TextFrameIndex(GetText().getLength())))
    {
        rRepaint.Top( nBottom );
        rRepaint.Height( 0 );
    }
    else
    {
        if( nOldTop )
        {
            if( nOldTop < rRepaint.Top() )
                rRepaint.Top( nOldTop );
            if( !rLine.IsUnclipped() || nOldBottom > rRepaint.Bottom() )
            {
                rRepaint.Bottom( nOldBottom - 1 );
                rLine.SetUnclipped( true );
            }
        }
        if( rLine.GetCurr()->IsClipping() && rLine.IsFlyInCntBase() )
        {
            SwTwips nTmpTop, nTmpBottom;
            rLine.CalcUnclipped( nTmpTop, nTmpBottom );
            if( nTmpTop < rRepaint.Top() )
                rRepaint.Top( nTmpTop );
            if( !rLine.IsUnclipped() || nTmpBottom > rRepaint.Bottom() )
            {
                rRepaint.Bottom( nTmpBottom - 1 );
                rLine.SetUnclipped( true );
            }
        }
        else
        {
            if( !rLine.IsUnclipped() || nBottom > rRepaint.Bottom() )
            {
                rRepaint.Bottom( nBottom - 1 );
                rLine.SetUnclipped( false );
            }
        }
        SwTwips nRght = std::max( nOldWidth, pNew->Width() +
                             pNew->GetHangingMargin() );
        SwViewShell *pSh = getRootFrame()->GetCurrShell();
        const SwViewOption *pOpt = pSh ? pSh->GetViewOptions() : nullptr;
        if( pOpt && (pOpt->IsParagraph() || pOpt->IsLineBreak()) )
            nRght += ( std::max( nOldAscent, pNew->GetAscent() ) );
        else
            nRght += ( std::max( nOldAscent, pNew->GetAscent() ) / 4);
        nRght += rLine.GetLeftMargin();
        if( rRepaint.GetOffset() || rRepaint.GetRightOfst() < nRght )
            rRepaint.SetRightOfst( nRght );

        // Finally we enlarge the repaint rectangle if we found an underscore
        // within our line. 40 Twips should be enough
        const bool bHasUnderscore =
                ( rLine.GetInfo().GetUnderScorePos() < nNewStart );
        if ( bHasUnderscore || rLine.GetCurr()->HasUnderscore() )
            rRepaint.Bottom( rRepaint.Bottom() + 40 );

        const_cast<SwLineLayout*>(rLine.GetCurr())->SetUnderscore( bHasUnderscore );
    }

    // Calculating the good ol' nDelta
    pPara->GetDelta() -= sal_Int32(pNew->GetLen()) - sal_Int32(nOldLen);

    // Stop!
    if( rLine.IsStop() )
        return false;

    // Absolutely another line
    if( rLine.IsNewLine() )
        return true;

    // Until the String's end?
    if (nNewStart >= TextFrameIndex(GetText().getLength()))
        return false;

    if( rLine.GetInfo().IsShift() )
        return true;

    // Reached the Reformat's end?
    const TextFrameIndex nEnd = pPara->GetReformat().Start() +
                        pPara->GetReformat().Len();

    if( nNewStart <= nEnd )
        return true;

    return 0 != pPara->GetDelta();
}

void SwTextFrame::Format_( SwTextFormatter &rLine, SwTextFormatInfo &rInf,
                        const bool bAdjust )
{
    OSL_ENSURE( ! IsVertical() || IsSwapped(),"SwTextFrame::Format_ with unswapped frame" );

    SwParaPortion *pPara = rLine.GetInfo().GetParaPortion();
    rLine.SetUnclipped( false );

    const OUString & rString = GetText();
    const TextFrameIndex nStrLen(rString.getLength());

    SwCharRange &rReformat = pPara->GetReformat();
    SwRepaint   &rRepaint = pPara->GetRepaint();
    std::unique_ptr<SwRepaint> pFreeze;

    // Due to performance reasons we set rReformat to COMPLETE_STRING in Init()
    // In this case we adjust rReformat
    if( rReformat.Len() > nStrLen )
        rReformat.Len() = nStrLen;

    if( rReformat.Start() + rReformat.Len() > nStrLen )
        rReformat.Len() = nStrLen - rReformat.Start();

    SwTwips nOldBottom;
    if( GetOffset() && !IsFollow() )
    {
        rLine.Bottom();
        nOldBottom = rLine.Y();
        rLine.Top();
    }
    else
        nOldBottom = 0;
    rLine.CharToLine( rReformat.Start() );

    // When inserting or removing a Space, words can be moved out of the edited
    // line and into the preceding line, hence the preceding line must be
    // formatted as well.
    // Optimization: If rReformat starts after the first word of the line,
    // this line cannot possibly influence the previous one.
    // ...Turns out that unfortunately it can: Text size changes + FlyFrames;
    // the feedback can affect multiple lines (Frames!)!

    // i#46560
    // FME: Yes, consider this case: "(word )" has to go to the next line
    // because ")" is a forbidden character at the beginning of a line although
    // "(word" would still fit on the previous line. Adding text right in front
    // of ")" would not trigger a reformatting of the previous line. Adding 1
    // to the result of FindBrk() does not solve the problem in all cases,
    // nevertheless it should be sufficient.
    bool bPrev = rLine.GetPrev() &&
                     (FindBrk(rString, rLine.GetStart(), rReformat.Start() + TextFrameIndex(1))
                       // i#46560
                       + TextFrameIndex(1)
                       >= rReformat.Start() ||
                       rLine.GetCurr()->IsRest() );
    if( bPrev )
    {
        while( rLine.Prev() )
            if( rLine.GetCurr()->GetLen() && !rLine.GetCurr()->IsRest() )
            {
                if( !rLine.GetStart() )
                    rLine.Top(); // So that NumDone doesn't get confused
                break;
            }
        TextFrameIndex nNew = rLine.GetStart() + rLine.GetLength();
        if( nNew )
        {
            --nNew;
            if (CH_BREAK == rString[sal_Int32(nNew)])
            {
                ++nNew;
                rLine.Next();
                bPrev = false;
            }
        }
        rReformat.Len()  += rReformat.Start() - nNew;
        rReformat.Start() = nNew;
    }

    rRepaint.SetOffset( 0 );
    rRepaint.SetRightOfst( 0 );
    rRepaint.Chg( getFrameArea().Pos() + getFramePrintArea().Pos(), getFramePrintArea().SSize() );
    if( pPara->IsMargin() )
        rRepaint.Width( rRepaint.Width() + pPara->GetHangingMargin() );
    rRepaint.Top( rLine.Y() );
    if( 0 >= rRepaint.Width() )
        rRepaint.Width(1);
    WidowsAndOrphans aFrameBreak( this, rInf.IsTest() ? 1 : 0 );

    // rLine is now set to the first line which needs formatting.
    // The bFirst flag makes sure that Next() is not called.
    // The whole thing looks weird, but we need to make sure that
    // rLine stops at the last non-fitting line when calling IsBreakNow.
    bool bFirst  = true;
    bool bFormat = true;

    // The CharToLine() can also get us into the danger zone.
    // In that case we need to walk back until rLine is set
    // to the non-fitting line. Or else the mass of text is lost,
    // because the Ofst was set wrongly in the Follow.

    bool bBreak = ( !pPara->IsPrepMustFit() || rLine.GetLineNr() > 1 )
                    && aFrameBreak.IsBreakNowWidAndOrp( rLine );
    if( bBreak )
    {
        bool bPrevDone = nullptr != rLine.Prev();
        while( bPrevDone && aFrameBreak.IsBreakNowWidAndOrp(rLine) )
            bPrevDone = nullptr != rLine.Prev();
        if( bPrevDone )
        {
            aFrameBreak.SetKeep( false );
            rLine.Next();
        }
        rLine.TruncLines();

        // Play it safe
        aFrameBreak.IsBreakNowWidAndOrp(rLine);
    }

 /* Meaning if the following flags are set:

    Watch(End/Mid)Hyph: we need to format if we have a break at
    the line end/Fly, as long as MaxHyph is reached

    Jump(End/Mid)Flag: the next line which has no break (line end/Fly),
    needs to be formatted, because we could wrap now. This might have been
    forbidden earlier by MaxHyph

    Watch(End/Mid)Hyph: if the last formatted line got a cutoff point, but
    didn't have one before

    Jump(End/Mid)Hyph: if a cutoff point disappears
 */
    bool bJumpEndHyph  = false;
    bool bWatchEndHyph = false;
    bool bJumpMidHyph  = false;
    bool bWatchMidHyph = false;

    const SwAttrSet& rAttrSet = GetTextNodeForParaProps()->GetSwAttrSet();
    rInf.MaxHyph() = rAttrSet.GetHyphenZone().GetMaxHyphens();
    bool bMaxHyph = 0 != rInf.MaxHyph();
    if ( bMaxHyph )
        rLine.InitCntHyph();

    if( IsFollow() && IsFieldFollow() && rLine.GetStart() == GetOffset() )
    {
        SwTextFrame *pMaster = FindMaster();
        OSL_ENSURE( pMaster, "SwTextFrame::Format: homeless follow" );
        const SwLineLayout* pLine=nullptr;
        if (pMaster)
        {
            if (!pMaster->HasPara())
            {   // master could be locked because it's being formatted upstack
                SAL_WARN("sw", "SwTextFrame::Format_: master not formatted!");
            }
            else
            {
                SwTextSizeInfo aInf( pMaster );
                SwTextIter aMasterLine( pMaster, &aInf );
                aMasterLine.Bottom();
                pLine = aMasterLine.GetCurr();
                assert(aMasterLine.GetEnd() == GetOffset());
            }
        }
        SwLinePortion* pRest = pLine ?
            rLine.MakeRestPortion(pLine, GetOffset()) : nullptr;
        if( pRest )
            rInf.SetRest( pRest );
        else
            SetFieldFollow( false );
    }

    /* Ad cancel criterion:
     * In order to recognize, whether a line does not fit onto the page
     * anymore, we need to format it. This overflow is removed again in
     * e.g. AdjustFollow.
     * Another complication: if we are the Master, we need to traverse
     * the lines, because it could happen that one line can overflow
     * from the Follow to the Master.
     */
    do
    {
        if( bFirst )
            bFirst = false;
        else
        {
            if ( bMaxHyph )
            {
                if ( rLine.GetCurr()->IsEndHyph() )
                    rLine.CntEndHyph()++;
                else
                    rLine.CntEndHyph() = 0;
                if ( rLine.GetCurr()->IsMidHyph() )
                    rLine.CntMidHyph()++;
                else
                    rLine.CntMidHyph() = 0;
            }
            if( !rLine.Next() )
            {
                if( !bFormat )
                {
                    SwLinePortion* pRest =
                        rLine.MakeRestPortion( rLine.GetCurr(), rLine.GetEnd() );
                    if( pRest )
                        rInf.SetRest( pRest );
                }
                rLine.Insert( new SwLineLayout() );
                rLine.Next();
                bFormat = true;
            }
        }
        if ( !bFormat && bMaxHyph &&
              (bWatchEndHyph || bJumpEndHyph || bWatchMidHyph || bJumpMidHyph) )
        {
            if ( rLine.GetCurr()->IsEndHyph() )
            {
                if ( bWatchEndHyph )
                    bFormat = ( rLine.CntEndHyph() == rInf.MaxHyph() );
            }
            else
            {
                bFormat = bJumpEndHyph;
                bWatchEndHyph = false;
                bJumpEndHyph = false;
            }
            if ( rLine.GetCurr()->IsMidHyph() )
            {
                if ( bWatchMidHyph && !bFormat )
                    bFormat = ( rLine.CntEndHyph() == rInf.MaxHyph() );
            }
            else
            {
                bFormat |= bJumpMidHyph;
                bWatchMidHyph = false;
                bJumpMidHyph = false;
            }
        }
        if( bFormat )
        {
            const bool bOldEndHyph = rLine.GetCurr()->IsEndHyph();
            const bool bOldMidHyph = rLine.GetCurr()->IsMidHyph();
            bFormat = FormatLine( rLine, bPrev );
            // There can only be one bPrev ... (???)
            bPrev = false;
            if ( bMaxHyph )
            {
                if ( rLine.GetCurr()->IsEndHyph() != bOldEndHyph )
                {
                    bWatchEndHyph = !bOldEndHyph;
                    bJumpEndHyph = bOldEndHyph;
                }
                if ( rLine.GetCurr()->IsMidHyph() != bOldMidHyph )
                {
                    bWatchMidHyph = !bOldMidHyph;
                    bJumpMidHyph = bOldMidHyph;
                }
            }
        }

        if( !rInf.IsNewLine() )
        {
            if( !bFormat )
                 bFormat = nullptr != rInf.GetRest();
            if( rInf.IsStop() || rInf.GetIdx() >= nStrLen )
                break;
            if( !bFormat && ( !bMaxHyph || ( !bWatchEndHyph &&
                    !bJumpEndHyph && !bWatchMidHyph && !bJumpMidHyph ) ) )
            {
                if( GetFollow() )
                {
                    while( rLine.Next() )
                        ; //Nothing
                    pFreeze.reset(new SwRepaint( rRepaint )); // to minimize painting
                }
                else
                    break;
            }
        }
        bBreak = aFrameBreak.IsBreakNowWidAndOrp(rLine);
    }while( !bBreak );

    if( pFreeze )
    {
        rRepaint = *pFreeze;
        pFreeze.reset();
    }

    if( !rLine.IsStop() )
    {
        // If we're finished formatting the text and we still
        // have other line objects left, these are superfluous
        // now because the text has gotten shorter.
        if( rLine.GetStart() + rLine.GetLength() >= nStrLen &&
            rLine.GetCurr()->GetNext() )
        {
            rLine.TruncLines();
            rLine.SetTruncLines( true );
        }
    }

    if( !rInf.IsTest() )
    {
        // FormatAdjust does not pay off at OnceMore
        if( bAdjust || !rLine.GetDropFormat() || !rLine.CalcOnceMore() )
        {
            FormatAdjust( rLine, aFrameBreak, nStrLen, rInf.IsStop() );
        }
        if( rRepaint.HasArea() )
            SetRepaint();
        rLine.SetTruncLines( false );
        if( nOldBottom ) // We check whether paragraphs that need scrolling can
                         // be shrunk, so that they don't need scrolling anymore
        {
            rLine.Bottom();
            SwTwips nNewBottom = rLine.Y();
            if( nNewBottom < nOldBottom )
                SetOffset_(TextFrameIndex(0));
        }
    }
}

void SwTextFrame::FormatOnceMore( SwTextFormatter &rLine, SwTextFormatInfo &rInf )
{
    OSL_ENSURE( ! IsVertical() || IsSwapped(),
            "A frame is not swapped in SwTextFrame::FormatOnceMore" );

    SwParaPortion *pPara = rLine.GetInfo().GetParaPortion();
    if( !pPara )
        return;

    // If necessary the pPara
    sal_uInt16 nOld  = static_cast<const SwTextMargin&>(rLine).GetDropHeight();
    bool bShrink = false;
    bool bGrow   = false;
    bool bGoOn   = rLine.IsOnceMore();
    sal_uInt8 nGo    = 0;
    while( bGoOn )
    {
        ++nGo;
        rInf.Init();
        rLine.Top();
        if( !rLine.GetDropFormat() )
            rLine.SetOnceMore( false );
        SwCharRange aRange(TextFrameIndex(0), TextFrameIndex(rInf.GetText().getLength()));
        pPara->GetReformat() = aRange;
        Format_( rLine, rInf );

        bGoOn = rLine.IsOnceMore();
        if( bGoOn )
        {
            const sal_uInt16 nNew = static_cast<const SwTextMargin&>(rLine).GetDropHeight();
            if( nOld == nNew )
                bGoOn = false;
            else
            {
                if( nOld > nNew )
                    bShrink = true;
                else
                    bGrow = true;

                if( bShrink == bGrow || 5 < nGo )
                    bGoOn = false;

                nOld = nNew;
            }

            // If something went wrong, we need to reformat again
            if( !bGoOn )
            {
                rInf.CtorInitTextFormatInfo( getRootFrame()->GetCurrShell()->GetOut(), this );
                rLine.CtorInitTextFormatter( this, &rInf );
                rLine.SetDropLines( 1 );
                rLine.CalcDropHeight( 1 );
                SwCharRange aTmpRange(TextFrameIndex(0), TextFrameIndex(rInf.GetText().getLength()));
                pPara->GetReformat() = aTmpRange;
                Format_( rLine, rInf, true );
                // We paint everything ...
                SetCompletePaint();
            }
        }
    }
}

void SwTextFrame::Format_( vcl::RenderContext* pRenderContext, SwParaPortion *pPara )
{
    const bool bIsEmpty = GetText().isEmpty();

    if ( bIsEmpty )
    {
        // Empty lines do not get tortured for very long:
        // pPara is cleared, which is the same as:
        // *pPara = SwParaPortion;
        const bool bMustFit = pPara->IsPrepMustFit();
        pPara->Truncate();
        pPara->FormatReset();

        // delete pSpaceAdd and pKanaComp
        pPara->FinishSpaceAdd();
        pPara->FinishKanaComp();
        pPara->ResetFlags();
        pPara->SetPrepMustFit( bMustFit );
    }

    OSL_ENSURE( ! IsSwapped(), "A frame is swapped before Format_" );

    if ( IsVertical() )
        SwapWidthAndHeight();

    SwTextFormatInfo aInf( pRenderContext, this );
    SwTextFormatter  aLine( this, &aInf );

    HideAndShowObjects();

    Format_( aLine, aInf );

    if( aLine.IsOnceMore() )
        FormatOnceMore( aLine, aInf );

    if ( IsVertical() )
        SwapWidthAndHeight();

    OSL_ENSURE( ! IsSwapped(), "A frame is swapped after Format_" );

    if( 1 < aLine.GetDropLines() )
    {
        if( SvxAdjust::Left != aLine.GetAdjust() &&
            SvxAdjust::Block != aLine.GetAdjust() )
        {
            aLine.CalcDropAdjust();
            aLine.SetPaintDrop( true );
        }

        if( aLine.IsPaintDrop() )
        {
            aLine.CalcDropRepaint();
            aLine.SetPaintDrop( false );
        }
    }
}

// We calculate the text frame's size and send a notification.
// Shrink() or Grow() to adjust the frame's size to the changed required space.
void SwTextFrame::Format( vcl::RenderContext* pRenderContext, const SwBorderAttrs * )
{
    SwRectFnSet aRectFnSet(this);

    CalcAdditionalFirstLineOffset();

    // The range autopilot or the BASIC interface pass us TextFrames with
    // a width <= 0 from time to time
    if( aRectFnSet.GetWidth(getFramePrintArea()) <= 0 )
    {
        // If MustFit is set, we shrink to the Upper's bottom edge if needed.
        // Else we just take a standard size of 12 Pt. (240 twip).
        SwTextLineAccess aAccess( this );
        long nFrameHeight = aRectFnSet.GetHeight(getFrameArea());

        if( aAccess.GetPara()->IsPrepMustFit() )
        {
            const SwTwips nLimit = aRectFnSet.GetPrtBottom(*GetUpper());
            const SwTwips nDiff = - aRectFnSet.BottomDist( getFrameArea(), nLimit );
            if( nDiff > 0 )
                Shrink( nDiff );
        }
        else if( 240 < nFrameHeight )
        {
            Shrink( nFrameHeight - 240 );
        }
        else if( 240 > nFrameHeight )
        {
            Grow( 240 - nFrameHeight );
        }

        nFrameHeight = aRectFnSet.GetHeight(getFrameArea());
        const long nTop = aRectFnSet.GetTopMargin(*this);

        if( nTop > nFrameHeight )
        {
            aRectFnSet.SetYMargins( *this, nFrameHeight, 0 );
        }
        else if( aRectFnSet.GetHeight(getFramePrintArea()) < 0 )
        {
            SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
            aRectFnSet.SetHeight( aPrt, 0 );
        }

        return;
    }

    const TextFrameIndex nStrLen(GetText().getLength());
    if ( nStrLen || !FormatEmpty() )
    {

        SetEmpty( false );
        // In order to not get confused by nested Formats
        FormatLevel aLevel;
        if( 12 == FormatLevel::GetLevel() )
            return;

        // We could be possibly not allowed to alter the format information
        if( IsLocked() )
            return;

        // Attention: Format() could be triggered by GetFormatted()
        if( IsHiddenNow() )
        {
            long nPrtHeight = aRectFnSet.GetHeight(getFramePrintArea());
            if( nPrtHeight )
            {
                HideHidden();
                Shrink( nPrtHeight );
            }
            else
            {
                // Assure that objects anchored
                // at paragraph resp. at/as character inside paragraph
                // are hidden.
                HideAndShowObjects();
            }
            ChgThisLines();
            return;
        }

        // We do not want to be interrupted during formatting
        TextFrameLockGuard aLock(this);

        // this is to ensure that the similar code in SwTextFrame::Format_
        // finds the master formatted in case it's needed
        if (IsFollow() && IsFieldFollow())
        {
            SwTextFrame *pMaster = FindMaster();
            assert(pMaster);
            if (!pMaster->HasPara())
            {
                pMaster->GetFormatted();
            }
            if (!pMaster->HasPara())
            {   // master could be locked because it's being formatted upstack
                SAL_WARN("sw", "SwTextFrame::Format: failed to format master!");
            }
            else
            {
                SwTextSizeInfo aInf( pMaster );
                SwTextIter aMasterLine( pMaster, &aInf );
                aMasterLine.Bottom();
                SetOffset(aMasterLine.GetEnd());
            }
        }

        SwTextLineAccess aAccess( this );
        const bool bNew = !aAccess.IsAvailable();
        const bool bSetOffset =
            (GetOffset() && GetOffset() > TextFrameIndex(GetText().getLength()));

        if( CalcPreps() )
            ; // nothing
        // We return if already formatted, but if the TextFrame was just created
        // and does not have any format information
        else if( !bNew && !aAccess.GetPara()->GetReformat().Len() )
        {
            if (GetTextNodeForParaProps()->GetSwAttrSet().GetRegister().GetValue())
            {
                aAccess.GetPara()->SetPrepAdjust();
                aAccess.GetPara()->SetPrep();
                CalcPreps();
            }
            SetWidow( false );
        }
        else if( bSetOffset && IsFollow() )
        {
            SwTextFrame *pMaster = FindMaster();
            OSL_ENSURE( pMaster, "SwTextFrame::Format: homeless follow" );
            if( pMaster )
                pMaster->Prepare( PrepareHint::FollowFollows );
            SwTwips nMaxY = aRectFnSet.GetPrtBottom(*GetUpper());

            if( aRectFnSet.OverStep( getFrameArea(), nMaxY  ) )
            {
                aRectFnSet.SetLimit( *this, nMaxY );
            }
            else if( aRectFnSet.BottomDist( getFrameArea(), nMaxY  ) < 0 )
            {
                SwFrameAreaDefinition::FrameAreaWriteAccess aFrm(*this);
                aRectFnSet.AddBottom( aFrm, -aRectFnSet.GetHeight(aFrm) );
            }
        }
        else
        {
            // bSetOffset here means that we have the "red arrow situation"
            if ( bSetOffset )
                SetOffset_(TextFrameIndex(0));

            const bool bOrphan = IsWidow();
            const SwFootnoteBossFrame* pFootnoteBoss = HasFootnote() ? FindFootnoteBossFrame() : nullptr;
            SwTwips nFootnoteHeight = 0;
            if( pFootnoteBoss )
            {
                const SwFootnoteContFrame* pCont = pFootnoteBoss->FindFootnoteCont();
                nFootnoteHeight = pCont ? aRectFnSet.GetHeight(pCont->getFrameArea()) : 0;
            }
            do
            {
                Format_( pRenderContext, aAccess.GetPara() );
                if( pFootnoteBoss && nFootnoteHeight )
                {
                    const SwFootnoteContFrame* pCont = pFootnoteBoss->FindFootnoteCont();
                    SwTwips nNewHeight = pCont ? aRectFnSet.GetHeight(pCont->getFrameArea()) : 0;
                    // If we lost some footnotes, we may have more space
                    // for our main text, so we have to format again ...
                    if( nNewHeight < nFootnoteHeight )
                        nFootnoteHeight = nNewHeight;
                    else
                        break;
                }
                else
                    break;
            } while ( pFootnoteBoss );
            if( bOrphan )
            {
                ValidateFrame();
                SetWidow( false );
            }
        }
        if( IsEmptyMaster() )
        {
            SwFrame* pPre = GetPrev();
            if( pPre &&
                // i#10826 It's the first, it cannot keep!
                pPre->GetIndPrev() &&
                pPre->GetAttrSet()->GetKeep().GetValue() )
            {
                pPre->InvalidatePos();
            }
        }
    }

    ChgThisLines();

    // the PrepMustFit should not survive a Format operation
    SwParaPortion *pPara = GetPara();
    if ( pPara )
           pPara->SetPrepMustFit( false );

    CalcBaseOfstForFly();
    CalcHeightOfLastLine(); // i#11860 - Adjust spacing implementation for
                             // object positioning - Compatibility to MS Word
    // tdf#117982 -- Fix cell spacing hides content
    // Check if the cell's content has greater size than the row height
    if (IsInTab() && GetUpper() && ((GetUpper()->getFramePrintArea().Height() < getFramePrintArea().Height())
            || (getFramePrintArea().Height() <= 0)))
    {
           SAL_INFO("sw.core", "Warn: Cell content has greater size than cell height!");
           //get font size...
           SwTwips aTmpHeight = getFrameArea().Height();
           //...and push it into the text frame
           SwFrameAreaDefinition::FramePrintAreaWriteAccess aPrt(*this);
           //if only bottom margin what we have:
           if (GetTopMargin() == 0)
               //set the frame to its original location
               aPrt.SetTopAndHeight(0, aTmpHeight);
    }
}

// bForceQuickFormat is set if GetFormatted() has been called during the
// painting process. Actually I cannot imagine a situation which requires
// a full formatting of the paragraph during painting, on the other hand
// a full formatting can cause the invalidation of other layout frames,
// e.g., if there are footnotes in this paragraph, and invalid layout
// frames will not calculated during the painting. So I actually want to
// avoid a formatting during painting, but since I'm a coward, I'll only
// force the quick formatting in the situation of issue i29062.
bool SwTextFrame::FormatQuick( bool bForceQuickFormat )
{
    OSL_ENSURE( ! IsVertical() || ! IsSwapped(),
            "SwTextFrame::FormatQuick with swapped frame" );

    if( IsEmpty() && FormatEmpty() )
        return true;

    // We're very picky:
    if( HasPara() || IsWidow() || IsLocked()
        || !isFrameAreaSizeValid() ||
        ( ( IsVertical() ? getFramePrintArea().Width() : getFramePrintArea().Height() ) && IsHiddenNow() ) )
        return false;

    SwTextLineAccess aAccess( this );
    SwParaPortion *pPara = aAccess.GetPara();
    if( !pPara )
        return false;

    SwFrameSwapper aSwapper( this, true );

    TextFrameLockGuard aLock(this);
    SwTextFormatInfo aInf( getRootFrame()->GetCurrShell()->GetOut(), this, false, true );
    if( 0 != aInf.MaxHyph() )   // Respect MaxHyphen!
        return false;

    SwTextFormatter  aLine( this, &aInf );

    // DropCaps are too complicated ...
    if( aLine.GetDropFormat() )
        return false;

    TextFrameIndex nStart = GetOffset();
    const TextFrameIndex nEnd = GetFollow()
                  ? GetFollow()->GetOffset()
                  : TextFrameIndex(aInf.GetText().getLength());

    int nLoopProtection = 0;
    do
    {
        TextFrameIndex nNewStart = aLine.FormatLine(nStart);
        if (nNewStart == nStart)
            ++nLoopProtection;
        else
            nLoopProtection = 0;
        nStart = nNewStart;
        const bool bWillEndlessInsert = nLoopProtection > 250;
        SAL_WARN_IF(bWillEndlessInsert, "sw", "loop detection triggered");
        if ((!bWillEndlessInsert) // Check for special case: line is invisible,
                                  // like in too thin table cell: tdf#66141
         && (aInf.IsNewLine() || (!aInf.IsStop() && nStart < nEnd)))
            aLine.Insert( new SwLineLayout() );
    } while( aLine.Next() );

    // Last exit: the heights need to match
    Point aTopLeft( getFrameArea().Pos() );
    aTopLeft += getFramePrintArea().Pos();
    const SwTwips nNewHeight = aLine.Y() + aLine.GetLineHeight();
    const SwTwips nOldHeight = aTopLeft.Y() + getFramePrintArea().Height();

    if( !bForceQuickFormat && nNewHeight != nOldHeight && !IsUndersized() )
    {
        // Attention: This situation can occur due to FormatLevel==12. Don't panic!
        TextFrameIndex const nStrt = GetOffset();
        InvalidateRange_( SwCharRange( nStrt, nEnd - nStrt) );
        return false;
    }

    if (m_pFollow && nStart != static_cast<SwTextFrame*>(m_pFollow)->GetOffset())
        return false; // can be caused by e.g. Orphans

    // We made it!

    // Set repaint
    pPara->GetRepaint().Pos( aTopLeft );
    pPara->GetRepaint().SSize( getFramePrintArea().SSize() );

    // Delete reformat
    pPara->GetReformat() = SwCharRange();
    pPara->GetDelta() = 0;

    return true;
}

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