summaryrefslogtreecommitdiff
path: root/chart2/source/view/axes/VCartesianAxis.cxx
blob: 7257a643260557b4a6b3bf6c3641ecec82f9dec6 (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
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
/* -*- 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 "VCartesianAxis.hxx"
#include <PlottingPositionHelper.hxx>
#include <ShapeFactory.hxx>
#include <PropertyMapper.hxx>
#include <NumberFormatterWrapper.hxx>
#include <LabelPositionHelper.hxx>
#include <TrueGuard.hxx>
#include <BaseGFXHelper.hxx>
#include <AxisHelper.hxx>
#include "Tickmarks_Equidistant.hxx"
#include <ExplicitCategoriesProvider.hxx>
#include <com/sun/star/chart2/AxisType.hpp>

#include <rtl/math.hxx>
#include <tools/diagnose_ex.h>
#include <tools/color.hxx>
#include <svx/unoshape.hxx>
#include <svx/unoshtxt.hxx>

#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/numeric/ftools.hxx>

#include <algorithm>
#include <memory>

using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::basegfx::B2DVector;
using ::basegfx::B2DPolygon;
using ::basegfx::B2DPolyPolygon;

namespace chart {

VCartesianAxis::VCartesianAxis( const AxisProperties& rAxisProperties
            , const Reference< util::XNumberFormatsSupplier >& xNumberFormatsSupplier
            , sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
            , PlottingPositionHelper* pPosHelper )//takes ownership
            : VAxisBase( nDimensionIndex, nDimensionCount, rAxisProperties, xNumberFormatsSupplier )
{
    if( pPosHelper )
        m_pPosHelper = pPosHelper;
    else
        m_pPosHelper = new PlottingPositionHelper();
}

VCartesianAxis::~VCartesianAxis()
{
    delete m_pPosHelper;
    m_pPosHelper = nullptr;
}

static void lcl_ResizeTextShapeToFitAvailableSpace( Reference< drawing::XShape > const & xShape2DText,
                                             const AxisLabelProperties& rAxisLabelProperties,
                                             const OUString& rLabel,
                                             const tNameSequence& rPropNames,
                                             const tAnySequence& rPropValues )
{
    uno::Reference< text::XTextRange > xTextRange( xShape2DText, uno::UNO_QUERY );

    if( !xTextRange.is() )
        return;

    const sal_Int32 nFullHeight = rAxisLabelProperties.m_aFontReferenceSize.Height;

    if( !nFullHeight || !rLabel.getLength() )
        return;

    sal_Int32 nMaxLabelsHeight = nFullHeight - rAxisLabelProperties.m_aMaximumSpaceForLabels.Height - rAxisLabelProperties.m_aMaximumSpaceForLabels.Y;
    const sal_Int32 nAvgCharWidth = xShape2DText->getSize().Width / rLabel.getLength();
    const sal_Int32 nTextSize = ShapeFactory::getSizeAfterRotation( xShape2DText,
                                            rAxisLabelProperties.fRotationAngleDegree ).Height;

    if( !nAvgCharWidth )
        return;

    const OUString sDots = "...";
    const sal_Int32 nCharsToRemove = ( nTextSize - nMaxLabelsHeight ) / nAvgCharWidth + 1;
    sal_Int32 nNewLen = rLabel.getLength() - nCharsToRemove - sDots.getLength();
    // Prevent from showing only dots
    if (nNewLen < 0)
        nNewLen = ( rLabel.getLength() >= sDots.getLength() ) ? sDots.getLength() : rLabel.getLength();

    bool bCrop = nCharsToRemove > 0;
    if( bCrop )
    {
        OUString aNewLabel = rLabel.copy( 0, nNewLen );
        if( nNewLen > sDots.getLength() )
            aNewLabel += sDots;
        xTextRange->setString( aNewLabel );

        uno::Reference< beans::XPropertySet > xProp( xTextRange, uno::UNO_QUERY );
        if( xProp.is() )
        {
            PropertyMapper::setMultiProperties( rPropNames, rPropValues, xProp );
        }
    }
}

static Reference< drawing::XShape > createSingleLabel(
            const Reference< lang::XMultiServiceFactory>& xShapeFactory
          , const Reference< drawing::XShapes >& xTarget
          , const awt::Point& rAnchorScreenPosition2D
          , const OUString& rLabel
          , const AxisLabelProperties& rAxisLabelProperties
          , const AxisProperties& rAxisProperties
          , const tNameSequence& rPropNames
          , const tAnySequence& rPropValues
          )
{
    if(rLabel.isEmpty())
        return nullptr;

    // #i78696# use mathematically correct rotation now
    const double fRotationAnglePi(-basegfx::deg2rad(rAxisLabelProperties.fRotationAngleDegree));
    uno::Any aATransformation = ShapeFactory::makeTransformation( rAnchorScreenPosition2D, fRotationAnglePi );
    OUString aLabel = ShapeFactory::getStackedString( rLabel, rAxisLabelProperties.bStackCharacters );

    Reference< drawing::XShape > xShape2DText = ShapeFactory::getOrCreateShapeFactory(xShapeFactory)
                    ->createText( xTarget, aLabel, rPropNames, rPropValues, aATransformation );

    if( rAxisProperties.m_bLimitSpaceForLabels )
        lcl_ResizeTextShapeToFitAvailableSpace(xShape2DText, rAxisLabelProperties, aLabel, rPropNames, rPropValues);

    LabelPositionHelper::correctPositionForRotation( xShape2DText
        , rAxisProperties.maLabelAlignment.meAlignment, rAxisLabelProperties.fRotationAngleDegree, rAxisProperties.m_bComplexCategories );

    return xShape2DText;
}

static bool lcl_doesShapeOverlapWithTickmark( const Reference< drawing::XShape >& xShape
                       , double fRotationAngleDegree
                       , const basegfx::B2DVector& rTickScreenPosition )
{
    if(!xShape.is())
        return false;

    ::basegfx::B2IRectangle aShapeRect = BaseGFXHelper::makeRectangle(xShape->getPosition(), ShapeFactory::getSizeAfterRotation( xShape, fRotationAngleDegree ));

    basegfx::B2IVector aPosition(
        static_cast<sal_Int32>( rTickScreenPosition.getX() )
        , static_cast<sal_Int32>( rTickScreenPosition.getY() ) );
    return aShapeRect.isInside(aPosition);
}

static void lcl_getRotatedPolygon( B2DPolygon &aPoly, const ::basegfx::B2DRectangle &aRect, const awt::Point &aPos, const double fRotationAngleDegree )
{
    aPoly = basegfx::utils::createPolygonFromRect( aRect );

    // For rotating the rectangle we use the opposite angle,
    // since `B2DHomMatrix` class used for
    // representing the transformation, performs rotations in the positive
    // direction (from the X axis to the Y axis). However since the coordinate
    // system used by the chart has the Y-axis pointing downward, a rotation in
    // the positive direction means a clockwise rotation. On the contrary text
    // labels are rotated counterclockwise.
    // The rotation is performed around the top-left vertex of the rectangle
    // which is then moved to its final position by using the top-left
    // vertex of the text label bounding box (aPos) as the translation vector.
    ::basegfx::B2DHomMatrix aMatrix;
    aMatrix.rotate(-basegfx::deg2rad(fRotationAngleDegree));
    aMatrix.translate( aPos.X, aPos.Y);
    aPoly.transform( aMatrix );
}

static bool doesOverlap( const Reference< drawing::XShape >& xShape1
                , const Reference< drawing::XShape >& xShape2
                , double fRotationAngleDegree )
{
    if( !xShape1.is() || !xShape2.is() )
        return false;

    ::basegfx::B2DRectangle aRect1( BaseGFXHelper::makeRectangle( awt::Point(0,0), xShape1->getSize()));
    ::basegfx::B2DRectangle aRect2( BaseGFXHelper::makeRectangle( awt::Point(0,0), xShape2->getSize()));

    B2DPolygon aPoly1;
    B2DPolygon aPoly2;
    lcl_getRotatedPolygon( aPoly1, aRect1, xShape1->getPosition(), fRotationAngleDegree );
    lcl_getRotatedPolygon( aPoly2, aRect2, xShape2->getPosition(), fRotationAngleDegree );

    B2DPolyPolygon aPolyPoly1, aPolyPoly2;
    aPolyPoly1.append( aPoly1 );
    aPolyPoly2.append( aPoly2 );
    B2DPolyPolygon overlapPoly = ::basegfx::utils::clipPolyPolygonOnPolyPolygon( aPolyPoly1, aPolyPoly2, true, false );

    return (overlapPoly.count() > 0);
}

static void removeShapesAtWrongRhythm( TickIter& rIter
                              , sal_Int32 nCorrectRhythm
                              , sal_Int32 nMaxTickToCheck
                              , const Reference< drawing::XShapes >& xTarget )
{
    sal_Int32 nTick = 0;
    for( TickInfo* pTickInfo = rIter.firstInfo()
        ; pTickInfo && nTick <= nMaxTickToCheck
        ; pTickInfo = rIter.nextInfo(), nTick++ )
    {
        //remove labels which does not fit into the rhythm
        if( nTick%nCorrectRhythm != 0)
        {
            if(pTickInfo->xTextShape.is())
            {
                xTarget->remove(pTickInfo->xTextShape);
                pTickInfo->xTextShape = nullptr;
            }
        }
    }
}

namespace {

/**
 * If the labels are staggered and bInnerLine is true we iterate through
 * only those labels that are closer to the diagram.
 *
 * If the labels are staggered and bInnerLine is false we iterate through
 * only those that are farther from the diagram.
 *
 * If the labels are not staggered we iterate through all labels.
 */
class LabelIterator : public TickIter
{
public:
    LabelIterator( TickInfoArrayType& rTickInfoVector
            , const AxisLabelStaggering eAxisLabelStaggering
            , bool bInnerLine );

    virtual TickInfo*   firstInfo() override;
    virtual TickInfo*   nextInfo() override;

private: //member
    PureTickIter m_aPureTickIter;
    const AxisLabelStaggering   m_eAxisLabelStaggering;
    bool m_bInnerLine;
};

}

LabelIterator::LabelIterator( TickInfoArrayType& rTickInfoVector
            , const AxisLabelStaggering eAxisLabelStaggering
            , bool bInnerLine )
            : m_aPureTickIter( rTickInfoVector )
            , m_eAxisLabelStaggering(eAxisLabelStaggering)
            , m_bInnerLine(bInnerLine)
{
}

