summaryrefslogtreecommitdiff
path: root/sw/source/core/text/frmcrsr.cxx
blob: 48ba68d3a81f6ae7654ae34fa656f5fb8380936f (plain)
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
/* -*- 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 <ndtxt.hxx>
#include <pam.hxx>
#include <frmatr.hxx>
#include <frmtool.hxx>
#include <viewopt.hxx>
#include <paratr.hxx>
#include <rootfrm.hxx>
#include <pagefrm.hxx>
#include <colfrm.hxx>
#include <swtypes.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/tstpitem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/lspcitem.hxx>
#include "pormulti.hxx"
#include <doc.hxx>
#include <IDocumentDeviceAccess.hxx>
#include <sortedobjs.hxx>

#include <unicode/ubidi.h>

#include <txtfrm.hxx>
#include "inftxt.hxx"
#include "itrtxt.hxx"
#include <crstate.hxx>
#include <viewsh.hxx>
#include <swfntcch.hxx>
#include <flyfrm.hxx>

#define MIN_OFFSET_STEP 10

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

/*
 * - SurvivalKit: For how long do we get past the last char of the line.
 * - RightMargin abstains from adjusting position with -1
 * - GetCharRect returns a GetEndCharRect for CursorMoveState::RightMargin
 * - GetEndCharRect sets bRightMargin to true
 * - SwTextCursor::bRightMargin is set to false by CharCursorToLine
 */

namespace
{

SwTextFrame *GetAdjFrameAtPos( SwTextFrame *pFrame, const SwPosition &rPos,
                          const bool bRightMargin, const bool bNoScroll = true )
{
    // RightMargin in the last master line
    TextFrameIndex const nOffset = pFrame->MapModelToViewPos(rPos);
    SwTextFrame *pFrameAtPos = pFrame;
    if( !bNoScroll || pFrame->GetFollow() )
    {
        pFrameAtPos = pFrame->GetFrameAtPos( rPos );
        if (nOffset < pFrameAtPos->GetOffset() &&
            !pFrameAtPos->IsFollow() )
        {
            assert(pFrameAtPos->MapModelToViewPos(rPos) == nOffset);
            TextFrameIndex nNew(nOffset);
            if (nNew < TextFrameIndex(MIN_OFFSET_STEP))
                nNew = TextFrameIndex(0);
            else
                nNew -= TextFrameIndex(MIN_OFFSET_STEP);
            sw_ChangeOffset( pFrameAtPos, nNew );
        }
    }
    while( pFrame != pFrameAtPos )
    {
        pFrame = pFrameAtPos;
        pFrame->GetFormatted();
        pFrameAtPos = pFrame->GetFrameAtPos( rPos );
    }

    if( nOffset && bRightMargin )
    {
        while (pFrameAtPos &&
               pFrameAtPos->MapViewToModelPos(pFrameAtPos->GetOffset()) == rPos &&
               pFrameAtPos->IsFollow() )
        {
            pFrameAtPos->GetFormatted();
            pFrameAtPos = pFrameAtPos->FindMaster();
        }
        OSL_ENSURE( pFrameAtPos, "+GetCharRect: no frame with my rightmargin" );
    }
    return pFrameAtPos ? pFrameAtPos : pFrame;
}

}

bool sw_ChangeOffset(SwTextFrame* pFrame, TextFrameIndex nNew)
{
    // Do not scroll in areas and outside of flies
    OSL_ENSURE( !pFrame->IsFollow(), "Illegal Scrolling by Follow!" );
    if( pFrame->GetOffset() != nNew && !pFrame->IsInSct() )
    {
        SwFlyFrame *pFly = pFrame->FindFlyFrame();
        // Attention: if e.g. in a column frame the size is still invalid
        // we must not scroll around just like that
        if ( ( pFly && pFly->isFrameAreaDefinitionValid() &&
             !pFly->GetNextLink() && !pFly->GetPrevLink() ) ||
             ( !pFly && pFrame->IsInTab() ) )
        {
            SwViewShell* pVsh = pFrame->getRootFrame()->GetCurrShell();
            if( pVsh )
            {
                if( pVsh->GetRingContainer().size() > 1 ||
                    ( pFrame->GetDrawObjs() && pFrame->GetDrawObjs()->size() ) )
                {
                    if( !pFrame->GetOffset() )
                        return false;
                    nNew = TextFrameIndex(0);
                }
                pFrame->SetOffset( nNew );
                pFrame->SetPara( nullptr );
                pFrame->GetFormatted();
                if( pFrame->getFrameArea().HasArea() )
                    pFrame->getRootFrame()->GetCurrShell()->InvalidateWindows( pFrame->getFrameArea() );
                return true;
            }
        }
    }
    return false;
}

SwTextFrame& SwTextFrame::GetFrameAtOfst(TextFrameIndex const nWhere)
{
    SwTextFrame* pRet = this;
    while( pRet->HasFollow() && nWhere >= pRet->GetFollow()->GetOffset() )
        pRet = pRet->GetFollow();
    return *pRet;
}

SwTextFrame *SwTextFrame::GetFrameAtPos( const SwPosition &rPos )
{
    TextFrameIndex const nPos(MapModelToViewPos(rPos));
    SwTextFrame *pFoll = this;
    while( pFoll->GetFollow() )
    {
        if (nPos > pFoll->GetFollow()->GetOffset())
            pFoll = pFoll->GetFollow();
        else
        {
            if (nPos == pFoll->GetFollow()->GetOffset()
                 && !SwTextCursor::IsRightMargin() )
                 pFoll = pFoll->GetFollow();
            else
                break;
        }
    }
    return pFoll;
}

/*
 * GetCharRect() returns the char's char line described by aPos.
 * GetModelPositionForViewPoint() does the reverse: It goes from a document coordinate to
 * a Pam.
 * Both are virtual in the frame base class and thus are redefined here.
 */

