generator_xps.cpp 77.2 KB
Newer Older
1
/*
2
  Copyright (C)  2006, 2009  Brad Hards <bradh@frogmouth.net>
3
4
5
6
7
8
9
10
11
12
13
14
15

  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

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
Pino Toscano's avatar
Pino Toscano committed
16
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17
18
19
  02110-1301, USA.
*/

Albert Astals Cid's avatar
Albert Astals Cid committed
20
21
#include "generator_xps.h"

22
23
24
#include <qdatetime.h>
#include <qfile.h>
#include <qlist.h>
25
#include <qpainter.h>
26
#include <qprinter.h>
27
#include <kaboutdata.h>
28
29
#include <kglobal.h>
#include <klocale.h>
30
#include <kurl.h>
31
#include <QBuffer>
32
#include <QImageReader>
33
#include <QMutex>
34

35
36
37
38
#include <core/document.h>
#include <core/page.h>
#include <core/area.h>
#include <core/fileprinter.h>
39

Pino Toscano's avatar
Pino Toscano committed
40
const int XpsDebug = 4712;
41

42
43
44
45
46
47
static KAboutData createAboutData()
{
    KAboutData aboutData(
         "okular_xps",
         "okular_xps",
         ki18n( "XPS Backend" ),
48
         "0.3.2",
49
50
51
         ki18n( "An XPS backend" ),
         KAboutData::License_GPL,
         ki18n( "© 2006-2007 Brad Hards\n"
52
53
                "© 2007 Jiri Klement\n"
                "© 2008 Pino Toscano" )
54
55
56
    );
    aboutData.addAuthor( ki18n( "Brad Hards" ), KLocalizedString(), "bradh@frogmouth.net" );
    aboutData.addAuthor( ki18n( "Jiri Klement" ), KLocalizedString(), "jiri.klement@gmail.com" );
57
    aboutData.addAuthor( ki18n( "Pino Toscano" ), KLocalizedString(), "pino@kde.org" );
58
59
60
61
    return aboutData;
}

OKULAR_EXPORT_PLUGIN( XpsGenerator, createAboutData() )
62

63
64
65
66
Q_DECLARE_METATYPE( QGradient* )
Q_DECLARE_METATYPE( XpsPathFigure* )
Q_DECLARE_METATYPE( XpsPathGeometry* )

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
// From Qt4
static int hex2int(char hex)
{
    QChar hexchar = QLatin1Char(hex);
    int v;
    if (hexchar.isDigit())
        v = hexchar.digitValue();
    else if (hexchar >= QLatin1Char('A') && hexchar <= QLatin1Char('F'))
        v = hexchar.cell() - 'A' + 10;
    else if (hexchar >= QLatin1Char('a') && hexchar <= QLatin1Char('f'))
        v = hexchar.cell() - 'a' + 10;
    else
        v = -1;
    return v;
}

// Modified from Qt4
static QColor hexToRgba(const char *name)
{
    if(name[0] != '#')
        return QColor();
    name++; // eat the leading '#'
    int len = qstrlen(name);
    int r, g, b;
    int a = 255;
    if (len == 6) {
        r = (hex2int(name[0]) << 4) + hex2int(name[1]);
        g = (hex2int(name[2]) << 4) + hex2int(name[3]);
        b = (hex2int(name[4]) << 4) + hex2int(name[5]);
    } else if (len == 8) {
        a = (hex2int(name[0]) << 4) + hex2int(name[1]);
        r = (hex2int(name[2]) << 4) + hex2int(name[3]);
        g = (hex2int(name[4]) << 4) + hex2int(name[5]);
        b = (hex2int(name[6]) << 4) + hex2int(name[7]);
    } else {
        r = g = b = -1;
    }
    if ((uint)r > 255 || (uint)g > 255 || (uint)b > 255) {
        return QColor();
    }
    return QColor(r,g,b,a);
}

static QRectF stringToRectF( const QString &data )
{
    QStringList numbers = data.split(',');
    QPointF origin( numbers.at(0).toDouble(), numbers.at(1).toDouble() );
    QSizeF size( numbers.at(2).toDouble(), numbers.at(3).toDouble() );
    return QRectF( origin, size );
}

Pino Toscano's avatar
Pino Toscano committed
118
static bool parseGUID( const QString &guidString, unsigned short guid[16]) {
119
120
121
122
123
124
125
126
127
128

    if (guidString.length() <= 35) {
        return false;
    }

    // Maps bytes to positions in guidString
    const static int indexes[] = {6, 4, 2, 0, 11, 9, 16, 14, 19, 21, 24, 26, 28, 30, 32, 34};

    for (int i = 0; i < 16; i++) {
        int hex1 = hex2int(guidString[indexes[i]].cell());
Jiri Klement's avatar
Jiri Klement committed
129
        int hex2 = hex2int(guidString[indexes[i]+1].cell());
130

Jiri Klement's avatar
Jiri Klement committed
131
132
133
134
        if ((hex1 < 0) || (hex2 < 0))
        {
            return false;
        }
135
136
137
138
139
140
141
142
143

        guid[i] = hex1 * 16 + hex2;
    }

    return true;

}


