File: KoOdfLoadingContext.cpp

package info (click to toggle)
calligra 1%3A3.2.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 260,432 kB
  • sloc: cpp: 650,911; xml: 27,662; python: 6,044; perl: 2,724; yacc: 1,817; ansic: 1,325; sh: 1,277; lex: 1,107; ruby: 1,010; javascript: 495; makefile: 24
file content (354 lines) | stat: -rw-r--r-- 12,171 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/* This file is part of the KDE project
   Copyright (C) 2005 David Faure <faure@kde.org>
   Copyright (C) 2010 Inge Wallin <inge@lysator.liu.se>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

// Own
#include "KoOdfLoadingContext.h"

#include "OdfDebug.h"

// Calligra
#include <KoOdfReadStore.h>
#include <KoOdfStylesReader.h>
#include <KoStore.h>
#include <KoStoreDevice.h>
#include <KoXmlNS.h>
#include <KoOdfManifestEntry.h>
#include "KoStyleStack.h"

// Qt
#include <QStandardPaths>
#include <QMimeDatabase>
#include <QMimeType>


class Q_DECL_HIDDEN KoOdfLoadingContext::Private
{
public:
    Private(KoOdfStylesReader &sr, KoStore *s)
        : store(s),
        stylesReader(sr),
        generatorType(KoOdfLoadingContext::Unknown),
        metaXmlParsed(false),
        useStylesAutoStyles(false)
    {
    }

    ~Private() {
        qDeleteAll(manifestEntries);
    }

    KoStore *store;
    KoOdfStylesReader &stylesReader;
    KoStyleStack styleStack;

    mutable QString generator;
    GeneratorType generatorType;
    mutable bool metaXmlParsed;
    bool useStylesAutoStyles;

    KoXmlDocument manifestDoc;
    QHash<QString, KoOdfManifestEntry *> manifestEntries;


    KoOdfStylesReader defaultStylesReader;
    KoXmlDocument doc; // the doc needs to be kept around so it is possible to access the styles
};

KoOdfLoadingContext::KoOdfLoadingContext(KoOdfStylesReader &stylesReader, KoStore* store, const QString &defaultStylesResourcePath)
        : d(new Private(stylesReader, store))
{
    // Ideally this should be done by KoDocument and passed as argument here...
    KoOdfReadStore oasisStore(store);
    QString dummy;
    (void)oasisStore.loadAndParse("tar:/META-INF/manifest.xml", d->manifestDoc, dummy);

    if (!defaultStylesResourcePath.isEmpty()) {
        Q_ASSERT(defaultStylesResourcePath.endsWith(QLatin1Char('/')));
        const QString fileName =
            QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                                   defaultStylesResourcePath + "defaultstyles.xml");
        if ( ! fileName.isEmpty() ) {
            QFile file( fileName );
            QString errorMessage;
            if ( KoOdfReadStore::loadAndParse( &file, d->doc, errorMessage, fileName ) ) {
                d->defaultStylesReader.createStyleMap( d->doc, true );
            }
            else {
                warnOdf << "reading of defaultstyles.xml failed:" << errorMessage;
            }
        }
        else {
            warnOdf << "defaultstyles.xml not found";
        }
    }

    if (!parseManifest(d->manifestDoc)) {
        debugOdf << "could not parse manifest document";
    }
}

KoOdfLoadingContext::~KoOdfLoadingContext()
{
    delete d;
}

void KoOdfLoadingContext::setManifestFile(const QString& fileName) {
    KoOdfReadStore oasisStore(d->store);
    QString dummy;
    (void)oasisStore.loadAndParse(fileName, d->manifestDoc, dummy);
    if (!parseManifest(d->manifestDoc)) {
        debugOdf << "could not parse manifest document";
    }
}

void KoOdfLoadingContext::fillStyleStack(const KoXmlElement& object, const QString &nsURI, const QString &attrName, const QString &family)
{
    // find all styles associated with an object and push them on the stack
    if (object.hasAttributeNS(nsURI, attrName)) {
        const QString styleName = object.attributeNS(nsURI, attrName, QString());
        const KoXmlElement * style = d->stylesReader.findStyle(styleName, family, d->useStylesAutoStyles);

        if (style)
            addStyles(style, family, d->useStylesAutoStyles);
        else
            warnOdf << "style" << styleName << "not found in" << (d->useStylesAutoStyles ? "styles.xml" : "content.xml");
    }
}

void KoOdfLoadingContext::addStyles(const KoXmlElement* style, const QString &family, bool usingStylesAutoStyles)
{
    Q_ASSERT(style);
    if (!style) return;

    // this recursive function is necessary as parent styles can have parents themselves
    if (style->hasAttributeNS(KoXmlNS::style, "parent-style-name")) {
        const QString parentStyleName = style->attributeNS(KoXmlNS::style, "parent-style-name", QString());
        const KoXmlElement* parentStyle = d->stylesReader.findStyle(parentStyleName, family, usingStylesAutoStyles);

        if (parentStyle)
            addStyles(parentStyle, family, usingStylesAutoStyles);
        else {
            warnOdf << "Parent style not found: " << family << parentStyleName << usingStylesAutoStyles;
            //we are handling a non compliant odf file. let's at the very least load the application default, and the eventual odf default
            if (!family.isEmpty()) {
                const KoXmlElement* def = d->stylesReader.defaultStyle(family);
                if (def) {   // then, the default style for this family
                    d->styleStack.push(*def);
                }
            }
        }
    } else if (!family.isEmpty()) {
        const KoXmlElement* def = d->stylesReader.defaultStyle(family);
        if (def) {   // then, the default style for this family
            d->styleStack.push(*def);
        }
    }

    //debugOdf <<"pushing style" << style->attributeNS( KoXmlNS::style,"name", QString() );
    d->styleStack.push(*style);
}

void KoOdfLoadingContext::parseGenerator() const
{
    // Regardless of whether we cd into the parent directory
    // or not to find a meta.xml, restore the directory that
    // we were in afterwards.
    d->store->pushDirectory();

    // Some embedded documents to not contain their own meta.xml
    // Use the parent directory's instead.
    if (!d->store->hasFile("meta.xml"))
        // Only has an effect if there is a parent directory
        d->store->leaveDirectory();

    if (d->store->hasFile("meta.xml")) {
        KoXmlDocument metaDoc;
        KoOdfReadStore oasisStore(d->store);
        QString errorMsg;
        if (oasisStore.loadAndParse("meta.xml", metaDoc, errorMsg)) {
            KoXmlNode meta   = KoXml::namedItemNS(metaDoc, KoXmlNS::office, "document-meta");
            KoXmlNode office = KoXml::namedItemNS(meta, KoXmlNS::office, "meta");
            KoXmlElement generator = KoXml::namedItemNS(office, KoXmlNS::meta, "generator");
            if (!generator.isNull()) {
                d->generator = generator.text();
                if (d->generator.startsWith(QLatin1String("Calligra"))) {
                    d->generatorType = Calligra;
                }
                // NeoOffice is a port of OpenOffice to Mac OS X
                else if (d->generator.startsWith(QLatin1String("OpenOffice.org")) ||
                         d->generator.startsWith(QLatin1String("NeoOffice")) ||
                         d->generator.startsWith(QLatin1String("LibreOffice")) ||
                         d->generator.startsWith(QLatin1String("StarOffice")) ||
                         d->generator.startsWith(QLatin1String("Lotus Symphony"))) {
                    d->generatorType = OpenOffice;
                }
                else if (d->generator.startsWith(QLatin1String("MicrosoftOffice"))) {
                    d->generatorType = MicrosoftOffice;
                }
            }
        }
    }
    d->metaXmlParsed = true;

    d->store->popDirectory();
}

QString KoOdfLoadingContext::generator() const
{
    if (!d->metaXmlParsed && d->store) {
        parseGenerator();
    }
    return d->generator;
}

KoOdfLoadingContext::GeneratorType KoOdfLoadingContext::generatorType() const
{
    if (!d->metaXmlParsed && d->store) {
        parseGenerator();
    }
    return d->generatorType;
}

KoStore *KoOdfLoadingContext::store() const
{
    return d->store;
}

KoOdfStylesReader &KoOdfLoadingContext::stylesReader()
{
    return d->stylesReader;
}

/**
* Get the application default styles styleReader
*/
KoOdfStylesReader &KoOdfLoadingContext::defaultStylesReader()
{
    return d->defaultStylesReader;
}

