File: SheetsOdfDoc.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 (417 lines) | stat: -rw-r--r-- 16,953 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/* This file is part of the KDE project
   Copyright 1998-2016 The Calligra Team <calligra-devel@kde.org>
   Copyright 2016 Tomas Mecir <mecirt@gmail.com>
   Copyright 2010 Marijn Kruisselbrink <mkruisselbrink@kde.org>
   Copyright 2007 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
   Copyright 2007 Thorsten Zachmann <zachmann@kde.org>
   Copyright 2005-2006 Inge Wallin <inge@lysator.liu.se>
   Copyright 2004 Ariya Hidayat <ariya@kde.org>
   Copyright 2002-2003 Norbert Andres <nandres@web.de>
   Copyright 2000-2002 Laurent Montel <montel@kde.org>
   Copyright 2002 John Dailey <dailey@vt.edu>
   Copyright 2002 Phillip Mueller <philipp.mueller@gmx.de>
   Copyright 2000 Werner Trobin <trobin@kde.org>
   Copyright 1999-2000 Simon Hausmann <hausmann@kde.org>
   Copyright 1999 David Faure <faure@kde.org>
   Copyright 1998-2000 Torben Weis <weis@kde.org>

   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.
*/

#include "SheetsOdf.h"
#include "SheetsOdfPrivate.h"

#include "DocBase.h"
#include "BindingModel.h"
#include "CalculationSettings.h"
#include "Map.h"
#include "SheetsDebug.h"
#include "SheetAccessModel.h"
#include "calligra_sheets_limits.h"

#include <KoGenStyles.h>
#include <KoOdfReadStore.h>
#include <KoOdfWriteStore.h>
#include <KoProgressUpdater.h>
#include <KoStore.h>
#include <KoStoreDevice.h>
#include <KoUnit.h>
#include <KoUpdater.h>
#include <KoXmlReader.h>
#include <KoXmlWriter.h>
#include <KoXmlNS.h>

#include <KCodecs>
#include <QBuffer>

// This file contains functionality to load/save a DocBase

