summaryrefslogtreecommitdiffstats
path: root/libkdchart/KDChartRingPainter.cpp
blob: ba1e6fed94c6b70c938c6759d189eff7187c18c4 (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
/* -*- Mode: C++ -*-
   KDChart - a multi-platform charting engine
   */

/****************************************************************************
 ** Copyright (C) 2001-2003 Klarälvdalens Datakonsult AB.  All rights reserved.
 **
 ** This file is part of the KDChart library.
 **
 ** This file may be distributed and/or modified under the terms of the
 ** GNU General Public License version 2 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.
 **
 ** Licensees holding valid commercial KDChart licenses may use this file in
 ** accordance with the KDChart Commercial License Agreement provided with
 ** the Software.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ** See http://www.klaralvdalens-datakonsult.se/?page=products for
 **   information about KDChart Commercial License Agreements.
 **
 ** Contact info@klaralvdalens-datakonsult.se if any conditions of this
 ** licensing are not clear to you.
 **
 **********************************************************************/
#include "KDChartRingPainter.h"
#include "KDChartParams.h"

#include <tqpainter.h>
#include <tqvaluestack.h>

#include <stdlib.h>

#define DEGTORAD(d) (d)*M_PI/180

/**
  \class KDChartRingPainter KDChartRingPainter.h

  \brief A chart painter implementation that can paint pie charts.

  PENDING(kalle) Write more documentation.
  */

/**
  Constructor. Sets up internal data structures as necessary.

  \param params the KDChartParams structure that defines the chart
  */
    KDChartRingPainter::KDChartRingPainter( KDChartParams* params ) :
KDChartPainter( params )
{
    // This constructor intentionally left blank so far; we cannot setup the
    // geometry yet since we do not know the size of the painter.
}


/**
  Destructor.
  */
KDChartRingPainter::~KDChartRingPainter()
{
    // intentionally left blank
}


/**
  Paints the actual data area.

  \param painter the TQPainter onto which the chart should be painted
  \param data the data that will be displayed as a chart
  \param paint2nd specifies whether the main chart or the additional chart is to be drawn now
  \param regions a pointer to a list of regions that will be filled
  with regions representing the data segments, if not null
  */
void KDChartRingPainter::paintData( TQPainter* painter,
        KDChartTableDataBase* data,
        bool paint2nd,
        KDChartDataRegionList* regions )
{
    uint chart = paint2nd ? 1 : 0;

    TQRect ourClipRect( _dataRect );

    const TQWMatrix & world = painter->worldMatrix();
    ourClipRect =
#if COMPAT_TQT_VERSION >= 0x030000
        world.mapRect( ourClipRect );
#else
    world.map( ourClipRect );
#endif

    ourClipRect.setTop(ourClipRect.top()-1);
    ourClipRect.setLeft(ourClipRect.left()-1);
    ourClipRect.setBottom(ourClipRect.bottom()+1);
    ourClipRect.setRight(ourClipRect.right()+1);
    painter->setClipRect( ourClipRect );

    uint datasetStart, datasetEnd;
    if ( params()->neverUsedSetChartSourceMode()
            || !params()->findDataset( KDChartParams::DataEntry,
                datasetStart,
                datasetEnd,
                chart ) ) {
        uint maxRow, maxRowMinus1;
        switch ( data->usedRows() ) {
            case 0:
                return ;
            case 1:
                maxRow = 0;
                maxRowMinus1 = 0;
                break;
            default:
                maxRow = data->usedRows() - 1;
                maxRowMinus1 = maxRow - 1;
        }
        datasetStart = paint2nd ? maxRow
            : 0;
        datasetEnd = paint2nd ? maxRow
            : ( ( KDChartParams::NoType
                        == params()->additionalChartType() )
                    ? maxRow
                    : maxRowMinus1 );
    }
    uint datasetNum = abs( (int)( datasetEnd - datasetStart ) + 1 );


    // Number of values: If -1, use all values, otherwise use the
    // specified number of values.
    if ( params()->numValues() != -1 )
        _numValues = params()->numValues();
    else
        _numValues = data->usedCols();

    // compute position
    _size = TQMIN( _dataRect.width(), _dataRect.height() ); // initial size
    // if the rings explode, we need to give them additional space =>
    // make the basic size smaller
    if ( params()->explode() ) {
        double doubleSize = ( double ) _size;
        doubleSize /= ( 1.0 + params()->explodeFactor() * 2 );
        _size = ( int ) doubleSize;
    }

    int x = ( _dataRect.width() == _size ) ? 0 : ( ( _dataRect.width() - _size ) / 2 );
    int y = ( _dataRect.height() == _size ) ? 0 : ( ( _dataRect.height() - _size ) / 2 );
    _position = TQRect( x, y, _size, _size );
    _position.moveBy( _dataRect.left(), _dataRect.top() );

    // We need the row sums anyway later, so we can just as well compute them
    // here, because we need them in case of relative ring thicknesses.
    TQMemArray<double> rowsums;
    double totalSum = 0.0;
    rowsums.resize( datasetEnd+1 ); // not datasetNum!
    for( int d1 = (int)datasetStart; d1 <= (int)datasetEnd; d1++ ) {
        rowsums[d1] = data->rowAbsSum( d1 );
        totalSum += rowsums[d1];
    }

    TQMemArray<int> ringthicknesses;
    ringthicknesses.resize( datasetEnd+1 ); // not datasetNum!

    // constant ring thickness
    int ringthickness = _size / ( datasetNum * 2 );
    // Never let the ring thickness be more than 1/10 of the size to
    // ensure "ringness"
    if( ringthickness > ( _size/10 ) )
        ringthickness = _size / 10;

    for( int d2 = (int)datasetStart; d2 <= (int)datasetEnd; d2++ )
        if( params()->relativeRingThickness() ) {
            // 50% should be the same thickness as the one used when ring
            // thickness is constant.
            ringthicknesses[d2] = (uint)floor( (rowsums[d2] / totalSum) *
                    ( 2.0 * (double)ringthickness ) + 0.5 );
        } else {
            ringthicknesses[d2] = ringthickness;
        }

    int currentouterradius = _size/2;

    // Loop through all the displayable datasets; each dataset is one ring
    for( int dataset = (int)datasetStart; dataset <= (int)datasetEnd; dataset++ ) {
        double sectorsPerValue = 5760.0 / rowsums[dataset]; // 5760 == 16*360, number of sections in TQt circle
        //int sectorsPerValueI = static_cast<int>( sectorsPerValue );
        double currentstartpos = (double)params()->ringStart() * 16.0;
        // Loop through all the values; each value is one piece on the ring.
        TQVariant vValY;
        for( int value = 0; value < _numValues; value++ ) {
            // is there anything at all at this value?
            double cellValue = 0.0;
            if( data->cellCoord( dataset, value, vValY, 1 ) &&
                TQVariant::Double == vValY.type() ){
                cellValue = fabs( vValY.toDouble() );
                // Explosion: Only explode if explosion is turned on generally
                // and we are on the first ring. Besides, if there is a list
                // of explodeable values, the current value must be on this
                // list.

                TQValueList<int> explodeList = params()->explodeValues();
                bool explode = params()->explode() && // explosion is on at all
                    ( dataset == (int)datasetStart ) && // outermost ring
                    ( ( explodeList.count() == 0 ) || // either nothing on explode list
                      ( explodeList.find( value ) != explodeList.end() ) ); // or pie is on it

                drawOneSegment( painter,
                        currentouterradius,
                        currentouterradius-ringthicknesses[dataset],
                        currentstartpos,
                        sectorsPerValue * cellValue,
                        dataset, value, chart, explode, regions );
            }
            currentstartpos += sectorsPerValue * cellValue;
        }
        currentouterradius -= ringthicknesses[dataset];
    }
}



void KDChartRingPainter::drawOneSegment( TQPainter* painter,
        uint outerRadius,
        uint innerRadius,
        double startAngle,
        double angles,
        uint dataset,
        uint value,
        uint chart,
        bool explode,
        KDChartDataRegionList* regions )
{
    // special case for full circle
    if( angles == 5760.0 )
        startAngle =  0.0;

    painter->setPen( TQPen( params()->outlineDataColor(),
                params()->outlineDataLineWidth() ) );
    painter->setBrush( params()->dataColor( value ) );

    uint outerRadius2 = outerRadius * 2;
    uint innerRadius2 = innerRadius * 2;

    TQRect drawPosition = _position;
    if ( explode ) {
        // need to compute a new position for each pie
        double explodeAngle = ( startAngle + angles / 2.0 ) / 16.0;
        double explodeAngleRad = DEGTORAD( explodeAngle );
        double cosAngle = cos( explodeAngleRad );
        double sinAngle = -sin( explodeAngleRad );

        // find the explode factor for this particular ring segment
        double explodeFactor = 0.0;
        TQMap<int,double> explodeFactors = params()->explodeFactors();
        if( !explodeFactors.contains( value ) ) // not on factors list, use default
            explodeFactor = params()->explodeFactor();
        else // on factors list, use segment-specific value
            explodeFactor = explodeFactors[value];

        double explodeX = explodeFactor * _size * cosAngle;
        double explodeY = explodeFactor * _size * sinAngle;
        drawPosition.moveBy( static_cast<int>( explodeX ), static_cast<int>( explodeY ) );
    }

    TQRect outerRect( drawPosition.x() +
            ( drawPosition.width() - outerRadius2 ) / 2,
            drawPosition.y() +
            ( drawPosition.height() - outerRadius2 ) / 2,
            outerRadius2, outerRadius2 );
    TQRect innerRect( drawPosition.x() +
            ( drawPosition.width() - innerRadius2 ) / 2,
            drawPosition.y() +
            ( drawPosition.height() - innerRadius2 ) / 2,
            innerRadius2, innerRadius2 );

    // Start with getting the points for the inner arc.
    TQPointArray innerArc;
    makeArc( innerArc, innerRect, startAngle, angles );

    // And the points for the outer arc
    TQPointArray outerArc;
    makeArc( outerArc, outerRect, startAngle, angles );

    // Now copy the points from the outer arc in the reverse order onto the
    // inner arc array and draw that.
    uint innerArcPoints = innerArc.size();
    uint outerArcPoints = outerArc.size();
    innerArc.resize( innerArcPoints + outerArcPoints );
    for ( int i = outerArcPoints - 1; i >= 0; i-- ) {
        innerArc.setPoint( innerArcPoints+outerArcPoints-i-1,
                outerArc.point( i ) );
    }

    painter->drawPolygon( innerArc );
    if ( regions /* && ( innerArc.size() > 2 )*/ ) {
        KDChartDataRegion* datReg = new KDChartDataRegion( dataset,
                                                           value,
                                                           chart,
                                                           innerArc );

        const int aA = static_cast<int>( startAngle );
        const int aM = static_cast<int>( startAngle + angles / 2.0 );
        const int aZ = static_cast<int>( startAngle + angles );

        datReg->points[ KDChartEnums::PosTopLeft ]
            = pointOnCircle( outerRect, aZ );
        datReg->points[ KDChartEnums::PosTopCenter ]
            = pointOnCircle( outerRect, aM );
        datReg->points[ KDChartEnums::PosTopRight ]
            = pointOnCircle( outerRect, aA );

        datReg->points[ KDChartEnums::PosBottomLeft ]
            = pointOnCircle( innerRect, aZ );
        datReg->points[ KDChartEnums::PosBottomCenter ]
            = pointOnCircle( innerRect, aM );
        datReg->points[ KDChartEnums::PosBottomRight ]
            = pointOnCircle( innerRect, aA );

        datReg->points[ KDChartEnums::PosCenterLeft ]
            = TQPoint( (   datReg->points[ KDChartEnums::PosTopLeft      ].x()
                        + datReg->points[ KDChartEnums::PosBottomLeft   ].x() ) / 2,
                      (   datReg->points[ KDChartEnums::PosTopLeft      ].y()
                        + datReg->points[ KDChartEnums::PosBottomLeft   ].y() ) / 2 );
        datReg->points[ KDChartEnums::PosCenter ]
            = TQPoint( (   datReg->points[ KDChartEnums::PosTopCenter    ].x()
                        + datReg->points[ KDChartEnums::PosBottomCenter ].x() ) / 2,
                      (   datReg->points[ KDChartEnums::PosTopCenter    ].y()
                        + datReg->points[ KDChartEnums::PosBottomCenter ].y() ) / 2 );
        datReg->points[ KDChartEnums::PosCenterRight ]
            = TQPoint( (   datReg->points[ KDChartEnums::PosTopRight     ].x()
                        + datReg->points[ KDChartEnums::PosBottomRight  ].x() ) / 2,
                      (   datReg->points[ KDChartEnums::PosTopRight     ].y()
                        + datReg->points[ KDChartEnums::PosBottomRight  ].y() ) / 2 );

        // test the 9 positions:
        /*
        painter->drawEllipse( datReg->points[ KDChartEnums::PosTopLeft     ].x() - 2,
                              datReg->points[ KDChartEnums::PosTopLeft     ].y() - 2,  5, 5);
        painter->drawEllipse( datReg->points[ KDChartEnums::PosCenterLeft  ].x() - 2,
                              datReg->points[ KDChartEnums::PosCenterLeft  ].y() - 2,  5, 5);
        painter->drawEllipse( datReg->points[ KDChartEnums::PosBottomLeft  ].x() - 2,
                              datReg->points[ KDChartEnums::PosBottomLeft  ].y() - 2,  5, 5);

        qDebug( "\ncenter: (%i, %i)",
                datReg->points[ KDChartEnums::PosCenter   ].x(),
                datReg->points[ KDChartEnums::PosCenter   ].y() );
        painter->drawEllipse( datReg->points[ KDChartEnums::PosTopCenter   ].x() - 2,
                              datReg->points[ KDChartEnums::PosTopCenter   ].y() - 2,  5, 5);
        painter->drawEllipse( datReg->points[ KDChartEnums::PosCenter      ].x() - 2,
                              datReg->points[ KDChartEnums::PosCenter      ].y() - 2,  5, 5);
        painter->drawEllipse( datReg->points[ KDChartEnums::PosBottomCenter].x() - 2,
                              datReg->points[ KDChartEnums::PosBottomCenter].y() - 2,  5, 5);

        painter->drawRect( datReg->points[ KDChartEnums::PosCenterRight ].x() - 2,
                              datReg->points[ KDChartEnums::PosCenterRight ].y() - 2,  5, 5);
        //painter->drawRect( datReg->points[ KDChartEnums::PosTopRight    ].x() - 2,
        //                    datReg->points[ KDChartEnums::PosTopRight    ].y() - 2,  5, 5);
        painter->drawRect( datReg->points[ KDChartEnums::PosBottomRight ].x() - 2,
                              datReg->points[ KDChartEnums::PosBottomRight ].y() - 2,  5, 5);
        */
        datReg->startAngle = static_cast<int>( startAngle );
        datReg->angleLen   = static_cast<int>( angles );
        regions->append( datReg );
    }
}


/**
  This method is a specialization that returns a fallback legend text
  appropriate for rings where the fallbacks should come from the values, not
  from the datasets.

  This method is only used when automatic legends are used, because
  manual and first-column legends do not need fallback texts.

  \param uint dataset the dataset number for which to generate a
  fallback text
  \return the fallback text to use for describing the specified
  dataset in the legend
  */
TQString KDChartRingPainter::fallbackLegendText( uint dataset ) const
{
    return TQObject::tr( "Item " ) + TQString::number( dataset + 1 );
}


/**
  This methods returns the number of elements to be shown in the
  legend in case fallback texts are used.

  This method is only used when automatic legends are used, because
  manual and first-column legends do not need fallback texts.

  \return the number of fallback texts to use
  */
uint KDChartRingPainter::numLegendFallbackTexts( KDChartTableDataBase* data ) const
{
    return data->usedCols();
}