KoStyleStack &KoOdfLoadingContext::styleStack() const
{
    return d->styleStack;
}

void KoOdfLoadingContext::setUseStylesAutoStyles(bool useStylesAutoStyles)
{
    d->useStylesAutoStyles = useStylesAutoStyles;
}

bool KoOdfLoadingContext::useStylesAutoStyles() const
{
    return d->useStylesAutoStyles;
}

QString KoOdfLoadingContext::mimeTypeForPath(const QString& path, bool guess) const
{
    QHash<QString, KoOdfManifestEntry *>::ConstIterator it(d->manifestEntries.constFind(path));
    if (it == d->manifestEntries.constEnd()) {
        // try to find it with an added / at the end
        QString dirPath = path + '/';
        it = d->manifestEntries.constFind(dirPath);
    }
    if (it != d->manifestEntries.constEnd()) {
        QString mimeType = it.value()->mediaType();

        // figure out mimetype by content if it is not provided
        if (mimeType.isEmpty() && guess) {
            Q_ASSERT(!d->store->isOpen());
            if (d->store->open(path)) {
                KoStoreDevice device(d->store);
                QByteArray data = device.read(16384);
                d->store->close();
                QMimeDatabase db;
                QMimeType mtp = db.mimeTypeForData(data);
                mimeType = mtp.name();
                if (!mimeType.isEmpty()) {
                    it.value()->setMediaType(mimeType);
                }
            }
        }

        return mimeType;
    }
    else {
        return QString();
    }
}