bool SwTextFrame::GetCharRect( SwRect& rOrig, const SwPosition &rPos,
                            SwCursorMoveState *pCMS, bool bAllowFarAway ) const
{
    OSL_ENSURE( ! IsVertical() || ! IsSwapped(),"SwTextFrame::GetCharRect with swapped frame" );

    if( IsLocked() || IsHiddenNow() )
        return false;

    // Find the right frame first. We need to keep in mind that:
    // - the cached information could be invalid  (GetPara() == 0)
    // - we could have a Follow
    // - the Follow chain grows dynamically; the one we end up in
    //   needs to be formatted

    // Optimisation: reading ahead saves us a GetAdjFrameAtPos
    const bool bRightMargin = pCMS && ( CursorMoveState::RightMargin == pCMS->m_eState );
    const bool bNoScroll = pCMS && pCMS->m_bNoScroll;
    SwTextFrame *pFrame = GetAdjFrameAtPos( const_cast<SwTextFrame*>(this), rPos, bRightMargin,
                                     bNoScroll );
    pFrame->GetFormatted();

    const SwFrame* pTmpFrame = pFrame->GetUpper();
    if (pTmpFrame->getFrameArea().Top() == FAR_AWAY && !bAllowFarAway)
        return false;

    SwRectFnSet aRectFnSet(pFrame);
    const SwTwips nUpperMaxY = aRectFnSet.GetPrtBottom(*pTmpFrame);
    const SwTwips nFrameMaxY = aRectFnSet.GetPrtBottom(*pFrame);

    // nMaxY is an absolute value
    SwTwips nMaxY = aRectFnSet.IsVert() ?
                    ( aRectFnSet.IsVertL2R() ? std::min( nFrameMaxY, nUpperMaxY ) : std::max( nFrameMaxY, nUpperMaxY ) ) :
                    std::min( nFrameMaxY, nUpperMaxY );

    bool bRet = false;

    if ( pFrame->IsEmpty() || ! aRectFnSet.GetHeight(pFrame->getFramePrintArea()) )
    {
        Point aPnt1 = pFrame->getFrameArea().Pos() + pFrame->getFramePrintArea().Pos();
        SwTextNode const*const pTextNd(GetTextNodeForParaProps());
        short nFirstOffset;
        pTextNd->GetFirstLineOfsWithNum( nFirstOffset );

        Point aPnt2;
        if ( aRectFnSet.IsVert() )
        {
            if( nFirstOffset > 0 )
                aPnt1.AdjustY(nFirstOffset );
            if ( aPnt1.X() < nMaxY && !aRectFnSet.IsVertL2R() )
                aPnt1.setX( nMaxY );
            aPnt2.setX( aPnt1.X() + pFrame->getFramePrintArea().Width() );
            aPnt2.setY( aPnt1.Y() );
            if( aPnt2.X() < nMaxY )
                aPnt2.setX( nMaxY );
        }
        else
        {
            if( nFirstOffset > 0 )
                aPnt1.AdjustX(nFirstOffset );

            if( aPnt1.Y() > nMaxY )
                aPnt1.setY( nMaxY );
            aPnt2.setX( aPnt1.X() );
            aPnt2.setY( aPnt1.Y() + pFrame->getFramePrintArea().Height() );
            if( aPnt2.Y() > nMaxY )
                aPnt2.setY( nMaxY );
        }

        rOrig = SwRect( aPnt1, aPnt2 );

        if ( pCMS )
        {
            pCMS->m_aRealHeight.setX( 0 );
            pCMS->m_aRealHeight.setY( aRectFnSet.IsVert() ? -rOrig.Width() : rOrig.Height() );
        }

        if ( pFrame->IsRightToLeft() )
            pFrame->SwitchLTRtoRTL( rOrig );

        bRet = true;
    }
    else
    {
        if( !pFrame->HasPara() )
            return false;

        SwFrameSwapper aSwapper( pFrame, true );
        if ( aRectFnSet.IsVert() )
            nMaxY = pFrame->SwitchVerticalToHorizontal( nMaxY );

        bool bGoOn = true;
        TextFrameIndex const nOffset = MapModelToViewPos(rPos);
        assert(nOffset != TextFrameIndex(COMPLETE_STRING)); // not going to end well
        TextFrameIndex nNextOfst;

        do
        {
            {
                SwTextSizeInfo aInf( pFrame );
                SwTextCursor  aLine( pFrame, &aInf );
                nNextOfst = aLine.GetEnd();
                // See comment in AdjustFrame
                // Include the line's last char?
                if (bRightMargin)
                    aLine.GetEndCharRect( &rOrig, nOffset, pCMS, nMaxY );
                else
                    aLine.GetCharRect( &rOrig, nOffset, pCMS, nMaxY );
                bRet = true;
            }

            if ( pFrame->IsRightToLeft() )
                pFrame->SwitchLTRtoRTL( rOrig );

            if ( aRectFnSet.IsVert() )
                pFrame->SwitchHorizontalToVertical( rOrig );

            if( pFrame->IsUndersized() && pCMS && !pFrame->GetNext() &&
                aRectFnSet.GetBottom(rOrig) == nUpperMaxY &&
                pFrame->GetOffset() < nOffset &&
                !pFrame->IsFollow() && !bNoScroll &&
                TextFrameIndex(pFrame->GetText().getLength()) != nNextOfst)
            {
                bGoOn = sw_ChangeOffset( pFrame, nNextOfst );
            }
            else
                bGoOn = false;
        } while ( bGoOn );

        if ( pCMS )
        {
            if ( pFrame->IsRightToLeft() )
            {
                if( pCMS->m_b2Lines && pCMS->m_p2Lines)
                {
                    pFrame->SwitchLTRtoRTL( pCMS->m_p2Lines->aLine );
                    pFrame->SwitchLTRtoRTL( pCMS->m_p2Lines->aPortion );
                }
            }

            if ( aRectFnSet.IsVert() )
            {
                if ( pCMS->m_bRealHeight )
                {
                    pCMS->m_aRealHeight.setY( -pCMS->m_aRealHeight.Y() );
                    if ( pCMS->m_aRealHeight.Y() < 0 )
                    {
                        // writing direction is from top to bottom
                        pCMS->m_aRealHeight.setX(  rOrig.Width() -
                                                   pCMS->m_aRealHeight.X() +
                                                   pCMS->m_aRealHeight.Y() );
                    }
                }
                if( pCMS->m_b2Lines && pCMS->m_p2Lines)
                {
                    pFrame->SwitchHorizontalToVertical( pCMS->m_p2Lines->aLine );
                    pFrame->SwitchHorizontalToVertical( pCMS->m_p2Lines->aPortion );
                }
            }

        }
    }
    if( bRet )
    {
        SwPageFrame *pPage = pFrame->FindPageFrame();
        OSL_ENSURE( pPage, "Text escaped from page?" );
        const SwTwips nOrigTop = aRectFnSet.GetTop(rOrig);
        const SwTwips nPageTop = aRectFnSet.GetTop(pPage->getFrameArea());
        const SwTwips nPageBott = aRectFnSet.GetBottom(pPage->getFrameArea());

        // We have the following situation: if the frame is in an invalid
        // sectionframe, it's possible that the frame is outside the page.
        // If we restrict the cursor position to the page area, we enforce
        // the formatting of the page, of the section frame and the frame itself.
        if( aRectFnSet.YDiff( nPageTop, nOrigTop ) > 0 )
            aRectFnSet.SetTop( rOrig, nPageTop );

        if ( aRectFnSet.YDiff( nOrigTop, nPageBott ) > 0 )
            aRectFnSet.SetTop( rOrig, nPageBott );
    }

    return bRet;
}

/*
 * GetAutoPos() looks up the char's char line which is described by rPos
 * and is used by the auto-positioned frame.
 */

bool SwTextFrame::GetAutoPos( SwRect& rOrig, const SwPosition &rPos ) const
{
    if( IsHiddenNow() )
        return false;

    TextFrameIndex const nOffset = MapModelToViewPos(rPos);
    SwTextFrame* pFrame = &(const_cast<SwTextFrame*>(this)->GetFrameAtOfst( nOffset ));

    pFrame->GetFormatted();
    const SwFrame* pTmpFrame = pFrame->GetUpper();

    SwRectFnSet aRectFnSet(pTmpFrame);
    SwTwips nUpperMaxY = aRectFnSet.GetPrtBottom(*pTmpFrame);

    // nMaxY is in absolute value
    SwTwips nMaxY;
    if ( aRectFnSet.IsVert() )
    {
        if ( aRectFnSet.IsVertL2R() )
            nMaxY = std::min( aRectFnSet.GetPrtBottom(*pFrame), nUpperMaxY );
        else
            nMaxY = std::max( aRectFnSet.GetPrtBottom(*pFrame), nUpperMaxY );
    }
    else
        nMaxY = std::min( aRectFnSet.GetPrtBottom(*pFrame), nUpperMaxY );
    if ( pFrame->IsEmpty() || ! aRectFnSet.GetHeight(pFrame->getFramePrintArea()) )
    {
        Point aPnt1 = pFrame->getFrameArea().Pos() + pFrame->getFramePrintArea().Pos();
        Point aPnt2;
        if ( aRectFnSet.IsVert() )
        {
            if ( aPnt1.X() < nMaxY && !aRectFnSet.IsVertL2R() )
                aPnt1.setX( nMaxY );

            aPnt2.setX( aPnt1.X() + pFrame->getFramePrintArea().Width() );
            aPnt2.setY( aPnt1.Y() );
            if( aPnt2.X() < nMaxY )
                aPnt2.setX( nMaxY );
        }
        else
        {
            if( aPnt1.Y() > nMaxY )
                aPnt1.setY( nMaxY );
            aPnt2.setX( aPnt1.X() );
            aPnt2.setY( aPnt1.Y() + pFrame->getFramePrintArea().Height() );
            if( aPnt2.Y() > nMaxY )
                aPnt2.setY( nMaxY );
        }
        rOrig = SwRect( aPnt1, aPnt2 );
        return true;
    }
    else
    {
        if( !pFrame->HasPara() )
            return false;

        SwFrameSwapper aSwapper( pFrame, true );
        if ( aRectFnSet.IsVert() )
            nMaxY = pFrame->SwitchVerticalToHorizontal( nMaxY );

        SwTextSizeInfo aInf( pFrame );
        SwTextCursor aLine( pFrame, &aInf );
        SwCursorMoveState aTmpState( CursorMoveState::SetOnlyText );
        aTmpState.m_bRealHeight = true;
        aLine.GetCharRect( &rOrig, nOffset, &aTmpState, nMaxY );
        if( aTmpState.m_aRealHeight.X() >= 0 )
        {
            rOrig.Pos().AdjustY(aTmpState.m_aRealHeight.X() );
            rOrig.Height( aTmpState.m_aRealHeight.Y() );
        }

        if ( pFrame->IsRightToLeft() )
            pFrame->SwitchLTRtoRTL( rOrig );

        if ( aRectFnSet.IsVert() )
            pFrame->SwitchHorizontalToVertical( rOrig );

        return true;
    }
}