144
145
146
147
148
149
// Read next token of abbreviated path data
static bool nextAbbPathToken(AbbPathToken *token)
{
    int *curPos = &token->curPos;
    QString data = token->data;

150
151
    while ((*curPos < data.length()) && (data.at(*curPos).isSpace()))
    {
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        (*curPos)++;
    }

    if (*curPos == data.length())
    {
        token->type = abtEOF;
        return true;
    }

    QChar ch = data.at(*curPos);

    if (ch.isNumber() || (ch == '+') || (ch == '-'))
    {
        int start = *curPos;
        while ((*curPos < data.length()) && (!data.at(*curPos).isSpace()) && (data.at(*curPos) != ',') && !data.at(*curPos).isLetter())
Jiri Klement's avatar
Jiri Klement committed
167
168
169
170
171
    {
        (*curPos)++;
    }
    token->number = data.mid(start, *curPos - start).toDouble();
    token->type = abtNumber;
172
173
174
175

    } else if (ch == ',')
    {
        token->type = abtComma;
Jiri Klement's avatar
Jiri Klement committed
176
        (*curPos)++;
177
    } else if (ch.isLetter())
178
179
    {
        token->type = abtCommand;
Jiri Klement's avatar
Jiri Klement committed
180
181
        token->command = data.at(*curPos).cell();
        (*curPos)++;
182
    } else
183
    {
184
        (*curPos)++;
185
186
187
188
189
190
        return false;
    }

    return true;
}

191
192
193
/**
    Read point (two reals delimited by comma) from abbreviated path data
*/
Pino Toscano's avatar
Pino Toscano committed
194
static QPointF getPointFromString(AbbPathToken *token, bool relative, const QPointF &currentPosition) {
195
    //TODO Check grammar
196

197
198
199
200
201
202
203
204
205
    QPointF result;
    result.rx() = token->number;
    nextAbbPathToken(token);
    nextAbbPathToken(token); // ,
    result.ry() = token->number;
    nextAbbPathToken(token);

    if (relative)
    {
206
        result += currentPosition;
207
    }
208
209
210

    return result;
}
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
/**
    Read point (two reals delimited by comma) from string
*/
static QPointF getPointFromString(const QString &string)
{
    const int commaPos = string.indexOf(QLatin1Char(','));
    if (commaPos == -1 || string.indexOf(QLatin1Char(','), commaPos + 1) != -1)
        return QPointF();

    QPointF result;
    bool ok = false;
    QStringRef ref = string.midRef(0, commaPos);
    result.setX(QString::fromRawData(ref.constData(), ref.count()).toDouble(&ok));
    if (!ok)
        return QPointF();

    ref = string.midRef(commaPos + 1);
    result.setY(QString::fromRawData(ref.constData(), ref.count()).toDouble(&ok));
    if (!ok)
        return QPointF();

    return result;
}

236
237
238
239
240
241
242
243
244
245
static Qt::FillRule fillRuleFromString( const QString &data, Qt::FillRule def = Qt::OddEvenFill )
{
    if ( data == QLatin1String( "EvenOdd" ) ) {
        return Qt::OddEvenFill;
    } else if ( data == QLatin1String( "NonZero" ) ) {
        return Qt::WindingFill;
    }
    return def;
}

