pagepainter.cpp 31.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/***************************************************************************
 *   Copyright (C) 2005 by Enrico Ros <eros.kde@email.it>                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

// qt / kde includes
#include <qrect.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qimage.h>
#include <qapplication.h>
#include <kimageeffect.h>
17
#include <kiconloader.h>
18

19
20
21
// system includes
#include <math.h>

22
23
24
// local includes
#include "pagepainter.h"
#include "core/page.h"
25
#include "core/annotations.h"
26
#include "conf/settings.h"
27

Enrico Ros's avatar
Enrico Ros committed
28
29
void PagePainter::paintPageOnPainter( QPainter * destPainter, const KPDFPage * page,
    int pixID, int flags, int scaledWidth, int scaledHeight, const QRect & limits )
30
{
31
32
    /** 1 - RETRIEVE THE 'PAGE+ID' PIXMAP OR A SIMILAR 'PAGE' ONE **/
    const QPixmap * pixmap = 0;
33
34

    // if a pixmap is present for given id, use it
Enrico Ros's avatar
Enrico Ros committed
35
36
    if ( page->m_pixmaps.contains( pixID ) )
        pixmap = page->m_pixmaps[ pixID ];
37
38

    // else find the closest match using pixmaps of other IDs (great optim!)
39
    else if ( !page->m_pixmaps.isEmpty() )
40
41
42
43
44
45
    {
        int minDistance = -1;
        QMap< int,QPixmap * >::const_iterator it = page->m_pixmaps.begin(), end = page->m_pixmaps.end();
        for ( ; it != end; ++it )
        {
            int pixWidth = (*it)->width(),
46
                distance = pixWidth > scaledWidth ? pixWidth - scaledWidth : scaledWidth - pixWidth;
47
48
49
50
51
52
53
54
            if ( minDistance == -1 || distance < minDistance )
            {
                pixmap = *it;
                minDistance = distance;
            }
        }
    }

55
    /** 1B - IF NO PIXMAP, DRAW EMPTY PAGE **/
56
    double pixmapRescaleRatio = pixmap ? scaledWidth / (double)pixmap->width() : -1;
Enrico Ros's avatar
Enrico Ros committed
57
58
59
    long pixmapPixels = pixmap ? (long)pixmap->width() * (long)pixmap->height() : 0;
    if ( !pixmap || pixmapRescaleRatio > 20.0 || pixmapRescaleRatio < 0.25 ||
         (scaledWidth != pixmap->width() && pixmapPixels > 6000000L) )
60
61
62
63
64
65
66
67
68
69
    {
        if ( Settings::changeColors() &&
             Settings::renderMode() == Settings::EnumRenderMode::Paper )
            destPainter->fillRect( limits, Settings::paperColor() );
        else
            destPainter->fillRect( limits, Qt::white );

        // draw a cross (to  that the pixmap as not yet been loaded)
        // helps a lot on pages that take much to render
        destPainter->setPen( Qt::gray );
70
71
        destPainter->drawLine( 0, 0, scaledWidth-1, scaledHeight-1 );
        destPainter->drawLine( 0, scaledHeight-1, scaledWidth-1, 0 );
72
        // idea here: draw a hourglass (or kpdf icon :-) on top-left corner
73
74
75
        return;
    }

76
    /** 2 - FIND OUT WHAT TO PAINT (Flags + Configuration + Presence) **/
77
78
    bool canDrawHighlights = (flags & Highlights) && !page->m_highlights.isEmpty();
    bool canDrawAnnotations = (flags & Annotations) && !page->m_annotations.isEmpty();
79
80
    bool enhanceLinks = (flags & EnhanceLinks) && Settings::highlightLinks();
    bool enhanceImages = (flags & EnhanceImages) && Settings::highlightImages();
81
82
83
84
85
86
    // vectors containing objects to draw
    QValueList< HighlightRect * > * bufferedHighlights = 0;
    QValueList< Annotation * > * bufferedAnnotations = 0;
    QValueList< Annotation * > * unbufferedAnnotations = 0;
    // fill up lists with visible annotation/highlight objects
    if ( canDrawHighlights || canDrawAnnotations )
