1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <BaseGFXHelper.hxx>
21 #include <VLineProperties.hxx>
22 #include "PieChart.hxx"
23 #include <PlottingPositionHelper.hxx>
24 #include <ShapeFactory.hxx>
25 #include <PolarLabelPositionHelper.hxx>
26 #include <CommonConverters.hxx>
27 #include <ObjectIdentifier.hxx>
29 #include <com/sun/star/chart/DataLabelPlacement.hpp>
30 #include <com/sun/star/chart2/XColorScheme.hpp>
32 #include <com/sun/star/container/XChild.hpp>
33 #include <com/sun/star/drawing/XShape.hpp>
34 #include <com/sun/star/beans/XPropertySet.hpp>
35 #include <rtl/math.hxx>
36 #include <sal/log.hxx>
37 #include <osl/diagnose.h>
38 #include <tools/diagnose_ex.h>
39 #include <tools/helpers.hxx>
43 using namespace ::com::sun::star
;
44 using namespace ::com::sun::star::chart2
;
48 struct PieChart::ShapeParam
50 /** the start angle of the slice
52 double mfUnitCircleStartAngleDegree
;
54 /** the angle width of the slice
56 double mfUnitCircleWidthAngleDegree
;
58 /** the normalized outer radius of the ring the slice belongs to.
60 double mfUnitCircleOuterRadius
;
62 /** the normalized inner radius of the ring the slice belongs to
64 double mfUnitCircleInnerRadius
;
66 /** relative distance offset of a slice from the pie center;
67 * this parameter is used for instance when the user performs manual
68 * dragging of a slice (the drag operation is possible only for slices that
69 * belong to the outer ring and only along the ray bisecting the slice);
70 * the value for the given entry in the data series is obtained by the
71 * `Offset` property attached to each entry; note that the value
72 * provided by the `Offset` property is used both as a logical value in
73 * `PiePositionHelper::getInnerAndOuterRadius` and as a percentage value in
74 * the `PieChart::createDataPoint` and `PieChart::createTextLabelShape`
75 * methods; since the logical height of a ring is always 1, this duality
76 * does not cause any incorrect behavior;
78 double mfExplodePercentage
;
80 /** sum of all Y values in a single series
84 /** for 3D pie chart: label z coordinate
88 /** for 3D pie chart: height
93 mfUnitCircleStartAngleDegree(0.0),
94 mfUnitCircleWidthAngleDegree(0.0),
95 mfUnitCircleOuterRadius(0.0),
96 mfUnitCircleInnerRadius(0.0),
97 mfExplodePercentage(0.0),
103 class PiePositionHelper
: public PolarPlottingPositionHelper
106 PiePositionHelper( double fAngleDegreeOffset
);
108 bool getInnerAndOuterRadius( double fCategoryX
, double& fLogicInnerRadius
, double& fLogicOuterRadius
, bool bUseRings
, double fMaxOffset
) const;
111 //Distance between different category rings, seen relative to width of a ring:
112 double m_fRingDistance
; //>=0 m_fRingDistance=1 --> distance == width
115 PiePositionHelper::PiePositionHelper( double fAngleDegreeOffset
)
116 : m_fRingDistance(0.0)
118 m_fRadiusOffset
= 0.0;
119 m_fAngleDegreeOffset
= fAngleDegreeOffset
;
122 /** Compute the outer and the inner radius for the current ring (not for the
123 * whole donut!), in general it is:
124 * inner_radius = (ring_index + 1) - 0.5 + max_offset,
125 * outer_radius = (ring_index + 1) + 0.5 + max_offset.
126 * When orientation for the radius axis is reversed these values are swapped.
127 * (Indeed the orientation for the radius axis is always reversed!
128 * See `PieChartTypeTemplate::adaptScales`.)
129 * The maximum relative offset (see notes for `PieChart::getMaxOffset`) is
130 * added to both the inner and the outer radius.
131 * It returns true if the ring is visible (that is not out of the radius
134 bool PiePositionHelper::getInnerAndOuterRadius( double fCategoryX
135 , double& fLogicInnerRadius
, double& fLogicOuterRadius
136 , bool bUseRings
, double fMaxOffset
) const
141 double fLogicInner
= fCategoryX
-0.5+m_fRingDistance
/2.0;
142 double fLogicOuter
= fCategoryX
+0.5-m_fRingDistance
/2.0;
144 if( !isMathematicalOrientationRadius() )
146 //in this case the given getMaximumX() was not correct instead the minimum should have been smaller by fMaxOffset
147 //but during getMaximumX and getMimumX we do not know the axis orientation
148 fLogicInner
+= fMaxOffset
;
149 fLogicOuter
+= fMaxOffset
;
152 if( fLogicInner
>= getLogicMaxX() )
154 if( fLogicOuter
<= getLogicMinX() )
157 if( fLogicInner
< getLogicMinX() )
158 fLogicInner
= getLogicMinX();
159 if( fLogicOuter
> getLogicMaxX() )
160 fLogicOuter
= getLogicMaxX();
162 fLogicInnerRadius
= fLogicInner
;
163 fLogicOuterRadius
= fLogicOuter
;
164 if( !isMathematicalOrientationRadius() )
165 std::swap(fLogicInnerRadius
,fLogicOuterRadius
);
169 PieChart::PieChart( const uno::Reference
<XChartType
>& xChartTypeModel
170 , sal_Int32 nDimensionCount
171 , bool bExcludingPositioning
)
172 : VSeriesPlotter( xChartTypeModel
, nDimensionCount
)
173 , m_pPosHelper( new PiePositionHelper( (m_nDimension
==3) ? 0.0 : 90.0 ) )
175 , m_bSizeExcludesLabelsAndExplodedSegments(bExcludingPositioning
)
177 ::rtl::math::setNan(&m_fMaxOffset
);
179 PlotterBase::m_pPosHelper
= m_pPosHelper
.get();
180 VSeriesPlotter::m_pMainPosHelper
= m_pPosHelper
.get();
181 m_pPosHelper
->m_fRadiusOffset
= 0.0;
182 m_pPosHelper
->m_fRingDistance
= 0.0;
184 uno::Reference
< beans::XPropertySet
> xChartTypeProps( xChartTypeModel
, uno::UNO_QUERY
);
185 if( xChartTypeProps
.is() ) try
187 xChartTypeProps
->getPropertyValue( "UseRings") >>= m_bUseRings
;
190 m_pPosHelper
->m_fRadiusOffset
= 1.0;
191 if( nDimensionCount
==3 )
192 m_pPosHelper
->m_fRingDistance
= 0.1;
195 catch( const uno::Exception
& )
197 TOOLS_WARN_EXCEPTION("chart2", "" );
201 PieChart::~PieChart()
205 void PieChart::setScales( const std::vector
< ExplicitScaleData
>& rScales
, bool /* bSwapXAndYAxis */ )
207 OSL_ENSURE(m_nDimension
<=static_cast<sal_Int32
>(rScales
.size()),"Dimension of Plotter does not fit two dimension of given scale sequence");
208 m_pPosHelper
->setScales( rScales
, true );
211 drawing::Direction3D
PieChart::getPreferredDiagramAspectRatio() const
213 if( m_nDimension
== 3 )
214 return drawing::Direction3D(1,1,0.10);
215 return drawing::Direction3D(1,1,1);
218 bool PieChart::shouldSnapRectToUsedArea()
223 uno::Reference
< drawing::XShape
> PieChart::createDataPoint(
224 const uno::Reference
<drawing::XShapes
>& xTarget
,
225 const uno::Reference
<beans::XPropertySet
>& xObjectProperties
,
226 tPropertyNameValueMap
const * pOverwritePropertiesMap
,
227 const ShapeParam
& rParam
)
229 //transform position:
230 drawing::Direction3D aOffset
;
231 if (rParam
.mfExplodePercentage
!= 0.0)
233 double fAngle
= rParam
.mfUnitCircleStartAngleDegree
+ rParam
.mfUnitCircleWidthAngleDegree
/2.0;
234 double fRadius
= (rParam
.mfUnitCircleOuterRadius
-rParam
.mfUnitCircleInnerRadius
)*rParam
.mfExplodePercentage
;
235 drawing::Position3D aOrigin
= m_pPosHelper
->transformUnitCircleToScene(0, 0, rParam
.mfLogicZ
);
236 drawing::Position3D aNewOrigin
= m_pPosHelper
->transformUnitCircleToScene(fAngle
, fRadius
, rParam
.mfLogicZ
);
237 aOffset
= aNewOrigin
- aOrigin
;
241 uno::Reference
< drawing::XShape
> xShape
;
244 xShape
= m_pShapeFactory
->createPieSegment( xTarget
245 , rParam
.mfUnitCircleStartAngleDegree
, rParam
.mfUnitCircleWidthAngleDegree
246 , rParam
.mfUnitCircleInnerRadius
, rParam
.mfUnitCircleOuterRadius
247 , aOffset
, B3DHomMatrixToHomogenMatrix( m_pPosHelper
->getUnitCartesianToScene() )
252 xShape
= m_pShapeFactory
->createPieSegment2D( xTarget
253 , rParam
.mfUnitCircleStartAngleDegree
, rParam
.mfUnitCircleWidthAngleDegree
254 , rParam
.mfUnitCircleInnerRadius
, rParam
.mfUnitCircleOuterRadius
255 , aOffset
, B3DHomMatrixToHomogenMatrix( m_pPosHelper
->getUnitCartesianToScene() ) );
257 setMappedProperties( xShape
, xObjectProperties
, PropertyMapper::getPropertyNameMapForFilledSeriesProperties(), pOverwritePropertiesMap
);
261 void PieChart::createTextLabelShape(
262 const uno::Reference
<drawing::XShapes
>& xTextTarget
,
263 VDataSeries
& rSeries
, sal_Int32 nPointIndex
, ShapeParam
& rParam
)
265 if (!rSeries
.getDataPointLabelIfLabel(nPointIndex
))
266 // There is no text label for this data point. Nothing to do.
269 ///by using the `mfExplodePercentage` parameter a normalized offset is added
270 ///to both normalized radii. (See notes for
271 ///`PolarPlottingPositionHelper::transformToRadius`, especially example 3,
272 ///and related comments).
273 if (rParam
.mfExplodePercentage
!= 0.0)
275 double fExplodeOffset
= (rParam
.mfUnitCircleOuterRadius
-rParam
.mfUnitCircleInnerRadius
)*rParam
.mfExplodePercentage
;
276 rParam
.mfUnitCircleInnerRadius
+= fExplodeOffset
;
277 rParam
.mfUnitCircleOuterRadius
+= fExplodeOffset
;
280 ///get the required label placement type. Available placements are
281 ///`AVOID_OVERLAP`, `CENTER`, `OUTSIDE` and `INSIDE`;
282 sal_Int32 nLabelPlacement
= rSeries
.getLabelPlacement(
283 nPointIndex
, m_xChartTypeModel
, m_pPosHelper
->isSwapXAndY());
285 ///when the placement is of `AVOID_OVERLAP` type a later rearrangement of
286 ///the label position is allowed; the `createTextLabelShape` treats the
287 ///`AVOID_OVERLAP` as if it was of `CENTER` type;
289 double nVal
= rSeries
.getYValue(nPointIndex
);
290 //AVOID_OVERLAP is in fact "Best fit" in the UI.
291 bool bMovementAllowed
= ( nLabelPlacement
== css::chart::DataLabelPlacement::AVOID_OVERLAP
);
292 if( bMovementAllowed
)
294 // Use center for "Best fit" for now. In the future we
295 // may want to implement a real best fit algorithm.
296 // But center is good enough, and close to what Excel
299 // Place the label outside if the sector is too small
300 // The threshold is set to 2%, but can be improved by making it a function of
301 // label width and radius too ?
302 double fFrac
= fabs( nVal
/ rParam
.mfLogicYSum
);
303 nLabelPlacement
= ( fFrac
<= 0.02 ) ? css::chart::DataLabelPlacement::OUTSIDE
:
304 css::chart::DataLabelPlacement::CENTER
;
307 ///for `OUTSIDE` (`INSIDE`) label placements an offset of 150 (-150), in the
308 ///radius direction, is added to the final screen position of the label
309 ///anchor point. This is required in order to ensure that the label is
310 ///completely outside (inside) the related slice. Indeed this value should
311 ///depend on the font height;
312 ///pay attention: 150 is not a big offset, in fact the screen position
313 ///coordinates for label anchor points are in the 10000-20000 range, hence
314 ///these are coordinates of a virtual screen and 150 is a small value;
315 LabelAlignment
eAlignment(LABEL_ALIGN_CENTER
);
316 sal_Int32 nScreenValueOffsetInRadiusDirection
= 0 ;
317 if( nLabelPlacement
== css::chart::DataLabelPlacement::OUTSIDE
)
318 nScreenValueOffsetInRadiusDirection
= (m_nDimension
!=3) ? 150 : 0;//todo maybe calculate this font height dependent
319 else if( nLabelPlacement
== css::chart::DataLabelPlacement::INSIDE
)
320 nScreenValueOffsetInRadiusDirection
= (m_nDimension
!=3) ? -150 : 0;//todo maybe calculate this font height dependent
322 ///the scene position of the label anchor point is calculated (see notes for
323 ///`PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForUnitCircleValues`),
324 ///and immediately transformed into the screen position.
325 PolarLabelPositionHelper
aPolarPosHelper(m_pPosHelper
.get(),m_nDimension
,m_xLogicTarget
,m_pShapeFactory
);
326 awt::Point
aScreenPosition2D(
327 aPolarPosHelper
.getLabelScreenPositionAndAlignmentForUnitCircleValues(eAlignment
, nLabelPlacement
328 , rParam
.mfUnitCircleStartAngleDegree
, rParam
.mfUnitCircleWidthAngleDegree
329 , rParam
.mfUnitCircleInnerRadius
, rParam
.mfUnitCircleOuterRadius
, rParam
.mfLogicZ
+0.5, 0 ));
331 ///the screen position of the pie/donut center is calculated.
332 PieLabelInfo aPieLabelInfo
;
333 aPieLabelInfo
.aFirstPosition
= basegfx::B2IVector( aScreenPosition2D
.X
, aScreenPosition2D
.Y
);
334 awt::Point
aOrigin( aPolarPosHelper
.transformSceneToScreenPosition( m_pPosHelper
->transformUnitCircleToScene( 0.0, 0.0, rParam
.mfLogicZ
+1.0 ) ) );
335 aPieLabelInfo
.aOrigin
= basegfx::B2IVector( aOrigin
.X
, aOrigin
.Y
);
337 ///add a scaling independent Offset if requested
338 if( nScreenValueOffsetInRadiusDirection
!= 0)
340 basegfx::B2IVector
aDirection( aScreenPosition2D
.X
- aOrigin
.X
, aScreenPosition2D
.Y
- aOrigin
.Y
);
341 aDirection
.setLength(nScreenValueOffsetInRadiusDirection
);
342 aScreenPosition2D
.X
+= aDirection
.getX();
343 aScreenPosition2D
.Y
+= aDirection
.getY();
346 // compute outer pie radius
347 awt::Point aOuterCirclePoint
= PlottingPositionHelper::transformSceneToScreenPosition(
348 m_pPosHelper
->transformUnitCircleToScene(
350 rParam
.mfUnitCircleOuterRadius
,
352 m_xLogicTarget
, m_pShapeFactory
, m_nDimension
);
353 basegfx::B2IVector
aRadiusVector(
354 aOuterCirclePoint
.X
- aPieLabelInfo
.aOrigin
.getX(),
355 aOuterCirclePoint
.Y
- aPieLabelInfo
.aOrigin
.getY() );
356 double fSquaredPieRadius
= aRadiusVector
.scalar(aRadiusVector
);
357 double fPieRadius
= sqrt( fSquaredPieRadius
);
359 // set the maximum text width to be used when text wrapping is enabled
360 double fTextMaximumFrameWidth
= 0.8 * fPieRadius
;
361 sal_Int32 nTextMaximumFrameWidth
= ceil(fTextMaximumFrameWidth
);
363 ///the text shape for the label is created
364 aPieLabelInfo
.xTextShape
= createDataLabel(
365 xTextTarget
, rSeries
, nPointIndex
, nVal
, rParam
.mfLogicYSum
,
366 aScreenPosition2D
, eAlignment
, 0, nTextMaximumFrameWidth
);
368 ///a new `PieLabelInfo` instance is initialized with all the info related to
369 ///the current label in order to simplify later label position rearrangement;
370 uno::Reference
< container::XChild
> xChild( aPieLabelInfo
.xTextShape
, uno::UNO_QUERY
);
372 ///text shape could be empty; in that case there is no need to add label info
376 aPieLabelInfo
.xLabelGroupShape
.set( xChild
->getParent(), uno::UNO_QUERY
);
378 aPieLabelInfo
.fValue
= nVal
;
379 aPieLabelInfo
.bMovementAllowed
= bMovementAllowed
;
380 aPieLabelInfo
.bMoved
= false;
381 aPieLabelInfo
.xTextTarget
= xTextTarget
;
383 if (bMovementAllowed
)
385 performLabelBestFit(rParam
, aPieLabelInfo
);
388 m_aLabelInfoList
.push_back(aPieLabelInfo
);
391 void PieChart::addSeries( std::unique_ptr
<VDataSeries
> pSeries
, sal_Int32
/* zSlot */, sal_Int32
/* xSlot */, sal_Int32
/* ySlot */ )
393 VSeriesPlotter::addSeries( std::move(pSeries
), 0, -1, 0 );
396 double PieChart::getMinimumX()
400 double PieChart::getMaxOffset()
402 if (!::rtl::math::isNan(m_fMaxOffset
))
403 // Value already cached. Use it.
407 if( m_aZSlots
.empty() )
409 if( m_aZSlots
.front().empty() )
412 const std::vector
< std::unique_ptr
<VDataSeries
> >& rSeriesList( m_aZSlots
.front().front().m_aSeriesVector
);
413 if(rSeriesList
.empty())
416 VDataSeries
* pSeries
= rSeriesList
.front().get();
417 uno::Reference
< beans::XPropertySet
> xSeriesProp( pSeries
->getPropertiesOfSeries() );
418 if( !xSeriesProp
.is() )
421 double fExplodePercentage
=0.0;
422 xSeriesProp
->getPropertyValue( "Offset") >>= fExplodePercentage
;
423 if(fExplodePercentage
>m_fMaxOffset
)
424 m_fMaxOffset
=fExplodePercentage
;
426 if(!m_bSizeExcludesLabelsAndExplodedSegments
)
428 uno::Sequence
< sal_Int32
> aAttributedDataPointIndexList
;
429 if( xSeriesProp
->getPropertyValue( "AttributedDataPoints" ) >>= aAttributedDataPointIndexList
)
431 for(sal_Int32 nN
=aAttributedDataPointIndexList
.getLength();nN
--;)
433 uno::Reference
< beans::XPropertySet
> xPointProp( pSeries
->getPropertiesOfPoint(aAttributedDataPointIndexList
[nN
]) );
436 fExplodePercentage
=0.0;
437 xPointProp
->getPropertyValue( "Offset") >>= fExplodePercentage
;
438 if(fExplodePercentage
>m_fMaxOffset
)
439 m_fMaxOffset
=fExplodePercentage
;
446 double PieChart::getMaximumX()
448 double fMaxOffset
= getMaxOffset();
449 if( !m_aZSlots
.empty() && m_bUseRings
)
450 return m_aZSlots
.front().size()+0.5+fMaxOffset
;
451 return 1.5+fMaxOffset
;
453 double PieChart::getMinimumYInRange( double /* fMinimumX */, double /* fMaximumX */, sal_Int32
/* nAxisIndex */ )
458 double PieChart::getMaximumYInRange( double /* fMinimumX */, double /* fMaximumX */, sal_Int32
/* nAxisIndex */ )
463 bool PieChart::isExpandBorderToIncrementRhythm( sal_Int32
/* nDimensionIndex */ )
468 bool PieChart::isExpandIfValuesCloseToBorder( sal_Int32
/* nDimensionIndex */ )
473 bool PieChart::isExpandWideValuesToZero( sal_Int32
/* nDimensionIndex */ )
478 bool PieChart::isExpandNarrowValuesTowardZero( sal_Int32
/* nDimensionIndex */ )
483 bool PieChart::isSeparateStackingForDifferentSigns( sal_Int32
/* nDimensionIndex */ )
488 void PieChart::createShapes()
490 ///a ZSlot is a vector< vector< VDataSeriesGroup > >. There is only one
491 ///ZSlot: m_aZSlots[0] which has a number of elements equal to the total
492 ///number of data series (in fact, even if m_aZSlots[0][i] is an object of
493 ///type `VDataSeriesGroup`, in the current implementation, there is only one
494 ///data series in each data series group).
495 if (m_aZSlots
.empty())
496 // No series to plot.
499 ///m_xLogicTarget is where the group of all data series shapes (e.g. a pie
500 ///slice) is added (xSeriesTarget);
502 ///m_xFinalTarget is where the group of all text shapes (labels) is added
505 ///both have been already created and added to the same root shape
506 ///( a member of a VDiagram object); this initialization occurs in
507 ///`ChartView::impl_createDiagramAndContent`.
509 OSL_ENSURE(m_pShapeFactory
&& m_xLogicTarget
.is() && m_xFinalTarget
.is(), "PieChart is not properly initialized.");
510 if (!m_pShapeFactory
|| !m_xLogicTarget
.is() || !m_xFinalTarget
.is())
513 ///the text labels should be always on top of the other series shapes
514 ///therefore create an own group for the texts to move them to front
515 ///(because the text group is created after the series group the texts are
517 uno::Reference
< drawing::XShapes
> xSeriesTarget(
518 createGroupShape( m_xLogicTarget
));
519 uno::Reference
< drawing::XShapes
> xTextTarget(
520 m_pShapeFactory
->createGroup2D( m_xFinalTarget
));
521 //check necessary here that different Y axis can not be stacked in the same group? ... hm?
523 ///pay attention that the `m_bSwapXAndY` parameter used by the polar
524 ///plotting position helper is always set to true for pie/donut charts
525 ///(see PieChart::setScales). This fact causes that `createShapes` expects
526 ///that the radius axis scale is the one with index 0 and the angle axis
527 ///scale is the one with index 1.
529 std::vector
< VDataSeriesGroup
>::iterator aXSlotIter
= m_aZSlots
.front().begin();
530 const std::vector
< VDataSeriesGroup
>::const_iterator aXSlotEnd
= m_aZSlots
.front().end();
532 ///m_bUseRings == true if chart type is `donut`, == false if chart type is
533 ///`pie`; if the chart is of `donut` type we have as many rings as many data
534 ///series, else we have a single ring (a pie) representing the first data
536 ///for what I can see the radius axis orientation is always reversed and
537 ///the angle axis orientation is always non-reversed;
538 ///the radius axis scale range is [0.5, number of rings + 0.5 + max_offset],
539 ///the angle axis scale range is [0, 1]. The max_offset parameter is used
540 ///for exploded pie chart and its value is 0.5.
542 ///the `explodeable` ring is the first one except when the radius axis
543 ///orientation is reversed (always!?) and we are dealing with a donut: in
544 ///such a case the `explodeable` ring is the last one.
545 std::vector
< VDataSeriesGroup
>::size_type nExplodeableSlot
= 0;
546 if( m_pPosHelper
->isMathematicalOrientationRadius() && m_bUseRings
)
547 nExplodeableSlot
= m_aZSlots
.front().size()-1;
549 m_aLabelInfoList
.clear();
550 ::rtl::math::setNan(&m_fMaxOffset
);
551 sal_Int32 n3DRelativeHeight
= 100;
552 uno::Reference
< beans::XPropertySet
> xPropertySet( m_xChartTypeModel
, uno::UNO_QUERY
);
553 if ( (m_nDimension
==3) && xPropertySet
.is())
557 uno::Any aAny
= xPropertySet
->getPropertyValue( "3DRelativeHeight" );
558 aAny
>>= n3DRelativeHeight
;
560 catch (const uno::Exception
&) { }
562 ///iterate over each xslot, that is on each data series (there is
563 ///only one data series in each data series group!); note that if the chart
564 ///type is a pie the loop iterates only over the first data series
565 ///(m_bUseRings||fSlotX<0.5)
566 for( double fSlotX
=0; aXSlotIter
!= aXSlotEnd
&& (m_bUseRings
||fSlotX
<0.5 ); ++aXSlotIter
, fSlotX
+=1.0 )
570 std::vector
< std::unique_ptr
<VDataSeries
> >* pSeriesList
= &(aXSlotIter
->m_aSeriesVector
);
571 if(pSeriesList
->empty())//there should be only one series in each x slot
573 VDataSeries
* pSeries
= pSeriesList
->front().get();
577 bool bHasFillColorMapping
= pSeries
->hasPropertyMapping("FillColor");
579 /// The angle degree offset is set by the same property of the
581 /// Counter-clockwise offset from the 3 o'clock position.
582 m_pPosHelper
->m_fAngleDegreeOffset
= pSeries
->getStartingAngle();
584 ///iterate through all points to get the sum of all entries of
585 ///the current data series
586 sal_Int32 nPointIndex
=0;
587 sal_Int32 nPointCount
=pSeries
->getTotalPointCount();
588 for( nPointIndex
= 0; nPointIndex
< nPointCount
; nPointIndex
++ )
590 double fY
= pSeries
->getYValue( nPointIndex
);
593 //@todo warn somehow that negative values are treated as positive
595 if( ::rtl::math::isNan(fY
) )
597 aParam
.mfLogicYSum
+= fabs(fY
);
600 if (aParam
.mfLogicYSum
== 0.0)
601 // Total sum of all Y values in this series is zero. Skip the whole series.
604 double fLogicYForNextPoint
= 0.0;
605 ///iterate through all points to create shapes
606 for( nPointIndex
= 0; nPointIndex
< nPointCount
; nPointIndex
++ )
608 double fLogicInnerRadius
, fLogicOuterRadius
;
610 ///compute the maximum relative distance offset of the current slice
611 ///from the pie center
612 ///it is worth noting that after the first invocation the maximum
613 ///offset value is cached, so it is evaluated only once per each
614 ///call to `createShapes`
615 double fOffset
= getMaxOffset();
617 ///compute the outer and the inner radius for the current ring slice
618 bool bIsVisible
= m_pPosHelper
->getInnerAndOuterRadius( fSlotX
+1.0, fLogicInnerRadius
, fLogicOuterRadius
, m_bUseRings
, fOffset
);
622 aParam
.mfDepth
= getTransformedDepth() * (n3DRelativeHeight
/ 100.0);
624 uno::Reference
< drawing::XShapes
> xSeriesGroupShape_Shapes
= getSeriesGroupShape(pSeries
, xSeriesTarget
);
625 ///collect data point information (logic coordinates, style ):
626 double fLogicYValue
= fabs(pSeries
->getYValue( nPointIndex
));
627 if( ::rtl::math::isNan(fLogicYValue
) )
629 if(fLogicYValue
==0.0)//@todo: continue also if the resolution is too small
631 double fLogicYPos
= fLogicYForNextPoint
;
632 fLogicYForNextPoint
+= fLogicYValue
;
634 uno::Reference
< beans::XPropertySet
> xPointProperties
= pSeries
->getPropertiesOfPoint( nPointIndex
);
636 //iterate through all subsystems to create partial points
638 //logic values on angle axis:
639 double fLogicStartAngleValue
= fLogicYPos
/ aParam
.mfLogicYSum
;
640 double fLogicEndAngleValue
= (fLogicYPos
+fLogicYValue
) / aParam
.mfLogicYSum
;
642 ///note that the explode percentage is set to the `Offset`
643 ///property of the current data series entry only for slices
644 ///belonging to the outer ring
645 aParam
.mfExplodePercentage
= 0.0;
646 bool bDoExplode
= ( nExplodeableSlot
== static_cast< std::vector
< VDataSeriesGroup
>::size_type
>(fSlotX
) );
649 xPointProperties
->getPropertyValue( "Offset") >>= aParam
.mfExplodePercentage
;
651 catch( const uno::Exception
& )
653 TOOLS_WARN_EXCEPTION("chart2", "" );
656 ///see notes for `PolarPlottingPositionHelper` methods
657 ///transform to unit circle:
658 aParam
.mfUnitCircleWidthAngleDegree
= m_pPosHelper
->getWidthAngleDegree( fLogicStartAngleValue
, fLogicEndAngleValue
);
659 aParam
.mfUnitCircleStartAngleDegree
= m_pPosHelper
->transformToAngleDegree( fLogicStartAngleValue
);
660 aParam
.mfUnitCircleInnerRadius
= m_pPosHelper
->transformToRadius( fLogicInnerRadius
);
661 aParam
.mfUnitCircleOuterRadius
= m_pPosHelper
->transformToRadius( fLogicOuterRadius
);
664 std::unique_ptr
< tPropertyNameValueMap
> apOverwritePropertiesMap
;
665 if (!pSeries
->hasPointOwnColor(nPointIndex
) && m_xColorScheme
.is())
667 apOverwritePropertiesMap
.reset( new tPropertyNameValueMap
);
668 (*apOverwritePropertiesMap
)["FillColor"] <<=
669 m_xColorScheme
->getColorByIndex( nPointIndex
);
673 aParam
.mfLogicZ
= -1.0; // For 3D pie chart label position
674 uno::Reference
<drawing::XShape
> xPointShape
=
676 xSeriesGroupShape_Shapes
, xPointProperties
, apOverwritePropertiesMap
.get(), aParam
);
678 if(bHasFillColorMapping
)
680 double nPropVal
= pSeries
->getValueByProperty(nPointIndex
, "FillColor");
681 if(!rtl::math::isNan(nPropVal
))
683 uno::Reference
< beans::XPropertySet
> xProps( xPointShape
, uno::UNO_QUERY_THROW
);
684 xProps
->setPropertyValue("FillColor", uno::Any(static_cast<sal_Int32
>( nPropVal
)));
689 createTextLabelShape(xTextTarget
, *pSeries
, nPointIndex
, aParam
);
693 ShapeFactory::setShapeName( xPointShape
694 , ObjectIdentifier::createPointCID( pSeries
->getPointCID_Stub(), nPointIndex
) );
698 ///enable dragging of outer segments
700 double fAngle
= aParam
.mfUnitCircleStartAngleDegree
+ aParam
.mfUnitCircleWidthAngleDegree
/2.0;
701 double fMaxDeltaRadius
= aParam
.mfUnitCircleOuterRadius
-aParam
.mfUnitCircleInnerRadius
;
702 drawing::Position3D aOrigin
= m_pPosHelper
->transformUnitCircleToScene( fAngle
, aParam
.mfUnitCircleOuterRadius
, aParam
.mfLogicZ
);
703 drawing::Position3D aNewOrigin
= m_pPosHelper
->transformUnitCircleToScene( fAngle
, aParam
.mfUnitCircleOuterRadius
+ fMaxDeltaRadius
, aParam
.mfLogicZ
);
705 sal_Int32
nOffsetPercent( static_cast<sal_Int32
>(aParam
.mfExplodePercentage
* 100.0) );
707 awt::Point
aMinimumPosition( PlottingPositionHelper::transformSceneToScreenPosition(
708 aOrigin
, m_xLogicTarget
, m_pShapeFactory
, m_nDimension
) );
709 awt::Point
aMaximumPosition( PlottingPositionHelper::transformSceneToScreenPosition(
710 aNewOrigin
, m_xLogicTarget
, m_pShapeFactory
, m_nDimension
) );
712 //enable dragging of piesegments
713 OUString
aPointCIDStub( ObjectIdentifier::createSeriesSubObjectStub( OBJECTTYPE_DATA_POINT
714 , pSeries
->getSeriesParticle()
715 , ObjectIdentifier::getPieSegmentDragMethodServiceName()
716 , ObjectIdentifier::createPieSegmentDragParameterString(
717 nOffsetPercent
, aMinimumPosition
, aMaximumPosition
)
720 ShapeFactory::setShapeName( xPointShape
721 , ObjectIdentifier::createPointCID( aPointCIDStub
, nPointIndex
) );
723 catch( const uno::Exception
& )
725 TOOLS_WARN_EXCEPTION("chart2", "" );
727 }//next series in x slot (next y slot)
735 ::basegfx::B2IRectangle
lcl_getRect( const uno::Reference
< drawing::XShape
>& xShape
)
737 ::basegfx::B2IRectangle aRect
;
739 aRect
= BaseGFXHelper::makeRectangle(xShape
->getPosition(),xShape
->getSize() );
743 bool lcl_isInsidePage( const awt::Point
& rPos
, const awt::Size
& rSize
, const awt::Size
& rPageSize
)
745 if( rPos
.X
< 0 || rPos
.Y
< 0 )
747 if( (rPos
.X
+ rSize
.Width
) > rPageSize
.Width
)
749 if( (rPos
.Y
+ rSize
.Height
) > rPageSize
.Height
)
754 }//end anonymous namespace
756 PieChart::PieLabelInfo::PieLabelInfo()
757 : aFirstPosition(), aOrigin(), fValue(0.0)
758 , bMovementAllowed(false), bMoved(false), pPrevious(nullptr),pNext(nullptr)
762 /** In case this label and the passed label overlap the routine moves this
763 * label in order to fix the issue. After the label position has been
764 * rearranged it is checked that the moved label is still inside the page
765 * document, if the test is positive the routine returns true else returns
768 bool PieChart::PieLabelInfo::moveAwayFrom( const PieChart::PieLabelInfo
* pFix
, const awt::Size
& rPageSize
, bool bMoveHalfWay
, bool bMoveClockwise
)
770 //return true if the move was successful
771 if(!bMovementAllowed
)
774 const sal_Int32 nLabelDistanceX
= rPageSize
.Width
/50;
775 const sal_Int32 nLabelDistanceY
= rPageSize
.Height
/50;
777 ///compute the rectangle representing the intersection of the label bounding
778 ///boxes (`aOverlap`).
779 ::basegfx::B2IRectangle
aOverlap( lcl_getRect( xLabelGroupShape
) );
780 aOverlap
.intersect( lcl_getRect( pFix
->xLabelGroupShape
) );
781 if( !aOverlap
.isEmpty() )
783 //TODO: alternative move direction
785 ///the label is shifted along the direction orthogonal to the vector
786 ///starting at the pie/donut center and ending at this label anchor
789 ///named `aTangentialDirection` the unit vector related to such a
790 ///direction, the magnitude of the shift along such a direction is
791 ///calculated in this way: if the horizontal component of
792 ///`aTangentialDirection` is greater than the vertical component,
793 ///the magnitude of the shift is equal to `aOverlap.Width` else to
794 ///`aOverlap.Height`;
795 basegfx::B2IVector aRadiusDirection
= aFirstPosition
- aOrigin
;
796 aRadiusDirection
.setLength(1.0);
797 basegfx::B2IVector
aTangentialDirection( -aRadiusDirection
.getY(), aRadiusDirection
.getX() );
798 bool bShiftHorizontal
= abs(aTangentialDirection
.getX()) > abs(aTangentialDirection
.getY());
799 sal_Int32 nShift
= bShiftHorizontal
? static_cast<sal_Int32
>(aOverlap
.getWidth()) : static_cast<sal_Int32
>(aOverlap
.getHeight());
800 ///the magnitude of the shift is also increased by 1/50-th of the width
801 ///or the height of the document page;
802 nShift
+= (bShiftHorizontal
? nLabelDistanceX
: nLabelDistanceY
);
803 ///in case the `bMoveHalfWay` parameter is true the magnitude of
804 ///the shift is halved.
807 ///in case the `bMoveClockwise` parameter is false the direction of
808 ///`aTangentialDirection` is reversed;
811 awt::Point
aOldPos( xLabelGroupShape
->getPosition() );
812 basegfx::B2IVector aNewPos
= basegfx::B2IVector( aOldPos
.X
, aOldPos
.Y
) + nShift
*aTangentialDirection
;
814 ///a final check is performed in order to be sure that the moved label
815 ///is still inside the page document;
816 awt::Point
aNewAWTPos( aNewPos
.getX(), aNewPos
.getY() );
817 if( !lcl_isInsidePage( aNewAWTPos
, xLabelGroupShape
->getSize(), rPageSize
) )
820 xLabelGroupShape
->setPosition( aNewAWTPos
);
825 ///note that no further test is performed in order to check that the
826 ///overlap is really fixed: this result is surely achieved if the shift
827 ///would occur in the horizontal or vertical direction (since, in such a
828 ///direction, the magnitude of the shift would be greater than the length
829 ///of the overlap), but in general this is not true;
830 ///adding a constant term equal to 1/50-th of the width or the height of
831 ///the document page increases the probability of success, anyway it is
832 ///worth noting that the method can return true even if the overlap issue
833 ///is not (completely) fixed;
836 void PieChart::resetLabelPositionsToPreviousState()
838 for (auto const& labelInfo
: m_aLabelInfoList
)
839 labelInfo
.xLabelGroupShape
->setPosition(labelInfo
.aPreviousPosition
);
842 bool PieChart::detectLabelOverlapsAndMove( const awt::Size
& rPageSize
)
844 ///the routine tries to individuate a chain of overlapping labels and
845 ///assigns the first and the last of them to `pFirstBorder` and
847 ///this result is achieved by performing two consecutive while loop.
849 ///find borders of a group of overlapping labels
851 ///a first while loop is started on the collection of `PieLabelInfo` objects;
852 ///the bounding box of each label is checked for overlap against the bounding
853 ///box of the previous and of the next label;
854 ///when an overlap is found `bOverlapFound` is set to true, however the
855 ///iteration is break only if the overlap occurs against only the next label
856 ///and not against the previous label: so we exit from the loop whenever an
857 ///overlap occurs except when the loop initial label overlaps with the
859 bool bOverlapFound
= false;
860 PieLabelInfo
* pStart
= &(*(m_aLabelInfoList
.rbegin()));
861 PieLabelInfo
* pFirstBorder
= nullptr;
862 PieLabelInfo
* pSecondBorder
= nullptr;
863 PieLabelInfo
* pCurrent
= pStart
;
866 ::basegfx::B2IRectangle
aPreviousOverlap( lcl_getRect( pCurrent
->xLabelGroupShape
) );
867 ::basegfx::B2IRectangle
aNextOverlap( aPreviousOverlap
);
868 aPreviousOverlap
.intersect( lcl_getRect( pCurrent
->pPrevious
->xLabelGroupShape
) );
869 aNextOverlap
.intersect( lcl_getRect( pCurrent
->pNext
->xLabelGroupShape
) );
871 bool bPreviousOverlap
= !aPreviousOverlap
.isEmpty();
872 bool bNextOverlap
= !aNextOverlap
.isEmpty();
873 if( bPreviousOverlap
|| bNextOverlap
)
874 bOverlapFound
= true;
875 if( !bPreviousOverlap
&& bNextOverlap
)
877 pFirstBorder
= pCurrent
;
880 pCurrent
= pCurrent
->pNext
;
882 while( pCurrent
!= pStart
);
887 ///in case we found a label (`pFirstBorder`) which overlaps with the next
888 ///label and not with the previous label a second while loop is started with
889 ///`pFirstBorder` as initial label; one more time the bounding box of each
890 ///label is checked for overlap against the bounding box of the previous and
891 ///of the next label, however this time we exit from the loop only if the
892 ///current label overlaps with the previous one but does not with the next
893 ///one (the opposite of what is required in the former loop);
894 ///in case such a label is found it is assigned to `pSecondBorder` and the
895 ///iteration is stopped; so in case there is a chain of overlapping labels
896 ///we end up having the first label of the chain pointed by `pFirstBorder`
897 ///and the last label of the chain pointed by `pSecondBorder`;
900 pCurrent
= pFirstBorder
;
903 ::basegfx::B2IRectangle
aPreviousOverlap( lcl_getRect( pCurrent
->xLabelGroupShape
) );
904 ::basegfx::B2IRectangle
aNextOverlap( aPreviousOverlap
);
905 aPreviousOverlap
.intersect( lcl_getRect( pCurrent
->pPrevious
->xLabelGroupShape
) );
906 aNextOverlap
.intersect( lcl_getRect( pCurrent
->pNext
->xLabelGroupShape
) );
908 if( !aPreviousOverlap
.isEmpty() && aNextOverlap
.isEmpty() )
910 pSecondBorder
= pCurrent
;
913 pCurrent
= pCurrent
->pNext
;
915 while( pCurrent
!= pFirstBorder
);
918 ///when two labels satisfying the required conditions are not found
919 ///(`pFirstBorder == 0 || pSecondBorder == 0`) but still an overlap occurs
920 ///(`bOverlapFound == true`) we are in the situation where each label
921 ///overlaps with both the previous and the next one; so `pFirstBorder` is
922 ///set to point to the last `PieLabelInfo` object in the collection and
923 ///`pSecondBorder` is set to point to the first one;
924 if( !pFirstBorder
|| !pSecondBorder
)
926 pFirstBorder
= &(*(m_aLabelInfoList
.rbegin()));
927 pSecondBorder
= &(*(m_aLabelInfoList
.begin()));
930 ///the total number of labels that made up the chain is calculated and used
931 ///for getting a pointer to the central label (`pCenter`);
932 PieLabelInfo
* pCenter
= pFirstBorder
;
933 sal_Int32 nOverlapGroupCount
= 1;
934 for( pCurrent
= pFirstBorder
;pCurrent
!= pSecondBorder
; pCurrent
= pCurrent
->pNext
)
935 nOverlapGroupCount
++;
936 sal_Int32 nCenterPos
= nOverlapGroupCount
/2;
937 bool bSingleCenter
= nOverlapGroupCount
%2 != 0;
942 pCurrent
= pFirstBorder
;
943 while( --nCenterPos
)
944 pCurrent
= pCurrent
->pNext
;
948 ///the current position of each label in the collection is saved in
949 ///`PieLabelInfo.aPreviousPosition`, so that it is possible to undo the label
950 ///move action if it is needed; the undo action is provided by the
951 ///`PieChart::resetLabelPositionsToPreviousState` method.
955 pCurrent
->aPreviousPosition
= pCurrent
->xLabelGroupShape
->getPosition();
956 pCurrent
= pCurrent
->pNext
;
958 while( pCurrent
!= pStart
);
960 ///the `PieChart::tryMoveLabels` method is invoked with
961 ///`rbAlternativeMoveDirection` boolean parameter set to false, such a method
962 ///tries to remove all overlaps that occur in the list of labels going from
963 ///`pFirstBorder` to `pSecondBorder`;
964 ///if the `PieChart::tryMoveLabels` returns true no further action is
965 ///performed, however it is worth noting that it does not mean that all
966 ///overlap issues have been surely fixed, but only that all moved labels are
967 ///at least completely inside the page document;
968 ///when `PieChart::tryMoveLabels` returns false, it means that the attempt
969 ///to fix one of the overlap issues caused that a label has been moved
970 ///(partially) outside the page document (anyway the `PieChart::tryMoveLabels`
971 ///method takes care to restore the position of all labels to their initial
972 ///position, and to set the `rbAlternativeMoveDirection` in/out parameter to
973 ///true); in such a case a second invocation of `PieChart::tryMoveLabels` is
974 ///performed (and this time the `rbAlternativeMoveDirection` boolean
975 ///parameter is true) and independently by what the `PieChart::tryMoveLabels`
976 ///method returns no further action is performed;
977 ///(see notes for `PieChart::tryMoveLabels`);
978 bool bAlternativeMoveDirection
= false;
979 if( !tryMoveLabels( pFirstBorder
, pSecondBorder
, pCenter
, bSingleCenter
, bAlternativeMoveDirection
, rPageSize
) )
980 tryMoveLabels( pFirstBorder
, pSecondBorder
, pCenter
, bSingleCenter
, bAlternativeMoveDirection
, rPageSize
);
982 ///in both cases (one or two invocations of `PieChart::tryMoveLabels`) the
983 ///`detectLabelOverlapsAndMove` method ends returning true.
988 /** Try to remove all overlaps that occur in the list of labels going from
989 * `pFirstBorder` to `pSecondBorder`
991 bool PieChart::tryMoveLabels( PieLabelInfo
const * pFirstBorder
, PieLabelInfo
const * pSecondBorder
992 , PieLabelInfo
* pCenter
993 , bool bSingleCenter
, bool& rbAlternativeMoveDirection
, const awt::Size
& rPageSize
)
996 PieLabelInfo
* p1
= bSingleCenter
? pCenter
->pPrevious
: pCenter
;
997 PieLabelInfo
* p2
= pCenter
->pNext
;
998 //return true when successful
1000 bool bLabelOrderIsAntiClockWise
= m_pPosHelper
->isMathematicalOrientationAngle();
1002 ///two loops are performed simultaneously: the outer loop iterates on
1003 ///`PieLabelInfo` objects in the list starting from the central element
1004 ///(`pCenter`) and moving forward until the last element (`pSecondBorder`);
1005 ///the inner loop starts from the previous element of `pCenter` and moves
1006 ///forward until the current `PieLabelInfo` object of the outer loop is
1008 PieLabelInfo
* pCurrent
= nullptr;
1009 for( pCurrent
= p2
;pCurrent
->pPrevious
!= pSecondBorder
; pCurrent
= pCurrent
->pNext
)
1011 PieLabelInfo
* pFix
= nullptr;
1012 for( pFix
= p2
->pPrevious
;pFix
!= pCurrent
; pFix
= pFix
->pNext
)
1014 ///on the current `PieLabelInfo` object of the outer loop the
1015 ///`moveAwayFrom` method is invoked by passing the current
1016 ///`PieLabelInfo` object of the inner loop as argument.
1018 ///so each label going from the central one to the last one is
1019 ///checked for overlapping against all previous labels (that comes
1020 ///after the central label) and in case the overlap occurs the
1021 ///`moveAwayFrom` method tries to fix the issue;
1022 ///if `moveAwayFrom` returns true (pay attention: that does not
1023 ///mean that the overlap issue has been surely fixed but only that
1024 ///the moved label is at least completely inside the page document:
1025 ///see notes on `PieChart::PieLabelInfo::moveAwayFrom`), the inner
1026 ///loop starts a new iteration else the `rbAlternativeMoveDirection`
1027 ///boolean parameter is tested: if it is false the parameter is set
1028 ///to true, the position of all labels is restored to the initial
1029 ///one (through the `PieChart::resetLabelPositionsToPreviousState`
1030 ///method) and the method ends by returning false, else the inner
1031 ///loop starts a new iteration step;
1032 ///so when `rbAlternativeMoveDirection` is true the method goes on
1033 ///trying to fix left overlap issues even if the last `moveAwayFrom`
1034 ///invocation has moved a label in a position that it is not
1035 ///completely inside the page document
1037 if( !pCurrent
->moveAwayFrom( pFix
, rPageSize
, !bSingleCenter
&& pCurrent
== p2
, !bLabelOrderIsAntiClockWise
) )
1039 if( !rbAlternativeMoveDirection
)
1041 rbAlternativeMoveDirection
= true;
1042 resetLabelPositionsToPreviousState();
1049 ///if the method does not return before ending the first pair of loops,
1050 ///a second pair of simultaneous loops is performed in the opposite
1051 ///direction (respect with the previous case): the outer loop iterates on
1052 ///`PieLabelInfo` objects in the list starting from the central element
1053 ///(`pCenter`) and moving backward until the first element (`pFirstBorder`);
1054 ///the inner loop starts from the next element of `pCenter` and moves
1055 ///backward until the current `PieLabelInfo` object of the outer loop is
1058 ///like in the previous case on the current `PieLabelInfo` object of
1059 ///the outer loop the `moveAwayFrom` method is invoked by passing
1060 ///the current `PieLabelInfo` object of the inner loop as argument
1062 ///so each label going from the central one to the first one is checked for
1063 ///overlapping on all subsequent labels (that come before the central label)
1064 ///and in case the overlap occurs the `moveAwayFrom` method tries to fix
1065 ///the issue. The subsequent actions performed after the invocation
1066 ///`moveAwayFrom` are the same detailed above for the first pair of loops
1068 for( pCurrent
= p1
;pCurrent
->pNext
!= pFirstBorder
; pCurrent
= pCurrent
->pPrevious
)
1070 PieLabelInfo
* pFix
= nullptr;
1071 for( pFix
= p2
->pNext
;pFix
!= pCurrent
; pFix
= pFix
->pPrevious
)
1073 if( !pCurrent
->moveAwayFrom( pFix
, rPageSize
, false, bLabelOrderIsAntiClockWise
) )
1075 if( !rbAlternativeMoveDirection
)
1077 rbAlternativeMoveDirection
= true;
1078 resetLabelPositionsToPreviousState();
1087 void PieChart::rearrangeLabelToAvoidOverlapIfRequested( const awt::Size
& rPageSize
)
1089 ///this method is invoked by `ChartView::impl_createDiagramAndContent` for
1090 ///pie and donut charts after text label creation;
1091 ///it tries to rearrange labels only when the label placement type is
1093 // no need to do anything when we only have one label
1094 if (m_aLabelInfoList
.size() < 2)
1097 ///check whether there are any labels that should be moved
1098 bool bMoveableFound
= false;
1099 for (auto const& labelInfo
: m_aLabelInfoList
)
1101 if(labelInfo
.bMovementAllowed
)
1103 bMoveableFound
= true;
1110 double fPageDiagonaleLength
= sqrt( double(rPageSize
.Width
)*double(rPageSize
.Width
) + double(rPageSize
.Height
)*double(rPageSize
.Height
) );
1111 if( fPageDiagonaleLength
== 0.0 )
1114 ///initialize next and previous member of `PieLabelInfo` objects
1115 auto aIt1
= m_aLabelInfoList
.begin();
1116 auto aEnd
= m_aLabelInfoList
.end();
1117 std::vector
< PieLabelInfo
>::iterator aIt2
= aIt1
;
1118 aIt1
->pPrevious
= &(*(m_aLabelInfoList
.rbegin()));
1120 for( ;aIt2
!=aEnd
; ++aIt1
, ++aIt2
)
1122 PieLabelInfo
& rInfo1( *aIt1
);
1123 PieLabelInfo
& rInfo2( *aIt2
);
1124 rInfo1
.pNext
= &rInfo2
;
1125 rInfo2
.pPrevious
= &rInfo1
;
1127 aIt1
->pNext
= &(*(m_aLabelInfoList
.begin()));
1129 ///detect overlaps and move
1130 sal_Int32 nMaxIterations
= 50;
1131 while( detectLabelOverlapsAndMove( rPageSize
) && nMaxIterations
> 0 )
1134 ///create connection lines for the moved labels
1135 VLineProperties aVLineProperties
;
1136 for (auto const& labelInfo
: m_aLabelInfoList
)
1138 if( labelInfo
.bMoved
)
1140 sal_Int32 nX1
= labelInfo
.aFirstPosition
.getX();
1141 sal_Int32 nY1
= labelInfo
.aFirstPosition
.getY();
1142 sal_Int32 nX2
= nX1
;
1143 sal_Int32 nY2
= nY1
;
1144 ::basegfx::B2IRectangle
aRect( lcl_getRect( labelInfo
.xLabelGroupShape
) );
1145 if( nX1
< aRect
.getMinX() )
1146 nX2
= aRect
.getMinX();
1147 else if( nX1
> aRect
.getMaxX() )
1148 nX2
= aRect
.getMaxX();
1150 if( nY1
< aRect
.getMinY() )
1151 nY2
= aRect
.getMinY();
1152 else if( nY1
> aRect
.getMaxY() )
1153 nY2
= aRect
.getMaxY();
1155 //when the line is very short compared to the page size don't create one
1156 ::basegfx::B2DVector
aLength(nX1
-nX2
, nY1
-nY2
);
1157 if( (aLength
.getLength()/fPageDiagonaleLength
) < 0.01 )
1160 drawing::PointSequenceSequence
aPoints(1);
1161 aPoints
[0].realloc(2);
1162 aPoints
[0][0].X
= nX1
;
1163 aPoints
[0][0].Y
= nY1
;
1164 aPoints
[0][1].X
= nX2
;
1165 aPoints
[0][1].Y
= nY2
;
1167 uno::Reference
< beans::XPropertySet
> xProp( labelInfo
.xTextShape
, uno::UNO_QUERY
);
1170 sal_Int32 nColor
= 0;
1171 xProp
->getPropertyValue("CharColor") >>= nColor
;
1172 if( nColor
!= -1 )//automatic font color does not work for lines -> fallback to black
1173 aVLineProperties
.Color
<<= nColor
;
1175 m_pShapeFactory
->createLine2D( labelInfo
.xTextTarget
, aPoints
, &aVLineProperties
);
1181 /** Handle the placement of the label in the best fit case:
1182 * the routine try to place the label inside the related pie slice,
1183 * in case of success it returns true else returns false.
1187 * s: the bisector ray of the current pie slice
1188 * alpha: the angle between the horizontal axis and the bisector ray s
1189 * N: the vertex of the label b.b. which is nearest to C
1190 * F: the vertex of the label b.b. not adjacent to N; F lies on the pie border
1191 * P, Q: the intersection points between the label b.b. and the bisector ray s;
1192 * P is the one at minimum distance respect with C
1193 * e: the edge of the label b.b. where P lies (the nearest edge to C)
1194 * M: the vertex of e that is not N
1195 * G: the vertex of the label b.b. which is adjacent to N and that is not M
1196 * beta: the angle MPF
1197 * theta: the angle CPF
1204 * | G _________________________/____________________________ F
1218 * | | / . \ beta . |
1219 * | |__________/._\___|_______.____________________________|
1233 * __|/__|_____________________________________________________________
1238 * When alpha = 45k (k integer) s crosses the label b.b. at N exactly.
1239 * In such a case the nearest edge e is defined as the edge having N as the
1240 * start vertex and that is covered in the counterclockwise direction when
1241 * we move from N to the adjacent vertex.
1243 * The nearest vertex N is:
1244 * 1. the bottom left vertex when 0 < alpha < 90
1245 * 2. the bottom right vertex when 90 < alpha < 180
1246 * 3. the top right vertex when 180 < alpha < 270
1247 * 4. the top left vertex when 270 < alpha < 360.
1249 * The nearest edge e is:
1250 * 1. the left edge when −45 < alpha < 45
1251 * 2. the bottom edge when 45 < alpha <135
1252 * 3. the right edge when 135 < alpha < 225
1253 * 4. the top edge when 225 < alpha < 315.
1256 bool PieChart::performLabelBestFitInnerPlacement(ShapeParam
& rShapeParam
, PieLabelInfo
const & rPieLabelInfo
)
1258 SAL_INFO( "chart2.pie.label.bestfit.inside",
1259 "** PieChart::performLabelBestFitInnerPlacement invoked **" );
1261 // get pie slice properties
1262 double fStartAngleDeg
= NormAngle360(rShapeParam
.mfUnitCircleStartAngleDegree
);
1263 double fWidthAngleDeg
= rShapeParam
.mfUnitCircleWidthAngleDegree
;
1264 double fHalfWidthAngleDeg
= fWidthAngleDeg
/ 2.0;
1265 double fBisectingRayAngleDeg
= NormAngle360(fStartAngleDeg
+ fHalfWidthAngleDeg
);
1267 // get the middle point of the arc representing the pie slice border
1268 double fLogicZ
= rShapeParam
.mfLogicZ
+ 1.0;
1269 awt::Point aMiddleArcPoint
= PlottingPositionHelper::transformSceneToScreenPosition(
1270 m_pPosHelper
->transformUnitCircleToScene(
1271 fBisectingRayAngleDeg
,
1272 rShapeParam
.mfUnitCircleOuterRadius
,
1274 m_xLogicTarget
, m_pShapeFactory
, m_nDimension
);
1276 // compute the pie radius
1277 basegfx::B2IVector aPieCenter
= rPieLabelInfo
.aOrigin
;
1278 basegfx::B2IVector
aRadiusVector(
1279 aMiddleArcPoint
.X
- aPieCenter
.getX(),
1280 aMiddleArcPoint
.Y
- aPieCenter
.getY() );
1281 double fSquaredPieRadius
= aRadiusVector
.scalar(aRadiusVector
);
1282 double fPieRadius
= sqrt( fSquaredPieRadius
);
1284 // the bb is moved as much as possible near to the border of the pie,
1285 // anyway a small offset from the border is present (0.025 * pie radius)
1286 const double fPieBorderOffset
= 0.025;
1287 fPieRadius
= fPieRadius
- fPieRadius
* fPieBorderOffset
;
1289 SAL_INFO( "chart2.pie.label.bestfit.inside",
1291 SAL_INFO( "chart2.pie.label.bestfit.inside",
1292 " start angle = " << fStartAngleDeg
);
1293 SAL_INFO( "chart2.pie.label.bestfit.inside",
1294 " angle width = " << fWidthAngleDeg
);
1295 SAL_INFO( "chart2.pie.label.bestfit.inside",
1296 " bisecting ray angle = " << fBisectingRayAngleDeg
);
1297 SAL_INFO( "chart2.pie.label.bestfit.inside",
1298 " pie radius = " << fPieRadius
);
1299 SAL_INFO( "chart2.pie.label.bestfit.inside",
1300 " pie center = " << rPieLabelInfo
.aOrigin
);
1301 SAL_INFO( "chart2.pie.label.bestfit.inside",
1302 " middle arc point = (" << aMiddleArcPoint
.X
<< ","
1303 << aMiddleArcPoint
.Y
<< ")" );
1304 SAL_INFO( "chart2.pie.label.bestfit.inside",
1305 " label bounding box:" );
1306 SAL_INFO( "chart2.pie.label.bestfit.inside",
1307 " old anchor point = " << rPieLabelInfo
.aFirstPosition
);
1310 if( fPieRadius
== 0.0 )
1313 // get label b.b. width and height
1314 ::basegfx::B2IRectangle
aBb( lcl_getRect( rPieLabelInfo
.xLabelGroupShape
) );
1315 double fLabelWidth
= aBb
.getWidth();
1316 double fLabelHeight
= aBb
.getHeight();
1318 // -45 <= fAlphaDeg < 315
1319 double fAlphaDeg
= NormAngle360(fBisectingRayAngleDeg
+ 45) - 45;
1320 double fAlphaRad
= basegfx::deg2rad(fAlphaDeg
);
1322 // compute nearest edge index
1327 int nSectorIndex
= floor( (fAlphaDeg
+ 45) / 45.0 );
1328 int nNearestEdgeIndex
= nSectorIndex
/ 2;
1330 // compute lengths of the nearest edge and of the orthogonal edges
1331 double fNearestEdgeLength
= fLabelWidth
;
1332 double fOrthogonalEdgeLength
= fLabelHeight
;
1334 int nOrthogonalAxisIndex
= 1;
1335 if( nNearestEdgeIndex
% 2 == 0 ) // nearest edge is vertical
1337 fNearestEdgeLength
= fLabelHeight
;
1338 fOrthogonalEdgeLength
= fLabelWidth
;
1340 nOrthogonalAxisIndex
= 0;
1343 // compute the distance between N and P
1344 // such a distance is piece wise linear respect with alpha:
1345 // given 45k <= alpha < 45(k+1) we have
1346 // when k is even: d(N,P) = (length(e) / 2) * (1 - (alpha - 45k)/45)
1347 // when k is odd: d(N,P) = (length(e) / 2) * (1 - (45(k+1) - alpha)/45)
1348 int nIndex
= nSectorIndex
-1; // nIndex = -1...6
1349 double fIndexMod2
= (nIndex
+ 8) % 2; // fIndexMod2 must be non negative
1350 double fSgn
= 2.0 * (fIndexMod2
- 0.5); // 0 -> -1, 1 -> 1
1351 double fDistanceNP
= (fNearestEdgeLength
/ 2.0) * (1 + fSgn
* ((fAlphaDeg
- 45 * (nIndex
+ fIndexMod2
)) / 45.0));
1352 double fDistancePM
= fNearestEdgeLength
- fDistanceNP
;
1354 // compute the length of the diagonal vector d,
1355 // that is the distance between P and F
1356 double fSquaredDistancePF
= fDistancePM
* fDistancePM
+ fOrthogonalEdgeLength
* fOrthogonalEdgeLength
;
1357 double fDistancePF
= sqrt( fSquaredDistancePF
);
1359 SAL_INFO( "chart2.pie.label.bestfit.inside",
1360 " width = " << fLabelWidth
);
1361 SAL_INFO( "chart2.pie.label.bestfit.inside",
1362 " height = " << fLabelHeight
);
1363 SAL_INFO( "chart2.pie.label.bestfit.inside",
1364 " nearest edge index = " << nNearestEdgeIndex
);
1365 SAL_INFO( "chart2.pie.label.bestfit.inside",
1366 " alpha = " << fAlphaDeg
);
1367 SAL_INFO( "chart2.pie.label.bestfit.inside",
1368 " distance(N,P) = " << fDistanceNP
);
1369 SAL_INFO( "chart2.pie.label.bestfit.inside",
1370 " nIndex = " << nIndex
);
1371 SAL_INFO( "chart2.pie.label.bestfit.inside",
1372 " fIndexMod2 = " << fIndexMod2
);
1373 SAL_INFO( "chart2.pie.label.bestfit.inside",
1374 " fSgn = " << fSgn
);
1375 SAL_INFO( "chart2.pie.label.bestfit.inside",
1376 " distance(P,F) = " << fDistancePF
);
1379 // we check that the condition length(d) <= pie radius holds
1380 if (fDistancePF
> fPieRadius
)
1385 // compute beta: the angle of the diagonal vector d,
1386 // that is, the angle in P respect with the triangle PMF;
1387 // since both arguments are non negative the returned value is in [0, PI/2]
1388 double fBetaRad
= atan2( fOrthogonalEdgeLength
, fDistancePM
);
1390 // compute the theta angle, that is the angle in P
1391 // respect with the triangle CFP;
1392 // when the second intersection edge is opposite to the nearest edge,
1393 // theta depends on alpha and beta according to the following relation:
1394 // theta = f(alpha, beta) = s * alpha + 90 * (1 - s * i) + beta
1395 // where i is the nearest edge index and s is the sign of (alpha' - 45),
1396 // with alpha' = (alpha + 45) mod 90;
1397 // when the second intersection edge is adjacent to the nearest edge,
1398 // we have theta = 360 - f(alpha, beta);
1399 // note that in the former case 0 <= f(alpha, beta) <= 180,
1400 // whilst in the latter case 180 <= f(alpha, beta) <= 360;
1401 double fAlphaMod90
= fmod( fAlphaDeg
+ 45, 90.0 ) - 45;
1402 double fSign
= fAlphaMod90
== 0.0
1404 : ( fAlphaMod90
< 0 ) ? -1.0 : 1.0;
1405 double fThetaRad
= fSign
* fAlphaRad
+ M_PI_2
* (1 - fSign
* nNearestEdgeIndex
) + fBetaRad
;
1406 if( fThetaRad
> M_PI
)
1408 fThetaRad
= 2 * M_PI
- fThetaRad
;
1411 // compute the length of the positional vector,
1412 // that is the distance between C and P
1414 // when the bisector ray intersects the b.b. in F we have theta mod 180 == 0
1415 if( fmod(fThetaRad
, M_PI
) == 0.0 )
1417 fDistanceCP
= fPieRadius
- fDistancePF
;
1419 else // general case
1421 // we can compute d(C,P) by applying some trigonometric formula to
1422 // the triangle CFP : we know length(d) and length(r) = r and we have
1423 // computed the angle in P (theta); so named delta the angle in C and
1424 // gamma the angle in F, by the relation:
1427 // --------- = --------- = ---------
1428 // sin theta sin delta sin gamma
1430 // we get the wanted distance
1431 double fSinTheta
= sin( fThetaRad
);
1432 double fSinDelta
= fDistancePF
* fSinTheta
/ fPieRadius
;
1433 double fDeltaRad
= asin( fSinDelta
);
1434 double fGammaRad
= M_PI
- (fThetaRad
+ fDeltaRad
);
1435 double fSinGamma
= sin( fGammaRad
);
1436 fDistanceCP
= fPieRadius
* fSinGamma
/ fSinTheta
;
1439 // define the positional vector
1440 basegfx::B2DVector
aPositionalVector( cos(fAlphaRad
), sin(fAlphaRad
) );
1441 aPositionalVector
.setLength(fDistanceCP
);
1443 // we define a direction vector in order to know
1444 // in which quadrant we are working
1445 basegfx::B2DVector
aDirection(1.0, 1.0);
1446 if( 90 <= fBisectingRayAngleDeg
&& fBisectingRayAngleDeg
< 270 )
1448 aDirection
.setX(-1.0);
1450 if( fBisectingRayAngleDeg
>= 180 )
1452 aDirection
.setY(-1.0);
1455 // compute vertices N, M and G respect with pie center C
1456 basegfx::B2DVector
aNearestVertex(aPositionalVector
);
1457 aNearestVertex
[nAxisIndex
] += -aDirection
[nAxisIndex
] * fDistanceNP
;
1458 basegfx::B2DVector
aVertexM(aNearestVertex
);
1459 aVertexM
[nAxisIndex
] += aDirection
[nAxisIndex
] * fNearestEdgeLength
;
1460 basegfx::B2DVector
aVertexG(aNearestVertex
);
1461 aVertexG
[nOrthogonalAxisIndex
] += aDirection
[nOrthogonalAxisIndex
] * fOrthogonalEdgeLength
;
1463 SAL_INFO( "chart2.pie.label.bestfit.inside",
1464 " beta = " << basegfx::rad2deg(fBetaRad
) );
1465 SAL_INFO( "chart2.pie.label.bestfit.inside",
1466 " theta = " << basegfx::rad2deg(fThetaRad
) );
1467 SAL_INFO( "chart2.pie.label.bestfit.inside",
1468 " fAlphaMod90 = " << fAlphaMod90
);
1469 SAL_INFO( "chart2.pie.label.bestfit.inside",
1470 " fSign = " << fSign
);
1471 SAL_INFO( "chart2.pie.label.bestfit.inside",
1472 " distance(C,P) = " << fDistanceCP
);
1473 SAL_INFO( "chart2.pie.label.bestfit.inside",
1474 " direction vector = " << aDirection
);
1475 SAL_INFO( "chart2.pie.label.bestfit.inside",
1476 " N = " << aNearestVertex
);
1477 SAL_INFO( "chart2.pie.label.bestfit.inside",
1478 " M = " << aVertexM
);
1479 SAL_INFO( "chart2.pie.label.bestfit.inside",
1480 " G = " << aVertexG
);
1482 // in order to be able to place the label inside the pie slice we need
1483 // to check that each angle between s and the ray starting from C and
1484 // passing through a b.b. vertex is less than half width of the pie slice;
1485 // when the nearest edge e crosses a Cartesian axis it is sufficient
1486 // to test only the vertices belonging to e, else we need to test
1487 // the 2 vertices that aren't either N or F. Note that if a b.b. edge
1488 // crosses a Cartesian axis then it is the nearest edge to C
1490 // check the angle between CP and CM
1491 double fAngleRad
= aPositionalVector
.angle(aVertexM
);
1492 double fAngleDeg
= NormAngle360(basegfx::rad2deg(fAngleRad
));
1493 if( fAngleDeg
> 180 ) // in case the wrong angle has been computed
1494 fAngleDeg
= 360 - fAngleDeg
;
1495 SAL_INFO( "chart2.pie.label.bestfit.inside",
1496 " angle between CP and CM: " << fAngleDeg
);
1497 if( fAngleDeg
> fHalfWidthAngleDeg
)
1502 if( ( aNearestVertex
[nAxisIndex
] >= 0 && aVertexM
[nAxisIndex
] <= 0 )
1503 || ( aNearestVertex
[nAxisIndex
] <= 0 && aVertexM
[nAxisIndex
] >= 0 ) )
1505 // check the angle between CP and CN
1506 fAngleRad
= aPositionalVector
.angle(aNearestVertex
);
1507 fAngleDeg
= NormAngle360(basegfx::rad2deg(fAngleRad
));
1508 if( fAngleDeg
> 180 ) // in case the wrong angle has been computed
1509 fAngleDeg
= 360 - fAngleDeg
;
1510 SAL_INFO( "chart2.pie.label.bestfit.inside",
1511 " angle between CP and CN: " << fAngleDeg
);
1512 if( fAngleDeg
> fHalfWidthAngleDeg
)
1519 // check the angle between CP and CG
1520 fAngleRad
= aPositionalVector
.angle(aVertexG
);
1521 fAngleDeg
= NormAngle360(basegfx::rad2deg(fAngleRad
));
1522 if( fAngleDeg
> 180 ) // in case the wrong angle has been computed
1523 fAngleDeg
= 360 - fAngleDeg
;
1524 SAL_INFO( "chart2.pie.label.bestfit.inside",
1525 " angle between CP and CG: " << fAngleDeg
);
1526 if( fAngleDeg
> fHalfWidthAngleDeg
)
1532 // compute the b.b. center respect with the pie center
1533 basegfx::B2DVector
aBBCenter(aNearestVertex
);
1534 aBBCenter
[nAxisIndex
] += aDirection
[nAxisIndex
] * fNearestEdgeLength
/ 2;
1535 aBBCenter
[nOrthogonalAxisIndex
] += aDirection
[nOrthogonalAxisIndex
] * fOrthogonalEdgeLength
/ 2;
1537 // compute the b.b. anchor point
1538 basegfx::B2IVector aNewAnchorPoint
= aPieCenter
;
1539 aNewAnchorPoint
[0] += floor(aBBCenter
[0]);
1540 aNewAnchorPoint
[1] -= floor(aBBCenter
[1]); // the Y axis on the screen points downward
1542 // compute the translation vector for moving the label from the current
1543 // screen position to the new one
1544 basegfx::B2IVector aTranslationVector
= aNewAnchorPoint
- rPieLabelInfo
.aFirstPosition
;
1546 // compute the new screen position and move the label
1547 // XShape::getPosition returns the top left vertex of the b.b. of the shape
1548 awt::Point
aOldPos( rPieLabelInfo
.xLabelGroupShape
->getPosition() );
1549 awt::Point
aNewPos( aOldPos
.X
+ aTranslationVector
.getX(),
1550 aOldPos
.Y
+ aTranslationVector
.getY() );
1551 rPieLabelInfo
.xLabelGroupShape
->setPosition(aNewPos
);
1553 SAL_INFO( "chart2.pie.label.bestfit.inside",
1554 " center = " << aBBCenter
);
1555 SAL_INFO( "chart2.pie.label.bestfit.inside",
1556 " new anchor point = " << aNewAnchorPoint
);
1557 SAL_INFO( "chart2.pie.label.bestfit.inside",
1558 " translation vector = " << aTranslationVector
);
1559 SAL_INFO( "chart2.pie.label.bestfit.inside",
1560 " old position = (" << aOldPos
.X
<< "," << aOldPos
.Y
<< ")" );
1561 SAL_INFO( "chart2.pie.label.bestfit.inside",
1562 " new position = (" << aNewPos
.X
<< "," << aNewPos
.Y
<< ")" );
1567 /** Handle the placement of the label in the best fit case.
1568 * First off the routine try to place the label inside the related pie slice,
1569 * if this is not possible the label is placed outside.
1571 void PieChart::performLabelBestFit(ShapeParam
& rShapeParam
, PieLabelInfo
const & rPieLabelInfo
)
1576 if( !performLabelBestFitInnerPlacement(rShapeParam
, rPieLabelInfo
) )
1578 // If it does not fit inside, let's put it outside
1579 PolarLabelPositionHelper
aPolarPosHelper(m_pPosHelper
.get(),m_nDimension
,m_xLogicTarget
,m_pShapeFactory
);
1580 auto eAlignment
= LABEL_ALIGN_CENTER
;
1581 awt::Point
aScreenPosition2D(
1582 aPolarPosHelper
.getLabelScreenPositionAndAlignmentForUnitCircleValues(eAlignment
, css::chart::DataLabelPlacement::OUTSIDE
1583 , rShapeParam
.mfUnitCircleStartAngleDegree
, rShapeParam
.mfUnitCircleWidthAngleDegree
1584 , rShapeParam
.mfUnitCircleInnerRadius
, rShapeParam
.mfUnitCircleOuterRadius
, rShapeParam
.mfLogicZ
+0.5, 0 ));
1585 basegfx::B2IVector aTranslationVector
= rPieLabelInfo
.aFirstPosition
- rPieLabelInfo
.aOrigin
;
1586 aTranslationVector
.setLength(150);
1587 aScreenPosition2D
.X
+= aTranslationVector
.getX();
1588 aScreenPosition2D
.Y
+= aTranslationVector
.getY();
1589 rPieLabelInfo
.xLabelGroupShape
->setPosition(aScreenPosition2D
);
1595 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */