File: textdocumentgenerator.cpp

package info (click to toggle)
okular 4%3A4.8.4-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,040 kB
  • sloc: cpp: 62,030; ansic: 3,964; xml: 66; sh: 22; makefile: 7
file content (488 lines) | stat: -rw-r--r-- 15,647 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/***************************************************************************
 *   Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/

#include "textdocumentgenerator.h"
#include "textdocumentgenerator_p.h"

#include <QtCore/QFile>
#include <QtCore/QMutex>
#include <QtCore/QStack>
#include <QtCore/QTextStream>
#include <QtCore/QVector>
#include <QtGui/QFontDatabase>
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtGui/QPrinter>
#if QT_VERSION >= 0x040500
#include <QtGui/QTextDocumentWriter>
#endif

#include "action.h"
#include "annotations.h"
#include "page.h"
#include "textpage.h"

#include "document.h"

using namespace Okular;

/**
 * Generic Converter Implementation
 */
TextDocumentConverter::TextDocumentConverter()
    : QObject( 0 ), d_ptr( new TextDocumentConverterPrivate )
{
}

TextDocumentConverter::~TextDocumentConverter()
{
    delete d_ptr;
}

DocumentViewport TextDocumentConverter::calculateViewport( QTextDocument *document, const QTextBlock &block )
{
    return TextDocumentUtils::calculateViewport( document, block );
}

TextDocumentGenerator* TextDocumentConverter::generator() const
{
    return d_ptr->mParent ? d_ptr->mParent->q_func() : 0;
}

/**
 * Generic Generator Implementation
 */
Okular::TextPage* TextDocumentGeneratorPrivate::createTextPage( int pageNumber ) const
{
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    Q_Q( const TextDocumentGenerator );
#endif

    Okular::TextPage *textPage = new Okular::TextPage;

    int start, end;

#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->lock();
#endif
    TextDocumentUtils::calculatePositions( mDocument, pageNumber, start, end );

    {
    QTextCursor cursor( mDocument );
    for ( int i = start; i < end - 1; ++i ) {
        cursor.setPosition( i );
        cursor.setPosition( i + 1, QTextCursor::KeepAnchor );

        QString text = cursor.selectedText();
        if ( text.length() == 1 ) {
            QRectF rect;
            TextDocumentUtils::calculateBoundingRect( mDocument, i, i + 1, rect, pageNumber );
            if ( pageNumber == -1 )
                text = "\n";

            textPage->append( text, new Okular::NormalizedRect( rect.left(), rect.top(), rect.right(), rect.bottom() ) );
        }
    }
    }
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->unlock();
#endif

    return textPage;
}

void TextDocumentGeneratorPrivate::addAction( Action *action, int cursorBegin, int cursorEnd )
{
    if ( !action )
        return;

    LinkPosition position;
    position.link = action;
    position.startPosition = cursorBegin;
    position.endPosition = cursorEnd;

    mLinkPositions.append( position );
}

void TextDocumentGeneratorPrivate::addAnnotation( Annotation *annotation, int cursorBegin, int cursorEnd )
{
    if ( !annotation )
        return;

    annotation->setFlags( annotation->flags() | Okular::Annotation::External );

    AnnotationPosition position;
    position.annotation = annotation;
    position.startPosition = cursorBegin;
    position.endPosition = cursorEnd;

    mAnnotationPositions.append( position );
}

void TextDocumentGeneratorPrivate::addTitle( int level, const QString &title, const QTextBlock &block )
{
    TitlePosition position;
    position.level = level;
    position.title = title;
    position.block = block;

    mTitlePositions.append( position );
}

void TextDocumentGeneratorPrivate::addMetaData( const QString &key, const QString &value, const QString &title )
{
    mDocumentInfo.set( key, value, title );
}

void TextDocumentGeneratorPrivate::addMetaData( DocumentInfo::Key key, const QString &value )
{
    mDocumentInfo.set( key, value );
}

void TextDocumentGeneratorPrivate::generateLinkInfos()
{
    for ( int i = 0; i < mLinkPositions.count(); ++i ) {
        const LinkPosition &linkPosition = mLinkPositions[ i ];

        LinkInfo info;
        info.link = linkPosition.link;

        TextDocumentUtils::calculateBoundingRect( mDocument, linkPosition.startPosition, linkPosition.endPosition,
                                                  info.boundingRect, info.page );

        if ( info.page >= 0 )
            mLinkInfos.append( info );
    }
}

void TextDocumentGeneratorPrivate::generateAnnotationInfos()
{
    for ( int i = 0; i < mAnnotationPositions.count(); ++i ) {
        const AnnotationPosition &annotationPosition = mAnnotationPositions[ i ];

        AnnotationInfo info;
        info.annotation = annotationPosition.annotation;

        TextDocumentUtils::calculateBoundingRect( mDocument, annotationPosition.startPosition, annotationPosition.endPosition,
                                                  info.boundingRect, info.page );

        if ( info.page >= 0 )
            mAnnotationInfos.append( info );
    }
}

void TextDocumentGeneratorPrivate::generateTitleInfos()
{
    QStack< QPair<int,QDomNode> > parentNodeStack;

    QDomNode parentNode = mDocumentSynopsis;

    parentNodeStack.push( qMakePair( 0, parentNode ) );

    for ( int i = 0; i < mTitlePositions.count(); ++i ) {
        const TitlePosition &position = mTitlePositions[ i ];

        Okular::DocumentViewport viewport = TextDocumentUtils::calculateViewport( mDocument, position.block );

        QDomElement item = mDocumentSynopsis.createElement( position.title );
        item.setAttribute( "Viewport", viewport.toString() );

        int headingLevel = position.level;

        // we need a parent, which has to be at a higher heading level than this heading level
        // so we just work through the stack
        while ( ! parentNodeStack.isEmpty() ) {
            int parentLevel = parentNodeStack.top().first;
            if ( parentLevel < headingLevel ) {
                // this is OK as a parent
                parentNode = parentNodeStack.top().second;
                break;
            } else {
                // we'll need to be further into the stack
                parentNodeStack.pop();
            }
        }
        parentNode.appendChild( item );
        parentNodeStack.push( qMakePair( headingLevel, QDomNode(item) ) );
    }
}

TextDocumentGenerator::TextDocumentGenerator( TextDocumentConverter *converter, QObject *parent, const QVariantList &args )
    : Okular::Generator( *new TextDocumentGeneratorPrivate( converter ), parent, args )
{
    converter->d_ptr->mParent = d_func();

    setFeature( TextExtraction );
    setFeature( PrintNative );
    setFeature( PrintToFile );
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    if ( QFontDatabase::supportsThreadedFontRendering() )
        setFeature( Threaded );
#endif

    connect( converter, SIGNAL(addAction(Action*,int,int)),
             this, SLOT(addAction(Action*,int,int)) );
    connect( converter, SIGNAL(addAnnotation(Annotation*,int,int)),
             this, SLOT(addAnnotation(Annotation*,int,int)) );
    connect( converter, SIGNAL(addTitle(int,QString,QTextBlock)),
             this, SLOT(addTitle(int,QString,QTextBlock)) );
    connect( converter, SIGNAL(addMetaData(QString,QString,QString)),
             this, SLOT(addMetaData(QString,QString,QString)) );
    connect( converter, SIGNAL(addMetaData(DocumentInfo::Key,QString)),
             this, SLOT(addMetaData(DocumentInfo::Key,QString)) );

    connect( converter, SIGNAL(error(QString,int)),
             this, SIGNAL(error(QString,int)) );
    connect( converter, SIGNAL(warning(QString,int)),
             this, SIGNAL(warning(QString,int)) );
    connect( converter, SIGNAL(notice(QString,int)),
             this, SIGNAL(notice(QString,int)) );
}

TextDocumentGenerator::~TextDocumentGenerator()
{
}