246
247
248
/**
    Parse an abbreviated path "Data" description
    \param data the string containing the whitespace separated values
249

250
251
252
    \see XPS specification 4.2.3 and Appendix G
*/
static QPainterPath parseAbbreviatedPathData( const QString &data)
253
{
Pino Toscano's avatar
Pino Toscano committed
254
    QPainterPath path;
255

256
    AbbPathToken token;
257
258
259
260
261

    token.data = data;
    token.curPos = 0;

    nextAbbPathToken(&token);
262

Jiri Klement's avatar
Jiri Klement committed
263
    // Used by Smooth cubic curve (command s)
264
    char lastCommand = ' ';
Jiri Klement's avatar
Jiri Klement committed
265
    QPointF lastSecondControlPoint;
266
267
268
269
270
271
272

    while (true)
    {
        if (token.type != abtCommand)
        {
            if (token.type != abtEOF)
            {
273
                kDebug(XpsDebug).nospace() << "Error in parsing abbreviated path data (" << token.type << "@" << token.curPos << "): " << data;
274
            }
275
            return path;
276
277
278
279
        }

        char command = QChar(token.command).toLower().cell();
        bool isRelative = QChar(token.command).isLower();
280
        QPointF currPos = path.currentPosition();
281
282
283
284
285
286
287
288
        nextAbbPathToken(&token);

        switch (command) {
            case 'f':
                int rule;
                rule = (int)token.number;
                if (rule == 0)
                {
289
                    path.setFillRule(Qt::OddEvenFill);
290
291
292
293
                }
                else if (rule == 1)
                {
                    // In xps specs rule 1 means NonZero fill. I think it's equivalent to WindingFill but I'm not sure
294
                    path.setFillRule(Qt::WindingFill);
295
                }
296
                nextAbbPathToken(&token);
297
298
299
300
                break;
            case 'm': // Move
                while (token.type == abtNumber)
                {
301
302
                    QPointF point = getPointFromString(&token, isRelative, currPos);
                    path.moveTo(point);
303
304
305
306
307
                }
                break;
            case 'l': // Line
                while (token.type == abtNumber)
                {
308
309
                    QPointF point = getPointFromString(&token, isRelative, currPos);
                    path.lineTo(point);
310
311
312
313
314
                }
                break;
            case 'h': // Horizontal line
                while (token.type == abtNumber)
                {
Pino Toscano's avatar
Pino Toscano committed
315
316
317
                    double x = token.number;
                    if ( isRelative )
                        x += path.currentPosition().x();
318
                    path.lineTo(x, path.currentPosition().y());
319
320
321
322
323
324
                    nextAbbPathToken(&token);
                }
                break;
            case 'v': // Vertical line
                while (token.type == abtNumber)
                {
Pino Toscano's avatar
Pino Toscano committed
325
326
327
                    double y = token.number;
                    if ( isRelative )
                        y += path.currentPosition().y();
328
                    path.lineTo(path.currentPosition().x(), y);
329
330
331
332
333
334
                    nextAbbPathToken(&token);
                }
                break;
            case 'c': // Cubic bezier curve
                while (token.type == abtNumber)
                {
335
336
337
338
                    QPointF firstControl = getPointFromString(&token, isRelative, currPos);
                    QPointF secondControl = getPointFromString(&token, isRelative, currPos);
                    QPointF endPoint = getPointFromString(&token, isRelative, currPos);
                    path.cubicTo(firstControl, secondControl, endPoint);
339

Jiri Klement's avatar
Jiri Klement committed
340
                    lastSecondControlPoint = secondControl;
341
342
343
344
345
                }
                break;
            case 'q': // Quadratic bezier curve
                while (token.type == abtNumber)
                {
346
347
                    QPointF point1 = getPointFromString(&token, isRelative, currPos);
                    QPointF point2 = getPointFromString(&token, isRelative, currPos);
348
                    path.quadTo(point1, point2);
349
350
351
352
353
                }
                break;
            case 's': // Smooth cubic bezier curve
                while (token.type == abtNumber)
                {
Jiri Klement's avatar
Jiri Klement committed
354
355
356
                    QPointF firstControl;
                    if ((lastCommand == 's') || (lastCommand == 'c'))
                    {
357
                        firstControl = lastSecondControlPoint + (lastSecondControlPoint + path.currentPosition());
358
                    }
Jiri Klement's avatar
Jiri Klement committed
359
360
                    else
                    {
361
                        firstControl = path.currentPosition();
Jiri Klement's avatar
Jiri Klement committed
362
                    }
363
364
365
                    QPointF secondControl = getPointFromString(&token, isRelative, currPos);
                    QPointF endPoint = getPointFromString(&token, isRelative, currPos);
                    path.cubicTo(firstControl, secondControl, endPoint);
366
367
368
369
370
371
                }
                break;
            case 'a': // Arc
                //TODO Implement Arc drawing
                while (token.type == abtNumber)
                {
372
                    /*QPointF rp =*/ getPointFromString(&token, isRelative, currPos);
373
374
                    /*double r = token.number;*/
                    nextAbbPathToken(&token);
375
                    /*double fArc = token.number; */
376
377
378
                    nextAbbPathToken(&token);
                    /*double fSweep = token.number; */
                    nextAbbPathToken(&token);
379
                    /*QPointF point = */getPointFromString(&token, isRelative, currPos);
380
381
382
                }
                break;
            case 'z': // Close path
383
                path.closeSubpath();
384
                break;
385
        }
386

Jiri Klement's avatar
Jiri Klement committed
387
        lastCommand = command;
388
    }
389
390

    return path;
391
}
392