/** determine top of line for given position in the text frame

    - Top of first paragraph line is the top of the printing area of the text frame
    - If a proportional line spacing is applied use top of anchor character as
      top of the line.
*/
bool SwTextFrame::GetTopOfLine( SwTwips& _onTopOfLine,
                             const SwPosition& _rPos ) const
{
    bool bRet = true;

    // get position offset
    TextFrameIndex const nOffset = MapModelToViewPos(_rPos);

    if (TextFrameIndex(GetText().getLength()) < nOffset)
    {
        bRet = false;
    }
    else
    {
        SwRectFnSet aRectFnSet(this);
        if ( IsEmpty() || !aRectFnSet.GetHeight(getFramePrintArea()) )
        {
            // consider upper space amount considered
            // for previous frame and the page grid.
            _onTopOfLine = aRectFnSet.GetPrtTop(*this);
        }
        else
        {
            // determine formatted text frame that contains the requested position
            SwTextFrame* pFrame = &(const_cast<SwTextFrame*>(this)->GetFrameAtOfst( nOffset ));
            pFrame->GetFormatted();
            aRectFnSet.Refresh(pFrame);
            // If proportional line spacing is applied
            // to the text frame, the top of the anchor character is also the
            // top of the line.
            // Otherwise the line layout determines the top of the line
            const SvxLineSpacingItem& rSpace = GetAttrSet()->GetLineSpacing();
            if ( rSpace.GetInterLineSpaceRule() == SvxInterLineSpaceRule::Prop )
            {
                SwRect aCharRect;
                if ( GetAutoPos( aCharRect, _rPos ) )
                {
                    _onTopOfLine = aRectFnSet.GetTop(aCharRect);
                }
                else
                {
                    bRet = false;
                }
            }
            else
            {
                // assure that text frame is in a horizontal layout
                SwFrameSwapper aSwapper( pFrame, true );
                // determine text line that contains the requested position
                SwTextSizeInfo aInf( pFrame );
                SwTextCursor aLine( pFrame, &aInf );
                aLine.CharCursorToLine( nOffset );
                // determine top of line
                _onTopOfLine = aLine.Y();
                if ( aRectFnSet.IsVert() )
                {
                    _onTopOfLine = pFrame->SwitchHorizontalToVertical( _onTopOfLine );
                }
            }
        }
    }

    return bRet;
}

// Minimum distance of non-empty lines is a little less than 2 cm
#define FILL_MIN_DIST 1100

struct SwFillData
{
    SwRect aFrame;
    const SwCursorMoveState *pCMS;
    SwPosition* pPos;
    const Point& rPoint;
    SwTwips nLineWidth;
    bool bFirstLine : 1;
    bool bInner     : 1;
    bool bColumn    : 1;
    bool bEmpty     : 1;
    SwFillData( const SwCursorMoveState *pC, SwPosition* pP, const SwRect& rR,
        const Point& rPt ) : aFrame( rR ), pCMS( pC ), pPos( pP ), rPoint( rPt ),
        nLineWidth( 0 ), bFirstLine( true ), bInner( false ), bColumn( false ),
        bEmpty( true ){}
    SwFillMode Mode() const { return pCMS->m_pFill->eMode; }
    tools::Long X() const { return rPoint.X(); }
    tools::Long Y() const { return rPoint.Y(); }
    tools::Long Left() const { return aFrame.Left(); }
    tools::Long Right() const { return aFrame.Right(); }
    tools::Long Bottom() const { return aFrame.Bottom(); }
    SwFillCursorPos &Fill() const { return *pCMS->m_pFill; }
    void SetTab( sal_uInt16 nNew ) { pCMS->m_pFill->nTabCnt = nNew; }
    void SetSpace( sal_uInt16 nNew ) { pCMS->m_pFill->nSpaceCnt = nNew; }
    void SetSpaceOnly( sal_uInt16 nNew ) { pCMS->m_pFill->nSpaceOnlyCnt = nNew; }
    void SetOrient( const sal_Int16 eNew ){ pCMS->m_pFill->eOrient = eNew; }
};

bool SwTextFrame::GetModelPositionForViewPoint_(SwPosition* pPos, const Point& rPoint,
                    const bool bChgFrame, SwCursorMoveState* pCMS ) const
{
    // GetModelPositionForViewPoint_ is called by GetModelPositionForViewPoint and GetKeyCursorOfst.
    // Never just a return false.

    if( IsLocked() || IsHiddenNow() )
        return false;

    const_cast<SwTextFrame*>(this)->GetFormatted();

    Point aOldPoint( rPoint );

    if ( IsVertical() )
    {
        SwitchVerticalToHorizontal( const_cast<Point&>(rPoint) );
        const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();
    }

    if ( IsRightToLeft() )
        SwitchRTLtoLTR( const_cast<Point&>(rPoint) );

    std::unique_ptr<SwFillData> pFillData;
    if ( pCMS && pCMS->m_pFill )
        pFillData.reset(new SwFillData( pCMS, pPos, getFrameArea(), rPoint ));

    if ( IsEmpty() )
    {
        *pPos = MapViewToModelPos(TextFrameIndex(0));
        if( pCMS && pCMS->m_bFieldInfo )
        {
            SwTwips nDiff = rPoint.X() - getFrameArea().Left() - getFramePrintArea().Left();
            if( nDiff > 50 || nDiff < 0 )
                pCMS->m_bPosCorr = true;
        }
    }
    else
    {
        SwTextSizeInfo aInf( const_cast<SwTextFrame*>(this) );
        SwTextCursor  aLine( const_cast<SwTextFrame*>(this), &aInf );

        // See comment in AdjustFrame()
        SwTwips nMaxY = getFrameArea().Top() + getFramePrintArea().Top() + getFramePrintArea().Height();
        aLine.TwipsToLine( rPoint.Y() );
        while( aLine.Y() + aLine.GetLineHeight() > nMaxY )
        {
            if( !aLine.Prev() )
                break;
        }

        if( aLine.GetDropLines() >= aLine.GetLineNr() && 1 != aLine.GetLineNr()
            && rPoint.X() < aLine.FirstLeft() + aLine.GetDropLeft() )
            while( aLine.GetLineNr() > 1 )
                aLine.Prev();

        TextFrameIndex nOffset = aLine.GetModelPositionForViewPoint(pPos, rPoint, bChgFrame, pCMS);

        if( pCMS && pCMS->m_eState == CursorMoveState::NONE && aLine.GetEnd() == nOffset )
            pCMS->m_eState = CursorMoveState::RightMargin;

    // pPos is a pure IN parameter and must not be evaluated.
    // pIter->GetModelPositionForViewPoint returns from a nesting with COMPLETE_STRING.
    // If SwTextIter::GetModelPositionForViewPoint calls GetModelPositionForViewPoint further by itself
    // nNode changes the position.
    // In such cases, pPos must not be calculated.
        if (TextFrameIndex(COMPLETE_STRING) != nOffset)
        {
            *pPos = MapViewToModelPos(nOffset);
            if( pFillData )
            {
                if (TextFrameIndex(GetText().getLength()) > nOffset ||
                    rPoint.Y() < getFrameArea().Top() )
                    pFillData->bInner = true;
                pFillData->bFirstLine = aLine.GetLineNr() < 2;
                if (GetText().getLength())
                {
                    pFillData->bEmpty = false;
                    pFillData->nLineWidth = aLine.GetCurr()->Width();
                }
            }
        }
    }
    bool bChgFillData = false;
    if( pFillData && FindPageFrame()->getFrameArea().IsInside( aOldPoint ) )
    {
        FillCursorPos( *pFillData );
        bChgFillData = true;
    }

    if ( IsVertical() )
    {
        if ( bChgFillData )
            SwitchHorizontalToVertical( pFillData->Fill().aCursor.Pos() );
        const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();
    }

    if ( IsRightToLeft() && bChgFillData )
    {
            SwitchLTRtoRTL( pFillData->Fill().aCursor.Pos() );
            const sal_Int16 eOrient = pFillData->pCMS->m_pFill->eOrient;

            if ( text::HoriOrientation::LEFT == eOrient )
                pFillData->SetOrient( text::HoriOrientation::RIGHT );
            else if ( text::HoriOrientation::RIGHT == eOrient )
                pFillData->SetOrient( text::HoriOrientation::LEFT );
    }

    const_cast<Point&>(rPoint) = aOldPoint;

    return true;
}