87
    {
88
        // precalc normalized 'limits rect' for intersection
89
90
91
92
        double nXMin = (double)limits.left() / (double)scaledWidth,
               nXMax = (double)limits.right() / (double)scaledWidth,
               nYMin = (double)limits.top() / (double)scaledHeight,
               nYMax = (double)limits.bottom() / (double)scaledHeight;
93
94
        // append all highlights inside limits to their list
        if ( canDrawHighlights )
95
        {
96
97
98
99
            QValueList< HighlightRect * >::const_iterator hIt = page->m_highlights.begin(), hEnd = page->m_highlights.end();
            for ( ; hIt != hEnd; ++hIt )
                if ( (*hIt)->intersects( nXMin, nYMin, nXMax, nYMax ) )
                {
100
101
102
                    if ( !bufferedHighlights )
                        bufferedHighlights = new QValueList< HighlightRect * >();
                    bufferedHighlights->append( *hIt );
103
104
                }
        }
105
106
        // append annotations inside limits to the un/buffered list
        if ( canDrawAnnotations )
107
108
109
110
        {
            QValueList< Annotation * >::const_iterator aIt = page->m_annotations.begin(), aEnd = page->m_annotations.end();
            for ( ; aIt != aEnd; ++aIt )
            {
111
112
                Annotation * ann = *aIt;
                if ( ann->boundary.intersects( nXMin, nYMin, nXMax, nYMax ) )
113
                {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
                    Annotation::SubType type = ann->subType();
                    if ( type == Annotation::ALine || type == Annotation::AHighlight ||
                         type == Annotation::AInk  /*|| (type == Annotation::AGeom && ann->style.opacity < 0.99)*/ )
                    {
                        if ( !bufferedAnnotations )
                            bufferedAnnotations = new QValueList< Annotation * >();
                        bufferedAnnotations->append( ann );
                    }
                    else
                    {
                        if ( !unbufferedAnnotations )
                            unbufferedAnnotations = new QValueList< Annotation * >();
                        unbufferedAnnotations->append( ann );
                    }
128
                }
129
130
            }
        }
131
        // end of intersections checking
132
    }
133

134
    /** 3 - ENABLE BACKBUFFERING IF DIRECT IMAGE MANIPULATION IS NEEDED **/
135
136
    bool bufferAccessibility = (flags & Accessibility) && Settings::changeColors() && (Settings::renderMode() != Settings::EnumRenderMode::Paper);
    bool useBackBuffer = bufferAccessibility || bufferedHighlights || bufferedAnnotations;
137
    QPixmap * backPixmap = 0;
138
    QPainter * mixedPainter = 0;
139
140
141

    /** 4A -- REGULAR FLOW. PAINT PIXMAP NORMAL OR RESCALED USING GIVEN QPAINTER **/
    if ( !useBackBuffer )
142
    {
143
        // 4A.1. if size is ok, draw the page pixmap using painter
144
        if ( pixmap->width() == scaledWidth && pixmap->height() == scaledHeight )
145
146
147
148
149
            destPainter->drawPixmap( limits.topLeft(), *pixmap, limits );
        // else draw a scaled portion of the magnified pixmap
        else
        {
            QImage destImage;
Enrico Ros's avatar
Enrico Ros committed
150
            scalePixmapOnImage( destImage, pixmap, scaledWidth, scaledHeight, limits );
151
152
153
            destPainter->drawPixmap( limits.left(), limits.top(), destImage, 0, 0,
                                     limits.width(),limits.height() );
        }
154

155
        // 4A.2. active painter is the one passed to this method
156
        mixedPainter = destPainter;
157
158
    }
    /** 4B -- BUFFERED FLOW. IMAGE PAINTING + OPERATIONS. QPAINTER OVER PIXMAP  **/
159
160
    else
    {
161
162
        // the image over which we are going to draw
        QImage backImage;
163

164
        // 4B.1. draw the page pixmap: normal or scaled
165
        if ( pixmap->width() == scaledWidth && pixmap->height() == scaledHeight )
Enrico Ros's avatar
Enrico Ros committed
166
            cropPixmapOnImage( backImage, pixmap, limits );
167
        else
Enrico Ros's avatar
Enrico Ros committed
168
            scalePixmapOnImage( backImage, pixmap, scaledWidth, scaledHeight, limits );
169
170

        // 4B.2. modify pixmap following accessibility settings
171
        if ( bufferAccessibility )
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
            switch ( Settings::renderMode() )
            {
                case Settings::EnumRenderMode::Inverted:
                    // Invert image pixels using QImage internal function
                    backImage.invertPixels(false);
                    break;
                case Settings::EnumRenderMode::Recolor:
                    // Recolor image using KImageEffect::flatten with dither:0
                    KImageEffect::flatten( backImage, Settings::recolorForeground(), Settings::recolorBackground() );
                    break;
                case Settings::EnumRenderMode::BlackWhite:
                    // Manual Gray and Contrast
                    unsigned int * data = (unsigned int *)backImage.bits();
                    int val, pixels = backImage.width() * backImage.height(),
                        con = Settings::bWContrast(), thr = 255 - Settings::bWThreshold();
                    for( int i = 0; i < pixels; ++i )
                    {
                        val = qGray( data[i] );
                        if ( val > thr )
                            val = 128 + (127 * (val - thr)) / (255 - thr);
                        else if ( val < thr )
                            val = (128 * val) / thr;
                        if ( con > 2 )
                        {
                            val = con * ( val - thr ) / 2 + thr;
                            if ( val > 255 )
                                val = 255;
                            else if ( val < 0 )
                                val = 0;
                        }
                        data[i] = qRgba( val, val, val, 255 );
                    }
                    break;
            }
        }