393
394
395
396
397
398
399
400
401
/**
   Parse a "Matrix" attribute string
   \param csv the comma separated list of values
   \return the QMatrix corresponding to the affine transform
   given in the attribute

   \see XPS specification 7.4.1
*/
static QMatrix attsToMatrix( const QString &csv )
402
403
404
405
{
    QStringList values = csv.split( ',' );
    if ( values.count() != 6 ) {
        return QMatrix(); // that is an identity matrix - no effect
406
    }
407
408
    return QMatrix( values.at(0).toDouble(), values.at(1).toDouble(),
                    values.at(2).toDouble(), values.at(3).toDouble(),
409
                    values.at(4).toDouble(), values.at(5).toDouble() );
410
}
411

412
413
414
415
/**
   \return Brush with given color or brush specified by reference to resource
*/
static QBrush parseRscRefColorForBrush( const QString &data )
416
417
418
{
    if (data[0] == '{') {
        //TODO
419
        kDebug(XpsDebug) << "Reference" << data;
420
        return QBrush();
421
    } else {
422
423
424
425
        return QBrush( hexToRgba( data.toLatin1() ) );
    }
}

426
427
428
429
/**
   \return Pen with given color or Pen specified by reference to resource
*/
static QPen parseRscRefColorForPen( const QString &data )
430
431
432
{
    if (data[0] == '{') {
        //TODO
433
        kDebug(XpsDebug) << "Reference" << data;
434
435
436
        return QPen();
    } else {
        return QPen( hexToRgba( data.toLatin1() ) );
437
438
439
    }
}

440
441
442
443
/**
   \return Matrix specified by given data or by referenced dictionary
*/
static QMatrix parseRscRefMatrix( const QString &data )
444
445
446
{
    if (data[0] == '{') {
        //TODO
447
        kDebug(XpsDebug) << "Reference" << data;
448
449
450
451
452
453
        return QMatrix();
    } else {
        return attsToMatrix( data );
    }
}

454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/**
   \return The path of the entry
*/
static QString entryPath( const QString &entry )
{
    const int index = entry.lastIndexOf( QChar::fromLatin1( '/' ) );
    QString ret = QString::fromLatin1( "/" ) + entry.mid( 0, index );
    if ( index > 0 ) {
        ret.append( QChar::fromLatin1( '/' ) );
    }
    return ret;
}

/**
   \return The path of the entry
*/
static QString entryPath( const KZipFileEntry* entry )
{
    return entryPath( entry->path() );
}

/**
   \return The absolute path of the \p location, according to \p path if it's non-absolute
*/
static QString absolutePath( const QString &path, const QString &location )
{
480
    QString retPath;
481
482
    if ( location.at( 0 ) == QLatin1Char( '/' ) ) {
        // already absolute
483
484
485
486
487
        retPath = location;
    } else {
        KUrl url = KUrl::fromPath( path );
        url.setFileName( location );
        retPath = url.toLocalFile();
488
    }
489
490
491
492
493
494
    // it seems paths & file names can also be percent-encoded
    // (XPS won't ever finish surprising me)
    if ( retPath.contains( QLatin1Char( '%' ) ) ) {
        retPath = QUrl::fromPercentEncoding( retPath.toUtf8() );
    }
    return retPath;
495
496
}

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/**
   Read the content of an archive entry in both the cases:
   a) single file
      + foobar
   b) directory
      + foobar/
        + [0].piece
        + [1].piece
        + ...
        + [x].last.piece

   \see XPS specification 10.1.2
*/
static QByteArray readFileOrDirectoryParts( const KArchiveEntry *entry, QString *pathOfFile = 0 )
{
    QByteArray data;
    if ( entry->isDirectory() ) {
        const KArchiveDirectory* relDir = static_cast<const KArchiveDirectory *>( entry );
        QStringList entries = relDir->entries();
        qSort( entries );
        Q_FOREACH ( const QString &entry, entries ) {
            const KArchiveEntry* relSubEntry = relDir->entry( entry );
            if ( !relSubEntry->isFile() )
                continue;

            const KZipFileEntry* relSubFile = static_cast<const KZipFileEntry *>( relSubEntry );
            data.append( relSubFile->data() );
        }
    } else {
        const KZipFileEntry* relFile = static_cast<const KZipFileEntry *>( entry );
        data.append( relFile->data() );
        if ( pathOfFile ) {
            *pathOfFile = entryPath( relFile );
        }
    }
    return data;
}