bool SwTextFrame::GetModelPositionForViewPoint(SwPosition* pPos, Point& rPoint,
                               SwCursorMoveState* pCMS, bool ) const
{
    const bool bChgFrame = !(pCMS && CursorMoveState::UpDown == pCMS->m_eState);
    return GetModelPositionForViewPoint_( pPos, rPoint, bChgFrame, pCMS );
}

/*
 * Layout-oriented cursor movement to the line start.
 */

bool SwTextFrame::LeftMargin(SwPaM *pPam) const
{
    assert(GetMergedPara() || &pPam->GetNode() == static_cast<SwContentNode const*>(GetDep()));

    SwTextFrame *pFrame = GetAdjFrameAtPos( const_cast<SwTextFrame*>(this), *pPam->GetPoint(),
                                     SwTextCursor::IsRightMargin() );
    pFrame->GetFormatted();
    TextFrameIndex nIndx;
    if ( pFrame->IsEmpty() )
        nIndx = TextFrameIndex(0);
    else
    {
        SwTextSizeInfo aInf( pFrame );
        SwTextCursor  aLine( pFrame, &aInf );

        aLine.CharCursorToLine(pFrame->MapModelToViewPos(*pPam->GetPoint()));
        nIndx = aLine.GetStart();
        if( pFrame->GetOffset() && !pFrame->IsFollow() && !aLine.GetPrev() )
        {
            sw_ChangeOffset(pFrame, TextFrameIndex(0));
            nIndx = TextFrameIndex(0);
        }
    }
    *pPam->GetPoint() = pFrame->MapViewToModelPos(nIndx);
    SwTextCursor::SetRightMargin( false );
    return true;
}

/*
 * To the line end: That's the position before the last char of the line.
 * Exception: In the last line, it should be able to place the cursor after
 * the last char in order to append text.
 */

bool SwTextFrame::RightMargin(SwPaM *pPam, bool bAPI) const
{
    assert(GetMergedPara() || &pPam->GetNode() == static_cast<SwContentNode const*>(GetDep()));

    SwTextFrame *pFrame = GetAdjFrameAtPos( const_cast<SwTextFrame*>(this), *pPam->GetPoint(),
                                     SwTextCursor::IsRightMargin() );
    pFrame->GetFormatted();
    TextFrameIndex nRightMargin(0);
    if (!IsEmpty())
    {
        SwTextSizeInfo aInf( pFrame );
        SwTextCursor  aLine( pFrame, &aInf );

        aLine.CharCursorToLine(MapModelToViewPos(*pPam->GetPoint()));
        nRightMargin = aLine.GetStart() + aLine.GetCurr()->GetLen();

        // We skip hard line breaks
        if( aLine.GetCurr()->GetLen() &&
            CH_BREAK == aInf.GetText()[sal_Int32(nRightMargin) - 1])
            --nRightMargin;
        else if( !bAPI && (aLine.GetNext() || pFrame->GetFollow()) )
        {
            while( nRightMargin > aLine.GetStart() &&
                ' ' == aInf.GetText()[sal_Int32(nRightMargin) - 1])
                --nRightMargin;
        }
    }
    *pPam->GetPoint() = pFrame->MapViewToModelPos(nRightMargin);
    SwTextCursor::SetRightMargin( !bAPI );
    return true;
}

// The following two methods try to put the Cursor into the next/successive
// line. If we do not have a preceding/successive line we forward the call
// to the base class.
// The Cursor's horizontal justification is done afterwards by the CursorShell.

namespace {

class SwSetToRightMargin
{
    bool bRight;
public:
    SwSetToRightMargin() : bRight( false ) { }
    ~SwSetToRightMargin() { SwTextCursor::SetRightMargin( bRight ); }
    void SetRight( const bool bNew ) { bRight = bNew; }
};

}

bool SwTextFrame::UnitUp_( SwPaM *pPam, const SwTwips nOffset,
                        bool bSetInReadOnly ) const
{
    // Set the RightMargin if needed
    SwSetToRightMargin aSet;

    if( IsInTab() &&
        pPam->GetNode().StartOfSectionNode() !=
        pPam->GetNode( false ).StartOfSectionNode() )
    {
        // If the PaM is located within different boxes, we have a table selection,
        // which is handled by the base class.
        return SwContentFrame::UnitUp( pPam, nOffset, bSetInReadOnly );
    }

    const_cast<SwTextFrame*>(this)->GetFormatted();
    const TextFrameIndex nPos = MapModelToViewPos(*pPam->GetPoint());
    SwRect aCharBox;

    if( !IsEmpty() && !IsHiddenNow() )
    {
        TextFrameIndex nFormat(COMPLETE_STRING);
        do
        {
            if (nFormat != TextFrameIndex(COMPLETE_STRING) && !IsFollow())
                sw_ChangeOffset( const_cast<SwTextFrame*>(this), nFormat );

            SwTextSizeInfo aInf( const_cast<SwTextFrame*>(this) );
            SwTextCursor  aLine( const_cast<SwTextFrame*>(this), &aInf );

            // Optimize away flys with no flow and IsDummy()
            if( nPos )
                aLine.CharCursorToLine( nPos );
            else
                aLine.Top();

            const SwLineLayout *pPrevLine = aLine.GetPrevLine();
            const TextFrameIndex nStart = aLine.GetStart();
            aLine.GetCharRect( &aCharBox, nPos );

            bool bSecondOfDouble = ( aInf.IsMulti() && ! aInf.IsFirstMulti() );
            bool bPrevLine = ( pPrevLine && pPrevLine != aLine.GetCurr() );

            if( !pPrevLine && !bSecondOfDouble && GetOffset() && !IsFollow() )
            {
                nFormat = GetOffset();
                TextFrameIndex nDiff = aLine.GetLength();
                if( !nDiff )
                    nDiff = TextFrameIndex(MIN_OFFSET_STEP);
                if( nFormat > nDiff )
                    nFormat = nFormat - nDiff;
                else
                    nFormat = TextFrameIndex(0);
                continue;
            }

            // We select the target line for the cursor, in case we are in a
            // double line portion, prev line = curr line
            if( bPrevLine && !bSecondOfDouble )
            {
                aLine.PrevLine();
                while ( aLine.GetStart() == nStart &&
                        nullptr != ( pPrevLine = aLine.GetPrevLine() ) &&
                        pPrevLine != aLine.GetCurr() )
                    aLine.PrevLine();
            }

            if ( bPrevLine || bSecondOfDouble )
            {
                aCharBox.Width( aCharBox.SSize().Width() / 2 );
                aCharBox.Pos().setX( aCharBox.Pos().X() - 150 );

                // See comment in SwTextFrame::GetModelPositionForViewPoint()
#if OSL_DEBUG_LEVEL > 0
                const sal_uLong nOldNode = pPam->GetPoint()->nNode.GetIndex();
#endif
                // The node should not be changed
                TextFrameIndex nTmpOfst = aLine.GetModelPositionForViewPoint(pPam->GetPoint(),
                                                         aCharBox.Pos(), false );
#if OSL_DEBUG_LEVEL > 0
                OSL_ENSURE( nOldNode == pPam->GetPoint()->nNode.GetIndex(),
                        "SwTextFrame::UnitUp: illegal node change" );
#endif

                // We make sure that we move up.
                if( nTmpOfst >= nStart && nStart && !bSecondOfDouble )
                {
                    nTmpOfst = nStart;
                    aSet.SetRight( true );
                }
                *pPam->GetPoint() = MapViewToModelPos(nTmpOfst);
                return true;
            }

            if ( IsFollow() )
            {
                aLine.GetCharRect( &aCharBox, nPos );
                aCharBox.Width( aCharBox.SSize().Width() / 2 );
            }
            break;
        } while ( true );
    }
    /* If 'this' is a follow and a prev failed, we need to go to the
     * last line of the master, which is us.
     * Or: If we are a follow with follow, we need to get the master.
     */
    if ( IsFollow() )
    {
        const SwTextFrame *pTmpPrev = FindMaster();
        TextFrameIndex nOffs = GetOffset();
        if( pTmpPrev )
        {
            SwViewShell *pSh = getRootFrame()->GetCurrShell();
            const bool bProtectedAllowed = pSh && pSh->GetViewOptions()->IsCursorInProtectedArea();
            const SwTextFrame *pPrevPrev = pTmpPrev;
            // We skip protected frames and frames without content here
            while( pPrevPrev && ( pPrevPrev->GetOffset() == nOffs ||
                   ( !bProtectedAllowed && pPrevPrev->IsProtected() ) ) )
            {
                pTmpPrev = pPrevPrev;
                nOffs = pTmpPrev->GetOffset();
                if ( pPrevPrev->IsFollow() )
                    pPrevPrev = pTmpPrev->FindMaster();
                else
                    pPrevPrev = nullptr;
            }
            if ( !pPrevPrev )
                return pTmpPrev->SwContentFrame::UnitUp( pPam, nOffset, bSetInReadOnly );
            aCharBox.Pos().setY( pPrevPrev->getFrameArea().Bottom() - 1 );
            return pPrevPrev->GetKeyCursorOfst( pPam->GetPoint(), aCharBox.Pos() );
        }
    }
    return SwContentFrame::UnitUp( pPam, nOffset, bSetInReadOnly );
}