namespace Calligra {
namespace Sheets {

namespace Odf {
    void loadDocSettings(DocBase *doc, const KoXmlDocument &settingsDoc);
    void loadDocIgnoreList(DocBase *doc, const KoOasisSettings& settings);
    void saveSettings(DocBase *doc, KoXmlWriter &settingsWriter);
};


bool Odf::loadDocument(DocBase *doc, KoOdfReadStore &odfStore)
{
    QPointer<KoUpdater> updater;
    if (doc->progressUpdater()) {
        updater = doc->progressUpdater()->startSubtask(1, "Calligra::Sheets::Odf::loadDocument");
        updater->setProgress(0);
    }

    doc->setSpellListIgnoreAll(QStringList());

    KoXmlElement content = odfStore.contentDoc().documentElement();
    KoXmlElement realBody(KoXml::namedItemNS(content, KoXmlNS::office, "body"));
    if (realBody.isNull()) {
        doc->setErrorMessage(i18n("Invalid OASIS OpenDocument file. No office:body tag found."));
        doc->map()->deleteLoadingInfo();
        return false;
    }
    KoXmlElement body = KoXml::namedItemNS(realBody, KoXmlNS::office, "spreadsheet");

    if (body.isNull()) {
        errorSheetsODF << "No office:spreadsheet found!" << endl;
        KoXmlElement childElem;
        QString localName;
        forEachElement(childElem, realBody) {
            localName = childElem.localName();
        }
        if (localName.isEmpty())
            doc->setErrorMessage(i18n("Invalid OASIS OpenDocument file. No tag found inside office:body."));
        else
            doc->setErrorMessage(i18n("This document is not a spreadsheet, but %1. Please try opening it with the appropriate application." , KoDocument::tagNameToDocumentType(localName)));
        doc->map()->deleteLoadingInfo();
        return false;
    }

    // Document Url for FILENAME function and page header/footer.
    doc->map()->calculationSettings()->setFileName(doc->url().toDisplayString());

    KoOdfLoadingContext context(odfStore.styles(), odfStore.store());

    // TODO check versions and mimetypes etc.

    // all <sheet:sheet> goes to workbook
    if (!loadMap(doc->map(), body, context)) {
        doc->map()->deleteLoadingInfo();
        return false;
    }

    if (!odfStore.settingsDoc().isNull()) {
        loadDocSettings(doc, odfStore.settingsDoc());
    }
    doc->initConfig();

    //update plugins that rely on bindings, as loading order can mess up the data of the plugins
    SheetAccessModel* sheetModel = doc->sheetAccessModel();
    QList< Sheet* > sheets = doc->map()->sheetList();
    Q_FOREACH( Sheet* sheet, sheets ){
        // This region contains the entire sheet
        const QRect region (0, 0, KS_colMax - 1, KS_rowMax - 1);
        QModelIndex index = sheetModel->index( 0, doc->map()->indexOf( sheet ) );
          QVariant bindingModelValue = sheetModel->data( index , Qt::DisplayRole );
          BindingModel *curBindingModel = dynamic_cast< BindingModel* >( qvariant_cast< QPointer< QAbstractItemModel > >( bindingModelValue ).data() );
          if ( curBindingModel ){
              curBindingModel->emitDataChanged( region );
          }
    }

    if (updater) updater->setProgress(100);

    return true;
}

void Odf::loadDocSettings(DocBase *doc, const KoXmlDocument &settingsDoc)
{
    KoOasisSettings settings(settingsDoc);
    KoOasisSettings::Items viewSettings = settings.itemSet("view-settings");
    if (!viewSettings.isNull()) {
        doc->setUnit(KoUnit::fromSymbol(viewSettings.parseConfigItemString("unit")));
    }
    loadMapSettings(doc->map(), settings);
    loadDocIgnoreList(doc, settings);
}

void Odf::loadDocIgnoreList(DocBase *doc, const KoOasisSettings& settings)
{
    KoOasisSettings::Items configurationSettings = settings.itemSet("configuration-settings");
    if (!configurationSettings.isNull()) {
        const QString ignorelist = configurationSettings.parseConfigItemString("SpellCheckerIgnoreList");
        //debugSheets<<" ignorelist :"<<ignorelist;
        doc->setSpellListIgnoreAll (ignorelist.split(',', QString::SkipEmptyParts));
    }
}

bool Odf::saveDocument(DocBase *doc, KoDocument::SavingContext &documentContext)
{
    KoStore * store = documentContext.odfStore.store();
    KoXmlWriter * manifestWriter = documentContext.odfStore.manifestWriter();

    KoStoreDevice dev(store);
    KoGenStyles mainStyles;//for compile

    KoXmlWriter* contentWriter = documentContext.odfStore.contentWriter();
    if (!contentWriter) return false;

    // Document Url for FILENAME function and page header/footer.
    doc->map()->calculationSettings()->setFileName(doc->url().toDisplayString());

    KoXmlWriter* bodyWriter = documentContext.odfStore.bodyWriter();
    KoShapeSavingContext savingContext(*bodyWriter, mainStyles, documentContext.embeddedSaver);

    //todo fixme just add a element for testing saving content.xml
    bodyWriter->startElement("office:body");
    bodyWriter->startElement("office:spreadsheet");

    // Saving the map.
    saveMap(doc->map(), *bodyWriter, savingContext);

    bodyWriter->endElement(); ////office:spreadsheet
    bodyWriter->endElement(); ////office:body

    // Done with writing out the contents to the tempfile, we can now write out the automatic styles
    mainStyles.saveOdfStyles(KoGenStyles::DocumentAutomaticStyles, contentWriter);

    documentContext.odfStore.closeContentWriter();

    //add manifest line for content.xml
    manifestWriter->addManifestEntry("content.xml",  "text/xml");

    mainStyles.saveOdfStylesDotXml(store, manifestWriter);

    if (!store->open("settings.xml"))
        return false;

    KoXmlWriter* settingsWriter = KoOdfWriteStore::createOasisXmlWriter(&dev, "office:document-settings");
    settingsWriter->startElement("office:settings");
    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "view-settings");

    doc->saveUnitOdf(settingsWriter);

    saveSettings(doc, *settingsWriter);