bool TextDocumentGenerator::loadDocument( const QString & fileName, QVector<Okular::Page*> & pagesVector )
{
    Q_D( TextDocumentGenerator );
    d->mDocument = d->mConverter->convert( fileName );

    if ( !d->mDocument )
    {
        // loading failed, cleanup all the stuff eventually gathered from the converter
        d->mTitlePositions.clear();
        Q_FOREACH ( const TextDocumentGeneratorPrivate::LinkPosition &linkPos, d->mLinkPositions )
        {
            delete linkPos.link;
        }
        d->mLinkPositions.clear();
        Q_FOREACH ( const TextDocumentGeneratorPrivate::AnnotationPosition &annPos, d->mAnnotationPositions )
        {
            delete annPos.annotation;
        }
        d->mAnnotationPositions.clear();

        return false;
    }

    d->generateTitleInfos();
    d->generateLinkInfos();
    d->generateAnnotationInfos();

    pagesVector.resize( d->mDocument->pageCount() );

    const QSize size = d->mDocument->pageSize().toSize();

    QVector< QLinkedList<Okular::ObjectRect*> > objects( d->mDocument->pageCount() );
    for ( int i = 0; i < d->mLinkInfos.count(); ++i ) {
        const TextDocumentGeneratorPrivate::LinkInfo &info = d->mLinkInfos.at( i );

        // in case that the converter report bogus link info data, do not assert here
        if ( info.page >= objects.count() )
          continue;

        const QRectF rect = info.boundingRect;
        objects[ info.page ].append( new Okular::ObjectRect( rect.left(), rect.top(), rect.right(), rect.bottom(), false,
                                                             Okular::ObjectRect::Action, info.link ) );
    }

    QVector< QLinkedList<Okular::Annotation*> > annots( d->mDocument->pageCount() );
    for ( int i = 0; i < d->mAnnotationInfos.count(); ++i ) {
        const TextDocumentGeneratorPrivate::AnnotationInfo &info = d->mAnnotationInfos[ i ];

        QRect rect( 0, info.page * size.height(), size.width(), size.height() );
        info.annotation->setBoundingRectangle( Okular::NormalizedRect( rect.left(), rect.top(), rect.right(), rect.bottom() ) );
        annots[ info.page ].append( info.annotation );
    }

    for ( int i = 0; i < d->mDocument->pageCount(); ++i ) {
        Okular::Page * page = new Okular::Page( i, size.width(), size.height(), Okular::Rotation0 );
        pagesVector[ i ] = page;

        if ( !objects.at( i ).isEmpty() ) {
            page->setObjectRects( objects.at( i ) );
        }
        QLinkedList<Okular::Annotation*>::ConstIterator annIt = annots.at( i ).begin(), annEnd = annots.at( i ).end();
        for ( ; annIt != annEnd; ++annIt ) {
            page->addAnnotation( *annIt );
        }
    }

    return true;
}

bool TextDocumentGenerator::doCloseDocument()
{
    Q_D( TextDocumentGenerator );
    delete d->mDocument;
    d->mDocument = 0;

    d->mTitlePositions.clear();
    d->mLinkPositions.clear();
    d->mLinkInfos.clear();
    d->mAnnotationPositions.clear();
    d->mAnnotationInfos.clear();
    // do not use clear() for the following two, otherwise they change type
    d->mDocumentInfo = Okular::DocumentInfo();
    d->mDocumentSynopsis = Okular::DocumentSynopsis();

    return true;
}

bool TextDocumentGenerator::canGeneratePixmap() const
{
    return Generator::canGeneratePixmap();
}

void TextDocumentGenerator::generatePixmap( Okular::PixmapRequest * request )
{
    Generator::generatePixmap( request );
}