// Used for Bidi. nPos is the logical position in the string, bLeft indicates
// if left arrow or right arrow was pressed. The return values are:
// nPos: the new visual position
// bLeft: whether the break iterator has to add or subtract from the
//        current position
static void lcl_VisualMoveRecursion(const SwLineLayout& rCurrLine, TextFrameIndex nIdx,
                              TextFrameIndex & nPos, bool& bRight,
                              sal_uInt8& nCursorLevel, sal_uInt8 nDefaultDir )
{
    const SwLinePortion* pPor = rCurrLine.GetFirstPortion();
    const SwLinePortion* pLast = nullptr;

    // What's the current portion?
    while ( pPor && nIdx + pPor->GetLen() <= nPos )
    {
        nIdx = nIdx + pPor->GetLen();
        pLast = pPor;
        pPor = pPor->GetNextPortion();
    }

    if ( bRight )
    {
        bool bRecurse = pPor && pPor->IsMultiPortion() &&
                           static_cast<const SwMultiPortion*>(pPor)->IsBidi();

        // 1. special case: at beginning of bidi portion
        if ( bRecurse && nIdx == nPos )
        {
            nPos = nPos + pPor->GetLen();

            // leave bidi portion
            if ( nCursorLevel != nDefaultDir )
            {
                bRecurse = false;
            }
            else
                // special case:
                // buffer: abcXYZ123 in LTR paragraph
                // view:   abc123ZYX
                // cursor is between c and X in the buffer and cursor level = 0
                nCursorLevel++;
        }

        // 2. special case: at beginning of portion after bidi portion
        else if ( pLast && pLast->IsMultiPortion() &&
                 static_cast<const SwMultiPortion*>(pLast)->IsBidi() && nIdx == nPos )
        {
            // enter bidi portion
            if ( nCursorLevel != nDefaultDir )
            {
                bRecurse = true;
                nIdx = nIdx - pLast->GetLen();
                pPor = pLast;
            }
        }

        // Recursion
        if ( bRecurse )
        {
            const SwLineLayout& rLine = static_cast<const SwMultiPortion*>(pPor)->GetRoot();
            TextFrameIndex nTmpPos = nPos - nIdx;
            bool bTmpForward = ! bRight;
            sal_uInt8 nTmpCursorLevel = nCursorLevel;
            lcl_VisualMoveRecursion(rLine, TextFrameIndex(0), nTmpPos, bTmpForward,
                                     nTmpCursorLevel, nDefaultDir + 1 );

            nPos = nTmpPos + nIdx;
            bRight = bTmpForward;
            nCursorLevel = nTmpCursorLevel;
        }

        // go forward
        else
        {
            bRight = true;
            nCursorLevel = nDefaultDir;
        }

    }
    else
    {
        bool bRecurse = pPor && pPor->IsMultiPortion() && static_cast<const SwMultiPortion*>(pPor)->IsBidi();

        // 1. special case: at beginning of bidi portion
        if ( bRecurse && nIdx == nPos )
        {
            // leave bidi portion
            if ( nCursorLevel == nDefaultDir )
            {
                bRecurse = false;
            }
        }

        // 2. special case: at beginning of portion after bidi portion
        else if ( pLast && pLast->IsMultiPortion() &&
                 static_cast<const SwMultiPortion*>(pLast)->IsBidi() && nIdx == nPos )
        {
            nPos = nPos - pLast->GetLen();

            // enter bidi portion
            if ( nCursorLevel % 2 == nDefaultDir % 2 )
            {
                bRecurse = true;
                nIdx = nIdx - pLast->GetLen();
                pPor = pLast;

                // special case:
                // buffer: abcXYZ123 in LTR paragraph
                // view:   abc123ZYX
                // cursor is behind 3 in the buffer and cursor level = 2
                if ( nDefaultDir + 2 == nCursorLevel )
                    nPos = nPos + pLast->GetLen();
            }
        }

        // go forward
        if ( bRecurse )
        {
            const SwLineLayout& rLine = static_cast<const SwMultiPortion*>(pPor)->GetRoot();
            TextFrameIndex nTmpPos = nPos - nIdx;
            bool bTmpForward = ! bRight;
            sal_uInt8 nTmpCursorLevel = nCursorLevel;
            lcl_VisualMoveRecursion(rLine, TextFrameIndex(0), nTmpPos, bTmpForward,
                                     nTmpCursorLevel, nDefaultDir + 1 );

            // special case:
            // buffer: abcXYZ123 in LTR paragraph
            // view:   abc123ZYX
            // cursor is between Z and 1 in the buffer and cursor level = 2
            if ( nTmpPos == pPor->GetLen() && nTmpCursorLevel == nDefaultDir + 1 )
            {
                nTmpPos = nTmpPos - pPor->GetLen();
                nTmpCursorLevel = nDefaultDir;
                bTmpForward = ! bTmpForward;
            }

            nPos = nTmpPos + nIdx;
            bRight = bTmpForward;
            nCursorLevel = nTmpCursorLevel;
        }

        // go backward
        else
        {
            bRight = false;
            nCursorLevel = nDefaultDir;
        }
    }
}