208
        // 4B.3. highlight rects in page
209
        if ( bufferedHighlights )
210
211
        {
            // draw highlights that are inside the 'limits' paint region
212
            QValueList< HighlightRect * >::const_iterator hIt = bufferedHighlights->begin(), hEnd = bufferedHighlights->end();
213
214
215
            for ( ; hIt != hEnd; ++hIt )
            {
                HighlightRect * r = *hIt;
216
217
218
219
220
221
222
223
224
225
226
227
                // find out the rect to highlight on pixmap
                QRect highlightRect = r->geometry( scaledWidth, scaledHeight ).intersect( limits );
                highlightRect.moveBy( -limits.left(), -limits.top() );

                // highlight composition (product: highlight color * destcolor)
                unsigned int * data = (unsigned int *)backImage.bits();
                int val, newR, newG, newB,
                    rh = r->color.red(),
                    gh = r->color.green(),
                    bh = r->color.blue(),
                    offset = highlightRect.top() * backImage.width();
                for( int y = highlightRect.top(); y <= highlightRect.bottom(); ++y )
228
                {
229
                    for( int x = highlightRect.left(); x <= highlightRect.right(); ++x )
230
                    {
231
232
233
234
235
                        val = data[ x + offset ];
                        newR = (qRed(val) * rh) / 255;
                        newG = (qGreen(val) * gh) / 255;
                        newB = (qBlue(val) * bh) / 255;
                        data[ x + offset ] = qRgba( newR, newG, newB, 255 );
236
                    }
237
                    offset += backImage.width();
238
                }
239
            }
240
        }
241
        // 4B.4. paint annotations [COMPOSITED ONES]
242
        if ( bufferedAnnotations )