TickInfo* LabelIterator::firstInfo()
{
    TickInfo* pTickInfo = m_aPureTickIter.firstInfo();
    while( pTickInfo && !pTickInfo->xTextShape.is() )
        pTickInfo = m_aPureTickIter.nextInfo();
    if(!pTickInfo)
        return nullptr;
    if( (m_eAxisLabelStaggering==AxisLabelStaggering::StaggerEven && m_bInnerLine)
        ||
        (m_eAxisLabelStaggering==AxisLabelStaggering::StaggerOdd && !m_bInnerLine)
        )
    {
        //skip first label
        do
            pTickInfo = m_aPureTickIter.nextInfo();
        while( pTickInfo && !pTickInfo->xTextShape.is() );
    }
    if(!pTickInfo)
        return nullptr;
    return pTickInfo;
}

TickInfo* LabelIterator::nextInfo()
{
    TickInfo* pTickInfo = nullptr;
    //get next label
    do
        pTickInfo = m_aPureTickIter.nextInfo();
    while( pTickInfo && !pTickInfo->xTextShape.is() );

    if(  m_eAxisLabelStaggering==AxisLabelStaggering::StaggerEven
      || m_eAxisLabelStaggering==AxisLabelStaggering::StaggerOdd )
    {
        //skip one label
        do
            pTickInfo = m_aPureTickIter.nextInfo();
        while( pTickInfo && !pTickInfo->xTextShape.is() );
    }
    return pTickInfo;
}

static B2DVector lcl_getLabelsDistance( TickIter& rIter, const B2DVector& rDistanceTickToText, double fRotationAngleDegree )
{
    //calculates the height or width of a line of labels
    //thus a following line of labels can be shifted for that distance

    B2DVector aRet(0,0);

    sal_Int32 nDistanceTickToText = static_cast<sal_Int32>( rDistanceTickToText.getLength() );
    if( nDistanceTickToText==0.0)
        return aRet;

    B2DVector aStaggerDirection(rDistanceTickToText);
    aStaggerDirection.normalize();

    sal_Int32 nDistance=0;
    Reference< drawing::XShape >  xShape2DText;
    for( TickInfo* pTickInfo = rIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = rIter.nextInfo() )
    {
        xShape2DText = pTickInfo->xTextShape;
        if( xShape2DText.is() )
        {
            awt::Size aSize = ShapeFactory::getSizeAfterRotation( xShape2DText, fRotationAngleDegree );
            if(fabs(aStaggerDirection.getX())>fabs(aStaggerDirection.getY()))
                nDistance = std::max(nDistance,aSize.Width);
            else
                nDistance = std::max(nDistance,aSize.Height);
        }
    }

    aRet = aStaggerDirection*nDistance;

    //add extra distance for vertical distance
    if(fabs(aStaggerDirection.getX())>fabs(aStaggerDirection.getY()))
        aRet += rDistanceTickToText;

    return aRet;
}

static void lcl_shiftLabels( TickIter& rIter, const B2DVector& rStaggerDistance )
{
    if(rStaggerDistance.getLength()==0.0)
        return;
    Reference< drawing::XShape >  xShape2DText;
    for( TickInfo* pTickInfo = rIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = rIter.nextInfo() )
    {
        xShape2DText = pTickInfo->xTextShape;
        if( xShape2DText.is() )
        {
            awt::Point aPos  = xShape2DText->getPosition();
            aPos.X += static_cast<sal_Int32>(rStaggerDistance.getX());
            aPos.Y += static_cast<sal_Int32>(rStaggerDistance.getY());
            xShape2DText->setPosition( aPos );
        }
    }
}

static bool lcl_hasWordBreak( const Reference<drawing::XShape>& xShape )
{
    if (!xShape.is())
        return false;

    SvxShape* pShape = comphelper::getUnoTunnelImplementation<SvxShape>(xShape);
    SvxShapeText* pShapeText = dynamic_cast<SvxShapeText*>(pShape);
    if (!pShapeText)
        return false;

    SvxTextEditSource* pTextEditSource = dynamic_cast<SvxTextEditSource*>(pShapeText->GetEditSource());
    if (!pTextEditSource)
        return false;

    pTextEditSource->UpdateOutliner();
    SvxTextForwarder* pTextForwarder = pTextEditSource->GetTextForwarder();
    if (!pTextForwarder)
        return false;

    sal_Int32 nParaCount = pTextForwarder->GetParagraphCount();
    for ( sal_Int32 nPara = 0; nPara < nParaCount; ++nPara )
    {
        sal_Int32 nLineCount = pTextForwarder->GetLineCount( nPara );
        for ( sal_Int32 nLine = 0; nLine < nLineCount; ++nLine )
        {
            sal_Int32 nLineStart = 0;
            sal_Int32 nLineEnd = 0;
            pTextForwarder->GetLineBoundaries( nLineStart, nLineEnd, nPara, nLine );
            assert(nLineStart >= 0);
            sal_Int32 nWordStart = 0;
            sal_Int32 nWordEnd = 0;
            if ( pTextForwarder->GetWordIndices( nPara, nLineStart, nWordStart, nWordEnd ) &&
                 ( nWordStart != nLineStart ) )
            {
                return true;
            }
        }
    }

    return false;
}

static OUString getTextLabelString(
    const FixedNumberFormatter& rFixedNumberFormatter, const uno::Sequence<OUString>* pCategories,
    const TickInfo* pTickInfo, bool bComplexCat, Color& rExtraColor, bool& rHasExtraColor )
{
    if (pCategories)
    {
        // This is a normal category axis.  Get the label string from the
        // label string array.
        sal_Int32 nIndex = static_cast<sal_Int32>(pTickInfo->getUnscaledTickValue()) - 1; //first category (index 0) matches with real number 1.0
        if( nIndex>=0 && nIndex<pCategories->getLength() )
            return (*pCategories)[nIndex];

        return OUString();
    }
    else if (bComplexCat)
    {
        // This is a complex category axis.  The label is stored in the tick.
        return pTickInfo->aText;
    }

    // This is a numeric axis.  Format the original tick value per number format.
    return rFixedNumberFormatter.getFormattedString(pTickInfo->getUnscaledTickValue(), rExtraColor, rHasExtraColor);
}

static void getAxisLabelProperties(
    tNameSequence& rPropNames, tAnySequence& rPropValues, const AxisProperties& rAxisProp,
    const AxisLabelProperties& rAxisLabelProp,
    sal_Int32 nLimitedSpaceForText, bool bLimitedHeight )
{
    Reference<beans::XPropertySet> xProps(rAxisProp.m_xAxisModel, uno::UNO_QUERY);

    PropertyMapper::getTextLabelMultiPropertyLists(
        xProps, rPropNames, rPropValues, false, nLimitedSpaceForText, bLimitedHeight, false);

    LabelPositionHelper::doDynamicFontResize(
        rPropValues, rPropNames, xProps, rAxisLabelProp.m_aFontReferenceSize);

    LabelPositionHelper::changeTextAdjustment(
        rPropValues, rPropNames, rAxisProp.maLabelAlignment.meAlignment);
}

namespace {

/**
 * Iterate through only 3 ticks including the one that has the longest text
 * length.  When the first tick has the longest text, it iterates through
 * the first 3 ticks.  Otherwise it iterates through 3 ticks such that the
 * 2nd tick is the one with the longest text.
 */
class MaxLabelTickIter : public TickIter
{
public:
    MaxLabelTickIter( TickInfoArrayType& rTickInfoVector, size_t nLongestLabelIndex );

    virtual TickInfo* firstInfo() override;
    virtual TickInfo* nextInfo() override;

private:
    TickInfoArrayType& m_rTickInfoVector;
    std::vector<size_t> m_aValidIndices;
    size_t m_nCurrentIndex;
};

}

MaxLabelTickIter::MaxLabelTickIter(
    TickInfoArrayType& rTickInfoVector, size_t nLongestLabelIndex ) :
    m_rTickInfoVector(rTickInfoVector), m_nCurrentIndex(0)
{
    assert(!rTickInfoVector.empty()); // should be checked by the caller.
    assert(nLongestLabelIndex < rTickInfoVector.size());

    size_t nMaxIndex = m_rTickInfoVector.size()-1;
    if (nLongestLabelIndex >= nMaxIndex-1)
        nLongestLabelIndex = 0;

    if (nLongestLabelIndex > 0)
        m_aValidIndices.push_back(nLongestLabelIndex-1);

    m_aValidIndices.push_back(nLongestLabelIndex);

    while (m_aValidIndices.size() < 3)
    {
        ++nLongestLabelIndex;
        if (nLongestLabelIndex > nMaxIndex)
            break;

        m_aValidIndices.push_back(nLongestLabelIndex);
    }
}

TickInfo* MaxLabelTickIter::firstInfo()
{
    m_nCurrentIndex = 0;
    if (m_nCurrentIndex < m_aValidIndices.size())
        return &m_rTickInfoVector[m_aValidIndices[m_nCurrentIndex]];
    return nullptr;
}

TickInfo* MaxLabelTickIter::nextInfo()
{
    m_nCurrentIndex++;
    if (m_nCurrentIndex < m_aValidIndices.size())
        return &m_rTickInfoVector[m_aValidIndices[m_nCurrentIndex]];
    return nullptr;
}