void SwTextFrame::PrepareVisualMove(TextFrameIndex & nPos, sal_uInt8& nCursorLevel,
                                  bool& bForward, bool bInsertCursor )
{
    if( IsEmpty() || IsHiddenNow() )
        return;

    GetFormatted();

    SwTextSizeInfo aInf(this);
    SwTextCursor  aLine(this, &aInf);

    if( nPos )
        aLine.CharCursorToLine( nPos );
    else
        aLine.Top();

    const SwLineLayout* pLine = aLine.GetCurr();
    const TextFrameIndex nStt = aLine.GetStart();
    const TextFrameIndex nLen = pLine->GetLen();

    // We have to distinguish between an insert and overwrite cursor:
    // The insert cursor position depends on the cursor level:
    // buffer:  abcXYZdef in LTR paragraph
    // display: abcZYXdef
    // If cursor is between c and X in the buffer and cursor level is 0,
    // the cursor blinks between c and Z and -> sets the cursor between Z and Y.
    // If the cursor level is 1, the cursor blinks between X and d and
    // -> sets the cursor between d and e.
    // The overwrite cursor simply travels to the next visual character.
    if ( bInsertCursor )
    {
        lcl_VisualMoveRecursion( *pLine, nStt, nPos, bForward,
                                 nCursorLevel, IsRightToLeft() ? 1 : 0 );
        return;
    }

    const sal_uInt8 nDefaultDir = static_cast<sal_uInt8>(IsRightToLeft() ? UBIDI_RTL : UBIDI_LTR);
    const bool bVisualRight = ( nDefaultDir == UBIDI_LTR && bForward ) ||
                                  ( nDefaultDir == UBIDI_RTL && ! bForward );

    // Bidi functions from icu 2.0

    const sal_Unicode* pLineString = GetText().getStr();

    UErrorCode nError = U_ZERO_ERROR;
    UBiDi* pBidi = ubidi_openSized( sal_Int32(nLen), 0, &nError );
    ubidi_setPara( pBidi, reinterpret_cast<const UChar *>(pLineString),
                    sal_Int32(nLen), nDefaultDir, nullptr, &nError );

    TextFrameIndex nTmpPos(0);
    bool bOutOfBounds = false;

    if ( nPos < nStt + nLen )
    {
        nTmpPos = TextFrameIndex(ubidi_getVisualIndex( pBidi, sal_Int32(nPos), &nError ));

        // visual indices are always LTR aligned
        if ( bVisualRight )
        {
            if (nTmpPos + TextFrameIndex(1) < nStt + nLen)
                ++nTmpPos;
            else
            {
                nPos = nDefaultDir == UBIDI_RTL ? TextFrameIndex(0) : nStt + nLen;
                bOutOfBounds = true;
            }
        }
        else
        {
            if ( nTmpPos )
                --nTmpPos;
            else
            {
                nPos = nDefaultDir == UBIDI_RTL ? nStt + nLen : TextFrameIndex(0);
                bOutOfBounds = true;
            }
        }
    }
    else
    {
        nTmpPos = nDefaultDir == UBIDI_LTR ? nPos - TextFrameIndex(1) : TextFrameIndex(0);
    }

    if ( ! bOutOfBounds )
    {
        nPos = TextFrameIndex(ubidi_getLogicalIndex( pBidi, sal_Int32(nTmpPos), &nError ));

        if ( bForward )
        {
            if ( nPos )
                --nPos;
            else
            {
                ++nPos;
                bForward = ! bForward;
            }
        }
        else
            ++nPos;
    }

    ubidi_close( pBidi );
}

bool SwTextFrame::UnitDown_(SwPaM *pPam, const SwTwips nOffset,
                         bool bSetInReadOnly ) const
{

    if ( IsInTab() &&
        pPam->GetNode().StartOfSectionNode() !=
        pPam->GetNode( false ).StartOfSectionNode() )
    {
        // If the PaM is located within different boxes, we have a table selection,
        // which is handled by the base class.
        return SwContentFrame::UnitDown( pPam, nOffset, bSetInReadOnly );
    }
    const_cast<SwTextFrame*>(this)->GetFormatted();
    const TextFrameIndex nPos = MapModelToViewPos(*pPam->GetPoint());
    SwRect aCharBox;
    const SwContentFrame *pTmpFollow = nullptr;

    if ( IsVertical() )
        const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();

    if ( !IsEmpty() && !IsHiddenNow() )
    {
        TextFrameIndex nFormat(COMPLETE_STRING);
        do
        {
            if (nFormat != TextFrameIndex(COMPLETE_STRING) && !IsFollow() &&
                !sw_ChangeOffset( const_cast<SwTextFrame*>(this), nFormat ) )
                break;

            SwTextSizeInfo aInf( const_cast<SwTextFrame*>(this) );
            SwTextCursor  aLine( const_cast<SwTextFrame*>(this), &aInf );
            nFormat = aLine.GetEnd();

            aLine.CharCursorToLine( nPos );

            const SwLineLayout* pNextLine = aLine.GetNextLine();
            const TextFrameIndex nStart = aLine.GetStart();
            aLine.GetCharRect( &aCharBox, nPos );

            bool bFirstOfDouble = ( aInf.IsMulti() && aInf.IsFirstMulti() );

            if( pNextLine || bFirstOfDouble )
            {
                aCharBox.Width( aCharBox.SSize().Width() / 2 );
#if OSL_DEBUG_LEVEL > 0
                // See comment in SwTextFrame::GetModelPositionForViewPoint()
                const sal_uLong nOldNode = pPam->GetPoint()->nNode.GetIndex();
#endif
                if ( pNextLine && ! bFirstOfDouble )
                    aLine.NextLine();

                TextFrameIndex nTmpOfst = aLine.GetModelPositionForViewPoint( pPam->GetPoint(),
                                 aCharBox.Pos(), false );
#if OSL_DEBUG_LEVEL > 0
                OSL_ENSURE( nOldNode == pPam->GetPoint()->nNode.GetIndex(),
                    "SwTextFrame::UnitDown: illegal node change" );
#endif

                // We make sure that we move down.
                if( nTmpOfst <= nStart && ! bFirstOfDouble )
                    nTmpOfst = nStart + TextFrameIndex(1);
                *pPam->GetPoint() = MapViewToModelPos(nTmpOfst);

                if ( IsVertical() )
                    const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();

                return true;
            }
            pTmpFollow = GetFollow();
            if( nullptr != pTmpFollow )
            {   // Skip protected follows
                const SwContentFrame* pTmp = pTmpFollow;
                SwViewShell *pSh = getRootFrame()->GetCurrShell();
                if( !pSh || !pSh->GetViewOptions()->IsCursorInProtectedArea() )
                {
                    while( pTmpFollow && pTmpFollow->IsProtected() )
                    {
                        pTmp = pTmpFollow;
                        pTmpFollow = pTmpFollow->GetFollow();
                    }
                }
                if( !pTmpFollow ) // Only protected ones left
                {
                    if ( IsVertical() )
                        const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();
                    return pTmp->SwContentFrame::UnitDown( pPam, nOffset, bSetInReadOnly );
                }

                aLine.GetCharRect( &aCharBox, nPos );
                aCharBox.Width( aCharBox.SSize().Width() / 2 );
            }
            else if( !IsFollow() )
            {
                TextFrameIndex nTmpLen(aInf.GetText().getLength());
                if( aLine.GetEnd() < nTmpLen )
                {
                    if( nFormat <= GetOffset() )
                    {
                        nFormat = std::min(GetOffset() + TextFrameIndex(MIN_OFFSET_STEP),
                                       nTmpLen );
                        if( nFormat <= GetOffset() )
                            break;
                    }
                    continue;
                }
            }
            break;
        } while( true );
    }
    else
        pTmpFollow = GetFollow();

    if ( IsVertical() )
        const_cast<SwTextFrame*>(this)->SwapWidthAndHeight();

    // We take a shortcut for follows
    if( pTmpFollow )
    {
        aCharBox.Pos().setY( pTmpFollow->getFrameArea().Top() + 1 );
        return static_cast<const SwTextFrame*>(pTmpFollow)->GetKeyCursorOfst( pPam->GetPoint(),
                                                     aCharBox.Pos() );
    }
    return SwContentFrame::UnitDown( pPam, nOffset, bSetInReadOnly );
}