535
536
537
/**
   Load the resource \p fileName from the specified \p archive using the case sensitivity \p cs
*/
538
static const KArchiveEntry* loadEntry( KZip *archive, const QString &fileName, Qt::CaseSensitivity cs )
539
540
{
    // first attempt: loading the entry straight as requested
541
    const KArchiveEntry* entry = archive->directory()->entry( fileName );
542
543
544
545
546
547
548
549
550
551
552
553
554
    // in case sensitive mode, or if we actually found something, return what we found
    if ( cs == Qt::CaseSensitive || entry ) {
        return entry;
    }

    QString path;
    QString entryName;
    const int index = fileName.lastIndexOf( QChar::fromLatin1( '/' ) );
    QString ret;
    if ( index > 0 ) {
        path = fileName.left( index );
        entryName = fileName.mid( index + 1 );
    } else {
555
        path = '/';
556
557
558
559
560
561
562
563
564
        entryName = fileName;
    }
    const KArchiveEntry * newEntry = archive->directory()->entry( path );
    if ( newEntry->isDirectory() ) {
        const KArchiveDirectory* relDir = static_cast< const KArchiveDirectory * >( newEntry );
        QStringList relEntries = relDir->entries();
        qSort( relEntries );
        Q_FOREACH ( const QString &relEntry, relEntries ) {
            if ( relEntry.compare( entryName, Qt::CaseInsensitive ) == 0 ) {
565
                return relDir->entry( relEntry );
566
567
568
569
570
571
            }
        }
    }
    return 0;
}

572
573
574
575
576
577
static const KZipFileEntry* loadFile( KZip *archive, const QString &fileName, Qt::CaseSensitivity cs )
{
    const KArchiveEntry *entry = loadEntry( archive, fileName, cs );
    return entry->isFile() ? static_cast< const KZipFileEntry * >( entry ) : 0;
}

578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/**
   \return The name of a resource from the \p fileName
*/
static QString resourceName( const QString &fileName )
{
    QString resource = fileName;
    const int slashPos = fileName.lastIndexOf( QLatin1Char( '/' ) );
    const int dotPos = fileName.lastIndexOf( QLatin1Char( '.' ) );
    if ( slashPos > -1 ) {
        if ( dotPos > -1 && dotPos > slashPos ) {
            resource = fileName.mid( slashPos + 1, dotPos - slashPos - 1 );
        } else {
            resource = fileName.mid( slashPos + 1 );
        }
    }
    return resource;
}

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
static QColor interpolatedColor( const QColor &c1, const QColor &c2 )
{
    QColor res;
    res.setAlpha( ( c1.alpha() + c2.alpha() ) / 2 );
    res.setRed( ( c1.red() + c2.red() ) / 2 );
    res.setGreen( ( c1.green() + c2.green() ) / 2 );
    res.setBlue( ( c1.blue() + c2.blue() ) / 2 );
    return res;
}

static bool xpsGradientLessThan( const XpsGradient &g1, const XpsGradient &g2 )
{
    return qFuzzyCompare( g1.offset, g2.offset )
        ? g1.color.name() < g2.color.name()
        : g1.offset < g2.offset;
}

static int xpsGradientWithOffset( const QList<XpsGradient> &gradients, double offset )
{
    int i = 0;
    Q_FOREACH ( const XpsGradient &grad, gradients ) {
        if ( grad.offset == offset ) {
            return i;
        }
        ++i;
    }
    return -1;
}

/**
   Preprocess a list of gradients.

   \see XPS specification 11.3.1.1
*/
static void preprocessXpsGradients( QList<XpsGradient> &gradients )
{
    if ( gradients.isEmpty() )
        return;

    // sort the gradients (case 1.)
    qStableSort( gradients.begin(), gradients.end(), xpsGradientLessThan );

    // no gradient with stop 0.0 (case 2.)
    if ( xpsGradientWithOffset( gradients, 0.0 ) == -1 ) {
        int firstGreaterThanZero = 0;
        while ( firstGreaterThanZero < gradients.count() && gradients.at( firstGreaterThanZero ).offset < 0.0 )
            ++firstGreaterThanZero;
        // case 2.a: no gradients with stop less than 0.0
        if ( firstGreaterThanZero == 0 ) {
            gradients.prepend( XpsGradient( 0.0, gradients.first().color ) );
        }
        // case 2.b: some gradients with stop more than 0.0
648
        else if ( firstGreaterThanZero != gradients.count() ) {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
            QColor col1 = gradients.at( firstGreaterThanZero - 1 ).color;
            QColor col2 = gradients.at( firstGreaterThanZero ).color;
            for ( int i = 0; i < firstGreaterThanZero; ++i ) {
                gradients.removeFirst();
            }
            gradients.prepend( XpsGradient( 0.0, interpolatedColor( col1, col2 ) ) );
        }
        // case 2.c: no gradients with stop more than 0.0
        else {
            XpsGradient newGrad( 0.0, gradients.last().color );
            gradients.clear();
            gradients.append( newGrad );
        }
    }

    if ( gradients.isEmpty() )
        return;

    // no gradient with stop 1.0 (case 3.)
    if ( xpsGradientWithOffset( gradients, 1.0 ) == -1 ) {
        int firstLessThanOne = gradients.count() - 1;
        while ( firstLessThanOne >= 0 && gradients.at( firstLessThanOne ).offset > 1.0 )
            --firstLessThanOne;
        // case 2.a: no gradients with stop greater than 1.0
        if ( firstLessThanOne == gradients.count() - 1 ) {
            gradients.append( XpsGradient( 1.0, gradients.last().color ) );
        }
        // case 2.b: some gradients with stop more than 1.0
677
        else if ( firstLessThanOne != -1 ) {
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
            QColor col1 = gradients.at( firstLessThanOne ).color;
            QColor col2 = gradients.at( firstLessThanOne + 1 ).color;
            for ( int i = firstLessThanOne + 1; i < gradients.count(); ++i ) {
                gradients.removeLast();
            }
            gradients.append( XpsGradient( 1.0, interpolatedColor( col1, col2 ) ) );
        }
        // case 2.c: no gradients with stop less than 1.0
        else {
            XpsGradient newGrad( 1.0, gradients.first().color );
            gradients.clear();
            gradients.append( newGrad );
        }
    }
}