243
        {
Enrico Ros's avatar
Enrico Ros committed
244
            // precalc costants for normalizing the quads to the image
245
246
247
248
249
            double pageScale = (double)scaledWidth / page->width();
            double xOffset = (double)limits.left() / (double)scaledWidth,
                   xScale = (double)scaledWidth / (double)limits.width(),
                   yOffset = (double)limits.top() / (double)scaledHeight,
                   yScale = (double)scaledHeight / (double)limits.height();
Enrico Ros's avatar
Enrico Ros committed
250
251

            // paint all buffered annotations in the page
252
253
254
255
256
257
            QValueList< Annotation * >::const_iterator aIt = bufferedAnnotations->begin(), aEnd = bufferedAnnotations->end();
            for ( ; aIt != aEnd; ++aIt )
            {
                Annotation * a = *aIt;
                Annotation::SubType type = a->subType();

Enrico Ros's avatar
Enrico Ros committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
                // draw TextAnnotation (InPlace) MISSING: all
                if ( type == Annotation::AText )
                {
                    // TODO
                }
                // draw LineAnnotation MISSING: all
                else if ( type == Annotation::ALine )
                {
                    // TODO
                    // get the annotation
                    /*LineAnnotation * la = (LineAnnotation *) a;

                    NormalizedPath path;
                    // normalize page point to image
                    const NormalizedPoint & inkPoint = *pIt;
                    NormalizedPoint point;
                    point.x = (inkPoint.x - xOffset) * xScale;
                    point.y = (inkPoint.y - yOffset) * yScale;
                    path.append( point );
                    // draw the normalized path into image
278
                    drawShapeOnImage( backImage, path, false, QPen( a->style.color ), QBrush(), pageScale );
Enrico Ros's avatar
Enrico Ros committed
279
280
281
282
283
284
285
286
287
                    */
                }
                // draw GeomAnnotation MISSING: all
                else if ( type == Annotation::AGeom )
                {
                    // TODO
                }
                // draw HighlightAnnotation MISSING: under/strike width, feather, capping
                else if ( type == Annotation::AHighlight )
288
289
290
                {
                    // get the annotation
                    HighlightAnnotation * ha = (HighlightAnnotation *) a;
Enrico Ros's avatar
Enrico Ros committed
291
                    HighlightAnnotation::HighlightType type = ha->highlightType;
292
293

                    // draw each quad of the annotation
Enrico Ros's avatar
Enrico Ros committed
294
                    int quads = ha->highlightQuads.size();
295
296
297
298
                    for ( int q = 0; q < quads; q++ )
                    {
                        NormalizedPath path;
                        const HighlightAnnotation::Quad & quad = ha->highlightQuads[ q ];
Enrico Ros's avatar
Enrico Ros committed
299
                        // normalize page point to image
300
301
302
303
304
305
306
                        for ( int i = 0; i < 4; i++ )
                        {
                            NormalizedPoint point;
                            point.x = (quad.points[ i ].x - xOffset) * xScale;
                            point.y = (quad.points[ i ].y - yOffset) * yScale;
                            path.append( point );
                        }
Enrico Ros's avatar
Enrico Ros committed
307
308
309
310
311
                        // draw the normalized path into image
                        switch ( type )
                        {
                            // highlight the whole rect
                            case HighlightAnnotation::Highlight:
312
                                drawShapeOnImage( backImage, path, true, QPen(), a->style.color, pageScale, Multiply );
Enrico Ros's avatar
Enrico Ros committed
313
314
315
316
317
318
319
                                break;
                            // highlight the bottom part of the rect
                            case HighlightAnnotation::Squiggly:
                                path[ 0 ].x = ( path[ 0 ].x + path[ 3 ].x ) / 2.0;
                                path[ 0 ].y = ( path[ 0 ].y + path[ 3 ].y ) / 2.0;
                                path[ 1 ].x = ( path[ 1 ].x + path[ 2 ].x ) / 2.0;
                                path[ 1 ].y = ( path[ 1 ].y + path[ 2 ].y ) / 2.0;
320
                                drawShapeOnImage( backImage, path, true, QPen(), a->style.color, pageScale, Multiply );
Enrico Ros's avatar
Enrico Ros committed
321
322
323
324
325
326
327
328
329
                                break;
                            // make a line at 3/4 of the height
                            case HighlightAnnotation::Underline:
                                path[ 0 ].x = ( path[ 0 ].x + 3*path[ 3 ].x ) / 4.0;
                                path[ 0 ].y = ( path[ 0 ].y + 3*path[ 3 ].y ) / 4.0;
                                path[ 1 ].x = ( path[ 1 ].x + 3*path[ 2 ].x ) / 4.0;
                                path[ 1 ].y = ( path[ 1 ].y + 3*path[ 2 ].y ) / 4.0;
                                path.pop_back();
                                path.pop_back();
330
                                drawShapeOnImage( backImage, path, false, QPen( a->style.color, 2 ), QBrush(), pageScale );
Enrico Ros's avatar
Enrico Ros committed
331
332
333
334
335
336
337
338
339
                                break;
                            // make a line at 1/2 of the height
                            case HighlightAnnotation::StrikeOut:
                                path[ 0 ].x = ( path[ 0 ].x + path[ 3 ].x ) / 2.0;
                                path[ 0 ].y = ( path[ 0 ].y + path[ 3 ].y ) / 2.0;
                                path[ 1 ].x = ( path[ 1 ].x + path[ 2 ].x ) / 2.0;
                                path[ 1 ].y = ( path[ 1 ].y + path[ 2 ].y ) / 2.0;
                                path.pop_back();
                                path.pop_back();
340
                                drawShapeOnImage( backImage, path, false, QPen( a->style.color, 2 ), QBrush(), pageScale );
Enrico Ros's avatar
Enrico Ros committed
341
342
                                break;
                        }
343
344
                    }
                }
Enrico Ros's avatar
Enrico Ros committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
                // draw InkAnnotation MISSING:invar width, PENTRACER
                else if ( type == Annotation::AInk )
                {
                    // get the annotation
                    InkAnnotation * ia = (InkAnnotation *) a;

                    // draw each ink path
                    int paths = ia->inkPaths.size();
                    for ( int p = 0; p < paths; p++ )
                    {
                        NormalizedPath path;
                        const QValueList<NormalizedPoint> & inkPath = ia->inkPaths[ p ];

                        // normalize page point to image
                        QValueList<NormalizedPoint>::const_iterator pIt = inkPath.begin(), pEnd = inkPath.end();
                        for ( ; pIt != pEnd; ++pIt )
                        {
                            const NormalizedPoint & inkPoint = *pIt;
                            NormalizedPoint point;
                            point.x = (inkPoint.x - xOffset) * xScale;
                            point.y = (inkPoint.y - yOffset) * yScale;
                            path.append( point );
                        }
                        // draw the normalized path into image
369
                        drawShapeOnImage( backImage, path, false, QPen( a->style.color, a->style.width ), QBrush(), pageScale );
Enrico Ros's avatar
Enrico Ros committed
370
371
372
373
                    }
                }
            } // end current annotation drawing
        }