    settingsWriter->endElement(); // config:config-item-set

    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "configuration-settings");
    settingsWriter->addConfigItem("SpellCheckerIgnoreList", doc->spellListIgnoreAll().join(","));
    settingsWriter->endElement(); // config:config-item-set
    settingsWriter->endElement(); // office:settings
    settingsWriter->endElement(); // Root:element
    settingsWriter->endDocument();
    delete settingsWriter;

    if (!store->close())
        return false;

    if (!savingContext.saveDataCenter(store, manifestWriter)) {
        return false;
    }

    manifestWriter->addManifestEntry("settings.xml", "text/xml");

    doc->setModified(false);

    return true;
}

void Odf::saveSettings(DocBase *doc, KoXmlWriter &settingsWriter)
{
    settingsWriter.startElement("config:config-item-map-indexed");
    settingsWriter.addAttribute("config:name", "Views");
    settingsWriter.startElement("config:config-item-map-entry");
    settingsWriter.addConfigItem("ViewId", QString::fromLatin1("View1"));
    //<config:config-item-map-named config:name="Tables">
    settingsWriter.startElement("config:config-item-map-named");
    settingsWriter.addAttribute("config:name", "Tables");
    foreach (Sheet *sheet, doc->map()->sheetList()) {
        settingsWriter.startElement("config:config-item-map-entry");
        settingsWriter.addAttribute("config:name", sheet->sheetName());
        saveSheetSettings(sheet, settingsWriter);
        settingsWriter.endElement();
    }
    settingsWriter.endElement();
    settingsWriter.endElement();
    settingsWriter.endElement();
}

void Odf::loadProtection(ProtectableObject *prot, const KoXmlElement& element)
{
    if (!element.hasAttributeNS(KoXmlNS::table, "protection-key")) return;
    QString p = element.attributeNS(KoXmlNS::table, "protection-key", QString());
    if (p.isNull()) return;

    QByteArray str(p.toUtf8());
    debugSheetsODF <<"Decoding password:" << str;
    prot->setProtected(KCodecs::base64Decode(str));
}

bool Odf::paste(QBuffer &buffer, Map *map)
{
    KoStore * store = KoStore::createStore(&buffer, KoStore::Read);

    KoOdfReadStore odfStore(store); // does not delete the store on destruction
    KoXmlDocument doc;
    QString errorMessage;
    bool ok = odfStore.loadAndParse("content.xml", doc, errorMessage);
    if (!ok) {
        errorSheetsODF << "Error parsing content.xml: " << errorMessage << endl;
    delete store;
        return false;
    }

    KoOdfStylesReader stylesReader;
    KoXmlDocument stylesDoc;
    (void)odfStore.loadAndParse("styles.xml", stylesDoc, errorMessage);
    // Load styles from style.xml
    stylesReader.createStyleMap(stylesDoc, true);
    // Also load styles from content.xml
    stylesReader.createStyleMap(doc, false);

    // from KSpreadDoc::loadOdf:
    KoXmlElement content = doc.documentElement();
    KoXmlElement realBody(KoXml::namedItemNS(content, KoXmlNS::office, "body"));
    if (realBody.isNull()) {
        debugSheetsUI << "Invalid OASIS OpenDocument file. No office:body tag found.";
        delete store;
        return false;
    }
    KoXmlElement body = KoXml::namedItemNS(realBody, KoXmlNS::office, "spreadsheet");

    if (body.isNull()) {
        errorSheetsODF << "No office:spreadsheet found!" << endl;
        delete store;
        return false;
    }

    KoOdfLoadingContext context(stylesReader, store);
    Q_ASSERT(!stylesReader.officeStyle().isNull());

    // all <sheet:sheet> goes to workbook
    bool result = loadMap(map, body, context);

    delete store;

    return result;
}