bool VCartesianAxis::isBreakOfLabelsAllowed(
    const AxisLabelProperties& rAxisLabelProperties, bool bIsHorizontalAxis, bool bIsVerticalAxis) const
{
    if( m_aTextLabels.getLength() > 100 )
        return false;
    if( !rAxisLabelProperties.bLineBreakAllowed )
        return false;
    if( rAxisLabelProperties.bStackCharacters )
        return false;
    //no break for value axis
    if( !m_bUseTextLabels )
        return false;
    if( !( rAxisLabelProperties.fRotationAngleDegree == 0.0 ||
           rAxisLabelProperties.fRotationAngleDegree == 90.0 ||
           rAxisLabelProperties.fRotationAngleDegree == 270.0 ) )
        return false;
    //no break for complex vertical category axis
    if( !m_aAxisProperties.m_bSwapXAndY )
        return bIsHorizontalAxis;
    else if( m_aAxisProperties.m_bSwapXAndY && !m_aAxisProperties.m_bComplexCategories )
        return bIsVerticalAxis;
    else
        return false;
}
namespace{

bool canAutoAdjustLabelPlacement(
    const AxisLabelProperties& rAxisLabelProperties, bool bIsHorizontalAxis, bool bIsVerticalAxis)
{
    // joined prerequisite checks for auto rotate and auto stagger
    if( rAxisLabelProperties.bOverlapAllowed )
        return false;
    if( rAxisLabelProperties.bLineBreakAllowed ) // auto line break may conflict with...
        return false;
    if( rAxisLabelProperties.fRotationAngleDegree != 0.0 )
        return false;
    // automatic adjusting labels only works for
    // horizontal axis with horizontal text
    // or vertical axis with vertical text
    if( bIsHorizontalAxis )
        return !rAxisLabelProperties.bStackCharacters;
    if( bIsVerticalAxis )
        return rAxisLabelProperties.bStackCharacters;
    return false;
}

bool isAutoStaggeringOfLabelsAllowed(
    const AxisLabelProperties& rAxisLabelProperties, bool bIsHorizontalAxis, bool bIsVerticalAxis )
{
    if( rAxisLabelProperties.eStaggering != AxisLabelStaggering::StaggerAuto )
        return false;
    return canAutoAdjustLabelPlacement(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis);
}

// make clear that we check for auto rotation prerequisites
const auto& isAutoRotatingOfLabelsAllowed = canAutoAdjustLabelPlacement;

} // namespace
void VCartesianAxis::createAllTickInfosFromComplexCategories( TickInfoArraysType& rAllTickInfos, bool bShiftedPosition )
{
    //no minor tickmarks will be generated!
    //order is: inner labels first , outer labels last (that is different to all other TickIter cases)
    if(!bShiftedPosition)
    {
        rAllTickInfos.clear();
        sal_Int32 nLevel=0;
        sal_Int32 nLevelCount = m_aAxisProperties.m_pExplicitCategoriesProvider->getCategoryLevelCount();
        for( ; nLevel<nLevelCount; nLevel++ )
        {
            TickInfoArrayType aTickInfoVector;
            const std::vector<ComplexCategory>* pComplexCategories =
                m_aAxisProperties.m_pExplicitCategoriesProvider->getCategoriesByLevel(nLevel);

            if (!pComplexCategories)
                continue;

            sal_Int32 nCatIndex = 0;

            for (auto const& complexCategory : *pComplexCategories)
            {
                TickInfo aTickInfo(nullptr);
                sal_Int32 nCount = complexCategory.Count;
                if( nCatIndex + 1.0 + nCount >= m_aScale.Maximum )
                {
                    nCount = static_cast<sal_Int32>(m_aScale.Maximum - 1.0 - nCatIndex);
                    if( nCount <= 0 )
                        nCount = 1;
                }
                aTickInfo.fScaledTickValue = nCatIndex + 1.0 + nCount/2.0;
                aTickInfo.nFactorForLimitedTextWidth = nCount;
                aTickInfo.aText = complexCategory.Text;
                aTickInfoVector.push_back(aTickInfo);
                nCatIndex += nCount;
                if( nCatIndex + 1.0 >= m_aScale.Maximum )
                    break;
            }
            rAllTickInfos.push_back(aTickInfoVector);
        }
    }
    else //bShiftedPosition==false
    {
        rAllTickInfos.clear();
        sal_Int32 nLevel=0;
        sal_Int32 nLevelCount = m_aAxisProperties.m_pExplicitCategoriesProvider->getCategoryLevelCount();
        for( ; nLevel<nLevelCount; nLevel++ )
        {
            TickInfoArrayType aTickInfoVector;
            const std::vector<ComplexCategory>* pComplexCategories =
                m_aAxisProperties.m_pExplicitCategoriesProvider->getCategoriesByLevel(nLevel);
            sal_Int32 nCatIndex = 0;
            if (pComplexCategories)
            {
                for (auto const& complexCategory : *pComplexCategories)
                {
                    TickInfo aTickInfo(nullptr);
                    aTickInfo.fScaledTickValue = nCatIndex + 1.0;
                    aTickInfoVector.push_back(aTickInfo);
                    nCatIndex += complexCategory.Count;
                    if( nCatIndex + 1.0 > m_aScale.Maximum )
                        break;
                }
            }

            //fill up with single ticks until maximum scale
            while( nCatIndex + 1.0 < m_aScale.Maximum )
            {
                TickInfo aTickInfo(nullptr);
                aTickInfo.fScaledTickValue = nCatIndex + 1.0;
                aTickInfoVector.push_back(aTickInfo);
                nCatIndex ++;
                if( nLevel>0 )
                    break;
            }
            //add an additional tick at the end
            {
                TickInfo aTickInfo(nullptr);
                aTickInfo.fScaledTickValue = m_aScale.Maximum;
                aTickInfoVector.push_back(aTickInfo);
            }
            rAllTickInfos.push_back(aTickInfoVector);
        }
    }
}

void VCartesianAxis::createAllTickInfos( TickInfoArraysType& rAllTickInfos )
{
    if( isComplexCategoryAxis() )
        createAllTickInfosFromComplexCategories( rAllTickInfos, false );
    else
        VAxisBase::createAllTickInfos(rAllTickInfos);
}

TickIter* VCartesianAxis::createLabelTickIterator( sal_Int32 nTextLevel )
{
    if( nTextLevel>=0 && nTextLevel < static_cast< sal_Int32 >(m_aAllTickInfos.size()) )
        return new PureTickIter( m_aAllTickInfos[nTextLevel] );
    return nullptr;
}

TickIter* VCartesianAxis::createMaximumLabelTickIterator( sal_Int32 nTextLevel )
{
    if( isComplexCategoryAxis() || isDateAxis() )
    {
        return createLabelTickIterator( nTextLevel ); //mmmm maybe todo: create less than all texts here
    }
    else
    {
        if(nTextLevel==0)
        {
            if( !m_aAllTickInfos.empty() )
            {
                size_t nLongestLabelIndex = m_bUseTextLabels ? getIndexOfLongestLabel(m_aTextLabels) : 0;
                if (nLongestLabelIndex >= m_aAllTickInfos[0].size())
                    return nullptr;

                return new MaxLabelTickIter( m_aAllTickInfos[0], nLongestLabelIndex );
            }
        }
    }
    return nullptr;
}

sal_Int32 VCartesianAxis::getTextLevelCount() const
{
    sal_Int32 nTextLevelCount = 1;
    if( isComplexCategoryAxis() )
        nTextLevelCount = m_aAxisProperties.m_pExplicitCategoriesProvider->getCategoryLevelCount();
    return nTextLevelCount;
}

