source: trunk/src/gui/text/qtextodfwriter.cpp@ 605

Last change on this file since 605 was 561, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.1 sources.

File size: 37.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <qglobal.h>
43
44#ifndef QT_NO_TEXTODFWRITER
45
46#include "qtextodfwriter_p.h"
47
48#include <QImageWriter>
49#include <QTextListFormat>
50#include <QTextList>
51#include <QBuffer>
52#include <QUrl>
53
54#include "qtextdocument_p.h"
55#include "qtexttable.h"
56#include "qtextcursor.h"
57#include "qtextimagehandler_p.h"
58#include "qzipwriter_p.h"
59
60#include <QDebug>
61
62QT_BEGIN_NAMESPACE
63
64/// Convert pixels to postscript point units
65static QString pixelToPoint(qreal pixels)
66{
67 // we hardcode 96 DPI, we do the same in the ODF importer to have a perfect roundtrip.
68 return QString::number(pixels * 72 / 96) + QString::fromLatin1("pt");
69}
70
71// strategies
72class QOutputStrategy {
73public:
74 QOutputStrategy() : contentStream(0), counter(1) { }
75 virtual ~QOutputStrategy() {}
76 virtual void addFile(const QString &fileName, const QString &mimeType, const QByteArray &bytes) = 0;
77
78 QString createUniqueImageName()
79 {
80 return QString::fromLatin1("Pictures/Picture%1").arg(counter++);
81 }
82
83 QIODevice *contentStream;
84 int counter;
85};
86
87class QXmlStreamStrategy : public QOutputStrategy {
88public:
89 QXmlStreamStrategy(QIODevice *device)
90 {
91 contentStream = device;
92 }
93
94 virtual ~QXmlStreamStrategy()
95 {
96 if (contentStream)
97 contentStream->close();
98 }
99 virtual void addFile(const QString &, const QString &, const QByteArray &)
100 {
101 // we ignore this...
102 }
103};
104
105class QZipStreamStrategy : public QOutputStrategy {
106public:
107 QZipStreamStrategy(QIODevice *device)
108 : zip(device),
109 manifestWriter(&manifest)
110 {
111 QByteArray mime("application/vnd.oasis.opendocument.text");
112 zip.setCompressionPolicy(QZipWriter::NeverCompress);
113 zip.addFile(QString::fromLatin1("mimetype"), mime); // for mime-magick
114 zip.setCompressionPolicy(QZipWriter::AutoCompress);
115 contentStream = &content;
116 content.open(QIODevice::WriteOnly);
117 manifest.open(QIODevice::WriteOnly);
118
119 manifestNS = QString::fromLatin1("urn:oasis:names:tc:opendocument:xmlns:manifest:1.0");
120 // prettyfy
121 manifestWriter.setAutoFormatting(true);
122 manifestWriter.setAutoFormattingIndent(1);
123
124 manifestWriter.writeNamespace(manifestNS, QString::fromLatin1("manifest"));
125 manifestWriter.writeStartDocument();
126 manifestWriter.writeStartElement(manifestNS, QString::fromLatin1("manifest"));
127 addFile(QString::fromLatin1("/"), QString::fromLatin1("application/vnd.oasis.opendocument.text"));
128 addFile(QString::fromLatin1("content.xml"), QString::fromLatin1("text/xml"));
129 }
130
131 ~QZipStreamStrategy()
132 {
133 manifestWriter.writeEndDocument();
134 manifest.close();
135 zip.addFile(QString::fromLatin1("META-INF/manifest.xml"), &manifest);
136 content.close();
137 zip.addFile(QString::fromLatin1("content.xml"), &content);
138 zip.close();
139 }
140
141 virtual void addFile(const QString &fileName, const QString &mimeType, const QByteArray &bytes)
142 {
143 zip.addFile(fileName, bytes);
144 addFile(fileName, mimeType);
145 }
146
147private:
148 void addFile(const QString &fileName, const QString &mimeType)
149 {
150 manifestWriter.writeEmptyElement(manifestNS, QString::fromLatin1("file-entry"));
151 manifestWriter.writeAttribute(manifestNS, QString::fromLatin1("media-type"), mimeType);
152 manifestWriter.writeAttribute(manifestNS, QString::fromLatin1("full-path"), fileName);
153 }
154
155 QBuffer content;
156 QBuffer manifest;
157 QZipWriter zip;
158 QXmlStreamWriter manifestWriter;
159 QString manifestNS;
160};
161
162static QString bulletChar(QTextListFormat::Style style)
163{
164 switch(style) {
165 case QTextListFormat::ListDisc:
166 return QChar(0x25cf); // bullet character
167 case QTextListFormat::ListCircle:
168 return QChar(0x25cb); // white circle
169 case QTextListFormat::ListSquare:
170 return QChar(0x25a1); // white square
171 case QTextListFormat::ListDecimal:
172 return QString::fromLatin1("1");
173 case QTextListFormat::ListLowerAlpha:
174 return QString::fromLatin1("a");
175 case QTextListFormat::ListUpperAlpha:
176 return QString::fromLatin1("A");
177 case QTextListFormat::ListLowerRoman:
178 return QString::fromLatin1("i");
179 case QTextListFormat::ListUpperRoman:
180 return QString::fromLatin1("I");
181 default:
182 case QTextListFormat::ListStyleUndefined:
183 return QString();
184 }
185}
186
187void QTextOdfWriter::writeFrame(QXmlStreamWriter &writer, const QTextFrame *frame)
188{
189 Q_ASSERT(frame);
190 const QTextTable *table = qobject_cast<const QTextTable*> (frame);
191
192 if (table) { // Start a table.
193 writer.writeStartElement(tableNS, QString::fromLatin1("table"));
194 writer.writeEmptyElement(tableNS, QString::fromLatin1("table-column"));
195 writer.writeAttribute(tableNS, QString::fromLatin1("number-columns-repeated"), QString::number(table->columns()));
196 } else if (frame->document() && frame->document()->rootFrame() != frame) { // start a section
197 writer.writeStartElement(textNS, QString::fromLatin1("section"));
198 }
199
200 QTextFrame::iterator iterator = frame->begin();
201 QTextFrame *child = 0;
202
203 int tableRow = -1;
204 while (! iterator.atEnd()) {
205 if (iterator.currentFrame() && child != iterator.currentFrame())
206 writeFrame(writer, iterator.currentFrame());
207 else { // no frame, its a block
208 QTextBlock block = iterator.currentBlock();
209 if (table) {
210 QTextTableCell cell = table->cellAt(block.position());
211 if (tableRow < cell.row()) {
212 if (tableRow >= 0)
213 writer.writeEndElement(); // close table row
214 tableRow = cell.row();
215 writer.writeStartElement(tableNS, QString::fromLatin1("table-row"));
216 }
217 writer.writeStartElement(tableNS, QString::fromLatin1("table-cell"));
218 if (cell.columnSpan() > 1)
219 writer.writeAttribute(tableNS, QString::fromLatin1("number-columns-spanned"), QString::number(cell.columnSpan()));
220 if (cell.rowSpan() > 1)
221 writer.writeAttribute(tableNS, QString::fromLatin1("number-rows-spanned"), QString::number(cell.rowSpan()));
222 if (cell.format().isTableCellFormat()) {
223 writer.writeAttribute(tableNS, QString::fromLatin1("style-name"), QString::fromLatin1("T%1").arg(cell.tableCellFormatIndex()));
224 }
225 }
226 writeBlock(writer, block);
227 if (table)
228 writer.writeEndElement(); // table-cell
229 }
230 child = iterator.currentFrame();
231 ++iterator;
232 }
233 if (tableRow >= 0)
234 writer.writeEndElement(); // close table-row
235
236 if (table || (frame->document() && frame->document()->rootFrame() != frame))
237 writer.writeEndElement(); // close table or section element
238}
239
240void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &block)
241{
242 if (block.textList()) { // its a list-item
243 const int listLevel = block.textList()->format().indent();
244 if (m_listStack.isEmpty() || m_listStack.top() != block.textList()) {
245 // not the same list we were in.
246 while (m_listStack.count() >= listLevel && !m_listStack.isEmpty() && m_listStack.top() != block.textList() ) { // we need to close tags
247 m_listStack.pop();
248 writer.writeEndElement(); // list
249 if (m_listStack.count())
250 writer.writeEndElement(); // list-item
251 }
252 while (m_listStack.count() < listLevel) {
253 if (m_listStack.count())
254 writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
255 writer.writeStartElement(textNS, QString::fromLatin1("list"));
256 if (m_listStack.count() == listLevel - 1) {
257 m_listStack.push(block.textList());
258 writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("L%1")
259 .arg(block.textList()->formatIndex()));
260 }
261 else {
262 m_listStack.push(0);
263 }
264 }
265 }
266 writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
267 }
268 else {
269 while (! m_listStack.isEmpty()) {
270 m_listStack.pop();
271 writer.writeEndElement(); // list
272 if (m_listStack.count())
273 writer.writeEndElement(); // list-item
274 }
275 }
276
277 if (block.length() == 1) { // only a linefeed
278 writer.writeEmptyElement(textNS, QString::fromLatin1("p"));
279 writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
280 .arg(block.blockFormatIndex()));
281 if (block.textList())
282 writer.writeEndElement(); // numbered-paragraph
283 return;
284 }
285 writer.writeStartElement(textNS, QString::fromLatin1("p"));
286 writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
287 .arg(block.blockFormatIndex()));
288 for (QTextBlock::Iterator frag= block.begin(); !frag.atEnd(); frag++) {
289 writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed in front of it.
290 writer.writeStartElement(textNS, QString::fromLatin1("span"));
291
292 QString fragmentText = frag.fragment().text();
293 if (fragmentText.length() == 1 && fragmentText[0] == 0xFFFC) { // its an inline character.
294 writeInlineCharacter(writer, frag.fragment());
295 writer.writeEndElement(); // span
296 continue;
297 }
298
299 writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("c%1")
300 .arg(frag.fragment().charFormatIndex()));
301 bool escapeNextSpace = true;
302 int precedingSpaces = 0;
303 int exportedIndex = 0;
304 for (int i=0; i <= fragmentText.count(); ++i) {
305 bool isSpace = false;
306 QChar character = fragmentText[i];
307 isSpace = character.unicode() == ' ';
308
309 // find more than one space. -> <text:s text:c="2" />
310 if (!isSpace && escapeNextSpace && precedingSpaces > 1) {
311 const bool startParag = exportedIndex == 0 && i == precedingSpaces;
312 if (!startParag)
313 writer.writeCharacters(fragmentText.mid(exportedIndex, i - precedingSpaces + 1 - exportedIndex));
314 writer.writeEmptyElement(textNS, QString::fromLatin1("s"));
315 const int count = precedingSpaces - (startParag?0:1);
316 if (count > 1)
317 writer.writeAttribute(textNS, QString::fromLatin1("c"), QString::number(count));
318 precedingSpaces = 0;
319 exportedIndex = i;
320 }
321
322 if (i < fragmentText.count()) {
323 if (character.unicode() == 0x2028) { // soft-return
324 //if (exportedIndex < i)
325 writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
326 writer.writeEmptyElement(textNS, QString::fromLatin1("line-break"));
327 exportedIndex = i+1;
328 continue;
329 } else if (character.unicode() == '\t') { // Tab
330 //if (exportedIndex < i)
331 writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
332 writer.writeEmptyElement(textNS, QString::fromLatin1("tab"));
333 exportedIndex = i+1;
334 precedingSpaces = 0;
335 } else if (isSpace) {
336 ++precedingSpaces;
337 escapeNextSpace = true;
338 } else if (!isSpace) {
339 precedingSpaces = 0;
340 }
341 }
342 }
343
344 writer.writeCharacters(fragmentText.mid(exportedIndex));
345 writer.writeEndElement(); // span
346 }
347 writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed behind it.
348 writer.writeEndElement(); // p
349 if (block.textList())
350 writer.writeEndElement(); // list-item
351}
352
353void QTextOdfWriter::writeInlineCharacter(QXmlStreamWriter &writer, const QTextFragment &fragment) const
354{
355 writer.writeStartElement(drawNS, QString::fromLatin1("frame"));
356 if (m_strategy == 0) {
357 // don't do anything.
358 }
359 else if (fragment.charFormat().isImageFormat()) {
360 QTextImageFormat imageFormat = fragment.charFormat().toImageFormat();
361 writer.writeAttribute(drawNS, QString::fromLatin1("name"), imageFormat.name());
362
363 // vvv Copy pasted mostly from Qt =================
364 QImage image;
365 QString name = imageFormat.name();
366 if (name.startsWith(QLatin1String(":/"))) // auto-detect resources
367 name.prepend(QLatin1String("qrc"));
368 QUrl url = QUrl::fromEncoded(name.toUtf8());
369 const QVariant data = m_document->resource(QTextDocument::ImageResource, url);
370 if (data.type() == QVariant::Image) {
371 image = qvariant_cast<QImage>(data);
372 } else if (data.type() == QVariant::ByteArray) {
373 image.loadFromData(data.toByteArray());
374 }
375
376 if (image.isNull()) {
377 QString context;
378 if (QTextImageHandler::externalLoader)
379 image = QTextImageHandler::externalLoader(name, context);
380
381 if (image.isNull()) { // try direct loading
382 name = imageFormat.name(); // remove qrc:/ prefix again
383 image.load(name);
384 }
385 }
386
387 // ^^^ Copy pasted mostly from Qt =================
388 if (! image.isNull()) {
389 QBuffer imageBytes;
390 QImageWriter imageWriter(&imageBytes, "png");
391 imageWriter.write(image);
392 QString filename = m_strategy->createUniqueImageName();
393 m_strategy->addFile(filename, QString::fromLatin1("image/png"), imageBytes.data());
394
395 // get the width/height from the format.
396 qreal width = (imageFormat.hasProperty(QTextFormat::ImageWidth)) ? imageFormat.width() : image.width();
397 writer.writeAttribute(svgNS, QString::fromLatin1("width"), pixelToPoint(width));
398 qreal height = (imageFormat.hasProperty(QTextFormat::ImageHeight)) ? imageFormat.height() : image.height();
399 writer.writeAttribute(svgNS, QString::fromLatin1("height"), pixelToPoint(height));
400
401 writer.writeStartElement(drawNS, QString::fromLatin1("image"));
402 writer.writeAttribute(xlinkNS, QString::fromLatin1("href"), filename);
403 writer.writeEndElement(); // image
404 }
405 }
406
407 writer.writeEndElement(); // frame
408}
409
410void QTextOdfWriter::writeFormats(QXmlStreamWriter &writer, QSet<int> formats) const
411{
412 writer.writeStartElement(officeNS, QString::fromLatin1("automatic-styles"));
413 QVector<QTextFormat> allStyles = m_document->allFormats();
414 QSetIterator<int> formatId(formats);
415 while(formatId.hasNext()) {
416 int formatIndex = formatId.next();
417 QTextFormat textFormat = allStyles.at(formatIndex);
418 switch (textFormat.type()) {
419 case QTextFormat::CharFormat:
420 if (textFormat.isTableCellFormat())
421 writeTableCellFormat(writer, textFormat.toTableCellFormat(), formatIndex);
422 else
423 writeCharacterFormat(writer, textFormat.toCharFormat(), formatIndex);
424 break;
425 case QTextFormat::BlockFormat:
426 writeBlockFormat(writer, textFormat.toBlockFormat(), formatIndex);
427 break;
428 case QTextFormat::ListFormat:
429 writeListFormat(writer, textFormat.toListFormat(), formatIndex);
430 break;
431 case QTextFormat::FrameFormat:
432 writeFrameFormat(writer, textFormat.toFrameFormat(), formatIndex);
433 break;
434 case QTextFormat::TableFormat:
435 ;break;
436 }
437 }
438
439 writer.writeEndElement(); // automatic-styles
440}
441
442void QTextOdfWriter::writeBlockFormat(QXmlStreamWriter &writer, QTextBlockFormat format, int formatIndex) const
443{
444 writer.writeStartElement(styleNS, QString::fromLatin1("style"));
445 writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("p%1").arg(formatIndex));
446 writer.writeAttribute(styleNS, QString::fromLatin1("family"), QString::fromLatin1("paragraph"));
447 writer.writeStartElement(styleNS, QString::fromLatin1("paragraph-properties"));
448
449 if (format.hasProperty(QTextFormat::BlockAlignment)) {
450 const Qt::Alignment alignment = format.alignment() & Qt::AlignHorizontal_Mask;
451 QString value;
452 if (alignment == Qt::AlignLeading)
453 value = QString::fromLatin1("start");
454 else if (alignment == Qt::AlignTrailing)
455 value = QString::fromLatin1("end");
456 else if (alignment == (Qt::AlignLeft | Qt::AlignAbsolute))
457 value = QString::fromLatin1("left");
458 else if (alignment == (Qt::AlignRight | Qt::AlignAbsolute))
459 value = QString::fromLatin1("right");
460 else if (alignment == Qt::AlignHCenter)
461 value = QString::fromLatin1("center");
462 else if (alignment == Qt::AlignJustify)
463 value = QString::fromLatin1("justify");
464 else
465 qWarning() << "QTextOdfWriter: unsupported paragraph alignment; " << format.alignment();
466 if (! value.isNull())
467 writer.writeAttribute(foNS, QString::fromLatin1("text-align"), value);
468 }
469
470 if (format.hasProperty(QTextFormat::BlockTopMargin))
471 writer.writeAttribute(foNS, QString::fromLatin1("margin-top"), pixelToPoint(qMax(qreal(0.), format.topMargin())) );
472 if (format.hasProperty(QTextFormat::BlockBottomMargin))
473 writer.writeAttribute(foNS, QString::fromLatin1("margin-bottom"), pixelToPoint(qMax(qreal(0.), format.bottomMargin())) );
474 if (format.hasProperty(QTextFormat::BlockLeftMargin) || format.hasProperty(QTextFormat::BlockIndent))
475 writer.writeAttribute(foNS, QString::fromLatin1("margin-left"), pixelToPoint(qMax(qreal(0.),
476 format.leftMargin() + format.indent())));
477 if (format.hasProperty(QTextFormat::BlockRightMargin))
478 writer.writeAttribute(foNS, QString::fromLatin1("margin-right"), pixelToPoint(qMax(qreal(0.), format.rightMargin())) );
479 if (format.hasProperty(QTextFormat::TextIndent))
480 writer.writeAttribute(foNS, QString::fromLatin1("text-indent"), pixelToPoint(format.textIndent()));
481 if (format.hasProperty(QTextFormat::PageBreakPolicy)) {
482 if (format.pageBreakPolicy() & QTextFormat::PageBreak_AlwaysBefore)
483 writer.writeAttribute(foNS, QString::fromLatin1("break-before"), QString::fromLatin1("page"));
484 if (format.pageBreakPolicy() & QTextFormat::PageBreak_AlwaysAfter)
485 writer.writeAttribute(foNS, QString::fromLatin1("break-after"), QString::fromLatin1("page"));
486 }
487 if (format.hasProperty(QTextFormat::BackgroundBrush)) {
488 QBrush brush = format.background();
489 writer.writeAttribute(foNS, QString::fromLatin1("background-color"), brush.color().name());
490 }
491 if (format.hasProperty(QTextFormat::BlockNonBreakableLines))
492 writer.writeAttribute(foNS, QString::fromLatin1("keep-together"),
493 format.nonBreakableLines() ? QString::fromLatin1("true") : QString::fromLatin1("false"));
494 if (format.hasProperty(QTextFormat::TabPositions)) {
495 QList<QTextOption::Tab> tabs = format.tabPositions();
496 writer.writeStartElement(styleNS, QString::fromLatin1("style-tab-stops"));
497 QList<QTextOption::Tab>::Iterator iterator = tabs.begin();
498 while(iterator != tabs.end()) {
499 writer.writeEmptyElement(styleNS, QString::fromLatin1("style-tab-stop"));
500 writer.writeAttribute(styleNS, QString::fromLatin1("position"), pixelToPoint(iterator->position) );
501 QString type;
502 switch(iterator->type) {
503 case QTextOption::DelimiterTab: type = QString::fromLatin1("char"); break;
504 case QTextOption::LeftTab: type = QString::fromLatin1("left"); break;
505 case QTextOption::RightTab: type = QString::fromLatin1("right"); break;
506 case QTextOption::CenterTab: type = QString::fromLatin1("center"); break;
507 }
508 writer.writeAttribute(styleNS, QString::fromLatin1("type"), type);
509 if (iterator->delimiter != 0)
510 writer.writeAttribute(styleNS, QString::fromLatin1("char"), iterator->delimiter);
511 ++iterator;
512 }
513
514 writer.writeEndElement(); // style-tab-stops
515 }
516
517 writer.writeEndElement(); // paragraph-properties
518 writer.writeEndElement(); // style
519}
520
521void QTextOdfWriter::writeCharacterFormat(QXmlStreamWriter &writer, QTextCharFormat format, int formatIndex) const
522{
523 writer.writeStartElement(styleNS, QString::fromLatin1("style"));
524 writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("c%1").arg(formatIndex));
525 writer.writeAttribute(styleNS, QString::fromLatin1("family"), QString::fromLatin1("text"));
526 writer.writeEmptyElement(styleNS, QString::fromLatin1("text-properties"));
527 if (format.fontItalic())
528 writer.writeAttribute(foNS, QString::fromLatin1("font-style"), QString::fromLatin1("italic"));
529 if (format.hasProperty(QTextFormat::FontWeight) && format.fontWeight() != QFont::Normal) {
530 QString value;
531 if (format.fontWeight() == QFont::Bold)
532 value = QString::fromLatin1("bold");
533 else
534 value = QString::number(format.fontWeight() * 10);
535 writer.writeAttribute(foNS, QString::fromLatin1("font-weight"), value);
536 }
537 if (format.hasProperty(QTextFormat::FontFamily))
538 writer.writeAttribute(foNS, QString::fromLatin1("font-family"), format.fontFamily());
539 else
540 writer.writeAttribute(foNS, QString::fromLatin1("font-family"), QString::fromLatin1("Sans")); // Qt default
541 if (format.hasProperty(QTextFormat::FontPointSize))
542 writer.writeAttribute(foNS, QString::fromLatin1("font-size"), QString::fromLatin1("%1pt").arg(format.fontPointSize()));
543 if (format.hasProperty(QTextFormat::FontCapitalization)) {
544 switch(format.fontCapitalization()) {
545 case QFont::MixedCase:
546 writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("none")); break;
547 case QFont::AllUppercase:
548 writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("uppercase")); break;
549 case QFont::AllLowercase:
550 writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("lowercase")); break;
551 case QFont::Capitalize:
552 writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("capitalize")); break;
553 case QFont::SmallCaps:
554 writer.writeAttribute(foNS, QString::fromLatin1("font-variant"), QString::fromLatin1("small-caps")); break;
555 }
556 }
557 if (format.hasProperty(QTextFormat::FontLetterSpacing))
558 writer.writeAttribute(foNS, QString::fromLatin1("letter-spacing"), pixelToPoint(format.fontLetterSpacing()));
559 if (format.hasProperty(QTextFormat::FontWordSpacing))
560 writer.writeAttribute(foNS, QString::fromLatin1("word-spacing"), pixelToPoint(format.fontWordSpacing()));
561 if (format.hasProperty(QTextFormat::FontUnderline))
562 writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-type"),
563 format.fontUnderline() ? QString::fromLatin1("single") : QString::fromLatin1("none"));
564 if (format.hasProperty(QTextFormat::FontOverline)) {
565 // bool fontOverline () const TODO
566 }
567 if (format.hasProperty(QTextFormat::FontStrikeOut))
568 writer.writeAttribute(styleNS,QString::fromLatin1( "text-line-through-type"),
569 format.fontStrikeOut() ? QString::fromLatin1("single") : QString::fromLatin1("none"));
570 if (format.hasProperty(QTextFormat::TextUnderlineColor))
571 writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-color"), format.underlineColor().name());
572 if (format.hasProperty(QTextFormat::FontFixedPitch)) {
573 // bool fontFixedPitch () const TODO
574 }
575 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
576 QString value;
577 switch (format.underlineStyle()) {
578 case QTextCharFormat::NoUnderline: value = QString::fromLatin1("none"); break;
579 case QTextCharFormat::SingleUnderline: value = QString::fromLatin1("solid"); break;
580 case QTextCharFormat::DashUnderline: value = QString::fromLatin1("dash"); break;
581 case QTextCharFormat::DotLine: value = QString::fromLatin1("dotted"); break;
582 case QTextCharFormat::DashDotLine: value = QString::fromLatin1("dash-dot"); break;
583 case QTextCharFormat::DashDotDotLine: value = QString::fromLatin1("dot-dot-dash"); break;
584 case QTextCharFormat::WaveUnderline: value = QString::fromLatin1("wave"); break;
585 case QTextCharFormat::SpellCheckUnderline: value = QString::fromLatin1("none"); break;
586 }
587 writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-style"), value);
588 }
589 if (format.hasProperty(QTextFormat::TextVerticalAlignment)) {
590 QString value;
591 switch (format.verticalAlignment()) {
592 case QTextCharFormat::AlignMiddle:
593 case QTextCharFormat::AlignNormal: value = QString::fromLatin1("0%"); break;
594 case QTextCharFormat::AlignSuperScript: value = QString::fromLatin1("super"); break;
595 case QTextCharFormat::AlignSubScript: value = QString::fromLatin1("sub"); break;
596 case QTextCharFormat::AlignTop: value = QString::fromLatin1("100%"); break;
597 case QTextCharFormat::AlignBottom : value = QString::fromLatin1("-100%"); break;
598 }
599 writer.writeAttribute(styleNS, QString::fromLatin1("text-position"), value);
600 }
601 if (format.hasProperty(QTextFormat::TextOutline))
602 writer.writeAttribute(styleNS, QString::fromLatin1("text-outline"), QString::fromLatin1("true"));
603 if (format.hasProperty(QTextFormat::TextToolTip)) {
604 // QString toolTip () const TODO
605 }
606 if (format.hasProperty(QTextFormat::IsAnchor)) {
607 // bool isAnchor () const TODO
608 }
609 if (format.hasProperty(QTextFormat::AnchorHref)) {
610 // QString anchorHref () const TODO
611 }
612 if (format.hasProperty(QTextFormat::AnchorName)) {
613 // QString anchorName () const TODO
614 }
615 if (format.hasProperty(QTextFormat::ForegroundBrush)) {
616 QBrush brush = format.foreground();
617 writer.writeAttribute(foNS, QString::fromLatin1("color"), brush.color().name());
618 }
619 if (format.hasProperty(QTextFormat::BackgroundBrush)) {
620 QBrush brush = format.background();
621 writer.writeAttribute(foNS, QString::fromLatin1("background-color"), brush.color().name());
622 }
623
624 writer.writeEndElement(); // style
625}
626
627void QTextOdfWriter::writeListFormat(QXmlStreamWriter &writer, QTextListFormat format, int formatIndex) const
628{
629 writer.writeStartElement(textNS, QString::fromLatin1("list-style"));
630 writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("L%1").arg(formatIndex));
631
632 QTextListFormat::Style style = format.style();
633 if (style == QTextListFormat::ListDecimal || style == QTextListFormat::ListLowerAlpha
634 || style == QTextListFormat::ListUpperAlpha
635 || style == QTextListFormat::ListLowerRoman
636 || style == QTextListFormat::ListUpperRoman) {
637 writer.writeStartElement(textNS, QString::fromLatin1("list-level-style-number"));
638 writer.writeAttribute(styleNS, QString::fromLatin1("num-format"), bulletChar(style));
639 writer.writeAttribute(styleNS, QString::fromLatin1("num-suffix"), QString::fromLatin1("."));
640 } else {
641 writer.writeStartElement(textNS, QString::fromLatin1("list-level-style-bullet"));
642 writer.writeAttribute(textNS, QString::fromLatin1("bullet-char"), bulletChar(style));
643 }
644
645 writer.writeAttribute(textNS, QString::fromLatin1("level"), QString::number(format.indent()));
646 writer.writeEmptyElement(styleNS, QString::fromLatin1("list-level-properties"));
647 writer.writeAttribute(foNS, QString::fromLatin1("text-align"), QString::fromLatin1("start"));
648 QString spacing = QString::fromLatin1("%1mm").arg(format.indent() * 8);
649 writer.writeAttribute(textNS, QString::fromLatin1("space-before"), spacing);
650 //writer.writeAttribute(textNS, QString::fromLatin1("min-label-width"), spacing);
651
652 writer.writeEndElement(); // list-level-style-*
653 writer.writeEndElement(); // list-style
654}
655
656void QTextOdfWriter::writeFrameFormat(QXmlStreamWriter &writer, QTextFrameFormat format, int formatIndex) const
657{
658 writer.writeStartElement(styleNS, QString::fromLatin1("style"));
659 writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("s%1").arg(formatIndex));
660 writer.writeAttribute(styleNS, QString::fromLatin1("family"), QString::fromLatin1("section"));
661 writer.writeEmptyElement(styleNS, QString::fromLatin1("section-properties"));
662 if (format.hasProperty(QTextFormat::BlockTopMargin))
663 writer.writeAttribute(foNS, QString::fromLatin1("margin-top"), pixelToPoint(qMax(qreal(0.), format.topMargin())) );
664 if (format.hasProperty(QTextFormat::BlockBottomMargin))
665 writer.writeAttribute(foNS, QString::fromLatin1("margin-bottom"), pixelToPoint(qMax(qreal(0.), format.bottomMargin())) );
666 if (format.hasProperty(QTextFormat::BlockLeftMargin))
667 writer.writeAttribute(foNS, QString::fromLatin1("margin-left"), pixelToPoint(qMax(qreal(0.), format.leftMargin())) );
668 if (format.hasProperty(QTextFormat::BlockRightMargin))
669 writer.writeAttribute(foNS, QString::fromLatin1("margin-right"), pixelToPoint(qMax(qreal(0.), format.rightMargin())) );
670
671 writer.writeEndElement(); // style
672
673// TODO consider putting the following properties in a qt-namespace.
674// Position position () const
675// qreal border () const
676// QBrush borderBrush () const
677// BorderStyle borderStyle () const
678// qreal padding () const
679// QTextLength width () const
680// QTextLength height () const
681// PageBreakFlags pageBreakPolicy () const
682}
683
684void QTextOdfWriter::writeTableCellFormat(QXmlStreamWriter &writer, QTextTableCellFormat format, int formatIndex) const
685{
686 writer.writeStartElement(styleNS, QString::fromLatin1("style"));
687 writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("T%1").arg(formatIndex));
688 writer.writeAttribute(styleNS, QString::fromLatin1("family"), QString::fromLatin1("table"));
689 writer.writeEmptyElement(styleNS, QString::fromLatin1("table-properties"));
690
691
692 qreal padding = format.topPadding();
693 if (padding > 0 && padding == format.bottomPadding()
694 && padding == format.leftPadding() && padding == format.rightPadding()) {
695 writer.writeAttribute(foNS, QString::fromLatin1("padding"), pixelToPoint(padding));
696 }
697 else {
698 if (padding > 0)
699 writer.writeAttribute(foNS, QString::fromLatin1("padding-top"), pixelToPoint(padding));
700 if (format.bottomPadding() > 0)
701 writer.writeAttribute(foNS, QString::fromLatin1("padding-top"), pixelToPoint(format.bottomPadding()));
702 if (format.leftPadding() > 0)
703 writer.writeAttribute(foNS, QString::fromLatin1("padding-top"), pixelToPoint(format.leftPadding()));
704 if (format.rightPadding() > 0)
705 writer.writeAttribute(foNS, QString::fromLatin1("padding-top"), pixelToPoint(format.rightPadding()));
706 }
707
708 if (format.hasProperty(QTextFormat::TextVerticalAlignment)) {
709 QString pos;
710 switch (format.verticalAlignment()) {
711 case QTextCharFormat::AlignMiddle:
712 pos = QString::fromLatin1("middle"); break;
713 case QTextCharFormat::AlignTop:
714 pos = QString::fromLatin1("top"); break;
715 case QTextCharFormat::AlignBottom:
716 pos = QString::fromLatin1("bottom"); break;
717 default:
718 pos = QString::fromLatin1("automatic"); break;
719 }
720 writer.writeAttribute(styleNS, QString::fromLatin1("vertical-align"), pos);
721 }
722
723 // TODO
724 // ODF just search for style-table-cell-properties-attlist)
725 // QTextFormat::BackgroundImageUrl
726 // format.background
727 // QTextFormat::FrameBorder
728
729 writer.writeEndElement(); // style
730}
731
732///////////////////////
733
734QTextOdfWriter::QTextOdfWriter(const QTextDocument &document, QIODevice *device)
735 : officeNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:office:1.0")),
736 textNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:text:1.0")),
737 styleNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:style:1.0")),
738 foNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0")),
739 tableNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:table:1.0")),
740 drawNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:drawing:1.0")),
741 xlinkNS (QLatin1String("http://www.w3.org/1999/xlink")),
742 svgNS (QLatin1String("urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0")),
743 m_document(&document),
744 m_device(device),
745 m_strategy(0),
746 m_codec(0),
747 m_createArchive(true)
748{
749}
750
751bool QTextOdfWriter::writeAll()
752{
753 if (m_createArchive)
754 m_strategy = new QZipStreamStrategy(m_device);
755 else
756 m_strategy = new QXmlStreamStrategy(m_device);
757
758 if (!m_device->isWritable() && ! m_device->open(QIODevice::WriteOnly)) {
759 qWarning() << "QTextOdfWriter::writeAll: the device can not be opened for writing";
760 return false;
761 }
762 QXmlStreamWriter writer(m_strategy->contentStream);
763#ifndef QT_NO_TEXTCODEC
764 if (m_codec)
765 writer.setCodec(m_codec);
766#endif
767 // prettyfy
768 writer.setAutoFormatting(true);
769 writer.setAutoFormattingIndent(2);
770
771 writer.writeNamespace(officeNS, QString::fromLatin1("office"));
772 writer.writeNamespace(textNS, QString::fromLatin1("text"));
773 writer.writeNamespace(styleNS, QString::fromLatin1("style"));
774 writer.writeNamespace(foNS, QString::fromLatin1("fo"));
775 writer.writeNamespace(tableNS, QString::fromLatin1("table"));
776 writer.writeNamespace(drawNS, QString::fromLatin1("draw"));
777 writer.writeNamespace(xlinkNS, QString::fromLatin1("xlink"));
778 writer.writeNamespace(svgNS, QString::fromLatin1("svg"));
779 writer.writeStartDocument();
780 writer.writeStartElement(officeNS, QString::fromLatin1("document-content"));
781
782 // add fragments. (for character formats)
783 QTextDocumentPrivate::FragmentIterator fragIt = m_document->docHandle()->begin();
784 QSet<int> formats;
785 while (fragIt != m_document->docHandle()->end()) {
786 const QTextFragmentData * const frag = fragIt.value();
787 formats << frag->format;
788 ++fragIt;
789 }
790
791 // add blocks (for blockFormats)
792 QTextDocumentPrivate::BlockMap &blocks = m_document->docHandle()->blockMap();
793 QTextDocumentPrivate::BlockMap::Iterator blockIt = blocks.begin();
794 while (blockIt != blocks.end()) {
795 const QTextBlockData * const block = blockIt.value();
796 formats << block->format;
797 ++blockIt;
798 }
799
800 // add objects for lists, frames and tables
801 QVector<QTextFormat> allFormats = m_document->allFormats();
802 QList<int> copy = formats.toList();
803 for (QList<int>::Iterator iter = copy.begin(); iter != copy.end(); ++iter) {
804 QTextObject *object = m_document->objectForFormat(allFormats[*iter]);
805 if (object)
806 formats << object->formatIndex();
807 }
808
809 writeFormats(writer, formats);
810
811 writer.writeStartElement(officeNS, QString::fromLatin1("body"));
812 writer.writeStartElement(officeNS, QString::fromLatin1("text"));
813 QTextFrame *rootFrame = m_document->rootFrame();
814 writeFrame(writer, rootFrame);
815 writer.writeEndElement(); // text
816 writer.writeEndElement(); // body
817 writer.writeEndElement(); // document-content
818 writer.writeEndDocument();
819 delete m_strategy;
820 m_strategy = 0;
821
822 return true;
823}
824
825QT_END_NAMESPACE
826
827#endif // QT_NO_TEXTODFWRITER
Note: See TracBrowser for help on using the repository browser.