static void addXpsGradientsToQGradient( const QList<XpsGradient> &gradients, QGradient *qgrad )
{
    Q_FOREACH ( const XpsGradient &grad, gradients ) {
        qgrad->setColorAt( grad.offset, grad.color );
    }
}

701
702
703
704
705
706
707
708
709
710
711
712
713
714
static void applySpreadStyleToQGradient( const QString &style, QGradient *qgrad )
{
    if ( style.isEmpty() )
        return;

    if ( style == QLatin1String( "Pad" ) ) {
        qgrad->setSpread( QGradient::PadSpread );
    } else if ( style == QLatin1String( "Reflect" ) ) {
        qgrad->setSpread( QGradient::ReflectSpread );
    } else if ( style == QLatin1String( "Repeat" ) ) {
        qgrad->setSpread( QGradient::RepeatSpread );
    }
}

715
716
717
718
719
720
721
722
723
724
725
/**
    Read an UnicodeString
    \param string the raw value of UnicodeString

    \see XPS specification 5.1.4
*/
static QString unicodeString( const QString &raw )
{
    QString ret;
    if ( raw.startsWith( QLatin1String( "{}" ) ) ) {
        ret = raw.mid( 2 );
726
727
    } else {
        ret = raw;
728
729
730
731
732
    }
    return ret;
}


733
XpsHandler::XpsHandler(XpsPage *page): m_page(page)
734
{
Jiri Klement's avatar
Jiri Klement committed
735
    m_painter = NULL;
736
737
738
}

XpsHandler::~XpsHandler()
Jiri Klement's avatar
Jiri Klement committed
739
740
{
}
741
742
743

bool XpsHandler::startDocument()
{
744
    kDebug(XpsDebug) << "start document" << m_page->m_fileName ;
745
746
747
748
749

    XpsRenderNode node;
    node.name = "document";
    m_nodes.push(node);

750
751
752
753
754
755
756
757
    return true;
}

bool XpsHandler::startElement( const QString &nameSpace,
                               const QString &localName,
                               const QString &qname,
                               const QXmlAttributes & atts )
{
758
759
760
761
762
763
764
765
766
    Q_UNUSED( nameSpace )
    Q_UNUSED( qname )

    XpsRenderNode node;
    node.name = localName;
    node.attributes = atts;
    processStartElement( node );
    m_nodes.push(node);

767
768
769
770
771
772
773
774

    return true;
}

bool XpsHandler::endElement( const QString &nameSpace,
                             const QString &localName,
                             const QString &qname)
{
775
776
777
778
779
780
    Q_UNUSED( nameSpace )
    Q_UNUSED( qname )


    XpsRenderNode node = m_nodes.pop();
    if (node.name != localName) {
781
        kDebug(XpsDebug) << "Name doesn't match";
782
783
784
785
786
787
788
    }
    processEndElement( node );
    node.children.clear();
    m_nodes.top().children.append(node);

    return true;
}
789