374
375
376
377
378

        // 4B.5. create the back pixmap converting from the local image
        backPixmap = new QPixmap( backImage );

        // 4B.6. create a painter over the pixmap and set it as the active one
379
380
        mixedPainter = new QPainter( backPixmap );
        mixedPainter->translate( -limits.left(), -limits.top() );
381
382
    }

383
    /** 5 -- MIXED FLOW. Draw ANNOTATIONS [OPAQUE ONES] on ACTIVE PAINTER  **/
384
    if ( unbufferedAnnotations )
385
    {
386
387
        // iterate over annotations and paint AText, AGeom, AStamp
        QValueList< Annotation * >::const_iterator aIt = unbufferedAnnotations->begin(), aEnd = unbufferedAnnotations->end();
388
389
390
        for ( ; aIt != aEnd; ++aIt )
        {
            Annotation * a = *aIt;
391

392
393
394
            // honour opacity settings on supported types
            unsigned int opacity = (unsigned int)( 255.0 * a->style.opacity );
            if ( opacity <= 0 )
395
396
                continue;

397
398
399
400
401
            // get annotation boundary and drawn rect
            QRect annotBoundary = a->boundary.geometry( scaledWidth, scaledHeight );
            QRect annotRect = annotBoundary.intersect( limits );
            QRect innerRect( annotRect.left() - annotBoundary.left(), annotRect.top() -
                    annotBoundary.top(), annotRect.width(), annotRect.height() );
402
403
404

            Annotation::SubType type = a->subType();

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
            // draw TextAnnotation (only the 'Linked' variant)
            if ( type == Annotation::AText )
            {
                TextAnnotation * text = (TextAnnotation *)a;
                if ( text->textType != TextAnnotation::Linked )
                    continue;

                // get pixmap, colorize and alpha-blend it
                QPixmap pixmap = DesktopIcon( text->textIcon );
                QImage scaledImage;
                scalePixmapOnImage( scaledImage, &pixmap, annotBoundary.width(),
                    annotBoundary.height(), innerRect );
                colorizeImage( scaledImage, a->style.color, opacity );
                scaledImage.setAlphaBuffer( true );
                pixmap.convertFromImage( scaledImage );

                // draw the mangled image to painter
                mixedPainter->drawPixmap( annotRect.topLeft(), pixmap );
            }
            // draw StampAnnotation
            else if ( type == Annotation::AStamp )
            {
                StampAnnotation * stamp = (StampAnnotation *)a;

                // get pixmap and alpha blend it if needed
                QPixmap pixmap = DesktopIcon( stamp->stampIconName );
                QImage scaledImage;
                scalePixmapOnImage( scaledImage, &pixmap, annotBoundary.width(),
                                    annotBoundary.height(), innerRect );
                if ( opacity < 255 )
                    changeImageAlpha( scaledImage, opacity );
                scaledImage.setAlphaBuffer( true );
                pixmap.convertFromImage( scaledImage );

                // draw the scaled and al
                mixedPainter->drawPixmap( annotRect.topLeft(), pixmap );
            }
            // draw GeomAnnotation
Enrico Ros's avatar
Enrico Ros committed
443
            else // WARNING: TEMPORARY CODE! migrate everything to AGG
444
            {
445
                //GeomAnnotation * geom = (GeomAnnotation *)a;
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                //if ( geom->geomType == GeomAnnotation::InscribedSquare )
                //{
                    QImage rectImage( innerRect.width(), innerRect.height(), 32 );
                    const QColor & c = a->style.color;
                    unsigned int color = qRgba( c.red(), c.green(), c.blue(), opacity );
                    rectImage.fill( color );
                    rectImage.setAlphaBuffer( true );
                    QPixmap pixmap( rectImage );
                    mixedPainter->drawPixmap( annotRect.topLeft(), pixmap );
                //}
                //else if ( geom->geomType == GeomAnnotation::InscribedCircle )
            }

            // draw extents rectangle
            if ( Settings::debugDrawAnnotationRect() )
            {
                mixedPainter->setPen( a->style.color );
                mixedPainter->drawRect( annotBoundary );
464
            }
465
466
467
        }
    }