void Odf::loadCalculationSettings(CalculationSettings *settings, const KoXmlElement& body)
{
    KoXmlNode xmlsettings = KoXml::namedItemNS(body, KoXmlNS::table, "calculation-settings");
    debugSheets << "Calculation settings found?" << !xmlsettings.isNull();
    if (!xmlsettings.isNull()) {
        KoXmlElement element = xmlsettings.toElement();
        if (element.hasAttributeNS(KoXmlNS::table,  "case-sensitive")) {
            settings->setCaseSensitiveComparisons(Qt::CaseSensitive);
            QString value = element.attributeNS(KoXmlNS::table, "case-sensitive", "true");
            if (value == "false")
                settings->setCaseSensitiveComparisons(Qt::CaseInsensitive);
        } else if (element.hasAttributeNS(KoXmlNS::table, "precision-as-shown")) {
            settings->setPrecisionAsShown(false);
            QString value = element.attributeNS(KoXmlNS::table, "precision-as-shown", "false");
            if (value == "true")
                settings->setPrecisionAsShown(true);
        } else if (element.hasAttributeNS(KoXmlNS::table, "search-criteria-must-apply-to-whole-cell")) {
            settings->setWholeCellSearchCriteria(true);
            QString value = element.attributeNS(KoXmlNS::table, "search-criteria-must-apply-to-whole-cell", "true");
            if (value == "false")
                settings->setWholeCellSearchCriteria(false);
        } else if (element.hasAttributeNS(KoXmlNS::table, "automatic-find-labels")) {
            settings->setAutomaticFindLabels(true);
            QString value = element.attributeNS(KoXmlNS::table, "automatic-find-labels", "true");
            if (value == "false")
                settings->setAutomaticFindLabels(false);
        } else if (element.hasAttributeNS(KoXmlNS::table, "use-regular-expressions")) {
            settings->setUseRegularExpressions(true);
            QString value = element.attributeNS(KoXmlNS::table, "use-regular-expressions", "true");
            if (value == "false")
                settings->setUseRegularExpressions(false);
        } else if (element.hasAttributeNS(KoXmlNS::table, "use-wildcards")) {
            settings->setUseWildcards(false);
            QString value = element.attributeNS(KoXmlNS::table, "use-wildcards", "false");
            if (value == "true")
                settings->setUseWildcards(true);
        } else if (element.hasAttributeNS(KoXmlNS::table, "null-year")) {
            settings->setReferenceYear(1930);
            QString value = element.attributeNS(KoXmlNS::table, "null-year", "1930");
            if (!value.isEmpty() && value != "1930") {
                bool ok;
                int refYear = value.toInt(&ok);
                if (ok)
                    settings->setReferenceYear(refYear);
            }
        }

        forEachElement(element, xmlsettings) {
            if (element.namespaceURI() != KoXmlNS::table)
                continue;
            else if (element.tagName() ==  "null-date") {
                settings->setReferenceDate(QDate(1899, 12, 30));
                QString valueType = element.attributeNS(KoXmlNS::table, "value-type", "date");
                if (valueType == "date") {
                    QString value = element.attributeNS(KoXmlNS::table, "date-value", "1899-12-30");
                    QDate date = QDate::fromString(value, Qt::ISODate);
                    if (date.isValid())
                        settings->setReferenceDate(date);
                } else {
                    debugSheets << "CalculationSettings: Error on loading null date."
                    << "Value type """ << valueType << """ not handled"
                    << ", falling back to default." << endl;
                    // NOTE Stefan: I don't know why different types are possible here!
                    // sebsauer: because according to ODF-specs a zero null date can
                    // mean QDate::currentDate(). Still unclear what a numeric value !=0
                    // means through :-/
                }
            } else if (element.tagName() ==  "iteration") {
                // TODO
            }
        }
    }
}

bool Odf::saveCalculationSettings(const CalculationSettings *settings, KoXmlWriter &xmlWriter)
{
    xmlWriter.startElement("table:calculation-settings");
    if (!settings->caseSensitiveComparisons())
        xmlWriter.addAttribute("table:case-sensitive", "false");
    if (settings->precisionAsShown())
        xmlWriter.addAttribute("table:precision-as-shown", "true");
    if (!settings->wholeCellSearchCriteria())
        xmlWriter.addAttribute("table:search-criteria-must-apply-to-whole-cell", "false");
    if (!settings->automaticFindLabels())
        xmlWriter.addAttribute("table:automatic-find-labels", "false");
    if (!settings->useRegularExpressions())
        xmlWriter.addAttribute("table:use-regular-expressions", "false");
    if (settings->useWildcards())
        xmlWriter.addAttribute("table:use-wildcards", "true");
    if (settings->referenceYear() != 1930)
        xmlWriter.addAttribute("table:null-year", QString::number(settings->referenceYear()));
    xmlWriter.endElement();
    return true;
}




}  // Sheets
}  // Calligra