bool VCartesianAxis::createTextShapes(
    const Reference<drawing::XShapes>& xTarget, TickIter& rTickIter,
    AxisLabelProperties& rAxisLabelProperties, TickFactory2D const * pTickFactory,
    sal_Int32 nScreenDistanceBetweenTicks )
{
    const bool bIsHorizontalAxis = pTickFactory->isHorizontalAxis();
    const bool bIsVerticalAxis = pTickFactory->isVerticalAxis();

    if (!isBreakOfLabelsAllowed(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis) &&
        !isAutoStaggeringOfLabelsAllowed(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis) &&
        !rAxisLabelProperties.isStaggered())
        return createTextShapesSimple(xTarget, rTickIter, rAxisLabelProperties, pTickFactory);

    FixedNumberFormatter aFixedNumberFormatter(
                m_xNumberFormatsSupplier, rAxisLabelProperties.nNumberFormatKey );

    bool bIsStaggered = rAxisLabelProperties.isStaggered();
    B2DVector aTextToTickDistance = pTickFactory->getDistanceAxisTickToText(m_aAxisProperties, true);
    sal_Int32 nLimitedSpaceForText = -1;

    if( isBreakOfLabelsAllowed( rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis ) )
    {
        nLimitedSpaceForText = nScreenDistanceBetweenTicks;
        if( bIsStaggered )
            nLimitedSpaceForText *= 2;

        if( nLimitedSpaceForText > 0 )
        { //reduce space for a small amount to have a visible distance between the labels:
            sal_Int32 nReduce = (nLimitedSpaceForText*5)/100;
            if(!nReduce)
                nReduce = 1;
            nLimitedSpaceForText -= nReduce;
        }

        // recalculate the nLimitedSpaceForText in case of 90 and 270 degree if the text break is true
        if ( rAxisLabelProperties.fRotationAngleDegree == 90.0 || rAxisLabelProperties.fRotationAngleDegree == 270.0 )
        {
            if ( rAxisLabelProperties.m_aFontReferenceSize.Height - rAxisLabelProperties.m_aMaximumSpaceForLabels.Height > 2 * rAxisLabelProperties.m_aMaximumSpaceForLabels.Y )
            {
                const sal_Int32 nFullHeight = rAxisLabelProperties.m_aFontReferenceSize.Height;
                sal_Int32 nMaxLabelsHeight = nFullHeight - ( rAxisLabelProperties.m_aMaximumSpaceForLabels.Height + rAxisLabelProperties.m_aMaximumSpaceForLabels.Y );
                nLimitedSpaceForText = nMaxLabelsHeight;
            }
            else
            {
                nLimitedSpaceForText = -1;
            }
        }

        // recalculate the nLimitedSpaceForText in case of vertical category axis if the text break is true
        if ( m_aAxisProperties.m_bSwapXAndY && bIsVerticalAxis && rAxisLabelProperties.fRotationAngleDegree == 0.0 )
        {
            nLimitedSpaceForText = rAxisLabelProperties.m_aMaximumSpaceForLabels.X;
        }
    }

    // Stores an array of text label strings in case of a normal
    // (non-complex) category axis.
    const uno::Sequence<OUString>* pCategories = nullptr;
    if( m_bUseTextLabels && !m_aAxisProperties.m_bComplexCategories )
        pCategories = &m_aTextLabels;

    bool bLimitedHeight;
    if( !m_aAxisProperties.m_bSwapXAndY )
        bLimitedHeight = fabs(aTextToTickDistance.getX()) > fabs(aTextToTickDistance.getY());
    else
        bLimitedHeight = fabs(aTextToTickDistance.getX()) < fabs(aTextToTickDistance.getY());
    //prepare properties for multipropertyset-interface of shape
    tNameSequence aPropNames;
    tAnySequence aPropValues;
    getAxisLabelProperties(aPropNames, aPropValues, m_aAxisProperties, rAxisLabelProperties, nLimitedSpaceForText, bLimitedHeight);

    uno::Any* pColorAny = PropertyMapper::getValuePointer(aPropValues,aPropNames,"CharColor");
    Color nColor = COL_AUTO;
    if(pColorAny)
        *pColorAny >>= nColor;

    uno::Any* pLimitedSpaceAny = PropertyMapper::getValuePointerForLimitedSpace(aPropValues,aPropNames,bLimitedHeight);

    const TickInfo* pPreviousVisibleTickInfo = nullptr;
    const TickInfo* pPREPreviousVisibleTickInfo = nullptr;
    sal_Int32 nTick = 0;
    for( TickInfo* pTickInfo = rTickIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = rTickIter.nextInfo(), nTick++ )
    {
        const TickInfo* pLastVisibleNeighbourTickInfo = bIsStaggered ?
                    pPREPreviousVisibleTickInfo : pPreviousVisibleTickInfo;

        //don't create labels which does not fit into the rhythm
        if( nTick%rAxisLabelProperties.nRhythm != 0 )
            continue;

        //don't create labels for invisible ticks
        if( !pTickInfo->bPaintIt )
            continue;

        if( pLastVisibleNeighbourTickInfo && !rAxisLabelProperties.bOverlapAllowed )
        {
            // Overlapping is not allowed.  If the label overlaps with its
            // neighbering label, try increasing the tick interval (or rhythm
            // as it's called) and start over.

            if( lcl_doesShapeOverlapWithTickmark( pLastVisibleNeighbourTickInfo->xTextShape
                       , rAxisLabelProperties.fRotationAngleDegree
                       , pTickInfo->aTickScreenPosition ) )
            {
                // This tick overlaps with its neighbor.  Try to stagger (if
                // auto staggering is allowed) to avoid overlapping.

                bool bOverlapsAfterAutoStagger = true;
                if( !bIsStaggered && isAutoStaggeringOfLabelsAllowed( rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis ) )
                {
                    bIsStaggered = true;
                    rAxisLabelProperties.eStaggering = AxisLabelStaggering::StaggerEven;
                    pLastVisibleNeighbourTickInfo = pPREPreviousVisibleTickInfo;
                    if( !pLastVisibleNeighbourTickInfo ||
                        !lcl_doesShapeOverlapWithTickmark( pLastVisibleNeighbourTickInfo->xTextShape
                                , rAxisLabelProperties.fRotationAngleDegree
                                , pTickInfo->aTickScreenPosition ) )
                        bOverlapsAfterAutoStagger = false;
                }

                if (bOverlapsAfterAutoStagger)
                {
                    // Still overlaps with its neighbor even after staggering.
                    // Increment the visible tick intervals (if that's
                    // allowed) and start over.

                    rAxisLabelProperties.nRhythm++;
                    removeShapesAtWrongRhythm( rTickIter, rAxisLabelProperties.nRhythm, nTick, xTarget );
                    return false;
                }
            }
        }

        bool bHasExtraColor=false;
        Color nExtraColor;

        OUString aLabel = getTextLabelString(
            aFixedNumberFormatter, pCategories, pTickInfo, isComplexCategoryAxis(),
            nExtraColor, bHasExtraColor);

        if(pColorAny)
            *pColorAny <<= bHasExtraColor?nExtraColor:nColor;
        if(pLimitedSpaceAny)
            *pLimitedSpaceAny <<= sal_Int32(nLimitedSpaceForText*pTickInfo->nFactorForLimitedTextWidth);

        B2DVector aTickScreenPos2D = pTickInfo->aTickScreenPosition;
        aTickScreenPos2D += aTextToTickDistance;
        awt::Point aAnchorScreenPosition2D(
            static_cast<sal_Int32>(aTickScreenPos2D.getX())
            ,static_cast<sal_Int32>(aTickScreenPos2D.getY()));

        //create single label
        if(!pTickInfo->xTextShape.is())
            pTickInfo->xTextShape = createSingleLabel( m_xShapeFactory, xTarget
                                    , aAnchorScreenPosition2D, aLabel
                                    , rAxisLabelProperties, m_aAxisProperties
                                    , aPropNames, aPropValues );
        if(!pTickInfo->xTextShape.is())
            continue;

        recordMaximumTextSize( pTickInfo->xTextShape, rAxisLabelProperties.fRotationAngleDegree );

        // Label has multiple lines and the words are broken
        if( nLimitedSpaceForText>0 && !rAxisLabelProperties.bOverlapAllowed
                && rAxisLabelProperties.fRotationAngleDegree == 0.0
                && lcl_hasWordBreak( pTickInfo->xTextShape ) )
        {
            // Label has multiple lines and belongs to a complex category
            // axis. Rotate 90 degrees to try to avoid overlaps.
            if ( m_aAxisProperties.m_bComplexCategories )
            {
                rAxisLabelProperties.fRotationAngleDegree = 90;
            }
            rAxisLabelProperties.bLineBreakAllowed = false;
            m_aAxisLabelProperties.fRotationAngleDegree = rAxisLabelProperties.fRotationAngleDegree;
            removeTextShapesFromTicks();
            return false;
        }

        //if NO OVERLAP -> remove overlapping shapes
        if( pLastVisibleNeighbourTickInfo && !rAxisLabelProperties.bOverlapAllowed )
        {
            // Check if the label still overlaps with its neighber.
            if( doesOverlap( pLastVisibleNeighbourTickInfo->xTextShape, pTickInfo->xTextShape, rAxisLabelProperties.fRotationAngleDegree ) )
            {
                // It overlaps.  Check if staggering helps.
                bool bOverlapsAfterAutoStagger = true;
                if( !bIsStaggered && isAutoStaggeringOfLabelsAllowed( rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis ) )
                {
                    // Compatibility option: starting from LibreOffice 5.1 the rotated
                    // layout is preferred to staggering for axis labels.
                    if( !isAutoRotatingOfLabelsAllowed(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis)
                        || m_aAxisProperties.m_bTryStaggeringFirst )
                    {
                        bIsStaggered = true;
                        rAxisLabelProperties.eStaggering = AxisLabelStaggering::StaggerEven;
                        pLastVisibleNeighbourTickInfo = pPREPreviousVisibleTickInfo;
                        if( !pLastVisibleNeighbourTickInfo ||
                            !lcl_doesShapeOverlapWithTickmark( pLastVisibleNeighbourTickInfo->xTextShape
                                , rAxisLabelProperties.fRotationAngleDegree
                                , pTickInfo->aTickScreenPosition ) )
                            bOverlapsAfterAutoStagger = false;
                    }
                }

                if (bOverlapsAfterAutoStagger)
                {
                    // Staggering didn't solve the overlap.
                    if( isAutoRotatingOfLabelsAllowed(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis) )
                    {
                        // Try auto-rotating the labels at 45 degrees and
                        // start over.  This rotation angle will be stored for
                        // all future text shape creation runs.
                        // The nRhythm parameter is reset to 1 since the layout
                        // used for text labels is changed.
                        rAxisLabelProperties.autoRotate45();
                        m_aAxisLabelProperties.fRotationAngleDegree = rAxisLabelProperties.fRotationAngleDegree; // Store it for future runs.
                        removeTextShapesFromTicks();
                        rAxisLabelProperties.nRhythm = 1;
                        return false;
                    }

                    // Try incrementing the tick interval and start over.
                    rAxisLabelProperties.nRhythm++;
                    removeShapesAtWrongRhythm( rTickIter, rAxisLabelProperties.nRhythm, nTick, xTarget );
                    return false;
                }
            }
        }

        pPREPreviousVisibleTickInfo = pPreviousVisibleTickInfo;
        pPreviousVisibleTickInfo = pTickInfo;
    }
    return true;
}

bool VCartesianAxis::createTextShapesSimple(
    const Reference<drawing::XShapes>& xTarget, TickIter& rTickIter,
    AxisLabelProperties& rAxisLabelProperties, TickFactory2D const * pTickFactory )
{
    FixedNumberFormatter aFixedNumberFormatter(
                m_xNumberFormatsSupplier, rAxisLabelProperties.nNumberFormatKey );

    const bool bIsHorizontalAxis = pTickFactory->isHorizontalAxis();
    const bool bIsVerticalAxis = pTickFactory->isVerticalAxis();
    B2DVector aTextToTickDistance = pTickFactory->getDistanceAxisTickToText(m_aAxisProperties, true);

     // Stores an array of text label strings in case of a normal
     // (non-complex) category axis.
    const uno::Sequence<OUString>* pCategories = nullptr;
    if( m_bUseTextLabels && !m_aAxisProperties.m_bComplexCategories )
        pCategories = &m_aTextLabels;

    bool bLimitedHeight = fabs(aTextToTickDistance.getX()) > fabs(aTextToTickDistance.getY());

    //prepare properties for multipropertyset-interface of shape
    tNameSequence aPropNames;
    tAnySequence aPropValues;
    getAxisLabelProperties(aPropNames, aPropValues, m_aAxisProperties, rAxisLabelProperties, -1, bLimitedHeight);

    uno::Any* pColorAny = PropertyMapper::getValuePointer(aPropValues,aPropNames,"CharColor");
    Color nColor = COL_AUTO;
    if(pColorAny)
        *pColorAny >>= nColor;

    uno::Any* pLimitedSpaceAny = PropertyMapper::getValuePointerForLimitedSpace(aPropValues,aPropNames,bLimitedHeight);

    const TickInfo* pPreviousVisibleTickInfo = nullptr;
    sal_Int32 nTick = 0;
    for( TickInfo* pTickInfo = rTickIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = rTickIter.nextInfo(), nTick++ )
    {
        const TickInfo* pLastVisibleNeighbourTickInfo = pPreviousVisibleTickInfo;

        //don't create labels which does not fit into the rhythm
        if( nTick%rAxisLabelProperties.nRhythm != 0 )
            continue;

        //don't create labels for invisible ticks
        if( !pTickInfo->bPaintIt )
            continue;

        if( pLastVisibleNeighbourTickInfo && !rAxisLabelProperties.bOverlapAllowed )
        {
            // Overlapping is not allowed.  If the label overlaps with its
            // neighbering label, try increasing the tick interval (or rhythm
            // as it's called) and start over.

            if( lcl_doesShapeOverlapWithTickmark( pLastVisibleNeighbourTickInfo->xTextShape
                       , rAxisLabelProperties.fRotationAngleDegree
                       , pTickInfo->aTickScreenPosition ) )
            {
                // This tick overlaps with its neighbor. Increment the visible
                // tick intervals (if that's allowed) and start over.

                rAxisLabelProperties.nRhythm++;
                removeShapesAtWrongRhythm( rTickIter, rAxisLabelProperties.nRhythm, nTick, xTarget );
                return false;
            }
        }

        bool bHasExtraColor=false;
        Color nExtraColor;

        OUString aLabel = getTextLabelString(
            aFixedNumberFormatter, pCategories, pTickInfo, isComplexCategoryAxis(),
            nExtraColor, bHasExtraColor);

        if(pColorAny)
            *pColorAny <<= bHasExtraColor?nExtraColor:nColor;
        if(pLimitedSpaceAny)
            *pLimitedSpaceAny <<= sal_Int32(-1*pTickInfo->nFactorForLimitedTextWidth);

        B2DVector aTickScreenPos2D = pTickInfo->aTickScreenPosition;
        aTickScreenPos2D += aTextToTickDistance;
        awt::Point aAnchorScreenPosition2D(
            static_cast<sal_Int32>(aTickScreenPos2D.getX())
            ,static_cast<sal_Int32>(aTickScreenPos2D.getY()));

        //create single label
        if(!pTickInfo->xTextShape.is())
            pTickInfo->xTextShape = createSingleLabel( m_xShapeFactory, xTarget
                                    , aAnchorScreenPosition2D, aLabel
                                    , rAxisLabelProperties, m_aAxisProperties
                                    , aPropNames, aPropValues );
        if(!pTickInfo->xTextShape.is())
            continue;

        recordMaximumTextSize( pTickInfo->xTextShape, rAxisLabelProperties.fRotationAngleDegree );

        //if NO OVERLAP -> remove overlapping shapes
        if( pLastVisibleNeighbourTickInfo && !rAxisLabelProperties.bOverlapAllowed )
        {
            // Check if the label still overlaps with its neighber.
            if( doesOverlap( pLastVisibleNeighbourTickInfo->xTextShape, pTickInfo->xTextShape, rAxisLabelProperties.fRotationAngleDegree ) )
            {
                // It overlaps.
                if( isAutoRotatingOfLabelsAllowed(rAxisLabelProperties, bIsHorizontalAxis, bIsVerticalAxis) )
                {
                    // Try auto-rotating the labels at 45 degrees and
                    // start over.  This rotation angle will be stored for
                    // all future text shape creation runs.
                    // The nRhythm parameter is reset to 1 since the layout
                    // used for text labels is changed.
                    rAxisLabelProperties.autoRotate45();
                    m_aAxisLabelProperties.fRotationAngleDegree = rAxisLabelProperties.fRotationAngleDegree; // Store it for future runs.
                    removeTextShapesFromTicks();
                    rAxisLabelProperties.nRhythm = 1;
                    return false;
                }

                // Try incrementing the tick interval and start over.
                rAxisLabelProperties.nRhythm++;
                removeShapesAtWrongRhythm( rTickIter, rAxisLabelProperties.nRhythm, nTick, xTarget );
                return false;
            }
        }

        pPreviousVisibleTickInfo = pTickInfo;
    }
    return true;
}