790
791
void XpsHandler::processGlyph( XpsRenderNode &node )
{
792
793
    //TODO Currently ignored attributes: CaretStops, DeviceFontName, IsSideways, OpacityMask, Name, FixedPage.NavigateURI, xml:lang, x:key
    //TODO Indices is only partially implemented
794
795
    //TODO Currently ignored child elements: Clip, OpacityMask
    //Handled separately: RenderTransform
796

797
798
799
800
801
    QString att;

    m_painter->save();

    // Get font (doesn't work well because qt doesn't allow to load font from file)
Jiri Klement's avatar
Jiri Klement committed
802
    // This works despite the fact that font size isn't specified in points as required by qt. It's because I set point size to be equal to drawing unit.
803
804
805
806
807
808
809
810
    float fontSize = node.attributes.value("FontRenderingEmSize").toFloat();
    // kDebug(XpsDebug) << "Font Rendering EmSize:" << fontSize;
    // a value of 0.0 means the text is not visible (see XPS specs, chapter 12, "Glyphs")
    if ( fontSize < 0.1 ) {
        m_painter->restore();
        return;
    }
    QFont font = m_page->m_file->getFontByName( node.attributes.value("FontUri"), fontSize );
811
812
813
814
815
816
817
818
819
820
821
    att = node.attributes.value( "StyleSimulations" );
    if  ( !att.isEmpty() ) {
        if ( att == QLatin1String( "ItalicSimulation" ) ) {
            font.setItalic( true );
        } else if ( att == QLatin1String( "BoldSimulation" ) ) {
            font.setBold( true );
        } else if ( att == QLatin1String( "BoldItalicSimulation" ) ) {
            font.setItalic( true );
            font.setBold( true );
        }
    }
822
823
824
825
826
827
828
829
830
    m_painter->setFont(font);

    //Origin
    QPointF origin( node.attributes.value("OriginX").toDouble(), node.attributes.value("OriginY").toDouble() );

    //Fill
    QBrush brush;
    att = node.attributes.value("Fill");
    if (att.isEmpty()) {
831
832
833
        QVariant data = node.getChildData( "Glyphs.Fill" );
        if (data.canConvert<QBrush>()) {
            brush = data.value<QBrush>();
834
        } else {
835
836
837
838
            // no "Fill" attribute and no "Glyphs.Fill" child, so show nothing
            // (see XPS specs, 5.10)
            m_painter->restore();
            return;
839
        }
840
    } else {
841
        brush = parseRscRefColorForBrush( att );
842
843
844
845
846
        if ( brush.style() > Qt::NoBrush && brush.style() < Qt::LinearGradientPattern
             && brush.color().alpha() == 0 ) {
            m_painter->restore();
            return;
        }
847
848
849
    }
    m_painter->setBrush( brush );
    m_painter->setPen( QPen( brush, 0 ) );
850

851
852
853
    // Opacity
    att = node.attributes.value("Opacity");
    if (! att.isEmpty()) {
854
855
856
857
858
859
860
861
        bool ok = true;
        double value = att.toDouble( &ok );
        if ( ok && value >= 0.1 ) {
            m_painter->setOpacity( value );
        } else {
            m_painter->restore();
            return;
        }
862
863
    }

864
865
866
867
868
869
    //RenderTransform
    att = node.attributes.value("RenderTransform");
    if (!att.isEmpty()) {
        m_painter->setWorldMatrix( parseRscRefMatrix( att ), true);
    }

870
871
872
873
874
875
876
877
878
    // Clip
    att = node.attributes.value( "Clip" );
    if ( !att.isEmpty() ) {
        QPainterPath clipPath = parseAbbreviatedPathData( att );
        if ( !clipPath.isEmpty() ) {
            m_painter->setClipPath( clipPath );
        }
    }

879
880
881
882
883
884
885
886
887
888
889
890
891
892
    // BiDiLevel - default Left-to-Right
    m_painter->setLayoutDirection( Qt::LeftToRight );
    att = node.attributes.value( "BiDiLevel" );
    if ( !att.isEmpty() ) {
        if ( (att.toInt() % 2) == 1 ) {
            // odd BiDiLevel, so Right-to-Left
            m_painter->setLayoutDirection( Qt::RightToLeft );
        }
    }

    // Indices - partial handling only
    att = node.attributes.value( "Indices" );
    QList<qreal> advanceWidths;
    if ( ! att.isEmpty() ) {
893
        QStringList indicesElements = att.split( ';' );
894
895
        for( int i = 0; i < indicesElements.size(); ++i ) {
            if ( indicesElements.at(i).contains( "," ) ) {
896
                QStringList parts = indicesElements.at(i).split( ',' );
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
                if (parts.size() == 2 ) {
                    // regular advance case, no offsets
                    advanceWidths.append( parts.at(1).toDouble() * fontSize / 100.0 );
                } else if (parts.size() == 3 ) {
                    // regular advance case, with uOffset
                    qreal AdvanceWidth = parts.at(1).toDouble() * fontSize / 100.0 ;
                    qreal uOffset = parts.at(2).toDouble() / 100.0;
                    advanceWidths.append( AdvanceWidth + uOffset );
                } else {
                    // has vertical offset, but don't know how to handle that yet
                    kDebug(XpsDebug) << "Unhandled Indices element: " << indicesElements.at(i);
                    advanceWidths.append( -1.0 );
                }
            } else {
                // no special advance case
                advanceWidths.append( -1.0 );
            }
        }
    }

    // UnicodeString
    QString stringToDraw( unicodeString( node.attributes.value( "UnicodeString" ) ) );
    QPointF originAdvance(0, 0);
    QFontMetrics metrics = m_painter->fontMetrics();
    for ( int i = 0; i < stringToDraw.size(); ++i ) {
        QChar thisChar = stringToDraw.at( i );
        m_painter->drawText( origin + originAdvance, QString( thisChar ) );
	const qreal advanceWidth = advanceWidths.value( i, qreal(-1.0) );
        if ( advanceWidth > 0.0 ) {
            originAdvance.rx() += advanceWidth;
        } else {
            originAdvance.rx() += metrics.width( thisChar );
        }
    }
931
932
933
    // kDebug(XpsDebug) << "Glyphs: " << atts.value("Fill") << ", " << atts.value("FontUri");
    // kDebug(XpsDebug) << "    Origin: " << atts.value("OriginX") << "," << atts.value("OriginY");
    // kDebug(XpsDebug) << "    Unicode: " << atts.value("UnicodeString");
934

935
936
937
938
939
    m_painter->restore();
}

