~ubuntu-branches/ubuntu/breezy/koffice/breezy

« back to all changes in this revision

Viewing changes to filters/kword/rtf/export/ExportFilter.cc

  • Committer: Bazaar Package Importer
  • Author(s): Ben Burton
  • Date: 2004-05-09 11:33:00 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20040509113300-vfrdadqsvjfuhn3b
Tags: 1:1.3.1-1
* New upstream bugfix release.
* Built against newer imagemagick (closes: #246623).
* Made koffice-libs/kformula recommend/depend on latex-xft-fonts, which
  provides mathematical fonts that the formula editor can use.  Also
  patched the kformula part to make these fonts the default.
* Changed kword menu hint from "WordProcessors" to "Word processors"
  (closes: #246209).
* Spellchecker configuration is now fixed (closes: #221256, #227568).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
//
 
2
 
 
3
/*
 
4
   This file is part of the KDE project
 
5
   Copuright 2001 Michael Johnson <mikej@xnet.com>
 
6
   Copyright 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
 
7
   Copyright 2002 Ariya Hidayat <ariya@kde.org>
 
8
 
 
9
   This library is free software; you can redistribute it and/or
 
10
   modify it under the terms of the GNU Library General Public
 
11
   License as published by the Free Software Foundation; either
 
12
   version 2 of the License, or (at your option) any later version.
 
13
 
 
14
   This library is distributed in the hope that it will be useful,
 
15
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
16
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
17
   Library General Public License for more details.
 
18
 
 
19
   You should have received a copy of the GNU Library General Public License
 
20
   along with this library; see the file COPYING.LIB.  If not, write to
 
21
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 
22
   Boston, MA 02111-1307, USA.
 
23
*/
 
24
 
 
25
#include <qstring.h>
 
26
#include <qtextcodec.h>
 
27
#include <qfile.h>
 
28
#include <qfileinfo.h>
 
29
#include <qfontinfo.h>
 
30
#include <qpicture.h>
 
31
#include <qregion.h> // for #include <kdebugclasses.h>
 
32
#include <qimage.h>
 
33
#include <qregexp.h>
 
34
#include <qcolor.h>
 
35
#include <qdatetime.h>
 
36
 
 
37
#include <klocale.h>
 
38
#include <kglobal.h>
 
39
#include <kdebug.h>
 
40
#include <kdebugclasses.h>
 
41
 
 
42
#include <KWEFUtil.h>
 
43
#include <KWEFBaseWorker.h>
 
44
 
 
45
#include "ExportFilter.h"
 
46
 
 
47
// 1 twip = 1/20 pt = 1/1400 inch
 
48
// 1 inch = 25.4 mm
 
49
 
 
50
// some conversion macros
 
51
#define TWIP_TO_MM(x) (x)*25.4/1440.0
 
52
#define MM_TO_TWIP(x) (x)*1440.0/25.4
 
53
#define PT_TO_TWIP(x) (x)*20
 
54
#define TWIP_TO_PT(x) (x)/20
 
55
 
 
56
// map KWord field name to RTF field name
 
57
// e.g authorName -> AUTHOR
 
58
static QString mapFieldName( const QString& kwordField )
 
59
{
 
60
  QString rtfField;
 
61
 
 
62
  if( kwordField == "fileName" ) rtfField = "FILENAME";
 
63
  else if( kwordField == "authorName" ) rtfField = "AUTHOR";
 
64
  else if( kwordField == "docTitle" ) rtfField = "TITLE";
 
65
 
 
66
  return rtfField;
 
67
}
 
68
 
 
69
RTFWorker::RTFWorker():
 
70
    m_ioDevice(NULL), m_streamOut(NULL), m_eol("\r\n"), m_inTable(false),
 
71
    m_paperOrientation(false), m_paperWidth(20), m_paperHeight(20),
 
72
    m_paperMarginTop(72), m_paperMarginLeft(72),
 
73
    m_paperMarginBottom(72), m_paperMarginRight(72), m_startPageNumber(1)
 
74
{
 
75
}
 
76
 
 
77
static QString WritePositiveKeyword(const QString& keyword, const int value)
 
78
{
 
79
    QString str;
 
80
    str += keyword;
 
81
 
 
82
    if (value>0) // The value of the keyword cannot be negative
 
83
        str += QString::number( value );
 
84
    else
 
85
        str += '0';
 
86
 
 
87
    return str;
 
88
}
 
89
 
 
90
QString RTFWorker::writeRow(const QString& textCellHeader, const QString& rowText, const FrameData& frame)
 
91
{
 
92
    QString row;
 
93
 
 
94
    row += "\\trowd\\trgaph60\\trql";  // start new row
 
95
    row += WritePositiveKeyword("\\trrh", qRound(PT_TO_TWIP(frame.minHeight)));
 
96
    row += WritePositiveKeyword("\\trleft", qRound(PT_TO_TWIP(frame.left) - m_paperMarginLeft));
 
97
    //row += "\\trautofit0"; // ### VERIFY
 
98
    row += textCellHeader;
 
99
    row += " "; // End of keyword
 
100
    row += rowText;
 
101
 
 
102
    return row;
 
103
}
 
104
 
 
105
QString RTFWorker::writeBorder(const char whichBorder, const int borderWidth, const QColor& color)
 
106
{
 
107
    QString str;
 
108
    if (borderWidth > 0)
 
109
    {
 
110
        str += "\\clbrdr"; // Define border
 
111
        str += whichBorder; // t=top, l=left, b=bottom, r=right
 
112
        str += "\\brdrs\\brdrw"; // Single border; thickness
 
113
        str += QString::number(borderWidth);
 
114
        if (color.isValid())
 
115
        {
 
116
            str += lookupColor("\\brdrcf",color);
 
117
        }
 
118
    }
 
119
    return str;
 
120
}
 
121
 
 
122
QString RTFWorker::makeTable(const FrameAnchor& anchor)
 
123
{
 
124
    QString textBody; // Text to be returned
 
125
    textBody += m_prefix;
 
126
    m_prefix = QString::null;
 
127
    QString rowText;
 
128
 
 
129
    int rowCurrent = 0;
 
130
    bool firstCellInRow = true;
 
131
    FrameData firstFrameData;
 
132
    int debugCellCurrent = 0; //DEBUG
 
133
    int debugRowCurrent = 0; //DEBUG
 
134
    QString textCellHeader; // <celldef>
 
135
 
 
136
    const bool oldInTable = m_inTable;
 
137
    m_inTable = true;
 
138
 
 
139
    QValueList<TableCell>::ConstIterator itCell;
 
140
    for (itCell=anchor.table.cellList.begin();
 
141
        itCell!=anchor.table.cellList.end(); itCell++)
 
142
    {
 
143
        // ### TODO: rowspan, colspan
 
144
        if (rowCurrent!=(*itCell).row)
 
145
        {
 
146
            rowCurrent = (*itCell).row;
 
147
            textBody += writeRow( textCellHeader, rowText, firstFrameData);
 
148
            textBody += "\\row";
 
149
            textBody += m_eol;
 
150
            rowText = QString::null;
 
151
            textCellHeader = QString::null;
 
152
            firstCellInRow=true;
 
153
            debugRowCurrent ++; // DEBUG
 
154
            debugCellCurrent = 0; //DEBUG
 
155
        }
 
156
 
 
157
        const FrameData& frame = (*itCell).frame;
 
158
 
 
159
        if (firstCellInRow) // Not yet set, so set the position of the left border.
 
160
        {
 
161
            firstFrameData=frame;
 
162
            firstCellInRow=false;
 
163
        }
 
164
 
 
165
        kdDebug(30515) << "Cell: " << debugRowCurrent << "," << debugCellCurrent
 
166
            << " left: " << frame.left << " right: " << frame.right << " top: " << frame.top << " bottom " << frame.bottom << endl;
 
167
        textCellHeader += writeBorder('t',qRound(PT_TO_TWIP(frame.tWidth)),frame.tColor);
 
168
        textCellHeader += writeBorder('l',qRound(PT_TO_TWIP(frame.lWidth)),frame.lColor);
 
169
        textCellHeader += writeBorder('b',qRound(PT_TO_TWIP(frame.bWidth)),frame.bColor);
 
170
        textCellHeader += writeBorder('r',qRound(PT_TO_TWIP(frame.rWidth)),frame.rColor);
 
171
        textCellHeader += WritePositiveKeyword("\\cellx",qRound(PT_TO_TWIP(frame.right) - m_paperMarginRight)); //right border of cell
 
172
 
 
173
        QString endOfParagraph;
 
174
        QValueList<ParaData> *paraList = (*itCell).paraList;
 
175
        QValueList<ParaData>::ConstIterator it;
 
176
        for (it=paraList->begin();it!=paraList->end();it++)
 
177
        {
 
178
            rowText += endOfParagraph;
 
179
            rowText += ProcessParagraphData( (*it).text,(*it).layout,(*it).formattingList);
 
180
            rowText += m_eol;
 
181
            endOfParagraph = "\\par"; // The problem is that the last paragraph ends with \cell not with \par
 
182
        }
 
183
        rowText += "\\cell";
 
184
        debugCellCurrent ++; // DEBUG
 
185
    }
 
186
 
 
187
    textBody += writeRow( textCellHeader, rowText, firstFrameData);
 
188
    textBody += "\\row\\pard";  // delimit last row
 
189
    textBody += m_eol;
 
190
    m_inTable = oldInTable;
 
191
 
 
192
    return textBody;
 
193
}
 
194
 
 
195
QString RTFWorker::makeImage(const FrameAnchor& anchor)
 
196
{
 
197
    QString textBody; // Text to be returned
 
198
 
 
199
    QString strImageName(anchor.picture.koStoreName);
 
200
    QString strExt;
 
201
    QByteArray image;
 
202
 
 
203
    kdDebug(30515) << "RTFWorker::makeImage" << endl << anchor.picture.koStoreName << endl;
 
204
 
 
205
    const int pos=strImageName.findRev('.');
 
206
    if(pos!=-1) strExt = strImageName.mid(pos+1).lower();
 
207
 
 
208
    QString strTag;
 
209
    if (strExt=="png")
 
210
        strTag="\\pngblip";
 
211
#if 0
 
212
    else if (strExt=="bmp")
 
213
        strTag="\\dibitmap";
 
214
#endif
 
215
    else if ( (strExt=="jpeg") || (strExt=="jpg") )
 
216
        strTag="\\jpegblip";
 
217
    else if (strExt=="wmf")
 
218
        strTag="\\wmetafile8"; // 8 == anisotropic
 
219
    else
 
220
    {
 
221
        // either without extension or format is unknown
 
222
        // let's try to convert it to PNG format
 
223
        kdDebug(30515) << "Converting image " << anchor.picture.koStoreName << endl;
 
224
 
 
225
        strTag="\\pngblip";
 
226
        if( !loadAndConvertToImage(anchor.picture.koStoreName,strExt,"PNG",image) )
 
227
        {
 
228
            kdWarning(30515) << "Unable to convert " << anchor.picture.koStoreName << endl;
 
229
            return QString::null;
 
230
        }
 
231
    }
 
232
    // ### TODO: SVG, QPicture
 
233
 
 
234
    // load the image, this isn't necessary for converted image
 
235
    if( !image.size() )
 
236
        if (!loadSubFile(anchor.picture.koStoreName,image))
 
237
        {
 
238
            kdWarning(30515) << "Unable to load picture " << anchor.picture.koStoreName << endl;
 
239
            return QString::null;
 
240
        }
 
241
 
 
242
 
 
243
    // find displayed width and height (in twips)
 
244
    const long width  = (long)(PT_TO_TWIP(anchor.frame.right  - anchor.frame.left));
 
245
    const long height = (long)(PT_TO_TWIP(anchor.frame.bottom - anchor.frame.top));
 
246
 
 
247
    // find original image width and height (in twips)
 
248
    long origWidth  = width;
 
249
    long origHeight = height;
 
250
    if( strExt == "wmf" )
 
251
    {
 
252
        // special treatment for WMF with metaheader
 
253
        // d7cdc69a is metaheader magic id
 
254
        Q_UINT8* data = (Q_UINT8*) image.data();
 
255
        if( ( data[0] == 0xd7 ) && ( data[1] == 0xcd ) &&
 
256
            ( data[2] == 0xc6 ) && ( data[3] == 0x9a ) &&
 
257
            ( image.size() > 22 ) )
 
258
        {
 
259
            // grab bounding box, find original size
 
260
            unsigned left = data[6]+(data[7]<<8);
 
261
            unsigned top = data[8]+(data[9]<<8);
 
262
            unsigned right = data[10]+(data[11]<<8);
 
263
            unsigned bottom = data[12]+(data[13]<<8);
 
264
            origWidth = (long) (MM_TO_TWIP(right-left)/100);
 
265
            origHeight = (long) (MM_TO_TWIP(bottom-top)/100);
 
266
 
 
267
            // throw away WMF metaheader (22 bytes)
 
268
            for( uint i=0; i<image.size()-22; i++)
 
269
                image.at(i) = image.at(i+22); // As we use uint, we need at()  ( [] uses int only .)
 
270
            image.resize( image.size()-22 );
 
271
        }
 
272
    }
 
273
    else
 
274
    {
 
275
        // It must be an image
 
276
        QImage img( image );
 
277
        if( img.isNull() )
 
278
        {
 
279
            kdWarning(30515) << "Unable to load picture as image " << anchor.picture.koStoreName << endl;
 
280
            return QString::null;
 
281
        }
 
282
        // check resolution, assume 2835 dpm (72 dpi) if not available
 
283
        int resx = img.dotsPerMeterX();
 
284
        int resy = img.dotsPerMeterY();
 
285
        if( resx <= 0 ) resx = 2835;
 
286
        if( resy <= 0 ) resy = 2835;
 
287
 
 
288
        origWidth =  long(img.width() * 2834.65 * 20 / resx);
 
289
        origHeight = long(img.height() * 2834.65 * 20 / resy);
 
290
    }
 
291
 
 
292
    // Now that we are sure to have a valid image, we can write the RTF tags
 
293
    textBody += "{\\pict";
 
294
    textBody += strTag;
 
295
 
 
296
    // calculate scaling factor (in percentage)
 
297
    int scaleX = width * 100 / origWidth;
 
298
    int scaleY = height * 100 / origHeight;
 
299
 
 
300
    // size in 1/100 mm
 
301
    int picw = (int)(100 * TWIP_TO_MM(origWidth));
 
302
    int pich = (int)(100 * TWIP_TO_MM(origHeight));
 
303
 
 
304
    textBody += "\\picscalex";
 
305
    textBody += QString::number(scaleX, 10);
 
306
    textBody += "\\picscaley";
 
307
    textBody += QString::number(scaleY, 10);
 
308
    textBody += "\\picw";
 
309
    textBody += QString::number(picw,10);
 
310
    textBody += "\\pich";
 
311
    textBody += QString::number(pich,10);
 
312
    textBody += "\\picwgoal";
 
313
    textBody += QString::number(origWidth, 10);
 
314
    textBody += "\\pichgoal";
 
315
    textBody += QString::number(origHeight, 10);
 
316
 
 
317
    textBody+=" ";
 
318
    const char hex[] = "0123456789abcdef";
 
319
    for (uint i=0; i<image.size(); i++)
 
320
    {
 
321
        if (!(i%40))
 
322
            textBody += m_eol;
 
323
        const char ch=image.at(i);
 
324
        textBody += hex[(ch>>4)&0x0f]; // Done this way to avoid signed/unsigned problems
 
325
        textBody += hex[(ch&0x0f)];
 
326
    }
 
327
 
 
328
 
 
329
    textBody+="}";
 
330
 
 
331
    return textBody;
 
332
}
 
333
 
 
334
QString RTFWorker::formatTextParagraph(const QString& strText,
 
335
    const FormatData& formatOrigin, const FormatData& format)
 
336
{
 
337
    QString str;
 
338
 
 
339
    if (!format.text.missing)
 
340
    {
 
341
        // Opening elements
 
342
        str+=openSpan(formatOrigin,format);
 
343
    }
 
344
 
 
345
    QString strEscaped = escapeRtfText(strText);
 
346
 
 
347
    // Replace line feeds by forced line breaks
 
348
    int pos;
 
349
    QString strBr("\\line ");
 
350
    while ((pos=strEscaped.find(QChar(10)))>-1)
 
351
    {
 
352
        strEscaped.replace(pos,1,strBr);
 
353
    }
 
354
 
 
355
    str+=strEscaped;
 
356
 
 
357
    if (!format.text.missing)
 
358
    {
 
359
        // Closing elements
 
360
        str+=closeSpan(formatOrigin,format);
 
361
    }
 
362
 
 
363
    return str;
 
364
}
 
365
 
 
366
QString RTFWorker::ProcessParagraphData ( const QString &paraText,
 
367
    const LayoutData& layout, const ValueListFormatData &paraFormatDataList)
 
368
{
 
369
    QString str;
 
370
    QString content;
 
371
    QString markup;
 
372
    // open paragraph
 
373
    markup += "\\pard";
 
374
    markup += "\\plain";
 
375
    if (m_inTable)
 
376
        markup += "\\intbl";
 
377
 
 
378
//lists
 
379
if (layout.counter.style)
 
380
        {
 
381
        markup += "{\\pntext\\pard\\plain";
 
382
        if( layout.formatData.text.fontSize >= 0)
 
383
        {
 
384
                markup += "\\fs";
 
385
                markup += QString::number((2 * layout.formatData.text.fontSize));
 
386
                markup += lookupFont("\\f",layout.formatData.text.fontName);
 
387
        }
 
388
        markup += " ";
 
389
        markup += layout.counter.text;
 
390
        markup += "\\tab}{\\*\\pn";
 
391
        if (layout.counter.style > 5)
 
392
        {
 
393
        markup += "\\pnlvlblt ";
 
394
        markup += "{\\pntxtb ";
 
395
        if (!layout.counter.lefttext.isEmpty() && layout.counter.lefttext != "{" && layout.counter.lefttext != "}")
 
396
        {
 
397
                markup += layout.counter.lefttext;
 
398
        }        
 
399
        switch (layout.counter.style)
 
400
        {
 
401
        case 6:
 
402
        {
 
403
                //custom bullets (one char)
 
404
                //TODO: use correct character/sign for bullet
 
405
                
 
406
            markup += layout.counter.customCharacter;
 
407
            break;
 
408
        }
 
409
        case 7:
 
410
        {
 
411
                //custom bullets (complex)
 
412
            markup += layout.counter.text;
 
413
            break;
 
414
        }
 
415
        case 8:
 
416
        {
 
417
                //circle bullets
 
418
                //TODO: use correct character/sign for bullet
 
419
            markup += "\\bullet";
 
420
            break;
 
421
        }
 
422
        case 9:
 
423
        {
 
424
                //square bullets
 
425
                //TODO: use correct character/sign for bullet
 
426
            markup += "\\bullet";
 
427
            break;
 
428
        }
 
429
        case 10:
 
430
        {
 
431
                //disc bullets
 
432
                //TODO: make work in OO
 
433
            markup += "\\bullet";
 
434
            break;
 
435
        }
 
436
        case 11:
 
437
        {
 
438
                //disc bullets
 
439
                //TODO: use correct character/sign for bullet
 
440
            markup += layout.counter.text;
 
441
            break;
 
442
        }
 
443
        default:
 
444
            markup += "\\bullet";
 
445
        }
 
446
        markup += "}";
 
447
        }
 
448
        else
 
449
        {
 
450
            if (layout.counter.numbering!=0)
 
451
                {
 
452
                    markup += "\\pnlvl";
 
453
                    markup += QString::number(layout.counter.depth + 1);
 
454
                    markup += "\\pnprev1";
 
455
                }
 
456
        else if (layout.counter.style==1)
 
457
        {
 
458
        markup += "\\pnlvlbody";
 
459
        }
 
460
        else
 
461
        {
 
462
        markup += "\\pnlvl";
 
463
        markup += QString::number(11 - layout.counter.style);
 
464
        }
 
465
        
 
466
        switch (layout.counter.style)
 
467
        {        
 
468
        case 1:
 
469
        {
 
470
        markup += "\\pndec";
 
471
        break;
 
472
        }
 
473
        case 2:
 
474
        {
 
475
        markup += "\\pnlcltr";
 
476
        break;
 
477
        }
 
478
        case 3:
 
479
        {
 
480
        markup += "\\pnucltr";
 
481
        break;
 
482
        }
 
483
        case 4:
 
484
        {
 
485
        markup += "\\pnlcrm";
 
486
        break;
 
487
        }
 
488
        case 5:
 
489
        {
 
490
        markup += "\\pnucrm";
 
491
        break;
 
492
        }
 
493
        default:
 
494
        markup += "\\pndec";
 
495
        }
 
496
        markup += "{\\pntxtb ";
 
497
        markup += layout.counter.lefttext;  
 
498
        markup += " }";
 
499
    }
 
500
        markup += "{\\pntxta ";
 
501
        markup += layout.counter.righttext;  
 
502
        markup += " }";
 
503
        
 
504
        if (layout.counter.start!=0)
 
505
        {
 
506
        markup += "\\pnstart";
 
507
        markup += QString::number(layout.counter.start);
 
508
        }
 
509
        else
 
510
        {
 
511
        markup += "\\pnstart1";
 
512
        }
 
513
        markup += "\\pnindent0\\pnhang";
 
514
        
 
515
        if( layout.formatData.text.fontSize > 0 )
 
516
        {
 
517
        markup += "\\pnfs";
 
518
        markup += QString::number((2 * layout.formatData.text.fontSize));
 
519
        }
 
520
 
 
521
        if( !layout.formatData.text.fontName.isEmpty() )
 
522
        {
 
523
            markup += lookupFont("\\pnf", layout.formatData.text.fontName);
 
524
        }
 
525
        
 
526
        markup += "}";
 
527
}    
 
528
 
 
529
 
 
530
    LayoutData styleLayout;
 
531
    markup += lookupStyle(layout.styleName, styleLayout);
 
532
    markup += layoutToRtf(styleLayout,layout,true);
 
533
 
 
534
    if ( 1==layout.formatData.text.verticalAlignment )
 
535
    {
 
536
        markup += "\\sub"; //Subscript
 
537
    }
 
538
    else if ( 2==layout.formatData.text.verticalAlignment )
 
539
    {
 
540
        markup += "\\super"; //Superscript
 
541
    }
 
542
 
 
543
 
 
544
    if (layout.pageBreakBefore)
 
545
        content += "\\page ";
 
546
 
 
547
 
 
548
 
 
549
 
 
550
 
 
551
    if (!paraText.isEmpty())
 
552
    {
 
553
 
 
554
        ValueListFormatData::ConstIterator  paraFormatDataIt;
 
555
 
 
556
        QString partialText;
 
557
 
 
558
        FormatData formatRef = layout.formatData;
 
559
 
 
560
        for ( paraFormatDataIt = paraFormatDataList.begin ();
 
561
              paraFormatDataIt != paraFormatDataList.end ();
 
562
              paraFormatDataIt++ )
 
563
        {
 
564
            if (1==(*paraFormatDataIt).id)
 
565
            {
 
566
                //Retrieve text
 
567
                partialText=paraText.mid ( (*paraFormatDataIt).pos, (*paraFormatDataIt).len );
 
568
                content +=formatTextParagraph(partialText, formatRef, *paraFormatDataIt);
 
569
            }
 
570
            else if (4==(*paraFormatDataIt).id)
 
571
            {
 
572
                // ### TODO: put dtae/time fields into own method.
 
573
                if ( (0==(*paraFormatDataIt).variable.m_type) // date
 
574
                    || (2==(*paraFormatDataIt).variable.m_type) ) // time
 
575
                {
 
576
                    // ### TODO: fixed/variable date
 
577
                    content += "{\\field{\\*\\fldinst ";
 
578
                    if (0==(*paraFormatDataIt).variable.m_type)
 
579
                        content += "DATE ";
 
580
                    else
 
581
                        content += "TIME ";
 
582
                    QString key((*paraFormatDataIt).variable.m_key.mid(4));
 
583
                    kdDebug(30515) << "Time format: " << key << endl;
 
584
                    if (key.startsWith("locale"))
 
585
                    {
 
586
                        if (key == "locale" )
 
587
                        {
 
588
                            if (0==(*paraFormatDataIt).variable.m_type)
 
589
                                key = KGlobal::locale()->dateFormat();
 
590
                            else
 
591
                                key = KGlobal::locale()->timeFormat();
 
592
                        }
 
593
                        else if ( key == "localeshort" )
 
594
                            key = KGlobal::locale()->dateFormatShort();
 
595
                        else if ( key == "localedatetime" )
 
596
                        {
 
597
                            key = KGlobal::locale()->dateFormat();
 
598
                            key += ' ';
 
599
                            key += KGlobal::locale()->timeFormat();
 
600
                        }
 
601
                        else if ( key == "localedatetimeshort" )
 
602
                        {
 
603
                            key = KGlobal::locale()->dateFormat();
 
604
                            key += ' ';
 
605
                            key += KGlobal::locale()->timeFormat();
 
606
                        }
 
607
                        kdDebug(30515) << "KDE format:  " << key << endl;
 
608
                        key=QString::null; // ### FIXME: KControl's key seems to differ from KWord :-(
 
609
                    }
 
610
                    if (!key.isEmpty())
 
611
                    {
 
612
                        const QRegExp regexp("AP",false); // Not case-sensitive
 
613
                        if (regexp.search(key)!=-1)
 
614
                        {
 
615
                            // 12h
 
616
                            key.replace("ap","am/pm");
 
617
                            key.replace("AP","AM/PM");
 
618
                        }
 
619
                        else
 
620
                        {
 
621
                            //24h
 
622
                            key.replace('h','H'); // MS Word uses H for 24hour times
 
623
                        }
 
624
                        // MS Word do not know possesive months
 
625
                        key.replace("PPP","MMM");
 
626
                        key.replace("PPPP","MMMM");
 
627
                        key.replace("zzz","000"); // replace microseconds by 000
 
628
                        kdDebug(30515) << "New format:  " << key << endl;
 
629
                        content += "\\@ \"";
 
630
                        content += key;
 
631
                        content += "\" ";
 
632
                    }
 
633
                    content += "\\* MERGEFORMAT }{\\fldrslt ";
 
634
                    content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
635
                    content += "}}";
 
636
                }
 
637
                else if (4==(*paraFormatDataIt).variable.m_type)
 
638
                {
 
639
                    QString strFieldType;
 
640
                    if ((*paraFormatDataIt).variable.isPageNumber())
 
641
                    {
 
642
                        content += "{\\field{\\*\\fldinst PAGE \\* MERGEFORMAT }{\\fldrslt ";
 
643
                        content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
644
                        content += "}}";
 
645
                    }
 
646
                    else if ((*paraFormatDataIt).variable.isPageCount())
 
647
                    {
 
648
                        content += "{\\field{\\*\\fldinst NUMPAGES \\* MERGEFORMAT }{\\fldrslt ";
 
649
                        content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
650
                        content += "}}";
 
651
                    }
 
652
                    else
 
653
                    {
 
654
                        // Unknown subtype, therefore write out the result
 
655
                        content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
656
                    }
 
657
                }
 
658
                else if (8==(*paraFormatDataIt).variable.m_type)
 
659
                {
 
660
                    // Field
 
661
                    QString name = escapeRtfText((*paraFormatDataIt).variable.getFieldName());
 
662
                    QString value = escapeRtfText((*paraFormatDataIt).variable.getFieldValue());
 
663
                    QString rtfField = mapFieldName(name);
 
664
 
 
665
                    if( rtfField.isEmpty() )
 
666
                        // Couldn't map field name, just write out the value
 
667
                        content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
668
                    else
 
669
                    {
 
670
                        content += "{\\field";
 
671
                        content += "{\\*\\fldinst ";
 
672
                        content +=  rtfField;
 
673
                        content += "  \\* MERGEFORMAT }";
 
674
                        content += "{\\fldrslt {";
 
675
                        content += value;
 
676
                        content += "}}}";
 
677
                    }
 
678
                }
 
679
                else if (9==(*paraFormatDataIt).variable.m_type)
 
680
                {
 
681
                    // A link
 
682
                    content += "{\\field";
 
683
                    content += "{\\*\\fldinst HYPERLINK ";
 
684
                    content +=  escapeRtfText((*paraFormatDataIt).variable.getHrefName());
 
685
                    content += "}";
 
686
                    content += "{\\fldrslt ";
 
687
                    content += "{\\ul";   // underline, ### TODO: use style Hyperlink
 
688
                    content += lookupColor("\\cf",QColor(0,0,255));// blue
 
689
                    content += escapeRtfText((*paraFormatDataIt).variable.getLinkName());
 
690
                    content += "}}}";
 
691
                }
 
692
                else if (11==(*paraFormatDataIt).variable.m_type)
 
693
                {
 
694
                    // Footnote
 
695
                    QString value = (*paraFormatDataIt).variable.getFootnoteValue();
 
696
                    bool automatic = (*paraFormatDataIt).variable.getFootnoteAuto();
 
697
                    QValueList<ParaData> *paraList = (*paraFormatDataIt).variable.getFootnotePara();
 
698
                    if( paraList )
 
699
                    {
 
700
                        QString fstr;
 
701
                        QValueList<ParaData>::ConstIterator it;
 
702
                        for (it=paraList->begin();it!=paraList->end();it++)
 
703
                            fstr += ProcessParagraphData( (*it).text, (*it).layout,(*it).formattingList);
 
704
                        content += "{\\super ";
 
705
                        content += automatic ? "\\chftn " : value;
 
706
                        content += "{\\footnote ";
 
707
                        content += "{\\super ";
 
708
                        content += automatic ? "\\chftn " : value;
 
709
                        content += fstr;
 
710
                        content += " }";
 
711
                        content += " }";
 
712
                        content += " }";
 
713
                    }
 
714
                }
 
715
                else
 
716
                {
 
717
                    // Generic variable
 
718
                    content += escapeRtfText((*paraFormatDataIt).variable.m_text);
 
719
                }
 
720
            }
 
721
            else if (6==(*paraFormatDataIt).id)
 
722
            {
 
723
                kdDebug(30515) << "Found an anchor of type: " << (*paraFormatDataIt).frameAnchor.type << endl;
 
724
                // We have an image, a clipart or a table
 
725
               
 
726
                if (6==(*paraFormatDataIt).frameAnchor.type)
 
727
                {
 
728
 
 
729
 
 
730
                    if (!content.isEmpty())
 
731
                    {
 
732
                        str += m_prefix;
 
733
                        str += markup;
 
734
                        str += " {";
 
735
                        str += content;
 
736
                        str += "}";
 
737
                        str += m_eol;
 
738
                        content = QString::null;
 
739
                        if (!m_inTable)
 
740
                        {
 
741
                            m_prefix = "\\par";
 
742
                        }
 
743
                    } 
 
744
                    str += makeTable((*paraFormatDataIt).frameAnchor);
 
745
                }
 
746
                else if ((2==(*paraFormatDataIt).frameAnchor.type) || (5==(*paraFormatDataIt).frameAnchor.type))
 
747
                {
 
748
                    content += makeImage((*paraFormatDataIt).frameAnchor);
 
749
                
 
750
                }
 
751
            }
 
752
        }
 
753
    }
 
754
 
 
755
    if (layout.pageBreakAfter)
 
756
        content += "\\page";
 
757
 
 
758
    if (!content.isEmpty())
 
759
    {
 
760
        str += m_prefix;
 
761
        str += markup;
 
762
        str += " {";
 
763
        str += content;
 
764
        str += "}";
 
765
        str += m_eol;
 
766
        if (m_inTable==false)
 
767
        {
 
768
           m_prefix = "\\par";
 
769
        }
 
770
    } 
 
771
    if (str.isEmpty())
 
772
    {
 
773
     str ="\\par\\pard\\plain";
 
774
    if (m_inTable==false)
 
775
    {
 
776
       m_prefix = "\\par";
 
777
    }
 
778
    }
 
779
    return str;
 
780
}
 
781
 
 
782
bool RTFWorker::doFullParagraph(const QString& paraText,
 
783
    const LayoutData& layout, const ValueListFormatData& paraFormatDataList)
 
784
{
 
785
    kdDebug(30515) << "Entering RTFWorker::doFullParagraph" << endl << paraText << endl;
 
786
    QString par = ProcessParagraphData( paraText, layout, paraFormatDataList);
 
787
    m_textBody += par;
 
788
    kdDebug(30515) << "Quiting RTFWorker::doFullParagraph" << endl;
 
789
    return true;
 
790
}
 
791
 
 
792
bool RTFWorker::doHeader(const HeaderData& header)
 
793
{
 
794
    QString str;
 
795
    QString content;
 
796
    if( header.page == HeaderData::PAGE_ODD )
 
797
        str = "\\facingp{\\headerr";
 
798
    else if( header.page == HeaderData::PAGE_EVEN )
 
799
        str = "\\facingp{\\headerl";
 
800
    else if( header.page == HeaderData::PAGE_FIRST )
 
801
        str = "\\facingp{\\headerl";
 
802
    else if( header.page == HeaderData::PAGE_ALL )
 
803
        str = "{\\header";
 
804
    else
 
805
        return false;
 
806
 
 
807
    str += " {";
 
808
 
 
809
    QValueList<ParaData>::ConstIterator it;
 
810
    for (it=header.para.begin();it!=header.para.end();it++)
 
811
        content += ProcessParagraphData( (*it).text,(*it).layout,(*it).formattingList);
 
812
 
 
813
    if (content!="\\par\\pard\\plain")
 
814
    {
 
815
    str += content;
 
816
    str += "}";
 
817
 
 
818
    str += "}";
 
819
    
 
820
    m_textBody += str;
 
821
    }
 
822
    m_prefix=QString::null;
 
823
    return true;
 
824
}
 
825
 
 
826
bool RTFWorker::doFooter(const FooterData& footer)
 
827
{
 
828
    QString str;
 
829
    QString content;
 
830
    if( footer.page == FooterData::PAGE_ODD )
 
831
        str = "\\facingp{\\footerr";
 
832
    else if( footer.page == FooterData::PAGE_EVEN )
 
833
        str = "\\facingp{\\footerl";
 
834
    else if( footer.page == FooterData::PAGE_FIRST )
 
835
        str = "\\facingp{\\headerl";
 
836
    else if( footer.page == FooterData::PAGE_ALL )
 
837
        str = "{\\footer";
 
838
    else
 
839
        return false;
 
840
 
 
841
    str += " {";
 
842
 
 
843
    QValueList<ParaData>::ConstIterator it;
 
844
    for (it=footer.para.begin();it!=footer.para.end();it++)
 
845
        content += ProcessParagraphData( (*it).text,(*it).layout,(*it).formattingList);
 
846
 
 
847
    if (content!="\\par\\pard\\plain")
 
848
    {
 
849
    str += content;
 
850
    str += "}";
 
851
 
 
852
    str += "}";
 
853
    
 
854
    m_textBody += str;
 
855
    }
 
856
    m_prefix=QString::null;
 
857
    return true;
 
858
}
 
859
 
 
860
bool RTFWorker::doOpenFile(const QString& filenameOut, const QString& /*to*/)
 
861
{
 
862
    m_ioDevice=new QFile(filenameOut);
 
863
 
 
864
    if (!m_ioDevice)
 
865
    {
 
866
        kdError(30515) << "No output file! Aborting!" << endl;
 
867
        return false;
 
868
    }
 
869
 
 
870
    if ( !m_ioDevice->open (IO_WriteOnly) )
 
871
    {
 
872
        kdError(30515) << "Unable to open output file!" << endl;
 
873
        return false;
 
874
    }
 
875
 
 
876
    m_streamOut=new QTextStream(m_ioDevice);
 
877
 
 
878
    m_streamOut->setEncoding(QTextStream::UnicodeUTF8); // We want ASCII, so use UTF-8
 
879
 
 
880
    m_fileName=filenameOut;
 
881
 
 
882
    return true;
 
883
}
 
884
 
 
885
bool RTFWorker::doCloseFile(void)
 
886
{
 
887
    kdDebug(30515) << __FILE__ << ":" << __LINE__ << endl;
 
888
    delete m_streamOut;
 
889
    m_streamOut=NULL;
 
890
    if (m_ioDevice)
 
891
        m_ioDevice->close();
 
892
    return true;
 
893
}
 
894
 
 
895
bool RTFWorker::doOpenDocument(void)
 
896
{
 
897
    // Make the file header
 
898
 
 
899
    // Note: we use \\ansicpg1252 because 1200 is not supposed to be supported
 
900
    // Note2: we assume using \\ansicpg1252 in RTFWorker::escapeRtfText
 
901
    *m_streamOut << "{\\rtf1\\ansi\\ansicpg1252\\uc1\\deff0" << m_eol;
 
902
 
 
903
    // Default color table
 
904
    m_colorList
 
905
        << QColor(0,0,0)     << QColor(0,0,255)     << QColor(0,255,255)
 
906
        << QColor(0,255,0)   << QColor(255,0,255)   << QColor(255,0,0)
 
907
        << QColor(255,255,0) << QColor(255,255,255) << QColor(0,0,128)
 
908
        << QColor(0,128,128) << QColor(0,128,0)     << QColor(128,0,128)
 
909
        << QColor(128,0,0)   << QColor(128,128,0)   << QColor(128,128,128);
 
910
 
 
911
    return true;
 
912
}
 
913
 
 
914
void RTFWorker::writeFontData(void)
 
915
{
 
916
    kdDebug(30515) << "Fonts:" << m_fontList << endl;
 
917
    *m_streamOut << "{\\fonttbl";
 
918
    uint count;
 
919
    QStringList::ConstIterator it;
 
920
    for (count=0, it=m_fontList.begin();
 
921
        it!=m_fontList.end();
 
922
        count++, it++)
 
923
    {
 
924
        QFontInfo info(*it);
 
925
        QString strLower(info.family().lower());
 
926
        *m_streamOut << "{\\f" << count;
 
927
        if ( (strLower.find("symbol")>-1) || (strLower.find("dingbat")>-1) )
 
928
            *m_streamOut << "\\ftech";
 
929
        else if ( (strLower.find("script")>-1) )
 
930
            *m_streamOut << "\\fscript";
 
931
 
 
932
#if 1
 
933
        else
 
934
        {
 
935
            // We do not know the font type that we have and we cannot even tell if it is TrueType
 
936
            *m_streamOut << "\\fnil";
 
937
        }
 
938
#else
 
939
        else
 
940
        // QFontInfo:styleHint() does not guess anything, it just returns what is in the QFont. Nothing put in, nothing gets out.
 
941
        {
 
942
            switch (info.styleHint())
 
943
            {
 
944
            case QFont::SansSerif:
 
945
            default:
 
946
                {
 
947
                    *m_streamOut << "\\fswiss";
 
948
                    break;
 
949
                }
 
950
            case QFont::Serif:
 
951
                {
 
952
                    *m_streamOut << "\\froman";
 
953
                    break;
 
954
                }
 
955
            case QFont::Courier:
 
956
                {
 
957
                    *m_streamOut << "\\fmodern";
 
958
                    break;
 
959
                }
 
960
            case QFont::OldEnglish:
 
961
                {
 
962
                    *m_streamOut << "\\fdecor";
 
963
                    break;
 
964
                }
 
965
            }
 
966
        }
 
967
#endif
 
968
        // ### TODO: check if QFontInfo::fixedPitch is really working
 
969
        *m_streamOut << "\\fprq" << (info.fixedPitch()?1:2) << " "; // font definition
 
970
        *m_streamOut << escapeRtfText(info.family()); // ### TODO: does RTF allows brackets in the font names?
 
971
        *m_streamOut <<  ";}" << m_eol; // end font table entry
 
972
    }
 
973
    *m_streamOut << "}"; // end of font table
 
974
}
 
975
 
 
976
void RTFWorker::writeColorData(void)
 
977
{
 
978
    *m_streamOut << "{\\colortbl;";
 
979
    uint count;
 
980
    QValueList<QColor>::ConstIterator it;
 
981
    for (count=0, it=m_colorList.begin();
 
982
        it!=m_colorList.end();
 
983
        count++, it++)
 
984
    {
 
985
        *m_streamOut << "\\red" << (*it).red();
 
986
        *m_streamOut << "\\green" << (*it).green();
 
987
        *m_streamOut << "\\blue" << (*it).blue();
 
988
        *m_streamOut <<  ";"; // end of entry
 
989
    }
 
990
    *m_streamOut << "}"; // end of color table
 
991
}
 
992
 
 
993
void RTFWorker::writeStyleData(void)
 
994
{
 
995
    *m_streamOut << "{\\stylesheet" << m_eol;
 
996
 
 
997
    uint count;
 
998
    QValueList<LayoutData>::ConstIterator it;
 
999
    for (count=0, it=m_styleList.begin();
 
1000
        it!=m_styleList.end();
 
1001
        count++, it++)
 
1002
    {
 
1003
        *m_streamOut << "{";
 
1004
        if (count>0) // \s0 is not written out
 
1005
            *m_streamOut << "\\s" << count;
 
1006
 
 
1007
        *m_streamOut << layoutToRtf((*it),(*it),true);
 
1008
 
 
1009
        // \snext must be the last keyword before the style name
 
1010
        // Find the number of the following style
 
1011
        uint counter=0;  // counts position in style table starting at 0
 
1012
        QValueList < LayoutData > ::ConstIterator it2;
 
1013
        for( it2 =  m_styleList.begin(); it2 != m_styleList.end(); counter++, it2++ )
 
1014
        {
 
1015
            if ( (*it2).styleName == (*it).styleFollowing )
 
1016
            {
 
1017
                *m_streamOut << "\\snext" << counter;
 
1018
                break;
 
1019
            }
 
1020
        }
 
1021
 
 
1022
        *m_streamOut << " " << (*it).styleName << ";";
 
1023
        *m_streamOut << "}";
 
1024
        *m_streamOut << m_eol;
 
1025
    }
 
1026
 
 
1027
    *m_streamOut << "}";
 
1028
}
 
1029
 
 
1030
bool RTFWorker::doCloseDocument(void)
 
1031
{
 
1032
 
 
1033
    writeFontData();
 
1034
    writeColorData();
 
1035
    writeStyleData();
 
1036
 
 
1037
    if (!m_textDocInfo.isEmpty())
 
1038
    {
 
1039
        *m_streamOut << "{\\info ";  // string of document information markup
 
1040
        *m_streamOut << m_textDocInfo;   // add document author, title, operator
 
1041
        *m_streamOut << "}";
 
1042
    }
 
1043
    *m_streamOut << "\\paperw" << int(m_paperWidth);
 
1044
    *m_streamOut << "\\paperh" << int(m_paperHeight);
 
1045
    if (1==m_paperOrientation)
 
1046
        *m_streamOut << "\\landscape";
 
1047
    *m_streamOut << "\\margl" << int(m_paperMarginLeft);
 
1048
    *m_streamOut << "\\margr" << int(m_paperMarginRight);
 
1049
    *m_streamOut << "\\margt" << int(m_paperMarginTop);
 
1050
    *m_streamOut << "\\margb" << int(m_paperMarginBottom);
 
1051
    *m_streamOut << m_textPage;  // add page size, margins, etc.
 
1052
    *m_streamOut << "\\widowctrl\\ftnbj\\aenddoc\\formshade \\fet0\\sectd\n";
 
1053
    if (m_startPageNumber >= 1)
 
1054
        *m_streamOut << "\\pgnstart" << m_startPageNumber << endl;
 
1055
    //*m_streamOut << "\\linex0\\endnhere\\plain";
 
1056
    *m_streamOut << "\\pard\\plain";
 
1057
    *m_streamOut << m_textBody;
 
1058
 
 
1059
    *m_streamOut << "}" << m_eol;
 
1060
    return true;
 
1061
}
 
1062
 
 
1063
bool RTFWorker::doFullDocumentInfo(const KWEFDocumentInfo& docInfo)
 
1064
{
 
1065
 
 
1066
    if ( !docInfo.title.isEmpty() )
 
1067
    {
 
1068
        m_textDocInfo += "{\\title ";
 
1069
        m_textDocInfo += escapeRtfText( docInfo.title );
 
1070
        m_textDocInfo += "}";
 
1071
    }
 
1072
 
 
1073
    if ( !docInfo.fullName.isEmpty() )
 
1074
    {
 
1075
        m_textDocInfo += "{\\author ";
 
1076
        m_textDocInfo += escapeRtfText( docInfo.fullName );
 
1077
        m_textDocInfo += "}";
 
1078
    }
 
1079
 
 
1080
    if ( !docInfo.company.isEmpty() )
 
1081
    {
 
1082
        m_textDocInfo += "{\\company ";
 
1083
        m_textDocInfo += escapeRtfText( docInfo.company );
 
1084
        m_textDocInfo += "}";
 
1085
    }
 
1086
 
 
1087
    // Now add who we are in a \comment
 
1088
    QString revision("$Revision: 2.96.2.2 $");
 
1089
    m_textDocInfo += "{\\comment ";
 
1090
    m_textDocInfo += "Generated by KWord's RTF Export Filter";
 
1091
    m_textDocInfo += revision.mid(10).remove('$'); // has a leading and a trailing space.
 
1092
    m_textDocInfo += "}";
 
1093
 
 
1094
    if ( !docInfo.abstract.isEmpty() )
 
1095
    {
 
1096
        m_textDocInfo += "{\\doccomm ";
 
1097
        m_textDocInfo += escapeRtfText( docInfo.abstract );
 
1098
        m_textDocInfo += "}";
 
1099
    }
 
1100
 
 
1101
    return true;
 
1102
}
 
1103
 
 
1104
bool RTFWorker::doOpenTextFrameSet(void)
 
1105
{
 
1106
    return true;
 
1107
}
 
1108
 
 
1109
bool RTFWorker::doCloseTextFrameSet(void)
 
1110
{
 
1111
    return true;
 
1112
}
 
1113
 
 
1114
QString RTFWorker::openSpan(const FormatData& formatOrigin, const FormatData& format)
 
1115
{
 
1116
    QString result;
 
1117
 
 
1118
    result += "{";
 
1119
    result += textFormatToRtf(formatOrigin.text,format.text,false);
 
1120
 
 
1121
    if ( 1==format.text.verticalAlignment )
 
1122
    {
 
1123
        result += "\\sub"; //Subscript
 
1124
    }
 
1125
    else if ( 2==format.text.verticalAlignment )
 
1126
    {
 
1127
        result += "\\super"; //Superscript
 
1128
    }
 
1129
 
 
1130
    result += " ";
 
1131
    return result;
 
1132
}
 
1133
 
 
1134
QString RTFWorker::closeSpan(const FormatData& , const FormatData& )
 
1135
{
 
1136
    QString result;
 
1137
    result += "}";
 
1138
    return result;
 
1139
}
 
1140
 
 
1141
// The following function encodes the kword unicode characters into
 
1142
// RTF seven bit ASCII. This affects any 8 bit characters.
 
1143
// They are encoded either with \' or with \u
 
1144
QString RTFWorker::escapeRtfText ( const QString& text ) const
 
1145
{
 
1146
    // initialize strings
 
1147
    QString escapedText;
 
1148
    const uint length = text.length();
 
1149
    for ( uint i = 0; i < length; i++ )
 
1150
    {
 
1151
        QChar QCh ( text.at( i ) );  // get out one unicode char from the string
 
1152
        const ushort ch = QCh.unicode();  // take unicode value of the char
 
1153
 
 
1154
        if ( QCh == '\\' )  escapedText += "\\\\"; // back-slash
 
1155
        else if ( QCh == '{' )   escapedText += "\\{";
 
1156
        else if ( QCh == '}' )   escapedText += "\\}";
 
1157
        else if ( ch >= 32 && ch <= 127) // ASCII character
 
1158
            escapedText += QCh;
 
1159
        else if ( ch == 0x0009 ) escapedText += "\\tab "; // tabulator
 
1160
        else if ( ch == 0x00a0 ) escapedText += "\\~"; // Non-breaking space
 
1161
        else if ( ch == 0x00ad ) escapedText += "\\-"; // Soft hyphen
 
1162
        else if ( ch == 0x00b7 ) escapedText += "\\|";
 
1163
        else if ( ch == 0x2011 ) escapedText += "\\_"; // Non-breaking hyphen
 
1164
        else if ( ch == 0x2002 ) escapedText += "\\enspace ";
 
1165
        else if ( ch == 0x2003 ) escapedText += "\\emspace ";
 
1166
        else if ( ch == 0x2004 ) escapedText += "\\qmspace ";
 
1167
        else if ( ch == 0x200c ) escapedText += "\\zwnj ";
 
1168
        else if ( ch == 0x200d ) escapedText += "\\zwj ";
 
1169
        else if ( ch == 0x200e ) escapedText += "\\ltrmark ";
 
1170
        else if ( ch == 0x200f ) escapedText += "\\rtlmark ";
 
1171
        else if ( ch == 0x2013 ) escapedText += "\\endash ";
 
1172
        else if ( ch == 0x2014 ) escapedText += "\\emdash ";
 
1173
        else if ( ch == 0x2018 ) escapedText += "\\lquote ";
 
1174
        else if ( ch == 0x2019 ) escapedText += "\\rquote ";
 
1175
        else if ( ch == 0x201c ) escapedText += "\\ldblquote ";
 
1176
        else if ( ch == 0x201d ) escapedText += "\\rdblquote ";
 
1177
        else if ( ch == 0x2022 ) escapedText += "\\bullet ";
 
1178
        else if ( ch >= 160 && ch < 256) // check for characters common between ISO-8859-1 and CP1252
 
1179
        {   // NOTE: 128 to 159 in CP1252 are somewhere else in UTF-8 and do not exist in ISO-8859-1 (### TODO?)
 
1180
            escapedText += "\\\'";   // escape upper page character to 7 bit
 
1181
            escapedText += QString::number ( ch, 16 );
 
1182
        }
 
1183
        else if ( ch >= 256) // check for a higher code non-ASCII character
 
1184
        {
 
1185
            // encode this as decimal unicode with a replacement character.
 
1186
            escapedText += "\\u";
 
1187
            escapedText += QString::number ( ch, 10 );
 
1188
            // We decompose the character. If it works, the first character is whitout any accent.
 
1189
            // (Of course this only works with Latin letters.)
 
1190
            // WARNING: QChar::decomposition is not re-entrant in Qt 3.x
 
1191
            QChar replacement ( QCh.decomposition().at(0) );
 
1192
            kdDebug(30515) << "Proposed replacement character: " << QString(replacement) << endl;
 
1193
 
 
1194
            if (replacement.isNull() || replacement<=' ' || replacement>=char(127)
 
1195
                || replacement=='{' || replacement=='}' || replacement=='\\')
 
1196
                replacement='?'; // Not a normal ASCII character, so default to show a ? sign
 
1197
 
 
1198
            escapedText += replacement; // The \uc1 dummy character.
 
1199
 
 
1200
        }
 
1201
        else
 
1202
            escapedText += QCh ;
 
1203
 
 
1204
    }
 
1205
 
 
1206
    return escapedText;
 
1207
 
 
1208
}
 
1209
 
 
1210
bool RTFWorker::doFullPaperFormat(const int /*format*/,
 
1211
    const double width, const double height, const int orientation)
 
1212
{
 
1213
    m_paperWidth=width*20;
 
1214
    m_paperHeight=height*20;
 
1215
    m_paperOrientation=orientation;
 
1216
    return true;
 
1217
}
 
1218
 
 
1219
bool RTFWorker::doFullPaperBorders (const double top, const double left,
 
1220
    const double bottom, const double right)
 
1221
{
 
1222
    m_paperMarginTop=top*20;
 
1223
    m_paperMarginLeft=left*20;
 
1224
    m_paperMarginBottom=bottom*20;
 
1225
    m_paperMarginRight=right*20;
 
1226
    return true;
 
1227
}
 
1228
 
 
1229
bool RTFWorker::doFullDefineStyle(LayoutData& layout)
 
1230
{
 
1231
    //Register the new style in the style list
 
1232
    m_styleList << layout;
 
1233
 
 
1234
    // Now we must register a few things (with help of the lookup methods.)
 
1235
    lookupFont("\\f", layout.formatData.text.fontName);
 
1236
    lookupColor(QString::null, layout.formatData.text.fgColor);
 
1237
    lookupColor(QString::null, layout.formatData.text.bgColor);
 
1238
 
 
1239
    return true;
 
1240
}
 
1241
 
 
1242
static QString writeDate(const QString keyword, const QDateTime& now)
 
1243
{
 
1244
    QString str;
 
1245
    if (now.isValid())
 
1246
    {
 
1247
        kdDebug(30515) << "Date " << keyword << " " << now.toString() << endl;
 
1248
        str += '{';
 
1249
        str += keyword;
 
1250
        const QDate nowDate(now.date());
 
1251
        str += "\\yr";
 
1252
        str += QString::number(nowDate.year());
 
1253
        str += "\\mo";
 
1254
        str += QString::number(nowDate.month());
 
1255
        str += "\\dy";
 
1256
        str += QString::number(nowDate.day());
 
1257
        const QTime nowTime(now.time());
 
1258
        str += "\\hr";
 
1259
        str += QString::number(nowTime.hour());
 
1260
        str += "\\min";
 
1261
        str += QString::number(nowTime.minute());
 
1262
        str += "\\sec";
 
1263
        str += QString::number(nowTime.second());
 
1264
        str += '}';
 
1265
    }
 
1266
    else
 
1267
        kdWarning(30515) << "Date " << keyword << " is not valid! Skipping!" << endl;
 
1268
 
 
1269
    return str;
 
1270
}
 
1271
 
 
1272
bool RTFWorker::doVariableSettings(const VariableSettingsData& vs)
 
1273
{
 
1274
    m_textDocInfo += writeDate("\\creatim",vs.creationTime);
 
1275
    m_textDocInfo += writeDate("\\revtim", vs.modificationTime);
 
1276
    m_textDocInfo += writeDate("\\printim",vs.printTime);
 
1277
    m_startPageNumber = vs.startingPageNumber;
 
1278
 
 
1279
    return true;
 
1280
}
 
1281
 
 
1282
QString RTFWorker::textFormatToRtf(const TextFormatting& formatOrigin,
 
1283
    const TextFormatting& formatData, const bool force)
 
1284
{
 
1285
    // TODO: rename variable formatData
 
1286
    QString strElement; // TODO: rename this variable
 
1287
 
 
1288
    // Font name
 
1289
    const QString fontName(formatData.fontName);
 
1290
    if (!fontName.isEmpty()
 
1291
        && (force || (formatOrigin.fontName!=formatData.fontName)))
 
1292
    {
 
1293
        strElement+=lookupFont("\\f", fontName);
 
1294
    }
 
1295
 
 
1296
    if (force || (formatOrigin.fontSize!=formatData.fontSize))
 
1297
    {
 
1298
        const int size=formatData.fontSize;
 
1299
        if (size>0)
 
1300
        {
 
1301
            strElement+="\\fs";
 
1302
            strElement+=QString::number(2*size,10);
 
1303
        }
 
1304
    }
 
1305
 
 
1306
    if (force || (formatOrigin.italic!=formatData.italic))
 
1307
    {
 
1308
        // Font style
 
1309
        if ( formatData.italic )
 
1310
        {
 
1311
            strElement+="\\i";
 
1312
        }
 
1313
        else
 
1314
        {
 
1315
            strElement+="\\i0";
 
1316
        }
 
1317
    }
 
1318
 
 
1319
    if (force || ((formatOrigin.weight>=75)!=(formatData.weight>=75)))
 
1320
    {
 
1321
        if ( formatData.weight >= 75 )
 
1322
        {
 
1323
            strElement+="\\b";
 
1324
        }
 
1325
        else
 
1326
        {
 
1327
            strElement+="\\b0";
 
1328
        }
 
1329
    }
 
1330
 
 
1331
    if (force || (formatOrigin.fgColor!=formatData.fgColor))
 
1332
    {
 
1333
        if ( formatData.fgColor.isValid() )
 
1334
        {
 
1335
            strElement+=lookupColor("\\cf", formatData.fgColor);
 
1336
        }
 
1337
    }
 
1338
 
 
1339
    if (force || (formatOrigin.bgColor!=formatData.bgColor))
 
1340
    {
 
1341
        if ( formatData.bgColor.isValid() )
 
1342
        {
 
1343
            strElement+=lookupColor("\\cb", formatData.bgColor);
 
1344
            strElement+=lookupColor("\\highlight", formatData.bgColor); // MS Word wants this
 
1345
            // ### FIXME: \highlight is not allowed in style definitions (RTF 1.6)
 
1346
        }
 
1347
    }
 
1348
 
 
1349
    if ( force
 
1350
        || ( formatOrigin.underline != formatData.underline )
 
1351
        || ( formatOrigin.underlineValue != formatData.underlineValue )
 
1352
        || ( formatOrigin.underlineStyle != formatData.underlineStyle )
 
1353
        || ( formatOrigin.underlineWord != formatData.underlineWord ) )
 
1354
    {
 
1355
        if ( formatData.underline )
 
1356
        {
 
1357
            QString underlineValue = formatData.underlineValue;
 
1358
            QString underlineStyle = formatData.underlineStyle;
 
1359
            bool underlineWord = formatData.underlineWord;
 
1360
            QString ul ( "\\ul" );  // fall-back: simple underline
 
1361
 
 
1362
            if( underlineStyle.isEmpty() ) underlineStyle = "solid";
 
1363
            if( underlineValue == "1" ) underlineValue = "single";
 
1364
 
 
1365
            if( underlineValue == "double" )
 
1366
                ul = "\\uldb";
 
1367
            else if( underlineValue == "single-bold" )
 
1368
                ul = "\\ulth";
 
1369
            else if( underlineValue == "wave" )
 
1370
                ul = "\\ulwave";
 
1371
            else if( underlineValue == "single" )
 
1372
            {
 
1373
                if( underlineStyle == "dash" )
 
1374
                    ul = "\\uldash";
 
1375
                else if( underlineStyle == "dot" )
 
1376
                    ul = "\\uld";
 
1377
                else if( underlineStyle == "dashdot" )
 
1378
                    ul = "\\uldashd";
 
1379
                else if( underlineStyle == "dashdotdot" )
 
1380
                    ul = "\\uldashdd";
 
1381
                else if( underlineWord )
 
1382
                    ul = "\\ulw";
 
1383
            };
 
1384
 
 
1385
            strElement+= ul;
 
1386
            if (formatData.underlineColor.isValid())
 
1387
            {
 
1388
                strElement+=lookupColor("\\ulc",formatData.underlineColor);
 
1389
            }
 
1390
        }
 
1391
        else
 
1392
        {
 
1393
            strElement+="\\ul0";
 
1394
        }
 
1395
    }
 
1396
 
 
1397
    if ( force
 
1398
        || ( formatOrigin.strikeout != formatData.strikeout )
 
1399
        || ( formatOrigin.strikeoutType != formatData.strikeoutType ) )
 
1400
    {
 
1401
        if ( formatData.strikeout )
 
1402
        {
 
1403
            if( formatData.strikeoutType == "double" )
 
1404
                strElement+="\\striked1"; // 1 needed! (The exception that confirms the rule!)
 
1405
            else
 
1406
                strElement+="\\strike";
 
1407
        }
 
1408
        else
 
1409
        {
 
1410
            strElement+="\\strike0"; // ### TODO: \striked0 too?
 
1411
        }
 
1412
    }
 
1413
 
 
1414
    return strElement;
 
1415
}
 
1416
 
 
1417
QString RTFWorker::layoutToRtf(const LayoutData& layoutOrigin,
 
1418
    const LayoutData& layout, const bool force)
 
1419
{
 
1420
    QString strLayout;
 
1421
 
 
1422
 
 
1423
    if (force || (layoutOrigin.alignment!=layout.alignment))
 
1424
    {
 
1425
        if (layout.alignment=="left")
 
1426
            strLayout += "\\ql";
 
1427
        else if (layout.alignment== "right")
 
1428
            strLayout += "\\qr";
 
1429
        else if (layout.alignment=="center")
 
1430
            strLayout += "\\qc";
 
1431
        else if (layout.alignment=="justify")
 
1432
            strLayout += "\\qj";
 
1433
        else if ( layout.alignment=="auto")
 
1434
        {
 
1435
            // ### TODO: what for BIDI?
 
1436
            //strLayout += "\\ql";
 
1437
        }
 
1438
        else
 
1439
        {
 
1440
            kdWarning(30515) << "Unknown alignment: " << layout.alignment << endl;
 
1441
        }
 
1442
    }
 
1443
 
 
1444
    if ((layout.indentLeft>=0.0)
 
1445
        && (force || (layoutOrigin.indentLeft!=layout.indentLeft)))
 
1446
    {
 
1447
       strLayout += "\\li";
 
1448
       strLayout += QString::number(int(layout.indentLeft)*20, 10);
 
1449
    }
 
1450
 
 
1451
    if ((layout.indentRight>=0.0)
 
1452
        && (force || (layoutOrigin.indentRight!=layout.indentRight)))
 
1453
    {
 
1454
       strLayout += "\\ri";
 
1455
       strLayout += QString::number(int(layout.indentRight)*20, 10);
 
1456
    }
 
1457
 
 
1458
    if (force || (layoutOrigin.indentFirst!=layout.indentFirst))
 
1459
    {
 
1460
       strLayout += "\\fi";
 
1461
       strLayout += QString::number(int(layout.indentFirst)*20, 10);
 
1462
    }
 
1463
 
 
1464
    if ((layout.marginBottom>=0.0)
 
1465
        && (force || (layoutOrigin.marginBottom!=layout.marginBottom)))
 
1466
    {
 
1467
       strLayout += "\\sa";
 
1468
       strLayout += QString::number(int(layout.marginBottom)*20 ,10);
 
1469
    }
 
1470
 
 
1471
    if ((layout.marginTop>=0.0)
 
1472
        && (force || (layoutOrigin.marginTop!=layout.marginTop)))
 
1473
    {
 
1474
       strLayout += "\\sb";
 
1475
       strLayout += QString::number(int(layout.marginTop)*20, 10);
 
1476
    }
 
1477
 
 
1478
    if (force || (layoutOrigin.keepLinesTogether!=layout.keepLinesTogether))
 
1479
    {
 
1480
       if(layout.keepLinesTogether) strLayout += "\\keep";
 
1481
    }
 
1482
 
 
1483
    // Note: there seems to be too many problems of using a page break in a layout
 
1484
    // - KWord's RTF import filter makes the page break immediately (also in styles)
 
1485
    // - AbiWord's RTF import does not like \*\pgbrk
 
1486
    // ### TODO: decide if we really remove this code
 
1487
#if 0
 
1488
    if (force || (layoutOrigin.pageBreakBefore!=layout.pageBreakBefore))
 
1489
    {
 
1490
       if(layout.pageBreakBefore) strLayout += "\\pagebb";
 
1491
    }
 
1492
 
 
1493
    // Note: RTF doesn't specify "page break after"
 
1494
    // \*\pgbrk0 is used after OpenOffice.org Writer
 
1495
    if (force || (layoutOrigin.pageBreakAfter!=layout.pageBreakAfter))
 
1496
    {
 
1497
       if(layout.pageBreakAfter) strLayout += "\\*\\pgbrk0";
 
1498
    }
 
1499
#endif
 
1500
 
 
1501
    if (force
 
1502
        || (layoutOrigin.lineSpacingType!=layoutOrigin.lineSpacingType)
 
1503
        || (layoutOrigin.lineSpacing!=layoutOrigin.lineSpacing))
 
1504
    {
 
1505
        if ( layout.lineSpacingType==LayoutData::LS_SINGLE  )
 
1506
           ;// do nothing, single linespace is default in RTF
 
1507
 
 
1508
        else if ( layout.lineSpacingType==LayoutData::LS_ONEANDHALF  )
 
1509
           strLayout += "\\sl360\\slmult1"; // one-and-half linespace
 
1510
 
 
1511
        else if ( layout.lineSpacingType==LayoutData::LS_DOUBLE  )
 
1512
           strLayout += "\\sl480\\slmult1"; // double linespace
 
1513
 
 
1514
        else if ( layout.lineSpacingType==LayoutData::LS_ATLEAST  )
 
1515
           strLayout += QString("\\sl%1\\slmult0").arg(int(layout.lineSpacing)*20);
 
1516
 
 
1517
        else if ( layout.lineSpacingType==LayoutData::LS_MULTIPLE  )
 
1518
           strLayout += QString("\\sl%1\\slmult1").arg( int(layout.lineSpacing)*240 );
 
1519
 
 
1520
        else if ( layout.lineSpacingType==LayoutData::LS_CUSTOM )
 
1521
           // "Custom" in KWord is like "Exactly" in MS Word
 
1522
           strLayout += QString("\\sl-%1\\slmult0").arg(int(layout.lineSpacing)*20);
 
1523
 
 
1524
        else
 
1525
            kdWarning(30515) << "Curious lineSpacingType: " << layout.lineSpacingType << " (Ignoring!)" << endl;
 
1526
    }
 
1527
 
 
1528
    if (!layout.tabulatorList.isEmpty()
 
1529
        && (force || (layoutOrigin.tabulatorList!=layout.tabulatorList) ))
 
1530
    {
 
1531
        TabulatorList::ConstIterator it;
 
1532
        for (it=layout.tabulatorList.begin();it!=layout.tabulatorList.end();it++)
 
1533
        {
 
1534
            switch ((*it).m_type)
 
1535
            {
 
1536
                case 0: default:  break; // left tab is default
 
1537
                case 1:  strLayout += "\\tqc"; break;
 
1538
                case 2:  strLayout += "\\tqr"; break;
 
1539
                case 3:  strLayout += "\\tqdec"; break;
 
1540
            }
 
1541
 
 
1542
            switch ((*it).m_filling)
 
1543
            {
 
1544
                case TabulatorData::TF_NONE: default: break; // without leader/filling
 
1545
                case TabulatorData::TF_DOT:  strLayout += "\\tldot"; break;
 
1546
                case TabulatorData::TF_LINE:  strLayout += "\\tlul"; break;
 
1547
 
 
1548
                // these belows are all treated as RTF's \tqul
 
1549
                case TabulatorData::TF_DASH:
 
1550
                case TabulatorData::TF_DASHDOT:
 
1551
                case TabulatorData::TF_DASHDOTDOT:
 
1552
                    strLayout += "\\tlul"; break;
 
1553
            }
 
1554
 
 
1555
            // must be the last
 
1556
            strLayout += "\\tx";
 
1557
            strLayout += QString::number(int((*it).m_ptpos)*20, 10);
 
1558
 
 
1559
        }
 
1560
    }
 
1561
 
 
1562
    // shadow support
 
1563
    // note shadow in KWord is more full-feature/sophisticated than RTF
 
1564
    // here we just treat KWord's shadow as simple \shad mark-up
 
1565
    if( layout.shadowDistance > 0 )
 
1566
    {
 
1567
       strLayout += "\\shad";
 
1568
    }
 
1569
 
 
1570
    // TODO: borders
 
1571
 
 
1572
    // This must remain last, as it adds a terminating space.
 
1573
    strLayout+=textFormatToRtf(layoutOrigin.formatData.text,
 
1574
        layout.formatData.text,force);
 
1575
 
 
1576
    return strLayout;
 
1577
}
 
1578
 
 
1579
 
 
1580
QString RTFWorker::lookupFont(const QString& markup, const QString& fontName)
 
1581
{
 
1582
    if (fontName.isEmpty())
 
1583
        return QString::null;
 
1584
 
 
1585
    // First we have to remove Qt-typical foundry names, as some RTF readers are confused by them.
 
1586
    QString cookedFontName(fontName);
 
1587
    QRegExp regexp("\\s*\\[\\S*\\]"); // Some white space, opening square bracket, some non-white-space, ending square bracket
 
1588
    cookedFontName.remove(regexp);
 
1589
    // But we cannot have an empty name font
 
1590
    if (cookedFontName.isEmpty())
 
1591
        cookedFontName=fontName;
 
1592
 
 
1593
    kdDebug(30515) << "RTFWorker::lookupFont " << fontName << " cooked: " << cookedFontName << endl;
 
1594
 
 
1595
    uint counter=0;  // counts position in font table (starts at 0)
 
1596
    QString strFont(markup); // markup for font selection
 
1597
    QStringList::ConstIterator it;
 
1598
 
 
1599
    // search font table for this font
 
1600
    for( it = m_fontList.begin(); it != m_fontList.end(); counter++, it++ )
 
1601
    {
 
1602
        if((*it) == cookedFontName)  // check for match
 
1603
        {
 
1604
            strFont += QString::number(counter);
 
1605
            kdDebug(30515) << strFont << endl;
 
1606
            return strFont;
 
1607
        }
 
1608
    }  // end for()
 
1609
 
 
1610
    kdDebug(30515) << "New font: " << cookedFontName << " count: " << counter << endl;
 
1611
    m_fontList << cookedFontName;
 
1612
 
 
1613
    strFont += QString::number(counter);
 
1614
    return strFont;
 
1615
}
 
1616
 
 
1617
QString RTFWorker::lookupColor(const QString& markup, const QColor& color)
 
1618
{
 
1619
    if (!color.isValid())
 
1620
        return QString::null;
 
1621
 
 
1622
    uint counter=1;  // counts position in color table starting at 1
 
1623
    QString strColor(markup);  // Holds RTF markup for the color
 
1624
 
 
1625
    QValueList < QColor > ::ConstIterator it;
 
1626
 
 
1627
    // search color table for this color
 
1628
    for( it =  m_colorList.begin(); it != m_colorList.end(); counter++, it++ )
 
1629
    {
 
1630
        if ( (*it) == color )
 
1631
        {
 
1632
            strColor += QString::number(counter);
 
1633
            return strColor;
 
1634
        }
 
1635
    }
 
1636
 
 
1637
    kdDebug(30515) << "New color: " << color.name() << " count: " << counter << endl;
 
1638
    m_colorList << color;
 
1639
 
 
1640
    strColor += QString::number(counter);
 
1641
    return strColor;
 
1642
}
 
1643
 
 
1644
QString RTFWorker::lookupStyle(const QString& styleName, LayoutData& returnLayout)
 
1645
{
 
1646
    if (styleName.isEmpty())
 
1647
        return QString::null;
 
1648
 
 
1649
    uint counter=0;  // counts position in style table starting at 0
 
1650
    QString strMarkup("\\s");  // Holds RTF markup for the style
 
1651
 
 
1652
    QValueList < LayoutData > ::ConstIterator it;
 
1653
 
 
1654
    // search color table for this color
 
1655
    for( it =  m_styleList.begin(); it != m_styleList.end(); counter++, it++ )
 
1656
    {
 
1657
        if ( (*it).styleName == styleName )
 
1658
        {
 
1659
            strMarkup += QString::number(counter);
 
1660
            returnLayout=(*it);
 
1661
            return strMarkup;
 
1662
        }
 
1663
    }
 
1664
 
 
1665
    kdDebug(30515) << "New style: " << styleName << " count: " << counter << endl;
 
1666
    LayoutData layout;
 
1667
    m_styleList << layout;
 
1668
    returnLayout=layout;
 
1669
 
 
1670
    strMarkup += QString::number(counter);
 
1671
    return strMarkup;
 
1672
}