bool SwTextFrame::UnitUp(SwPaM *pPam, const SwTwips nOffset,
                      bool bSetInReadOnly ) const
{
    /* We call ContentNode::GertFrame() in CursorSh::Up().
     * This _always returns the master.
     * In order to not mess with cursor travelling, we correct here
     * in SwTextFrame.
     * We calculate UnitUp for pFrame. pFrame is either a master (= this) or a
     * follow (!= this).
     */
    const SwTextFrame *pFrame = GetAdjFrameAtPos( const_cast<SwTextFrame*>(this), *(pPam->GetPoint()),
                                           SwTextCursor::IsRightMargin() );
    const bool bRet = pFrame->UnitUp_( pPam, nOffset, bSetInReadOnly );

    // No SwTextCursor::SetRightMargin( false );
    // Instead we have a SwSetToRightMargin in UnitUp_
    return bRet;
}

bool SwTextFrame::UnitDown(SwPaM *pPam, const SwTwips nOffset,
                        bool bSetInReadOnly ) const
{
    const SwTextFrame *pFrame = GetAdjFrameAtPos(const_cast<SwTextFrame*>(this), *(pPam->GetPoint()),
                                           SwTextCursor::IsRightMargin() );
    const bool bRet = pFrame->UnitDown_( pPam, nOffset, bSetInReadOnly );
    SwTextCursor::SetRightMargin( false );
    return bRet;
}