468
    /** 6 -- MIXED FLOW. Draw LINKS+IMAGES BORDER on ACTIVE PAINTER  **/
469
    if ( enhanceLinks || enhanceImages )
470
471
472
473
474
475
476
    {
        QColor normalColor = QApplication::palette().active().highlight();
        QColor lightColor = normalColor.light( 140 );
        // enlarging limits for intersection is like growing the 'rectGeometry' below
        QRect limitsEnlarged = limits;
        limitsEnlarged.addCoords( -2, -2, 2, 2 );
        // draw rects that are inside the 'limits' paint region as opaque rects
477
        QValueList< ObjectRect * >::const_iterator lIt = page->m_rects.begin(), lEnd = page->m_rects.end();
478
479
        for ( ; lIt != lEnd; ++lIt )
        {
480
481
482
            ObjectRect * rect = *lIt;
            if ( (enhanceLinks && rect->objectType() == ObjectRect::Link) ||
                 (enhanceImages && rect->objectType() == ObjectRect::Image) )
483
            {
484
                QRect rectGeometry = rect->geometry( scaledWidth, scaledHeight );
485
486
487
488
                if ( rectGeometry.intersects( limitsEnlarged ) )
                {
                    // expand rect and draw inner border
                    rectGeometry.addCoords( -1,-1,1,1 );
489
490
                    mixedPainter->setPen( lightColor );
                    mixedPainter->drawRect( rectGeometry );
491
492
                    // expand rect to draw outer border
                    rectGeometry.addCoords( -1,-1,1,1 );
493
494
                    mixedPainter->setPen( normalColor );
                    mixedPainter->drawRect( rectGeometry );
495
496
497
498
499
                }
            }
        }
    }

500
501
    /** 7 -- BUFFERED FLOW. Copy BACKPIXMAP on DESTINATION PAINTER **/
    if ( useBackBuffer )
502
    {
503
        delete mixedPainter;
504
505
506
        destPainter->drawPixmap( limits.left(), limits.top(), *backPixmap );
        delete backPixmap;
    }
507
508
509
510
511

    // delete object containers
    delete bufferedHighlights;
    delete bufferedAnnotations;
    delete unbufferedAnnotations;
512
}
513
514


515
/** Private Helpers :: Pixmap conversion **/
Enrico Ros's avatar
Enrico Ros committed
516
void PagePainter::cropPixmapOnImage( QImage & dest, const QPixmap * src, const QRect & r )
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
{
    // handle quickly the case in which the whole pixmap has to be converted
    if ( r == QRect( 0, 0, src->width(), src->height() ) )
    {
        dest = src->convertToImage();
    }
    // else copy a portion of the src to an internal pixmap (smaller) and convert it
    else
    {
        QPixmap croppedPixmap( r.width(), r.height() );
        copyBlt( &croppedPixmap, 0, 0, src, r.left(), r.top(), r.width(), r.height() );
        dest = croppedPixmap.convertToImage();
    }
}

Enrico Ros's avatar
Enrico Ros committed
532
void PagePainter::scalePixmapOnImage ( QImage & dest, const QPixmap * src,
533
    int scaledWidth, int scaledHeight, const QRect & cropRect )
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
{
    // {source, destination, scaling} params
    int srcWidth = src->width(),
        srcHeight = src->height(),
        destLeft = cropRect.left(),
        destTop = cropRect.top(),
        destWidth = cropRect.width(),
        destHeight = cropRect.height();

    // destination image (same geometry as the pageLimits rect)
    dest = QImage( destWidth, destHeight, 32 );
    unsigned int * destData = (unsigned int *)dest.bits();

    // source image (1:1 conversion from pixmap)
    QImage srcImage = src->convertToImage();
    unsigned int * srcData = (unsigned int *)srcImage.bits();

    // precalc the x correspondancy conversion in a lookup table
    unsigned int xOffset[ destWidth ];
    for ( int x = 0; x < destWidth; x++ )
554
        xOffset[ x ] = ((x + destLeft) * srcWidth) / scaledWidth;
555
556
557
558
559

    // for each pixel of the destination image apply the color of the
    // corresponsing pixel on the source image (note: keep parenthesis)
    for ( int y = 0; y < destHeight; y++ )
    {
560
        unsigned int srcOffset = srcWidth * (((destTop + y) * srcHeight) / scaledHeight);
561
562
563
564
        for ( int x = 0; x < destWidth; x++ )
            (*destData++) = srcData[ srcOffset + xOffset[x] ];
    }
}
565
566