double VCartesianAxis::getAxisIntersectionValue() const
{
    if (m_aAxisProperties.m_pfMainLinePositionAtOtherAxis)
        return *m_aAxisProperties.m_pfMainLinePositionAtOtherAxis;

    double fMin = (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMinX() : m_pPosHelper->getLogicMinY();
    double fMax = (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMaxX() : m_pPosHelper->getLogicMaxY();

    return (m_aAxisProperties.m_eCrossoverType == css::chart::ChartAxisPosition_END) ? fMax : fMin;
}

double VCartesianAxis::getLabelLineIntersectionValue() const
{
    if (m_aAxisProperties.m_eLabelPos == css::chart::ChartAxisLabelPosition_OUTSIDE_START)
        return (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMinX() : m_pPosHelper->getLogicMinY();

    if (m_aAxisProperties.m_eLabelPos == css::chart::ChartAxisLabelPosition_OUTSIDE_END)
        return (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMaxX() : m_pPosHelper->getLogicMaxY();

    return getAxisIntersectionValue();
}

double VCartesianAxis::getExtraLineIntersectionValue() const
{
    double fNan;
    rtl::math::setNan(&fNan);

    if( !m_aAxisProperties.m_pfExrtaLinePositionAtOtherAxis )
        return fNan;

    double fMin = (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMinX() : m_pPosHelper->getLogicMinY();
    double fMax = (m_nDimensionIndex==1) ? m_pPosHelper->getLogicMaxX() : m_pPosHelper->getLogicMaxY();

    if( *m_aAxisProperties.m_pfExrtaLinePositionAtOtherAxis <= fMin
        || *m_aAxisProperties.m_pfExrtaLinePositionAtOtherAxis >= fMax )
        return fNan;

    return *m_aAxisProperties.m_pfExrtaLinePositionAtOtherAxis;
}

B2DVector VCartesianAxis::getScreenPosition( double fLogicX, double fLogicY, double fLogicZ ) const
{
    B2DVector aRet(0,0);

    if( m_pPosHelper )
    {
        drawing::Position3D aScenePos = m_pPosHelper->transformLogicToScene( fLogicX, fLogicY, fLogicZ, true );
        if(m_nDimension==3)
        {
            if (m_xLogicTarget.is() && m_pShapeFactory)
            {
                tPropertyNameMap aDummyPropertyNameMap;
                Reference< drawing::XShape > xShape3DAnchor = m_pShapeFactory->createCube( m_xLogicTarget
                        , aScenePos,drawing::Direction3D(1,1,1), 0, nullptr, aDummyPropertyNameMap);
                awt::Point a2DPos = xShape3DAnchor->getPosition(); //get 2D position from xShape3DAnchor
                m_xLogicTarget->remove(xShape3DAnchor);
                aRet.setX( a2DPos.X );
                aRet.setY( a2DPos.Y );
            }
            else
            {
                OSL_FAIL("cannot calculate screen position in VCartesianAxis::getScreenPosition");
            }
        }
        else
        {
            aRet.setX( aScenePos.PositionX );
            aRet.setY( aScenePos.PositionY );
        }
    }

    return aRet;
}

VCartesianAxis::ScreenPosAndLogicPos VCartesianAxis::getScreenPosAndLogicPos( double fLogicX_, double fLogicY_, double fLogicZ_ ) const
{
    ScreenPosAndLogicPos aRet;
    aRet.fLogicX = fLogicX_;
    aRet.fLogicY = fLogicY_;
    aRet.fLogicZ = fLogicZ_;
    aRet.aScreenPos = getScreenPosition( fLogicX_, fLogicY_, fLogicZ_ );
    return aRet;
}

typedef std::vector< VCartesianAxis::ScreenPosAndLogicPos > tScreenPosAndLogicPosList;

namespace {

struct lcl_LessXPos
{
    bool operator() ( const VCartesianAxis::ScreenPosAndLogicPos& rPos1, const VCartesianAxis::ScreenPosAndLogicPos& rPos2 )
    {
        return ( rPos1.aScreenPos.getX() < rPos2.aScreenPos.getX() );
    }
};

struct lcl_GreaterYPos
{
    bool operator() ( const VCartesianAxis::ScreenPosAndLogicPos& rPos1, const VCartesianAxis::ScreenPosAndLogicPos& rPos2 )
    {
        return ( rPos1.aScreenPos.getY() > rPos2.aScreenPos.getY() );
    }
};

}

void VCartesianAxis::get2DAxisMainLine(
    B2DVector& rStart, B2DVector& rEnd, AxisLabelAlignment& rAlignment, double fCrossesOtherAxis ) const
{
    //m_aAxisProperties might get updated and changed here because
    //    the label alignment and inner direction sign depends exactly of the choice of the axis line position which is made here in this method

    double const fMinX = m_pPosHelper->getLogicMinX();
    double const fMinY = m_pPosHelper->getLogicMinY();
    double const fMinZ = m_pPosHelper->getLogicMinZ();
    double const fMaxX = m_pPosHelper->getLogicMaxX();
    double const fMaxY = m_pPosHelper->getLogicMaxY();
    double const fMaxZ = m_pPosHelper->getLogicMaxZ();

    double fXOnXPlane = fMinX;
    double fXOther = fMaxX;
    int nDifferentValue = !m_pPosHelper->isMathematicalOrientationX() ? -1 : 1;
    if( !m_pPosHelper->isSwapXAndY() )
        nDifferentValue *= (m_eLeftWallPos != CuboidPlanePosition_Left) ? -1 : 1;
    else
        nDifferentValue *= (m_eBottomPos != CuboidPlanePosition_Bottom) ? -1 : 1;
    if( nDifferentValue<0 )
    {
        fXOnXPlane = fMaxX;
        fXOther = fMinX;
    }

    double fYOnYPlane = fMinY;
    double fYOther = fMaxY;
    nDifferentValue = !m_pPosHelper->isMathematicalOrientationY() ? -1 : 1;
    if( !m_pPosHelper->isSwapXAndY() )
        nDifferentValue *= (m_eBottomPos != CuboidPlanePosition_Bottom) ? -1 : 1;
    else
        nDifferentValue *= (m_eLeftWallPos != CuboidPlanePosition_Left) ? -1 : 1;
    if( nDifferentValue<0 )
    {
        fYOnYPlane = fMaxY;
        fYOther = fMinY;
    }

    double fZOnZPlane = fMaxZ;
    double fZOther = fMinZ;
    nDifferentValue = !m_pPosHelper->isMathematicalOrientationZ() ? -1 : 1;
    nDifferentValue *= (m_eBackWallPos != CuboidPlanePosition_Back) ? -1 : 1;
    if( nDifferentValue<0 )
    {
        fZOnZPlane = fMinZ;
        fZOther = fMaxZ;
    }

    double fXStart = fMinX;
    double fYStart = fMinY;
    double fZStart = fMinZ;
    double fXEnd;
    double fYEnd;
    double fZEnd = fZStart;

    if( m_nDimensionIndex==0 ) //x-axis
    {
        if( fCrossesOtherAxis < fMinY )
            fCrossesOtherAxis = fMinY;
        else if( fCrossesOtherAxis > fMaxY )
            fCrossesOtherAxis = fMaxY;

        fYStart = fYEnd = fCrossesOtherAxis;
        fXEnd=m_pPosHelper->getLogicMaxX();

        if(m_nDimension==3)
        {
            if( AxisHelper::isAxisPositioningEnabled() )
            {
                if( ::rtl::math::approxEqual( fYOther, fYStart) )
                    fZStart = fZEnd = fZOnZPlane;
                else
                    fZStart = fZEnd = fZOther;
            }
            else
            {
                rStart = getScreenPosition( fXStart, fYStart, fZStart );
                rEnd = getScreenPosition( fXEnd, fYEnd, fZEnd );

                double fDeltaX = rEnd.getX() - rStart.getX();
                double fDeltaY = rEnd.getY() - rStart.getY();

                //only those points are candidates which are lying on exactly one wall as these are outer edges
                tScreenPosAndLogicPosList aPosList;
                aPosList.push_back( getScreenPosAndLogicPos( fMinX, fYOnYPlane, fZOther ) );
                aPosList.push_back( getScreenPosAndLogicPos( fMinX, fYOther, fZOnZPlane ) );

                if( fabs(fDeltaY) > fabs(fDeltaX)  )
                {
                    rAlignment.meAlignment = LABEL_ALIGN_LEFT;
                    //choose most left positions
                    std::sort( aPosList.begin(), aPosList.end(), lcl_LessXPos() );
                    rAlignment.mfLabelDirection = (fDeltaY < 0) ? -1.0 : 1.0;
                }
                else
                {
                    rAlignment.meAlignment = LABEL_ALIGN_BOTTOM;
                    //choose most bottom positions
                    std::sort( aPosList.begin(), aPosList.end(), lcl_GreaterYPos() );
                    rAlignment.mfLabelDirection = (fDeltaX < 0) ? -1.0 : 1.0;
                }
                ScreenPosAndLogicPos aBestPos( aPosList[0] );
                fYStart = fYEnd = aBestPos.fLogicY;
                fZStart = fZEnd = aBestPos.fLogicZ;
                if( !m_pPosHelper->isMathematicalOrientationX() )
                    rAlignment.mfLabelDirection *= -1.0;
            }
        }//end 3D x axis
    }
    else if( m_nDimensionIndex==1 ) //y-axis
    {
        if( fCrossesOtherAxis < fMinX )
            fCrossesOtherAxis = fMinX;
        else if( fCrossesOtherAxis > fMaxX )
            fCrossesOtherAxis = fMaxX;

        fXStart = fXEnd = fCrossesOtherAxis;
        fYEnd=m_pPosHelper->getLogicMaxY();

        if(m_nDimension==3)
        {
            if( AxisHelper::isAxisPositioningEnabled() )
            {
                if( ::rtl::math::approxEqual( fXOther, fXStart) )
                    fZStart = fZEnd = fZOnZPlane;
                else
                    fZStart = fZEnd = fZOther;
            }
            else
            {
                rStart = getScreenPosition( fXStart, fYStart, fZStart );
                rEnd = getScreenPosition( fXEnd, fYEnd, fZEnd );

                double fDeltaX = rEnd.getX() - rStart.getX();
                double fDeltaY = rEnd.getY() - rStart.getY();

                //only those points are candidates which are lying on exactly one wall as these are outer edges
                tScreenPosAndLogicPosList aPosList;
                aPosList.push_back( getScreenPosAndLogicPos( fXOnXPlane, fMinY, fZOther ) );
                aPosList.push_back( getScreenPosAndLogicPos( fXOther, fMinY, fZOnZPlane ) );

                if( fabs(fDeltaY) > fabs(fDeltaX)  )
                {
                    rAlignment.meAlignment = LABEL_ALIGN_LEFT;
                    //choose most left positions
                    std::sort( aPosList.begin(), aPosList.end(), lcl_LessXPos() );
                    rAlignment.mfLabelDirection = (fDeltaY < 0) ? -1.0 : 1.0;
                }
                else
                {
                    rAlignment.meAlignment = LABEL_ALIGN_BOTTOM;
                    //choose most bottom positions
                    std::sort( aPosList.begin(), aPosList.end(), lcl_GreaterYPos() );
                    rAlignment.mfLabelDirection = (fDeltaX < 0) ? -1.0 : 1.0;
                }
                ScreenPosAndLogicPos aBestPos( aPosList[0] );
                fXStart = fXEnd = aBestPos.fLogicX;
                fZStart = fZEnd = aBestPos.fLogicZ;
                if( !m_pPosHelper->isMathematicalOrientationY() )
                    rAlignment.mfLabelDirection *= -1.0;
            }
        }//end 3D y axis
    }
    else //z-axis
    {
        fZEnd = m_pPosHelper->getLogicMaxZ();
        if( AxisHelper::isAxisPositioningEnabled() )
        {
            if( !m_aAxisProperties.m_bSwapXAndY )
            {
                if( fCrossesOtherAxis < fMinY )
                    fCrossesOtherAxis = fMinY;
                else if( fCrossesOtherAxis > fMaxY )
                    fCrossesOtherAxis = fMaxY;
                fYStart = fYEnd = fCrossesOtherAxis;

                if( ::rtl::math::approxEqual( fYOther, fYStart) )
                    fXStart = fXEnd = fXOnXPlane;
                else
                    fXStart = fXEnd = fXOther;
            }
            else
            {
                if( fCrossesOtherAxis < fMinX )
                    fCrossesOtherAxis = fMinX;
                else if( fCrossesOtherAxis > fMaxX )
                    fCrossesOtherAxis = fMaxX;
                fXStart = fXEnd = fCrossesOtherAxis;

                if( ::rtl::math::approxEqual( fXOther, fXStart) )
                    fYStart = fYEnd = fYOnYPlane;
                else
                    fYStart = fYEnd = fYOther;
            }
        }
        else
        {
            if( !m_pPosHelper->isSwapXAndY() )
            {
                fXStart = fXEnd = m_pPosHelper->isMathematicalOrientationX() ? m_pPosHelper->getLogicMaxX() : m_pPosHelper->getLogicMinX();
                fYStart = fYEnd = m_pPosHelper->isMathematicalOrientationY() ? m_pPosHelper->getLogicMinY() : m_pPosHelper->getLogicMaxY();
            }
            else
            {
                fXStart = fXEnd = m_pPosHelper->isMathematicalOrientationX() ? m_pPosHelper->getLogicMinX() : m_pPosHelper->getLogicMaxX();
                fYStart = fYEnd = m_pPosHelper->isMathematicalOrientationY() ? m_pPosHelper->getLogicMaxY() : m_pPosHelper->getLogicMinY();
            }

            if(m_nDimension==3)
            {
                rStart = getScreenPosition( fXStart, fYStart, fZStart );
                rEnd = getScreenPosition( fXEnd, fYEnd, fZEnd );

                double fDeltaX = rEnd.getX() - rStart.getX();

                //only those points are candidates which are lying on exactly one wall as these are outer edges
                tScreenPosAndLogicPosList aPosList;
                aPosList.push_back( getScreenPosAndLogicPos( fXOther, fYOnYPlane, fMinZ ) );
                aPosList.push_back( getScreenPosAndLogicPos( fXOnXPlane, fYOther, fMinZ ) );

                std::sort( aPosList.begin(), aPosList.end(), lcl_GreaterYPos() );
                ScreenPosAndLogicPos aBestPos( aPosList[0] );
                ScreenPosAndLogicPos aNotSoGoodPos( aPosList[1] );

                //choose most bottom positions
                if( fDeltaX != 0.0 ) // prefer left-right alignments
                {
                    if( aBestPos.aScreenPos.getX() > aNotSoGoodPos.aScreenPos.getX() )
                        rAlignment.meAlignment = LABEL_ALIGN_RIGHT;
                    else
                         rAlignment.meAlignment = LABEL_ALIGN_LEFT;
                }
                else
                {
                    if( aBestPos.aScreenPos.getY() > aNotSoGoodPos.aScreenPos.getY() )
                        rAlignment.meAlignment = LABEL_ALIGN_BOTTOM;
                    else
                        rAlignment.meAlignment = LABEL_ALIGN_TOP;
                }

                rAlignment.mfLabelDirection = (fDeltaX < 0) ? -1.0 : 1.0;
                if( !m_pPosHelper->isMathematicalOrientationZ() )
                    rAlignment.mfLabelDirection *= -1.0;

                fXStart = fXEnd = aBestPos.fLogicX;
                fYStart = fYEnd = aBestPos.fLogicY;
            }
        }//end 3D z axis
    }

    rStart = getScreenPosition( fXStart, fYStart, fZStart );
    rEnd = getScreenPosition( fXEnd, fYEnd, fZEnd );

    if(m_nDimension==3 && !AxisHelper::isAxisPositioningEnabled() )
        rAlignment.mfInnerTickDirection = rAlignment.mfLabelDirection;//to behave like before

    if(m_nDimension==3 && AxisHelper::isAxisPositioningEnabled() )
    {
        double fDeltaX = rEnd.getX() - rStart.getX();
        double fDeltaY = rEnd.getY() - rStart.getY();

        if( m_nDimensionIndex==2 )
        {
            if( m_eLeftWallPos != CuboidPlanePosition_Left )
            {
                rAlignment.mfLabelDirection *= -1.0;
                rAlignment.mfInnerTickDirection *= -1.0;
            }

            rAlignment.meAlignment =
                (rAlignment.mfLabelDirection < 0) ?
                    LABEL_ALIGN_LEFT :  LABEL_ALIGN_RIGHT;

            if( ( fDeltaY<0 && m_aScale.Orientation == chart2::AxisOrientation_REVERSE ) ||
                ( fDeltaY>0 && m_aScale.Orientation == chart2::AxisOrientation_MATHEMATICAL ) )
                rAlignment.meAlignment =
                    (rAlignment.meAlignment == LABEL_ALIGN_RIGHT) ?
                        LABEL_ALIGN_LEFT : LABEL_ALIGN_RIGHT;
        }
        else if( fabs(fDeltaY) > fabs(fDeltaX) )
        {
            if( m_eBackWallPos != CuboidPlanePosition_Back )
            {
                rAlignment.mfLabelDirection *= -1.0;
                rAlignment.mfInnerTickDirection *= -1.0;
            }

            rAlignment.meAlignment =
                (rAlignment.mfLabelDirection < 0) ?
                    LABEL_ALIGN_LEFT : LABEL_ALIGN_RIGHT;

            if( ( fDeltaY<0 && m_aScale.Orientation == chart2::AxisOrientation_REVERSE ) ||
                ( fDeltaY>0 && m_aScale.Orientation == chart2::AxisOrientation_MATHEMATICAL ) )
                rAlignment.meAlignment =
                    (rAlignment.meAlignment == LABEL_ALIGN_RIGHT) ?
                        LABEL_ALIGN_LEFT :  LABEL_ALIGN_RIGHT;
        }
        else
        {
            if( m_eBackWallPos != CuboidPlanePosition_Back )
            {
                rAlignment.mfLabelDirection *= -1.0;
                rAlignment.mfInnerTickDirection *= -1.0;
            }

            rAlignment.meAlignment =
                (rAlignment.mfLabelDirection < 0) ?
                    LABEL_ALIGN_TOP : LABEL_ALIGN_BOTTOM;

            if( ( fDeltaX>0 && m_aScale.Orientation == chart2::AxisOrientation_REVERSE ) ||
                ( fDeltaX<0 && m_aScale.Orientation == chart2::AxisOrientation_MATHEMATICAL ) )
                rAlignment.meAlignment =
                    (rAlignment.meAlignment == LABEL_ALIGN_TOP) ?
                        LABEL_ALIGN_BOTTOM : LABEL_ALIGN_TOP;
        }
    }
}

TickFactory* VCartesianAxis::createTickFactory()
{
    return createTickFactory2D();
}

TickFactory2D* VCartesianAxis::createTickFactory2D()
{
    AxisLabelAlignment aLabelAlign = m_aAxisProperties.maLabelAlignment;
    B2DVector aStart, aEnd;
    get2DAxisMainLine(aStart, aEnd, aLabelAlign, getAxisIntersectionValue());

    B2DVector aLabelLineStart, aLabelLineEnd;
    get2DAxisMainLine(aLabelLineStart, aLabelLineEnd, aLabelAlign, getLabelLineIntersectionValue());
    m_aAxisProperties.maLabelAlignment = aLabelAlign;

    return new TickFactory2D( m_aScale, m_aIncrement, aStart, aEnd, aLabelLineStart-aStart );
}

static void lcl_hideIdenticalScreenValues( TickIter& rTickIter )
{
    TickInfo* pPrevTickInfo = rTickIter.firstInfo();
    if (!pPrevTickInfo)
        return;

    pPrevTickInfo->bPaintIt = true;
    for( TickInfo* pTickInfo = rTickIter.nextInfo(); pTickInfo; pTickInfo = rTickIter.nextInfo())
    {
        pTickInfo->bPaintIt = (pTickInfo->aTickScreenPosition != pPrevTickInfo->aTickScreenPosition);
        pPrevTickInfo = pTickInfo;
    }
}

//'hide' tickmarks with identical screen values in aAllTickInfos
void VCartesianAxis::hideIdenticalScreenValues( TickInfoArraysType& rTickInfos ) const
{
    if( isComplexCategoryAxis() || isDateAxis() )
    {
        sal_Int32 nCount = rTickInfos.size();
        for( sal_Int32 nN=0; nN<nCount; nN++ )
        {
            PureTickIter aTickIter( rTickInfos[nN] );
            lcl_hideIdenticalScreenValues( aTickIter );
        }
    }
    else
    {
        EquidistantTickIter aTickIter( rTickInfos, m_aIncrement, -1 );
        lcl_hideIdenticalScreenValues( aTickIter );
    }
}

sal_Int32 VCartesianAxis::estimateMaximumAutoMainIncrementCount()
{
    sal_Int32 nRet = 10;

    if( m_nMaximumTextWidthSoFar==0 && m_nMaximumTextHeightSoFar==0 )
        return nRet;

    B2DVector aStart, aEnd;
    AxisLabelAlignment aLabelAlign = m_aAxisProperties.maLabelAlignment;
    get2DAxisMainLine(aStart, aEnd, aLabelAlign, getAxisIntersectionValue());
    m_aAxisProperties.maLabelAlignment = aLabelAlign;

    sal_Int32 nMaxHeight = static_cast<sal_Int32>(fabs(aEnd.getY()-aStart.getY()));
    sal_Int32 nMaxWidth = static_cast<sal_Int32>(fabs(aEnd.getX()-aStart.getX()));

    sal_Int32 nTotalAvailable = nMaxHeight;
    sal_Int32 nSingleNeeded = m_nMaximumTextHeightSoFar;
    sal_Int32 nMaxSameLabel = 0;

    // tdf#48041: do not duplicate the value labels because of rounding
    if (m_aAxisProperties.m_nAxisType != css::chart2::AxisType::DATE)
    {
        FixedNumberFormatter aFixedNumberFormatterTest(m_xNumberFormatsSupplier, m_aAxisLabelProperties.nNumberFormatKey);
        OUString sPreviousValueLabel;
        sal_Int32 nSameLabel = 0;
        for (sal_Int32 nLabel = 0; nLabel < static_cast<sal_Int32>(m_aAllTickInfos[0].size()); ++nLabel)
        {
            Color nColor = COL_AUTO;
            bool bHasColor = false;
            OUString sValueLabel = aFixedNumberFormatterTest.getFormattedString(m_aAllTickInfos[0][nLabel].fScaledTickValue, nColor, bHasColor);
            if (sValueLabel == sPreviousValueLabel)
            {
                nSameLabel++;
                if (nSameLabel > nMaxSameLabel)
                    nMaxSameLabel = nSameLabel;
            }
            else
                nSameLabel = 0;
            sPreviousValueLabel = sValueLabel;
        }
    }
    //for horizontal axis:
    if( (m_nDimensionIndex == 0 && !m_aAxisProperties.m_bSwapXAndY)
        || (m_nDimensionIndex == 1 && m_aAxisProperties.m_bSwapXAndY) )
    {
        nTotalAvailable = nMaxWidth;
        nSingleNeeded = m_nMaximumTextWidthSoFar;
    }

    if( nSingleNeeded>0 )
        nRet = nTotalAvailable/nSingleNeeded;

    if ( nMaxSameLabel > 0 )
    {
        sal_Int32 nRetNoSameLabel = m_aAllTickInfos[0].size() / (nMaxSameLabel + 1);
        if ( nRet > nRetNoSameLabel )
           nRet = nRetNoSameLabel;
    }

    return nRet;
}

void VCartesianAxis::doStaggeringOfLabels( const AxisLabelProperties& rAxisLabelProperties, TickFactory2D const * pTickFactory2D )
{
    if( !pTickFactory2D )
        return;

    if( isComplexCategoryAxis() )
    {
        sal_Int32 nTextLevelCount = getTextLevelCount();
        B2DVector aCummulatedLabelsDistance(0,0);
        for( sal_Int32 nTextLevel=0; nTextLevel<nTextLevelCount; nTextLevel++ )
        {
            std::unique_ptr<TickIter> apTickIter(createLabelTickIterator(nTextLevel));
            if (apTickIter)
            {
                double fRotationAngleDegree = m_aAxisLabelProperties.fRotationAngleDegree;
                if( nTextLevel>0 )
                {
                    lcl_shiftLabels(*apTickIter, aCummulatedLabelsDistance);
                    //multilevel labels: 0 or 90 by default
                    if( m_aAxisProperties.m_bSwapXAndY )
                        fRotationAngleDegree = 90.0;
                    else
                        fRotationAngleDegree = 0.0;
                }
                aCummulatedLabelsDistance += lcl_getLabelsDistance(
                    *apTickIter, pTickFactory2D->getDistanceAxisTickToText(m_aAxisProperties),
                    fRotationAngleDegree);
            }
        }
    }
    else if (rAxisLabelProperties.isStaggered())
    {
        if( !m_aAllTickInfos.empty() )
        {
            LabelIterator aInnerIter( m_aAllTickInfos[0], rAxisLabelProperties.eStaggering, true );
            LabelIterator aOuterIter( m_aAllTickInfos[0], rAxisLabelProperties.eStaggering, false );

            lcl_shiftLabels( aOuterIter
                , lcl_getLabelsDistance( aInnerIter
                    , pTickFactory2D->getDistanceAxisTickToText( m_aAxisProperties ), 0.0 ) );
        }
    }
}

void VCartesianAxis::createLabels()
{
    if( !prepareShapeCreation() )
        return;

    //create labels
    if (!m_aAxisProperties.m_bDisplayLabels)
        return;

    std::unique_ptr<TickFactory2D> apTickFactory2D(createTickFactory2D()); // throws on failure
    TickFactory2D* pTickFactory2D = apTickFactory2D.get();

    //get the transformed screen values for all tickmarks in aAllTickInfos
    pTickFactory2D->updateScreenValues( m_aAllTickInfos );
    //'hide' tickmarks with identical screen values in aAllTickInfos
    hideIdenticalScreenValues( m_aAllTickInfos );

    removeTextShapesFromTicks();

    //create tick mark text shapes
    sal_Int32 nTextLevelCount = getTextLevelCount();
    sal_Int32 nScreenDistanceBetweenTicks = -1;
    for( sal_Int32 nTextLevel=0; nTextLevel<nTextLevelCount; nTextLevel++ )
    {
        std::unique_ptr< TickIter > apTickIter(createLabelTickIterator( nTextLevel ));
        if(apTickIter)
        {
            if(nTextLevel==0)
            {
                nScreenDistanceBetweenTicks = TickFactory2D::getTickScreenDistance(*apTickIter);
                if( nTextLevelCount>1 )
                    nScreenDistanceBetweenTicks*=2; //the above used tick iter does contain also the sub ticks -> thus the given distance is only the half
            }

            AxisLabelProperties aComplexProps(m_aAxisLabelProperties);
            if( m_aAxisProperties.m_bComplexCategories )
            {
                aComplexProps.bLineBreakAllowed = true;
                aComplexProps.bOverlapAllowed = aComplexProps.fRotationAngleDegree != 0.0;
                if( nTextLevel > 0 )
                {
                    //multilevel labels: 0 or 90 by default
                    if( m_aAxisProperties.m_bSwapXAndY )
                        aComplexProps.fRotationAngleDegree = 90.0;
                    else
                        aComplexProps.fRotationAngleDegree = 0.0;
                }
            }
            AxisLabelProperties& rAxisLabelProperties =  m_aAxisProperties.m_bComplexCategories ? aComplexProps : m_aAxisLabelProperties;
            while (!createTextShapes(m_xTextTarget, *apTickIter, rAxisLabelProperties,
                                     pTickFactory2D, nScreenDistanceBetweenTicks))
            {
            };
        }
    }
    doStaggeringOfLabels( m_aAxisLabelProperties, pTickFactory2D );
}

void VCartesianAxis::createMaximumLabels()
{
    TrueGuard aRecordMaximumTextSize(m_bRecordMaximumTextSize);

    if( !prepareShapeCreation() )
        return;

    //create labels
    if (!m_aAxisProperties.m_bDisplayLabels)
        return;

    std::unique_ptr<TickFactory2D> apTickFactory2D(createTickFactory2D()); // throws on failure
    TickFactory2D* pTickFactory2D = apTickFactory2D.get();

    //get the transformed screen values for all tickmarks in aAllTickInfos
    pTickFactory2D->updateScreenValues( m_aAllTickInfos );

    //create tick mark text shapes
    //@todo: iterate through all tick depth which should be labeled

    AxisLabelProperties aAxisLabelProperties( m_aAxisLabelProperties );
    if( isAutoStaggeringOfLabelsAllowed( aAxisLabelProperties, pTickFactory2D->isHorizontalAxis(), pTickFactory2D->isVerticalAxis() ) )
        aAxisLabelProperties.eStaggering = AxisLabelStaggering::StaggerEven;

    aAxisLabelProperties.bOverlapAllowed = true;
    aAxisLabelProperties.bLineBreakAllowed = false;
    sal_Int32 nTextLevelCount = getTextLevelCount();
    for( sal_Int32 nTextLevel=0; nTextLevel<nTextLevelCount; nTextLevel++ )
    {
        std::unique_ptr< TickIter > apTickIter(createMaximumLabelTickIterator( nTextLevel ));
        if(apTickIter)
        {
            while (!createTextShapes(m_xTextTarget, *apTickIter, aAxisLabelProperties,
                                     pTickFactory2D, -1))
            {
            };
        }
    }
    doStaggeringOfLabels( aAxisLabelProperties, pTickFactory2D );
}

void VCartesianAxis::updatePositions()
{
    //update positions of labels
    if (!m_aAxisProperties.m_bDisplayLabels)
        return;

    std::unique_ptr<TickFactory2D> apTickFactory2D(createTickFactory2D()); // throws on failure
    TickFactory2D* pTickFactory2D = apTickFactory2D.get();

    //update positions of all existing text shapes
    pTickFactory2D->updateScreenValues( m_aAllTickInfos );

    sal_Int32 nDepth=0;
    for (auto const& tickInfos : m_aAllTickInfos)
    {
        for (auto const& tickInfo : tickInfos)
        {
            Reference< drawing::XShape > xShape2DText(tickInfo.xTextShape);
            if( xShape2DText.is() )
            {
                B2DVector aTextToTickDistance( pTickFactory2D->getDistanceAxisTickToText( m_aAxisProperties, true ) );
                B2DVector aTickScreenPos2D(tickInfo.aTickScreenPosition);
                aTickScreenPos2D += aTextToTickDistance;
                awt::Point aAnchorScreenPosition2D(
                    static_cast<sal_Int32>(aTickScreenPos2D.getX())
                    ,static_cast<sal_Int32>(aTickScreenPos2D.getY()));

                double fRotationAngleDegree = m_aAxisLabelProperties.fRotationAngleDegree;
                if( nDepth > 0 )
                {
                    //multilevel labels: 0 or 90 by default
                    if( pTickFactory2D->isHorizontalAxis() )
                        fRotationAngleDegree = 0.0;
                    else
                        fRotationAngleDegree = 90;
                }

                // #i78696# use mathematically correct rotation now
                const double fRotationAnglePi(-basegfx::deg2rad(fRotationAngleDegree));
                uno::Any aATransformation = ShapeFactory::makeTransformation(aAnchorScreenPosition2D, fRotationAnglePi);

                //set new position
                uno::Reference< beans::XPropertySet > xProp( xShape2DText, uno::UNO_QUERY );
                if( xProp.is() )
                {
                    try
                    {
                        xProp->setPropertyValue( "Transformation", aATransformation );
                    }
                    catch( const uno::Exception& )
                    {
                        TOOLS_WARN_EXCEPTION("chart2", "" );
                    }
                }

                //correctPositionForRotation
                LabelPositionHelper::correctPositionForRotation( xShape2DText
                    , m_aAxisProperties.maLabelAlignment.meAlignment, fRotationAngleDegree, m_aAxisProperties.m_bComplexCategories );
            }
        }
        ++nDepth;
    }

    doStaggeringOfLabels( m_aAxisLabelProperties, pTickFactory2D );
}

void VCartesianAxis::createTickMarkLineShapes( TickInfoArrayType& rTickInfos, const TickmarkProperties& rTickmarkProperties, TickFactory2D const & rTickFactory2D, bool bOnlyAtLabels )
{
    sal_Int32 nPointCount = rTickInfos.size();
    drawing::PointSequenceSequence aPoints(2*nPointCount);

    sal_Int32 nN = 0;
    for (auto const& tickInfo : rTickInfos)
    {
        if( !tickInfo.bPaintIt )
            continue;

        bool bTicksAtLabels = ( m_aAxisProperties.m_eTickmarkPos != css::chart::ChartAxisMarkPosition_AT_AXIS );
        double fInnerDirectionSign = m_aAxisProperties.maLabelAlignment.mfInnerTickDirection;
        if( bTicksAtLabels && m_aAxisProperties.m_eLabelPos == css::chart::ChartAxisLabelPosition_OUTSIDE_END )
            fInnerDirectionSign *= -1.0;
        bTicksAtLabels = bTicksAtLabels || bOnlyAtLabels;
        //add ticks at labels:
        rTickFactory2D.addPointSequenceForTickLine( aPoints, nN++, tickInfo.fScaledTickValue
            , fInnerDirectionSign , rTickmarkProperties, bTicksAtLabels );
        //add ticks at axis (without labels):
        if( !bOnlyAtLabels && m_aAxisProperties.m_eTickmarkPos == css::chart::ChartAxisMarkPosition_AT_LABELS_AND_AXIS )
            rTickFactory2D.addPointSequenceForTickLine( aPoints, nN++, tickInfo.fScaledTickValue
                , m_aAxisProperties.maLabelAlignment.mfInnerTickDirection, rTickmarkProperties, !bTicksAtLabels );
    }
    aPoints.realloc(nN);
    m_pShapeFactory->createLine2D( m_xGroupShape_Shapes, aPoints
                                , &rTickmarkProperties.aLineProperties );
}

void VCartesianAxis::createShapes()
{
    if( !prepareShapeCreation() )
        return;

    std::unique_ptr<TickFactory2D> apTickFactory2D(createTickFactory2D()); // throws on failure
    TickFactory2D* pTickFactory2D = apTickFactory2D.get();

    //create line shapes
    if(m_nDimension==2)
    {
        //create extra long ticks to separate complex categories (create them only there where the labels are)
        if( isComplexCategoryAxis() )
        {
            TickInfoArraysType aComplexTickInfos;
            createAllTickInfosFromComplexCategories( aComplexTickInfos, true );
            pTickFactory2D->updateScreenValues( aComplexTickInfos );
            hideIdenticalScreenValues( aComplexTickInfos );

            std::vector<TickmarkProperties> aTickmarkPropertiesList;
            static const bool bIncludeSpaceBetweenTickAndText = false;
            sal_Int32 nOffset = static_cast<sal_Int32>(pTickFactory2D->getDistanceAxisTickToText( m_aAxisProperties, false, bIncludeSpaceBetweenTickAndText ).getLength());
            sal_Int32 nTextLevelCount = getTextLevelCount();
            for( sal_Int32 nTextLevel=0; nTextLevel<nTextLevelCount; nTextLevel++ )
            {
                std::unique_ptr< TickIter > apTickIter(createLabelTickIterator( nTextLevel ));
                if( apTickIter )
                {
                    double fRotationAngleDegree = m_aAxisLabelProperties.fRotationAngleDegree;
                    if( nTextLevel > 0 )
                    {
                        //Multi-level Labels: default to 0 or 90
                        if( m_aAxisProperties.m_bSwapXAndY )
                            fRotationAngleDegree = 90.0;
                        else
                            fRotationAngleDegree = 0.0;
                    }
                    B2DVector aLabelsDistance(lcl_getLabelsDistance(
                        *apTickIter, pTickFactory2D->getDistanceAxisTickToText(m_aAxisProperties),
                        fRotationAngleDegree));
                    sal_Int32 nCurrentLength = static_cast<sal_Int32>(aLabelsDistance.getLength());
                    aTickmarkPropertiesList.push_back( m_aAxisProperties.makeTickmarkPropertiesForComplexCategories( nOffset + nCurrentLength, 0 ) );
                    nOffset += nCurrentLength;
                }
            }

            sal_Int32 nTickmarkPropertiesCount = aTickmarkPropertiesList.size();
            TickInfoArraysType::iterator aDepthIter             = aComplexTickInfos.begin();
            const TickInfoArraysType::const_iterator aDepthEnd  = aComplexTickInfos.end();
            for( sal_Int32 nDepth=0; aDepthIter != aDepthEnd && nDepth < nTickmarkPropertiesCount; ++aDepthIter, nDepth++ )
            {
                if(nDepth==0 && !m_aAxisProperties.m_nMajorTickmarks)
                    continue;
                createTickMarkLineShapes( *aDepthIter, aTickmarkPropertiesList[nDepth], *pTickFactory2D, true /*bOnlyAtLabels*/ );
            }
        }
        //create normal ticks for major and minor intervals
        {
            TickInfoArraysType aUnshiftedTickInfos;
            if( m_aScale.ShiftedCategoryPosition )// if ShiftedCategoryPosition==true the tickmarks in m_aAllTickInfos are shifted
            {
                pTickFactory2D->getAllTicks( aUnshiftedTickInfos );
                pTickFactory2D->updateScreenValues( aUnshiftedTickInfos );
                hideIdenticalScreenValues( aUnshiftedTickInfos );
            }
            TickInfoArraysType& rAllTickInfos = m_aScale.ShiftedCategoryPosition ? aUnshiftedTickInfos : m_aAllTickInfos;

            if (rAllTickInfos.empty())
                return;

            sal_Int32 nDepth = 0;
            sal_Int32 nTickmarkPropertiesCount = m_aAxisProperties.m_aTickmarkPropertiesList.size();
            for( auto& rTickInfos : rAllTickInfos )
            {
                if (nDepth == nTickmarkPropertiesCount)
                    break;

                createTickMarkLineShapes( rTickInfos, m_aAxisProperties.m_aTickmarkPropertiesList[nDepth], *pTickFactory2D, false /*bOnlyAtLabels*/ );
                nDepth++;
            }
        }
        //create axis main lines
        //it serves also as the handle shape for the axis selection
        {
            drawing::PointSequenceSequence aPoints(1);
            apTickFactory2D->createPointSequenceForAxisMainLine( aPoints );
            Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D(
                    m_xGroupShape_Shapes, aPoints
                    , &m_aAxisProperties.m_aLineProperties );
            //because of this name this line will be used for marking the axis
            ::chart::ShapeFactory::setShapeName( xShape, "MarkHandles" );
        }
        //create an additional line at NULL
        if( !AxisHelper::isAxisPositioningEnabled() )
        {
            double fExtraLineCrossesOtherAxis = getExtraLineIntersectionValue();
            if (!rtl::math::isNan(fExtraLineCrossesOtherAxis))
            {
                B2DVector aStart, aEnd;
                AxisLabelAlignment aLabelAlign = m_aAxisProperties.maLabelAlignment;
                get2DAxisMainLine(aStart, aEnd, aLabelAlign, fExtraLineCrossesOtherAxis);
                m_aAxisProperties.maLabelAlignment = aLabelAlign;
                drawing::PointSequenceSequence aPoints{{
                        {static_cast<sal_Int32>(aStart.getX()), static_cast<sal_Int32>(aStart.getY())},
                        {static_cast<sal_Int32>(aEnd.getX()), static_cast<sal_Int32>(aEnd.getY())} }};
                m_pShapeFactory->createLine2D(
                        m_xGroupShape_Shapes, aPoints, &m_aAxisProperties.m_aLineProperties );
            }
        }
    }

    createLabels();
}

} //namespace chart

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