void SwTextFrame::FillCursorPos( SwFillData& rFill ) const
{
    if( !rFill.bColumn && GetUpper()->IsColBodyFrame() ) // ColumnFrames now with BodyFrame
    {
        const SwColumnFrame* pTmp =
            static_cast<const SwColumnFrame*>(GetUpper()->GetUpper()->GetUpper()->Lower()); // The 1st column
        // The first SwFrame in BodyFrame of the first column
        const SwFrame* pFrame = static_cast<const SwLayoutFrame*>(pTmp->Lower())->Lower();
        sal_uInt16 nNextCol = 0;
        // In which column do we end up in?
        while( rFill.X() > pTmp->getFrameArea().Right() && pTmp->GetNext() )
        {
            pTmp = static_cast<const SwColumnFrame*>(pTmp->GetNext());
            if( static_cast<const SwLayoutFrame*>(pTmp->Lower())->Lower() ) // ColumnFrames now with BodyFrame
            {
                pFrame = static_cast<const SwLayoutFrame*>(pTmp->Lower())->Lower();
                nNextCol = 0;
            }
            else
                ++nNextCol; // Empty columns require column brakes
        }
        if( pTmp != GetUpper()->GetUpper() ) // Did we end up in another column?
        {
            if( !pFrame )
                return;
            if( nNextCol )
            {
                while( pFrame->GetNext() )
                    pFrame = pFrame->GetNext();
            }
            else
            {
                while( pFrame->GetNext() && pFrame->getFrameArea().Bottom() < rFill.Y() )
                    pFrame = pFrame->GetNext();
            }
            // No filling, if the last frame in the targeted column does
            // not contain a paragraph, but e.g. a table
            if( pFrame->IsTextFrame() )
            {
                rFill.Fill().nColumnCnt = nNextCol;
                rFill.bColumn = true;
                if( rFill.pPos )
                {
                    SwTextFrame const*const pTextFrame(static_cast<const SwTextFrame*>(pFrame));
                    *rFill.pPos = pTextFrame->MapViewToModelPos(
                            TextFrameIndex(pTextFrame->GetText().getLength()));
                }
                if( nNextCol )
                {
                    rFill.aFrame = pTmp->getFramePrintArea();
                    rFill.aFrame += pTmp->getFrameArea().Pos();
                }
                else
                    rFill.aFrame = pFrame->getFrameArea();
                static_cast<const SwTextFrame*>(pFrame)->FillCursorPos( rFill );
            }
            return;
        }
    }
    std::unique_ptr<SwFont> pFnt;
    SwTextFormatColl* pColl = GetTextNodeForParaProps()->GetTextColl();
    SwTwips nFirst = GetTextNodeForParaProps()->GetSwAttrSet().GetULSpace().GetLower();
    SwTwips nDiff = rFill.Y() - getFrameArea().Bottom();
    if( nDiff < nFirst )
        nDiff = -1;
    else
        pColl = &pColl->GetNextTextFormatColl();
    SwAttrSet aSet(const_cast<SwDoc&>(GetDoc()).GetAttrPool(), aTextFormatCollSetRange );
    const SwAttrSet* pSet = &pColl->GetAttrSet();
    SwViewShell *pSh = getRootFrame()->GetCurrShell();
    if (GetTextNodeForParaProps()->HasSwAttrSet())
    {
        // sw_redlinehide: pSet is mostly used for para props, but there are
        // accesses to char props via pFnt - why does it use only the node's
        // props for this, and not hints?
        aSet.Put( *GetTextNodeForParaProps()->GetpSwAttrSet() );
        aSet.SetParent( pSet );
        pSet = &aSet;
        pFnt.reset(new SwFont( pSet, &GetDoc().getIDocumentSettingAccess() ));
    }
    else
    {
        SwFontAccess aFontAccess( pColl, pSh );
        pFnt.reset(new SwFont( aFontAccess.Get()->GetFont() ));
        pFnt->CheckFontCacheId( pSh, pFnt->GetActual() );
    }
    OutputDevice* pOut = pSh->GetOut();
    if( !pSh->GetViewOptions()->getBrowseMode() || pSh->GetViewOptions()->IsPrtFormat() )
        pOut = GetDoc().getIDocumentDeviceAccess().getReferenceDevice( true );

    pFnt->SetFntChg( true );
    pFnt->ChgPhysFnt( pSh, *pOut );

    SwTwips nLineHeight = pFnt->GetHeight( pSh, *pOut );

    bool bFill = false;
    if( nLineHeight )
    {
        bFill = true;
        const SvxULSpaceItem &rUL = pSet->GetULSpace();
        SwTwips nDist = std::max( rUL.GetLower(), rUL.GetUpper() );
        if( rFill.Fill().nColumnCnt )
        {
            rFill.aFrame.Height( nLineHeight );
            nDiff = rFill.Y() - rFill.Bottom();
            nFirst = 0;
        }
        else if( nDist < nFirst )
            nFirst = nFirst - nDist;
        else
            nFirst = 0;
        nDist = std::max( nDist, GetLineSpace() );
        nDist += nLineHeight;
        nDiff -= nFirst;

        if( nDiff > 0 )
        {
            nDiff /= nDist;
            rFill.Fill().nParaCnt = static_cast<sal_uInt16>(nDiff + 1);
            rFill.nLineWidth = 0;
            rFill.bInner = false;
            rFill.bEmpty = true;
            rFill.SetOrient( text::HoriOrientation::LEFT );
        }
        else
            nDiff = -1;
        if( rFill.bInner )
            bFill = false;
        else
        {
            const SvxTabStopItem &rRuler = pSet->GetTabStops();
            const SvxLRSpaceItem &rLRSpace = pSet->GetLRSpace();

            SwRect &rRect = rFill.Fill().aCursor;
            rRect.Top( rFill.Bottom() + (nDiff+1) * nDist - nLineHeight );
            if( nFirst && nDiff > -1 )
                rRect.Top( rRect.Top() + nFirst );
            rRect.Height( nLineHeight );
            SwTwips nLeft = rFill.Left() + rLRSpace.GetLeft() +
                            GetTextNodeForParaProps()->GetLeftMarginWithNum();
            SwTwips nRight = rFill.Right() - rLRSpace.GetRight();
            SwTwips nCenter = ( nLeft + nRight ) / 2;
            rRect.Left( nLeft );
            if( SwFillMode::Margin == rFill.Mode() )
            {
                if( rFill.bEmpty )
                {
                    rFill.SetOrient( text::HoriOrientation::LEFT );
                    if( rFill.X() < nCenter )
                    {
                        if( rFill.X() > ( nLeft + 2 * nCenter ) / 3 )
                        {
                            rFill.SetOrient( text::HoriOrientation::CENTER );
                            rRect.Left( nCenter );
                        }
                    }
                    else if( rFill.X() > ( nRight + 2 * nCenter ) / 3 )
                    {
                        rFill.SetOrient( text::HoriOrientation::RIGHT );
                        rRect.Left( nRight );
                    }
                    else
                    {
                        rFill.SetOrient( text::HoriOrientation::CENTER );
                        rRect.Left( nCenter );
                    }
                }
                else
                    bFill = false;
            }
            else
            {
                SwTwips nSpace = 0;
                if( SwFillMode::Tab != rFill.Mode() )
                {
                    SwDrawTextInfo aDrawInf( pSh, *pOut, "  ", 0, 2 );
                    nSpace = pFnt->GetTextSize_( aDrawInf ).Width()/2;
                }
                if( rFill.X() >= nRight )
                {
                    if( SwFillMode::Indent != rFill.Mode() && ( rFill.bEmpty ||
                        rFill.X() > rFill.nLineWidth + FILL_MIN_DIST ) )
                    {
                        rFill.SetOrient( text::HoriOrientation::RIGHT );
                        rRect.Left( nRight );
                    }
                    else
                        bFill = false;
                }
                else if( SwFillMode::Indent == rFill.Mode() )
                {
                    SwTwips nIndent = rFill.X();
                    if( !rFill.bEmpty || nIndent > nRight )
                        bFill = false;
                    else
                    {
                        nIndent -= rFill.Left();
                        if( nIndent >= 0 && nSpace )
                        {
                            nIndent /= nSpace;
                            nIndent *= nSpace;
                            rFill.SetTab( sal_uInt16( nIndent ) );
                            rRect.Left( nIndent + rFill.Left() );
                        }
                        else
                            bFill = false;
                    }
                }
                else if( rFill.X() > nLeft )
                {
                    SwTwips nTextLeft = rFill.Left() + rLRSpace.GetTextLeft() +
                        GetTextNodeForParaProps()->GetLeftMarginWithNum(true);
                    rFill.nLineWidth += rFill.bFirstLine ? nLeft : nTextLeft;
                    SwTwips nLeftTab;
                    SwTwips nRightTab = nLeft;
                    sal_uInt16 nSpaceCnt = 0;
                    sal_uInt16 nSpaceOnlyCnt = 0;
                    sal_uInt16 nTabCnt = 0;
                    sal_uInt16 nIdx = 0;
                    do
                    {
                        nLeftTab = nRightTab;
                        if( nIdx < rRuler.Count() )
                        {
                            const SvxTabStop &rTabStop = rRuler.operator[](nIdx);
                            nRightTab = nTextLeft + rTabStop.GetTabPos();
                            if( nLeftTab < nTextLeft && nRightTab > nTextLeft )
                                nRightTab = nTextLeft;
                            else
                                ++nIdx;
                            if( nRightTab > rFill.nLineWidth )
                                ++nTabCnt;
                        }
                        else
                        {
                            const SvxTabStopItem& rTab =
                                pSet->GetPool()->GetDefaultItem( RES_PARATR_TABSTOP );
                            const SwTwips nDefTabDist = rTab[0].GetTabPos();
                            nRightTab = nLeftTab - nTextLeft;
                            nRightTab /= nDefTabDist;
                            nRightTab = nRightTab * nDefTabDist + nTextLeft;
                            while ( nRightTab <= nLeftTab )
                                nRightTab += nDefTabDist;
                            if( nRightTab > rFill.nLineWidth )
                                ++nTabCnt;
                            while ( nRightTab < rFill.X() )
                            {
                                nRightTab += nDefTabDist;
                                if( nRightTab > rFill.nLineWidth )
                                    ++nTabCnt;
                            }
                            if( nLeftTab < nRightTab - nDefTabDist )
                                nLeftTab = nRightTab - nDefTabDist;
                        }
                        if( nRightTab > nRight )
                            nRightTab = nRight;
                    }
                    while( rFill.X() > nRightTab );
                    --nTabCnt;
                    if( SwFillMode::TabSpace == rFill.Mode() )
                    {
                        if( nSpace > 0 )
                        {
                            if( !nTabCnt )
                                nLeftTab = rFill.nLineWidth;
                            while( nLeftTab < rFill.X() )
                            {
                                nLeftTab += nSpace;
                                ++nSpaceCnt;
                            }
                            if( nSpaceCnt )
                            {
                                nLeftTab -= nSpace;
                                --nSpaceCnt;
                            }
                            if( rFill.X() - nLeftTab > nRightTab - rFill.X() )
                            {
                                nSpaceCnt = 0;
                                ++nTabCnt;
                                rRect.Left( nRightTab );
                            }
                            else
                            {
                                if( rFill.X() - nLeftTab > nSpace/2 )
                                {
                                    ++nSpaceCnt;
                                    rRect.Left( nLeftTab + nSpace );
                                }
                                else
                                    rRect.Left( nLeftTab );
                            }
                        }
                        else if( rFill.X() - nLeftTab < nRightTab - rFill.X() )
                            rRect.Left( nLeftTab );
                        else
                        {
                            if( nRightTab >= nRight )
                            {
                                rFill.SetOrient( text::HoriOrientation::RIGHT );
                                rRect.Left( nRight );
                                nTabCnt = 0;
                                nSpaceCnt = 0;
                            }
                            else
                            {
                                rRect.Left( nRightTab );
                                ++nTabCnt;
                            }
                        }
                    }
                    else if( SwFillMode::Space == rFill.Mode() )
                    {
                        SwTwips nLeftSpace = nLeft;
                        while( nLeftSpace < rFill.X() )
                        {
                            nLeftSpace += nSpace;
                            ++nSpaceOnlyCnt;
                        }
                        rRect.Left( nLeftSpace );
                    }
                    else
                    {
                        if( rFill.X() - nLeftTab < nRightTab - rFill.X() )
                            rRect.Left( nLeftTab );
                        else
                        {
                            if( nRightTab >= nRight )
                            {
                                rFill.SetOrient( text::HoriOrientation::RIGHT );
                                rRect.Left( nRight );
                                nTabCnt = 0;
                                nSpaceCnt = 0;
                            }
                            else
                            {
                                rRect.Left( nRightTab );
                                ++nTabCnt;
                            }
                        }
                    }
                    rFill.SetTab( nTabCnt );
                    rFill.SetSpace( nSpaceCnt );
                    rFill.SetSpaceOnly( nSpaceOnlyCnt );
                    if( bFill )
                    {
                        if( std::abs( rFill.X() - nCenter ) <=
                            std::abs( rFill.X() - rRect.Left() ) )
                        {
                            rFill.SetOrient( text::HoriOrientation::CENTER );
                            rFill.SetTab( 0 );
                            rFill.SetSpace( 0 );
                            rFill.SetSpaceOnly( 0 );
                            rRect.Left( nCenter );
                        }
                        if( !rFill.bEmpty )
                            rFill.nLineWidth += FILL_MIN_DIST;
                        if( rRect.Left() < rFill.nLineWidth )
                            bFill = false;
                    }
                }
            }
            // Do we extend over the page's/column's/etc. lower edge?
            const SwFrame* pUp = GetUpper();
            if( pUp->IsInSct() )
            {
                if( pUp->IsSctFrame() )
                    pUp = pUp->GetUpper();
                else if( pUp->IsColBodyFrame() &&
                         pUp->GetUpper()->GetUpper()->IsSctFrame() )
                    pUp = pUp->GetUpper()->GetUpper()->GetUpper();
            }
            SwRectFnSet aRectFnSet(this);
            SwTwips nLimit = aRectFnSet.GetPrtBottom(*pUp);
            SwTwips nRectBottom = rRect.Bottom();
            if ( aRectFnSet.IsVert() )
                nRectBottom = SwitchHorizontalToVertical( nRectBottom );

            if( aRectFnSet.YDiff( nLimit, nRectBottom ) < 0 )
                bFill = false;
            else
                rRect.Width( 1 );
        }
    }
    const_cast<SwCursorMoveState*>(rFill.pCMS)->m_bFillRet = bFill;
}

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