void XpsHandler::processFill( XpsRenderNode &node )
{
Pino Toscano's avatar
Pino Toscano committed
940
    //TODO Ignored child elements: VirtualBrush
941

Jiri Klement's avatar
Jiri Klement committed
942
    if (node.children.size() != 1) {
943
        kDebug(XpsDebug) << "Fill element should have exactly one child";
Jiri Klement's avatar
Jiri Klement committed
944
945
    } else {
        node.data = node.children[0].data;
946
947
948
    }
}

949
950
void XpsHandler::processStroke( XpsRenderNode &node )
{
Pino Toscano's avatar
Pino Toscano committed
951
    //TODO Ignored child elements: VirtualBrush
952
953
954
955
956
957
958
959

    if (node.children.size() != 1) {
        kDebug(XpsDebug) << "Stroke element should have exactly one child";
    } else {
        node.data = node.children[0].data;
    }
}

960
961
void XpsHandler::processImageBrush( XpsRenderNode &node )
{
962
963
    //TODO Ignored attributes: Opacity, x:key, TileMode, ViewBoxUnits, ViewPortUnits
    //TODO Check whether transformation works for non standard situations (viewbox different that whole image, Transform different that simple move & scale, Viewport different than [0, 0, 1, 1]
964

965
966
    QString att;
    QBrush brush;
967

968
969
970
    QRectF viewport = stringToRectF( node.attributes.value( "Viewport" ) );
    QRectF viewbox = stringToRectF( node.attributes.value( "Viewbox" ) );
    QImage image = m_page->loadImageFromFile( node.attributes.value( "ImageSource" ) );
971

972
973
974
975
976
977
978
979
    // Matrix which can transform [0, 0, 1, 1] rectangle to given viewbox
    QMatrix viewboxMatrix = QMatrix( viewbox.width() * image.physicalDpiX() / 96, 0, 0, viewbox.height() * image.physicalDpiY() / 96, viewbox.x(), viewbox.y() );

    // Matrix which can transform [0, 0, 1, 1] rectangle to given viewport
    //TODO Take ViewPort into account
    QMatrix viewportMatrix;
    att = node.attributes.value( "Transform" );
    if ( att.isEmpty() ) {
980
981
982
        QVariant data = node.getChildData( "ImageBrush.Transform" );
        if (data.canConvert<QMatrix>()) {
            viewportMatrix = data.value<QMatrix>();
983
984
985
986
987
988
        } else {
            viewportMatrix = QMatrix();
        }
    } else {
        viewportMatrix = parseRscRefMatrix( att );
    }
989
    viewportMatrix = viewportMatrix * QMatrix( viewport.width(), 0, 0, viewport.height(), viewport.x(), viewport.y() );
990

991

992
    brush = QBrush( image );
993
994
    brush.setMatrix( viewboxMatrix.inverted() * viewportMatrix );

995
    node.data = qVariantFromValue( brush );
996
997
998
999
}

void XpsHandler::processPath( XpsRenderNode &node )
{
1000
    //TODO Ignored attributes: Clip, OpacityMask, StrokeEndLineCap, StorkeStartLineCap, Name, FixedPage.NavigateURI, xml:lang, x:key, AutomationProperties.Name, AutomationProperties.HelpText, SnapsToDevicePixels
For faster browsing, not all history is shown. View entire blame