/** Private Helpers :: Image Drawing **/
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
// from Arthur - qt4
inline int qt_div_255(int x) { return (x + (x>>8) + 0x80) >> 8; }

void PagePainter::changeImageAlpha( QImage & image, unsigned int destAlpha )
{
    // iterate over all pixels changing the alpha component value
    unsigned int * data = (unsigned int *)image.bits();
    unsigned int pixels = image.width() * image.height();

    int source, sourceAlpha;
    for( register unsigned int i = 0; i < pixels; ++i )
    {   // optimize this loop keeping byte order into account
        source = data[i];
        if ( (sourceAlpha = qAlpha( source )) == 255 )
        {
            // use destAlpha
            data[i] = qRgba( qRed(source), qGreen(source), qBlue(source), destAlpha );
        }
        else
        {
            // use destAlpha * sourceAlpha product
            sourceAlpha = qt_div_255( destAlpha * sourceAlpha );
            data[i] = qRgba( qRed(source), qGreen(source), qBlue(source), sourceAlpha );
        }
    }
}

void PagePainter::colorizeImage( QImage & grayImage, const QColor & color,
    unsigned int destAlpha )
{
    // iterate over all pixels changing the alpha component value
    unsigned int * data = (unsigned int *)grayImage.bits();
    unsigned int pixels = grayImage.width() * grayImage.height();
    int red = color.red(),
        green = color.green(),
        blue = color.blue();

    int source, sourceSat, sourceAlpha;
    for( register unsigned int i = 0; i < pixels; ++i )
    {   // optimize this loop keeping byte order into account
        source = data[i];
        sourceSat = qRed( source );
        int newR = qt_div_255( sourceSat * red ),
            newG = qt_div_255( sourceSat * green ),
            newB = qt_div_255( sourceSat * blue );
        if ( (sourceAlpha = qAlpha( source )) == 255 )
        {
            // use destAlpha
            data[i] = qRgba( newR, newG, newB, destAlpha );
        }
        else
        {
            // use destAlpha * sourceAlpha product
            if ( destAlpha < 255 )
                sourceAlpha = qt_div_255( destAlpha * sourceAlpha );
            data[i] = qRgba( newR, newG, newB, sourceAlpha );
        }
    }
}
626

Enrico Ros's avatar
Enrico Ros committed
627
628
629
630
631
632
//BEGIN of Anti-Grain dependant code
/** Shape Drawing using Anti-Grain Geometry library **/
// The following code uses the AGG2.3 lib imported into the "painter_agg2"
// directory. This is to be replaced by Arthur calls for drawing antialiased
// primitives, but until that AGG2 does its job very fast and good-looking.

Enrico Ros's avatar
Enrico Ros committed
633
#include "kpdf_pixfmt_rgba.h"
Enrico Ros's avatar
Enrico Ros committed
634
635
636
637
638
639
640
641
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_scanline_u.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_renderer_scanline.h"
#include "agg_conv_stroke.h"
#include "agg_path_storage.h"

642
643
void PagePainter::drawShapeOnImage(
    QImage & image,
Enrico Ros's avatar
Enrico Ros committed
644
645
    const NormalizedPath & normPath,
    bool closeShape,
646
647
    const QPen & pen,
    const QBrush & brush,
648
    double penWidthMultiplier,
Enrico Ros's avatar
Enrico Ros committed
649
    RasterOperation op
Enrico Ros's avatar
Enrico Ros committed
650
651
    //float antiAliasRadius
    )