QList<KoOdfManifestEntry*> KoOdfLoadingContext::manifestEntries() const
{
    return d->manifestEntries.values();
}

bool KoOdfLoadingContext::parseManifest(const KoXmlDocument &manifestDocument)
{
    // First find the manifest:manifest node.
    KoXmlNode  n = manifestDocument.firstChild();
    debugOdf << "Searching for manifest:manifest " << n.toElement().nodeName();
    for (; !n.isNull(); n = n.nextSibling()) {
        if (!n.isElement()) {
            debugOdf << "NOT element";
            continue;
        } else {
            debugOdf << "element";
        }

        debugOdf << "name:" << n.toElement().localName()
                      << "namespace:" << n.toElement().namespaceURI();

        if (n.toElement().localName() == "manifest"
            && n.toElement().namespaceURI() == KoXmlNS::manifest)
        {
            debugOdf << "found manifest:manifest";
            break;
        }
    }
    if (n.isNull()) {
        debugOdf << "Could not find manifest:manifest";
        return false;
    }

    // Now loop through the children of the manifest:manifest and
    // store all the manifest:file-entry elements.
    const KoXmlElement  manifestElement = n.toElement();
    for (n = manifestElement.firstChild(); !n.isNull(); n = n.nextSibling()) {

        if (!n.isElement())
            continue;

        KoXmlElement el = n.toElement();
        if (!(el.localName() == "file-entry" && el.namespaceURI() == KoXmlNS::manifest))
            continue;

        QString fullPath  = el.attributeNS(KoXmlNS::manifest, "full-path", QString());
        QString mediaType = el.attributeNS(KoXmlNS::manifest, "media-type", QString(""));
        QString version   = el.attributeNS(KoXmlNS::manifest, "version", QString());

        // Only if fullPath is valid, should we store this entry.
        // If not, we don't bother to find out exactly what is wrong, we just skip it.
        if (!fullPath.isNull()) {
            d->manifestEntries.insert(fullPath,
                                      new KoOdfManifestEntry(fullPath, mediaType, version));
        }
    }

    return true;
}