QImage TextDocumentGeneratorPrivate::image( PixmapRequest * request )
{
    if ( !mDocument )
        return QImage();

#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    Q_Q( TextDocumentGenerator );
#endif

    QImage image( request->width(), request->height(), QImage::Format_ARGB32 );
    image.fill( Qt::white );

    QPainter p;
    p.begin( &image );

    qreal width = request->width();
    qreal height = request->height();

    const QSize size = mDocument->pageSize().toSize();

    p.scale( width / (qreal)size.width(), height / (qreal)size.height() );

    QRect rect;
    rect = QRect( 0, request->pageNumber() * size.height(), size.width(), size.height() );
    p.translate( QPoint( 0, request->pageNumber() * size.height() * -1 ) );
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->lock();
#endif
    mDocument->drawContents( &p, rect );
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->unlock();
#endif
    p.end();

    return image;
}

Okular::TextPage* TextDocumentGenerator::textPage( Okular::Page * page )
{
    Q_D( TextDocumentGenerator );
    return d->createTextPage( page->number() );
}

bool TextDocumentGenerator::print( QPrinter& printer )
{
    Q_D( TextDocumentGenerator );
    if ( !d->mDocument )
        return false;

    d->mDocument->print( &printer );

    return true;
}

const Okular::DocumentInfo* TextDocumentGenerator::generateDocumentInfo()
{
    Q_D( TextDocumentGenerator );
    return &d->mDocumentInfo;
}

const Okular::DocumentSynopsis* TextDocumentGenerator::generateDocumentSynopsis()
{
    Q_D( TextDocumentGenerator );
    if ( !d->mDocumentSynopsis.hasChildNodes() )
        return 0;
    else
        return &d->mDocumentSynopsis;
}

QVariant TextDocumentGeneratorPrivate::metaData( const QString &key, const QVariant &option ) const
{
    Q_UNUSED( option )
    if ( key == "DocumentTitle" )
    {
        return mDocumentInfo.get( "title" );
    }
    return QVariant();
}

Okular::ExportFormat::List TextDocumentGenerator::exportFormats(   ) const
{
    static Okular::ExportFormat::List formats;
    if ( formats.isEmpty() ) {
        formats.append( Okular::ExportFormat::standardFormat( Okular::ExportFormat::PlainText ) );
        formats.append( Okular::ExportFormat::standardFormat( Okular::ExportFormat::PDF ) );
#if QT_VERSION >= 0x040500
        if ( QTextDocumentWriter::supportedDocumentFormats().contains( "ODF" ) ) {
            formats.append( Okular::ExportFormat::standardFormat( Okular::ExportFormat::OpenDocumentText ) );
        }
        if ( QTextDocumentWriter::supportedDocumentFormats().contains( "HTML" ) ) {
            formats.append( Okular::ExportFormat::standardFormat( Okular::ExportFormat::HTML ) );
        }
#endif
    }

    return formats;
}

bool TextDocumentGenerator::exportTo( const QString &fileName, const Okular::ExportFormat &format )
{
    Q_D( TextDocumentGenerator );
    if ( !d->mDocument )
        return false;

    if ( format.mimeType()->name() == QLatin1String( "application/pdf" ) ) {
        QFile file( fileName );
        if ( !file.open( QIODevice::WriteOnly ) )
            return false;

        QPrinter printer( QPrinter::HighResolution );
        printer.setOutputFormat( QPrinter::PdfFormat );
        printer.setOutputFileName( fileName );
        d->mDocument->print( &printer );

        return true;
    } else if ( format.mimeType()->name() == QLatin1String( "text/plain" ) ) {
        QFile file( fileName );
        if ( !file.open( QIODevice::WriteOnly ) )
            return false;

        QTextStream out( &file );
        out << d->mDocument->toPlainText();

        return true;
#if QT_VERSION >= 0x040500
    } else if ( format.mimeType()->name() == QLatin1String( "application/vnd.oasis.opendocument.text" ) ) {
        QTextDocumentWriter odfWriter( fileName, "odf" );

        return odfWriter.write( d->mDocument );
    } else if ( format.mimeType()->name() == QLatin1String( "text/html" ) ) {
        QTextDocumentWriter odfWriter( fileName, "html" );

        return odfWriter.write( d->mDocument );
#endif
    }
    return false;
}

#include "textdocumentgenerator.moc"