652
653
{
    // safety checks
Enrico Ros's avatar
Enrico Ros committed
654
655
    int pointsNumber = normPath.size();
    if ( pointsNumber < 2 )
656
657
        return;

Enrico Ros's avatar
Enrico Ros committed
658
659
660
661
662
663
664
665
666
667
    int imageWidth = image.width();
    int imageHeight = image.height();
    double fImageWidth = (double)imageWidth;
    double fImageHeight = (double)imageHeight;

    // create a 'path'
    agg::path_storage path;
    path.move_to( normPath[ 0 ].x * fImageWidth, normPath[ 0 ].y * fImageHeight );
    for ( int i = 1; i < pointsNumber; i++ )
        path.line_to( normPath[ i ].x * fImageWidth, normPath[ i ].y * fImageHeight );
Enrico Ros's avatar
Enrico Ros committed
668
669
        //path.curve4( normPath[ i ].x * fImageWidth + 2, normPath[ i ].y * fImageHeight - 2,
        //             normPath[ i ].x * fImageWidth, normPath[ i ].y * fImageHeight );
Enrico Ros's avatar
Enrico Ros committed
670
671
672
673
674
675
676
677
    if ( closeShape )
        path.close_polygon();

    // create the 'rendering buffer' over qimage memory
    agg::rendering_buffer buffer( image.bits(), imageWidth, imageHeight, imageWidth << 2 );
    // create 'pixel buffer', 'clipped renderer', 'scanline renderer' on bgra32 format
    typedef agg::pixfmt_bgra32 bgra32;
    typedef agg::renderer_base< bgra32 > rb_bgra32;
Enrico Ros's avatar
Enrico Ros committed
678
679
    bgra32 pixels( buffer, op == Multiply ? 1 : 0 );
    rb_bgra32 rb( pixels );
Enrico Ros's avatar
Enrico Ros committed
680
681
682
683
684
685
686
687
688
    agg::renderer_scanline_aa_solid< rb_bgra32 > render( rb );
    // create rasterizer and scaline
    agg::rasterizer_scanline_aa<> rasterizer;
    agg::scanline_u8 scanline;

#if 0
    //draw RAINBOW
    agg::rgba8 span[ imageWidth ];
    for( int x = 0; x < imageWidth; x++ )
689
    {
Enrico Ros's avatar
Enrico Ros committed
690
691
        agg::rgba c( 380.0 + 400.0 * x / imageWidth, 0.8 );
        span[ x ] = agg::rgba8(c);
692
    }
Enrico Ros's avatar
Enrico Ros committed
693
    for( int y = 0; y < imageHeight; y++ )
Enrico Ros's avatar
Enrico Ros committed
694
        pixels.blend_color_hspan( 0, y, imageWidth, span, 0, (123*y)/imageHeight );
Enrico Ros's avatar
Enrico Ros committed
695
#endif
696

Enrico Ros's avatar
Enrico Ros committed
697
698
    // fill rect
    if ( brush.style() != Qt::NoBrush )
699
    {
Enrico Ros's avatar
Enrico Ros committed
700
701
702
703
704
        const QColor & brushColor = brush.color();
        render.color( agg::rgba8( brushColor.red(), brushColor.green(), brushColor.blue() ) );
        rasterizer.add_path( path );
        agg::render_scanlines( rasterizer, scanline, render );
        rasterizer.reset();
705
706
    }

Enrico Ros's avatar
Enrico Ros committed
707
    // stroke outline
708
709
    double penWidth = (double)pen.width() * penWidthMultiplier;
    if ( penWidth > 0.1 )
710
    {
Enrico Ros's avatar
Enrico Ros committed
711
712
        const QColor & penColor = pen.color();
        render.color( agg::rgba8( penColor.red(), penColor.green(), penColor.blue() ) );
Enrico Ros's avatar
Enrico Ros committed
713
714
715
716
717
718
719
#if 0
        // BSPLINE curve over path
        typedef agg::conv_bspline< agg::path_storage > conv_bspline_type;
        conv_bspline_type bspline( path );
        bspline.interpolation_step( 0.2 );
        agg::conv_stroke< conv_bspline_type > strokedPath( bspline );
#else
Enrico Ros's avatar
Enrico Ros committed
720
        agg::conv_stroke< agg::path_storage > strokedPath( path );
721
#endif
722
        strokedPath.width( penWidth );
Enrico Ros's avatar
Enrico Ros committed
723
724
        rasterizer.add_path( strokedPath );
        agg::render_scanlines( rasterizer, scanline, render );
725
726
    }
}
Enrico Ros's avatar
Enrico Ros committed
727
728

//END of Anti-Grain dependant code