Exemplo n.º 1
0
bool WBSDefinition::loadXML(KoXmlElement &element, XMLLoaderObject & ) {
    m_projectCode = element.attribute( "project-code" );
    m_projectSeparator = element.attribute( "project-separator" );
    m_levelsEnabled = (bool)element.attribute( "levels-enabled", "0" ).toInt();
    KoXmlNode n = element.firstChild();
    for ( ; ! n.isNull(); n = n.nextSibling() ) {
        if ( ! n.isElement() ) {
            continue;
        }
        KoXmlElement e = n.toElement();
        if (e.tagName() == "default") {
            m_defaultDef.code = e.attribute( "code", "Number" );
            m_defaultDef.separator = e.attribute( "separator", "." );
        } else if (e.tagName() == "levels") {
            KoXmlNode n = e.firstChild();
            for ( ; ! n.isNull(); n = n.nextSibling() ) {
                if ( ! n.isElement() ) {
                    continue;
                }
                KoXmlElement el = n.toElement();
                CodeDef d;
                d.code = el.attribute( "code" );
                d.separator = el.attribute( "separator" );
                int lvl = el.attribute( "level", "-1" ).toInt();
                if ( lvl >= 0 ) {
                    setLevelsDef( lvl, d );
                } else kError()<<"Invalid levels definition";
            }
        }
    }
    return true;
}
Exemplo n.º 2
0
void TestKoShapeFactory::testOdfElement()
{
    KoShapeFactoryBase * factory = new KoPathShapeFactory(QStringList());
    QVERIFY(factory->odfElements().front().second.contains("path"));
    QVERIFY(factory->odfElements().front().second.contains("line"));
    QVERIFY(factory->odfElements().front().second.contains("polyline"));
    QVERIFY(factory->odfElements().front().second.contains("polygon"));
    QVERIFY(factory->odfElements().front().first == KoXmlNS::draw);

    QBuffer xmldevice;
    xmldevice.open(QIODevice::WriteOnly);
    QTextStream xmlstream(&xmldevice);

    xmlstream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    xmlstream << "<office:document-content xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\" xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\" xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\" xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\" xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\" xmlns:math=\"http://www.w3.org/1998/Math/MathML\" xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" xmlns:koffice=\"http://www.koffice.org/2005/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">";
    xmlstream << "<office:body>";
    xmlstream << "<office:text>";
    xmlstream << "<text:p text:style-name=\"P1\"><?opendocument cursor-position?></text:p>";
    xmlstream << "<draw:path svg:d=\"M10,10L100,100\"></draw:path>";
    xmlstream << "</office:text>";
    xmlstream << "</office:body>";
    xmlstream << "</office:document-content>";
    xmldevice.close();

    KoXmlDocument doc;
    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;

    QCOMPARE(doc.setContent(&xmldevice, true, &errorMsg, &errorLine, &errorColumn), true);
    QCOMPARE(errorMsg.isEmpty(), true);
    QCOMPARE(errorLine, 0);
    QCOMPARE(errorColumn, 0);

    KoXmlElement contentElement = doc.documentElement();
    KoXmlElement bodyElement = contentElement.firstChild().toElement();

    // XXX: When loading is implemented, these no doubt have to be
    // sensibly filled.
    KoOdfStylesReader stylesReader;
    KoOdfLoadingContext odfContext(stylesReader, 0);
    KoShapeLoadingContext shapeContext(odfContext, 0);

    KoXmlElement textElement = bodyElement.firstChild().firstChild().toElement();
    QVERIFY(textElement.tagName() == "p");
    QCOMPARE(factory->supports(textElement, shapeContext), false);

    KoXmlElement pathElement = bodyElement.firstChild().lastChild().toElement();
    QVERIFY(pathElement.tagName() == "path");
    QCOMPARE(factory->supports(pathElement, shapeContext), true);

    KoShape *shape = factory->createDefaultShape();
    QVERIFY(shape);

    QVERIFY(shape->loadOdf(pathElement, shapeContext));

    delete shape;
    delete factory;
}
Exemplo n.º 3
0
void KisKraLoader::loadCompositions(const KoXmlElement& elem, KisImageWSP image)
{
    KoXmlNode child;

    for (child = elem.firstChild(); !child.isNull(); child = child.nextSibling()) {

        KoXmlElement e = child.toElement();
        QString name = e.attribute("name");
        bool exportEnabled = e.attribute("exportEnabled", "1") == "0" ? false : true;

        KisLayerComposition* composition = new KisLayerComposition(image, name);
        composition->setExportEnabled(exportEnabled);

        KoXmlNode value;
        for (value = child.lastChild(); !value.isNull(); value = value.previousSibling()) {
            KoXmlElement e = value.toElement();
            QUuid uuid(e.attribute("uuid"));
            bool visible = e.attribute("visible", "1") == "0" ? false : true;
            composition->setVisible(uuid, visible);
            bool collapsed = e.attribute("collapsed", "1") == "0" ? false : true;
            composition->setCollapsed(uuid, collapsed);
        }

        image->addComposition(composition);
    }
}
Exemplo n.º 4
0
KisNodeSP KisKraLoader::loadNodes(const KoXmlElement& element, KisImageWSP image, KisNodeSP parent)
{

    KoXmlNode node = element.firstChild();
    KoXmlNode child;

    if (!node.isNull()) {

        if (node.isElement()) {

            if (node.nodeName().toUpper() == LAYERS.toUpper() || node.nodeName().toUpper() == MASKS.toUpper()) {
                for (child = node.lastChild(); !child.isNull(); child = child.previousSibling()) {
                    KisNodeSP node = loadNode(child.toElement(), image, parent);
                    if (node) {
                        image->nextLayerName(); // Make sure the nameserver is current with the number of nodes.
                        image->addNode(node, parent);
                        if (node->inherits("KisLayer") && child.childNodesCount() > 0) {
                            loadNodes(child.toElement(), image, node);
                        }
                    }
                }
            }
        }
    }

    return parent;
}
Exemplo n.º 5
0
bool ComponentTransferEffect::load(const KoXmlElement &element, const KoFilterEffectLoadingContext &)
{
    if (element.tagName() != id())
        return false;

    // reset data
    m_data[ChannelR] = Data();
    m_data[ChannelG] = Data();
    m_data[ChannelB] = Data();
    m_data[ChannelA] = Data();

    for (KoXmlNode n = element.firstChild(); !n.isNull(); n = n.nextSibling()) {
        KoXmlElement node = n.toElement();
        if (node.tagName() == "feFuncR") {
            loadChannel(ChannelR, node);
        } else if (node.tagName() == "feFuncG") {
            loadChannel(ChannelG, node);
        } else if (node.tagName() == "feFuncB") {
            loadChannel(ChannelB, node);
        } else if (node.tagName() == "feFuncA") {
            loadChannel(ChannelA, node);
        }
    }

    return true;
}
KoFilterEffectStack * FilterEffectResource::toFilterStack() const
{
    KoFilterEffectStack * filterStack = new KoFilterEffectStack();
    if (!filterStack)
        return 0;

    QByteArray data = m_data.toByteArray();
    KoXmlDocument doc;
    doc.setContent(data);
    KoXmlElement e = doc.documentElement();

    // only allow obect bounding box units
    if (e.hasAttribute("filterUnits") && e.attribute("filterUnits") != "objectBoundingBox")
        return 0;

    if (e.attribute("primitiveUnits") != "objectBoundingBox")
        return 0;

    // parse filter region rectangle
    QRectF filterRegion;
    filterRegion.setX(fromPercentage(e.attribute("x", "-0.1")));
    filterRegion.setY(fromPercentage(e.attribute("y", "-0.1")));
    filterRegion.setWidth(fromPercentage(e.attribute("width", "1.2")));
    filterRegion.setHeight(fromPercentage(e.attribute("height", "1.2")));
    filterStack->setClipRect(filterRegion);

    KoFilterEffectLoadingContext context(QString(""));

    KoFilterEffectRegistry * registry = KoFilterEffectRegistry::instance();

    // create the filter effects and add them to the shape
    for (KoXmlNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
        KoXmlElement primitive = n.toElement();
        KoFilterEffect * filterEffect = registry->createFilterEffectFromXml(primitive, context);
        if (!filterEffect) {
            qWarning() << "filter effect" << primitive.tagName() << "is not implemented yet";
            continue;
        }

        // parse subregion
        qreal x = fromPercentage(primitive.attribute("x", "0"));
        qreal y = fromPercentage(primitive.attribute("y", "0"));
        qreal w = fromPercentage(primitive.attribute("width", "1"));
        qreal h = fromPercentage(primitive.attribute("height", "1"));
        QRectF subRegion(QPointF(x, y), QSizeF(w, h));

        if (primitive.hasAttribute("in"))
            filterEffect->setInput(0, primitive.attribute("in"));
        if (primitive.hasAttribute("result"))
            filterEffect->setOutput(primitive.attribute("result"));

        filterEffect->setFilterRect(subRegion);

        filterStack->appendFilterEffect(filterEffect);
    }

    return filterStack;
}
Exemplo n.º 7
0
void TestKoShapeRegistry::testCreateFramedShapes()
{
    QBuffer xmldevice;
    xmldevice.open(QIODevice::WriteOnly);
    QTextStream xmlstream(&xmldevice);

    xmlstream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    xmlstream << "<office:document-content xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\" xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\" xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\" xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\" xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\" xmlns:math=\"http://www.w3.org/1998/Math/MathML\" xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" xmlns:calligra=\"http://www.calligra.org/2005/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">";
    xmlstream << "<office:body>";
    xmlstream << "<office:text>";
    xmlstream << "<draw:path svg:d=\"M0,0L100,100\"></draw:path>";
    xmlstream << "</office:text>";
    xmlstream << "</office:body>";
    xmlstream << "</office:document-content>";
    xmldevice.close();

    KoXmlDocument doc;
    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;

    QCOMPARE(doc.setContent(&xmldevice, true, &errorMsg, &errorLine, &errorColumn), true);
    QCOMPARE(errorMsg.isEmpty(), true);
    QCOMPARE(errorLine, 0);
    QCOMPARE(errorColumn, 0);

    KoXmlElement contentElement = doc.documentElement();
    KoXmlElement bodyElement = contentElement.firstChild().toElement();

    KoShapeRegistry * registry = KoShapeRegistry::instance();

    // XXX: When loading is implemented, these no doubt have to be
    // sensibly filled.
    KoOdfStylesReader stylesReader;
    KoOdfLoadingContext odfContext(stylesReader, 0);
    KoShapeLoadingContext shapeContext(odfContext, 0);

    KoShape * shape = registry->createShapeFromOdf(bodyElement, shapeContext);
    QVERIFY(shape == 0);

    KoXmlElement pathElement = bodyElement.firstChild().firstChild().toElement();
    shape = registry->createShapeFromOdf(pathElement, shapeContext);
    QVERIFY(shape != 0);
    QVERIFY(shape->shapeId() == KoPathShapeId);
}
Exemplo n.º 8
0
bool KoInlineNote::loadOdf(const KoXmlElement & element)
{
    if (element.namespaceURI() != KoXmlNS::text || element.localName() != "note")
        return false;

    QString className = element.attributeNS(KoXmlNS::text, "note-class");
    if (className == "footnote")
        d->type = Footnote;
    else if (className == "endnote")
        d->type = Endnote;
    else
        return false;

    d->id = element.attributeNS(KoXmlNS::text, "id");
    for (KoXmlNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) {
        setAutoNumbering(false);
        KoXmlElement ts = node.toElement();
        if (ts.namespaceURI() != KoXmlNS::text)
            continue;
        if (ts.localName() == "note-body") {
            d->text = "";
            KoXmlNode node = ts.firstChild();
            while (!node.isNull()) {
                KoXmlElement commentElement = node.toElement();
                if (!commentElement.isNull()) {
                    if (commentElement.localName() == "p" && commentElement.namespaceURI() == KoXmlNS::text) {
                        if (!d->text.isEmpty())
                            d->text.append('\n');
                        d->text.append(commentElement.text());
                    }
                }
                node = node.nextSibling();
            }
        } else if (ts.localName() == "note-citation") {
            d->label = ts.attributeNS(KoXmlNS::text, "label");
            if (d->label.isEmpty()) {
                setAutoNumbering(true);
                d->label = ts.text();
            }
        }
    }

    return true;
}
Exemplo n.º 9
0
bool KoInlineNote::loadOdf(const KoXmlElement & element, KoShapeLoadingContext &context, KoStyleManager *styleManager, KoChangeTracker *changeTracker)
{
    QTextDocument *document = new QTextDocument();
    QTextCursor cursor(document);
    KoTextDocument textDocument(document);
    textDocument.setStyleManager(styleManager);
    d->styleManager = styleManager;
    textDocument.setChangeTracker(changeTracker);

    KoTextLoader loader(context);

    if (element.namespaceURI() == KoXmlNS::text && element.localName() == "note") {

        QString className = element.attributeNS(KoXmlNS::text, "note-class");
        if (className == "footnote") {
            d->type = Footnote;
        }
        else if (className == "endnote") {
            d->type = Endnote;
        }
        else {
            delete document;
            return false;
        }

        d->id = element.attributeNS(KoXmlNS::text, "id");
        for (KoXmlNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) {
            setAutoNumbering(false);
            KoXmlElement ts = node.toElement();
            if (ts.namespaceURI() != KoXmlNS::text)
                continue;
            if (ts.localName() == "note-body") {
                loader.loadBody(ts, cursor);
            } else if (ts.localName() == "note-citation") {
                d->label = ts.attributeNS(KoXmlNS::text, "label");
                if (d->label.isEmpty()) {
                    setAutoNumbering(true);
                    d->label = ts.text();
                }
            }
        }
    }
    else if (element.namespaceURI() == KoXmlNS::office && element.localName() == "annotation") {
        d->author = element.attributeNS(KoXmlNS::text, "dc-creator");
        d->date = QDateTime::fromString(element.attributeNS(KoXmlNS::text, "dc-date"), Qt::ISODate);
        loader.loadBody(element, cursor); // would skip author and date, and do just the <text-p> and <text-list> elements
    }
    else {
        delete document;
        return false;
    }

    d->text = QTextDocumentFragment(document);
    delete document;
    return true;
}
Exemplo n.º 10
0
bool KoOdfLoadingContext::parseManifest(const KoXmlDocument &manifestDocument)
{
    // First find the manifest:manifest node.
    KoXmlNode  n = manifestDocument.firstChild();
    kDebug(30006) << "Searching for manifest:manifest " << n.toElement().nodeName();
    for (; !n.isNull(); n = n.nextSibling()) {
        if (!n.isElement()) {
            kDebug(30006) << "NOT element";
            continue;
        } else {
            kDebug(30006) << "element";
        }

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

        if (n.toElement().localName() == "manifest"
            && n.toElement().namespaceURI() == KoXmlNS::manifest)
        {
            kDebug(30006) << "found manifest:manifest";
            break;
        }
    }
    if (n.isNull()) {
        kDebug(30006) << "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;
}
Exemplo n.º 11
0
bool KPlatoXmlLoader::load( const KoXmlElement& plan )
{
    kDebug(kplatoXmlDebugArea())<<"plan";
    QString syntaxVersion = plan.attribute( "version" );
    m_loader.setVersion( syntaxVersion );
    if ( syntaxVersion.isEmpty() ) {
        int ret = KMessageBox::warningContinueCancel(
                      0, i18n( "This document has no syntax version.\n"
                               "Opening it in Plan may lose information." ),
                      i18n( "File-Format Error" ), KGuiItem( i18n( "Continue" ) ) );
        if ( ret == KMessageBox::Cancel ) {
            m_message = "USER_CANCELED";
            return false;
        }
        // set to max version and hope for the best
        m_loader.setVersion( KPLATO_MAX_FILE_SYNTAX_VERSION );
    } else if ( syntaxVersion > KPLATO_MAX_FILE_SYNTAX_VERSION ) {
        int ret = KMessageBox::warningContinueCancel(
                      0, i18n( "This document was created with a newer version of KPlato than Plan can load.\n"
                               "Syntax version: %1\n"
                               "Opening it in this version of Plan may lose some information.", syntaxVersion ),
                      i18n( "File-Format Mismatch" ), KGuiItem( i18n( "Continue" ) ) );
        if ( ret == KMessageBox::Cancel ) {
            m_message = "USER_CANCELED";
            return false;
        }
    }
    m_loader.startLoad();
    bool result = false;
    KoXmlNode n = plan.firstChild();
    for ( ; ! n.isNull(); n = n.nextSibling() ) {
        if ( ! n.isElement() ) {
            continue;
        }
        KoXmlElement e = n.toElement();
        if ( e.tagName() == "project" ) {
            m_loader.setProject( m_project );
            result = load( m_project, e, m_loader );
            if ( result ) {
                if ( m_project->id().isEmpty() ) {
                    m_project->setId( m_project->uniqueNodeId() );
                    m_project->registerNodeId( m_project );
                }
            } else {
                m_loader.addMsg( XMLLoaderObject::Errors, "Loading of project failed" );
                kError()<<"Loading of project failed";
                //TODO add some ui here
            }
        }
    }
    m_loader.stopLoad();
    return result;
}
Exemplo n.º 12
0
void KisKraLoader::loadAssistantsList(const KoXmlElement &elem)
{
    KoXmlNode child;
    int count = 0;
    for (child = elem.firstChild(); !child.isNull(); child = child.nextSibling()) {
        KoXmlElement e = child.toElement();
        QString type = e.attribute("type");
        QString file_name = e.attribute("filename");
        m_d->assistantsFilenames.insert(file_name,type);
        count++;

    }
}
Exemplo n.º 13
0
bool KraConverter::loadXML(const KoXmlDocument &doc, KoStore *store)
{
    Q_UNUSED(store);

    KoXmlElement root;
    KoXmlNode node;

    if (doc.doctype().name() != "DOC") {
       m_doc->setErrorMessage(i18n("The format is not supported or the file is corrupted"));
        return false;
    }
    root = doc.documentElement();
    int syntaxVersion = root.attribute("syntaxVersion", "3").toInt();
    if (syntaxVersion > 2) {
       m_doc->setErrorMessage(i18n("The file is too new for this version of Krita (%1).", syntaxVersion));
        return false;
    }

    if (!root.hasChildNodes()) {
       m_doc->setErrorMessage(i18n("The file has no layers."));
        return false;
    }

    m_kraLoader = new KisKraLoader(m_doc, syntaxVersion);

    // Legacy from the multi-image .kra file period.
    for (node = root.firstChild(); !node.isNull(); node = node.nextSibling()) {
        if (node.isElement()) {
            if (node.nodeName() == "IMAGE") {
                KoXmlElement elem = node.toElement();
                if (!(m_image = m_kraLoader->loadXML(elem))) {
                    if (m_kraLoader->errorMessages().isEmpty()) {
                        m_doc->setErrorMessage(i18n("Unknown error."));
                    }
                    else {
                        m_doc->setErrorMessage(m_kraLoader->errorMessages().join(".\n"));
                    }
                    return false;
                }
                return true;
            }
            else {
                if (m_kraLoader->errorMessages().isEmpty()) {
                    m_doc->setErrorMessage(i18n("The file does not contain an image."));
                }
                return false;
            }
        }
    }
    return false;
}
Exemplo n.º 14
0
bool Context::load( const KoXmlDocument &document ) {
    m_document = document; // create a copy, document is deleted under our feet

    // Check if this is the right app
    KoXmlElement elm = m_document.documentElement();
    QString value = elm.attribute( "mime", QString() );
    if ( value.isEmpty() ) {
        errorPlan << "No mime type specified!";
//        setErrorMessage( i18n( "Invalid document. No mimetype specified." ) );
        return false;
    } else if ( value != "application/x-vnd.kde.plan" ) {
        if ( value == "application/x-vnd.kde.kplato" ) {
            // accept, since we forgot to change kplato to plan for so long...
        } else {
            errorPlan << "Unknown mime type " << value;
//        setErrorMessage( i18n( "Invalid document. Expected mimetype application/x-vnd.kde.kplato, got %1", value ) );
            return false;
        }
    }
/*    QString m_syntaxVersion = elm.attribute( "version", "0.0" );
    if ( m_syntaxVersion > "0.0" ) {
        int ret = KMessageBox::warningContinueCancel(
                      0, i18n( "This document was created with a newer version of Plan (syntax version: %1)\n"
                               "Opening it in this version of Plan will lose some information.", m_syntaxVersion ),
                      i18n( "File-Format Mismatch" ), KGuiItem( i18n( "Continue" ) ) );
        if ( ret == KMessageBox::Cancel ) {
            setErrorMessage( "USER_CANCELED" );
            return false;
        }
    }
*/
/*
#ifdef KOXML_USE_QDOM
    int numNodes = elm.childNodes().count();
#else
    int numNodes = elm.childNodesCount();
#endif
*/
    KoXmlNode n = elm.firstChild();
    for ( ; ! n.isNull(); n = n.nextSibling() ) {
        if ( ! n.isElement() ) {
            continue;
        }
        KoXmlElement element = n.toElement();
        if ( element.tagName() == "context" ) {
            m_context = element;
            m_contextLoaded = true;
        }
    }
    return true;
}
Exemplo n.º 15
0
void SvgStyleParser::parseColorStops(QGradient *gradient, const KoXmlElement &e)
{
    QGradientStops stops;
    QColor c;

    for (KoXmlNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
        KoXmlElement stop = n.toElement();
        if (stop.tagName() == "stop") {
            float offset;
            QString temp = stop.attribute("offset");
            if (temp.contains('%')) {
                temp = temp.left(temp.length() - 1);
                offset = temp.toFloat() / 100.0;
            } else
                offset = temp.toFloat();

            QString stopColorStr = stop.attribute("stop-color");
            if (!stopColorStr.isEmpty()) {
                if (stopColorStr == "inherit") {
                    stopColorStr = inheritedAttribute("stop-color", stop);
                }
                parseColor(c, stopColorStr);
            }
            else {
                // try style attr
                QString style = stop.attribute("style").simplified();
                QStringList substyles = style.split(';', QString::SkipEmptyParts);
                for (QStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it) {
                    QStringList substyle = it->split(':');
                    QString command = substyle[0].trimmed();
                    QString params  = substyle[1].trimmed();
                    if (command == "stop-color")
                        parseColor(c, params);
                    if (command == "stop-opacity")
                        c.setAlphaF(params.toDouble());
                }

            }
            QString opacityStr = stop.attribute("stop-opacity");
            if (!opacityStr.isEmpty()) {
                if (opacityStr == "inherit") {
                    opacityStr = inheritedAttribute("stop-opacity", stop);
                }
                c.setAlphaF(opacityStr.toDouble());
            }
            stops.append(QPair<qreal, QColor>(offset, c));
        }
    }
    if (stops.count())
        gradient->setStops(stops);
}
Exemplo n.º 16
0
bool KPlatoXmlLoader::loadWorkpackage( const KoXmlElement& plan )
{
    kDebug(kplatoXmlDebugArea());
    bool ok = false;
    if ( m_loader.workVersion() > KPLATOWORK_MAX_FILE_SYNTAX_VERSION ) {
        int ret = KMessageBox::warningContinueCancel(
                0, i18n( "This document was created with a newer version of KPlatoWork (syntax version: %1)\n"
                "Opening it in this version of PlanWork will lose some information.", m_loader.workVersion() ),
                i18n( "File-Format Mismatch" ), KGuiItem( i18n( "Continue" ) ) );
        if ( ret == KMessageBox::Cancel ) {
            m_message = "USER_CANCELED";
            return false;
        }
    }
    m_loader.startLoad();
    Project *proj = new Project();
    Package *package = new Package();
    package->project = proj;
    KoXmlNode n = plan.firstChild();
    for ( ; ! n.isNull(); n = n.nextSibling() ) {
        if ( ! n.isElement() ) {
            continue;
        }
        KoXmlElement e = n.toElement();
        if ( e.tagName() == "project" ) {
            m_loader.setProject( proj );
            ok = load( proj, e, m_loader );
            if ( ! ok ) {
                m_loader.addMsg( XMLLoaderObject::Errors, "Loading of work package failed" );
                //TODO add some ui here
            }
        } else if ( e.tagName() == "workpackage" ) {
            m_timeTag = e.attribute( "time-tag" );
            package->ownerId = e.attribute( "owner-id" );
            package->ownerName = e.attribute( "owner" );
            KoXmlElement elem;
            forEachElement( elem, e ) {
                if ( elem.tagName() != "settings" ) {
                    continue;
                }
                package->settings.usedEffort = (bool)elem.attribute( "used-effort" ).toInt();
                package->settings.progress = (bool)elem.attribute( "progress" ).toInt();
                package->settings.documents = (bool)elem.attribute( "documents" ).toInt();
            }
        }
    }
Exemplo n.º 17
0
// static
bool PasteCommand::unknownShiftDirection(const QMimeData *mimeData)
{
    if (!mimeData) {
        return false;
    }

    QByteArray byteArray;

    if (mimeData->hasFormat("application/x-kspread-snippet")) {
        byteArray = mimeData->data("application/x-kspread-snippet");
    } else {
        return false;
    }

    QString errorMsg;
    int errorLine;
    int errorColumn;
    KoXmlDocument d;
    if (!d.setContent(byteArray, false, &errorMsg, &errorLine, &errorColumn)) {
        // an error occurred
        kDebug() << "An error occurred."
        << "line:" << errorLine << "col:" << errorColumn << errorMsg;
        return false;
    }

    KoXmlElement e = d.documentElement();
    if (!e.namedItem("columns").toElement().isNull()) {
        return false;
    }

    if (!e.namedItem("rows").toElement().isNull()) {
        return false;
    }

    KoXmlElement c = e.firstChild().toElement();
    for (; !c.isNull(); c = c.nextSibling().toElement()) {
        if (c.tagName() == "cell") {
            return true;
        }
    }
    return false;
}
Exemplo n.º 18
0
bool InfoVariable::loadOdf(const KoXmlElement & element, KoShapeLoadingContext & /*context*/)
{
    if (!s_loadInfo.exists() ) {
        for (unsigned int i = 0; i < numPropertyData; ++i) {
            s_loadInfo->insert(propertyData[i].tag, propertyData[i].property);
        }
    }

    const QString localName(element.localName());
    m_type = s_loadInfo->value(localName);

    for(KoXmlNode node = element.firstChild(); !node.isNull(); node = node.nextSibling() ) {
        if (node.isText()) {
            setValue(node.toText().data());
            break;
        }
    }

    return true;
}
Exemplo n.º 19
0
bool Context::load( const KoXmlDocument &document ) {
    m_document = document; // create a copy, document is deleted under our feet
    
    // Check if this is the right app
    KoXmlElement elm = m_document.documentElement();
    QString value = elm.attribute( "mime", QString() );
    if ( value.isEmpty() ) {
        kError() << "No mime type specified!" << endl;
//        setErrorMessage( i18n( "Invalid document. No mimetype specified." ) );
        return false;
    } else if ( value != "application/x-vnd.kde.kplato" ) {
        kError() << "Unknown mime type " << value << endl;
//        setErrorMessage( i18n( "Invalid document. Expected mimetype application/x-vnd.kde.kplato, got %1", value ) );
        return false;
    }
    QString m_syntaxVersion = elm.attribute( "version", "0.0" );
    if ( m_syntaxVersion > "0.0" ) {
/*        int ret = KMessageBox::warningContinueCancel(
                      0, i18n( "This document was created with a newer version of KPlato (syntax version: %1)\n"
                               "Opening it in this version of KPlato will lose some information.", m_syntaxVersion ),
                      i18n( "File-Format Mismatch" ), KGuiItem( i18n( "Continue" ) ) );
        if ( ret == KMessageBox::Cancel ) {
            setErrorMessage( "USER_CANCELED" );
            return false;
        }*/
    }

#ifdef KOXML_USE_QDOM
    int numNodes = elm.childNodes().count();
#else
    int numNodes = elm.childNodesCount();
#endif
    
    KoXmlNode n = elm.firstChild();
    for ( ; ! n.isNull(); n = n.nextSibling() ) {
        if ( ! n.isElement() ) {
            continue;
        }
        KoXmlElement element = n.toElement();
        if ( element.tagName() == "context" ) {
            m_context = element;
            m_contextLoaded = true;
/*            currentView = element.attribute("current-view");
            currentEstimateType = element.attribute("estimate-type").toInt();
            currentSchedule = element.attribute("current-schedule").toLong();
            actionViewExpected = element.attribute("view-expected").toInt();
            actionViewOptimistic = element.attribute("view-optimistic").toInt();
            actionViewPessimistic = element.attribute("view-pessimistic").toInt();
        
            QDomNodeList list = element.childNodes();
            for (int i=0; i<list.count(); ++i) {
                if (list.item(i).isElement()) {
                    QDomElement e = list.item(i).toElement();
                    if (e.tagName() == "gantt-view") {
                        ganttview.ganttviewsize = e.attribute("ganttview-size").toInt();
                        ganttview.taskviewsize = e.attribute("taskview-size").toInt();
                        ganttview.currentNode = e.attribute("current-node");
                        ganttview.showResources = e.attribute("show-resources").toInt();
                        ganttview.showTaskName = e.attribute("show-taskname").toInt();
                        ganttview.showTaskLinks = e.attribute("show-tasklinks").toInt();
                        ganttview.showProgress = e.attribute("show-progress").toInt();
                        ganttview.showPositiveFloat = e.attribute("show-positivefloat").toInt();
                        ganttview.showCriticalTasks = attribute("show-criticaltasks").toInt();
                        ganttview.showCriticalPath = e.attribute("show-criticalpath").toInt();
                        ganttview.showNoInformation = e.attribute("show-noinformation").toInt();
        
                        QDomNodeList list = e.childNodes();
                        for (int i=0; i<list.count(); ++i) {
                            if (list.item(i).isElement()) {
                              QDomElement g = list.item(i).toElement();
                                if (g.tagName() == "closed-nodes") {
                                    QDomNodeList list = g.childNodes();
                                    for (int i=0; i<list.count(); ++i) {
                                        if (list.item(i).isElement()) {
                                            QDomElement ei = list.item(i).toElement();
                                            if (ei.tagName() == "node") {
                                                ganttview.closedNodes.append(ei.attribute("id"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (e.tagName() == "accounts-view") {
                        accountsview.accountsviewsize = e.attribute("accountsview-size").toInt();
                        accountsview.periodviewsize = e.attribute("periodview-size").toInt();
                        accountsview.date = QDate::fromString(e.attribute("date"), Qt::ISODate);
                        accountsview.period = e.attribute("period").toInt();
                        accountsview.cumulative = e.attribute("cumulative").toInt();
        
                        QDomNodeList list = e.childNodes();
                        for (int i=0; i<list.count(); ++i) {
                            if (list.item(i).isElement()) {
                                QDomElement g = list.item(i).toElement();
                                if (g.tagName() == "closed-items") {
                                    QDomNodeList list = g.childNodes();
                                    for (int i=0; i<list.count(); ++i) {
                                        if (list.item(i).isElement()) {
                                            QDomElement ei = list.item(i).toElement();
                                            if (ei.tagName() == "account") {
                                                 accountsview.closedItems.append(ei.attribute("name"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        kError()<<"Unknown tag: "<<e.tagName()<<endl;
                    }
                }
            }*/
        }
    }
    return true;
}
Exemplo n.º 20
0
bool PasteCommand::processXmlData(Element *element, KoXmlDocument *data)
{
    const QRect pasteArea = element->rect();
    Sheet *const sheet = element->sheet();
    Q_ASSERT(sheet == m_sheet);
    Map *const map = sheet->map();

    const KoXmlElement root = data->documentElement(); // "spreadsheet-snippet"
    if (root.hasAttribute("cut")) {
        const Region cutRegion(root.attribute("cut"), map, sheet);
        if (cutRegion.isValid()) {
            const Cell destination(sheet, pasteArea.topLeft());
            map->dependencyManager()->regionMoved(cutRegion, destination);
        }
    }

    const int sourceHeight = root.attribute("rows").toInt();
    const int sourceWidth  = root.attribute("columns").toInt();

    // Find size of rectangle that we want to paste to (either clipboard size or current selection)
    const bool noRowsInClipboard    = root.namedItem("rows").toElement().isNull();
    const bool noColumnsInClipboard = root.namedItem("columns").toElement().isNull();
    const bool noRowsSelected       = !Region::Range(pasteArea).isRow();
    const bool noColumnsSelected    = !Region::Range(pasteArea).isColumn();
    const bool biggerSelectedWidth  = pasteArea.width()  >= sourceWidth;
    const bool biggerSelectedHeight = pasteArea.height() >= sourceHeight;

    const int pasteWidth  = biggerSelectedWidth && noRowsSelected && noRowsInClipboard
                            ? pasteArea.width() : sourceWidth;
    const int pasteHeight = biggerSelectedHeight && noColumnsSelected && noColumnsInClipboard
                            ? pasteArea.height() : sourceHeight;

    const int xOffset = noRowsInClipboard ? pasteArea.left() - 1 : 0;
    const int yOffset = noColumnsInClipboard ? pasteArea.top() - 1 : 0;

    kDebug(36005) << "selected size (col x row):" << pasteArea.width() << 'x' << pasteArea.height();
    kDebug(36005) << "source size (col x row):" << sourceWidth << 'x' << sourceHeight;
    kDebug(36005) << "paste area size (col x row):" << pasteWidth << 'x' << pasteHeight;
    kDebug(36005) << "xOffset:" << xOffset << "yOffset:" << yOffset;

    // Determine the shift direction, if needed.
    if (m_insertMode == ShiftCells) {
        if (!noColumnsInClipboard && !noRowsInClipboard) {
            // There are columns and rows in the source data.
            m_insertMode = ShiftCellsRight; // faster than down
        } else if (!noColumnsInClipboard) {
            // There are columns in the source data.
            m_insertMode = ShiftCellsRight;
        } else if (!noRowsInClipboard) {
            // There are rows in the source data.
            m_insertMode = ShiftCellsDown;
        } else {
            // Should not happen.
            // ShiftCells should only be set, if the data contains columns/rows.
            Q_ASSERT(false);
            m_insertMode = ShiftCellsRight; // faster than down
        }
    }

    const bool noColumns = noColumnsInClipboard && noColumnsSelected;
    const bool noRows = noRowsInClipboard && noRowsSelected;

    // Shift cells down.
    if (m_insertMode == ShiftCellsDown) {
        // Cases:
        // 1. Columns AND rows are contained in either source or selection
        // 1.a Columns in source and rows in selection
        //      I.e. yOffset=0
        //      Clear everything.
        //      Taking the column data/style and fill all columns.
        // 1.b Columns and rows in source, but not in selection
        //      I.e. xOffset=0,yOffset=0
        //      Leave everything as is? No, data from different sheet is possible!
        //      Clear everything.
        //      Fill with the source column/row data/style,
        //      i.e. the sheet data becomes equal to the source data.
        //      Same procedure as in 1.e
        // 1.c Columns and rows in selection, but not in source
        //      Clear everything.
        //      Fill with the source data. Tiling -> HUGE task!
        // 1.d Rows in source and columns in selection
        //      I.e. xOffset=0
        //      Clear everything.
        //      Taking the row data/style and fill all rows.
        // 1.e Columns AND rows in both
        //      I.e. xOffset=0,yOffset=0
        //      Leave everything as is? No, data from different sheet is possible!
        //      Clear everything.
        //      Fill with the source column/row data/style,
        //      i.e. the sheet data becomes equal to the source data.
        //      Same procedure as in 1.b
        // 2. Columns are present in either source or selection, but no rows
        // 2a Columns in source
        //      I.e. yOffset=0
        //      Clear the appropriate columns in the paste area.
        //      Fill them with the source data.
        // 2b Columns in selection
        //      Clear the selected columns.
        //      Fill them with the source data. Tiling -> HUGE task!
        // 2c Columns in both
        //      I.e. yOffset=0
        //      Clear the selected columns.
        //      Fill them with the source column data/style.
        // 3. Rows are present in either source or selection, but no columns
        // 3a Rows in source
        //      I.e. xOffset=0
        //      Insert rows.
        //      Fill in data.
        // 3b Rows in selection
        //      Insert rows.
        //      Fill in data. Tiling -> HUGE task!
        // 3c Rows in both
        //      I.e. xOffset=0
        //      Insert rows.
        //      Fill in data/style from source rows.
        // 4. Neither column, nor rows are present
        //      Shift the cell down.
        //      Fill in data.
        if ((!noColumns && !noRows) || (!noColumns && noRows)) {
            // Everything or only columns present.
            DeleteCommand *const command = new DeleteCommand(this);
            command->setSheet(m_sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
            command->setMode(DeleteCommand::OnlyCells);
        } else if (noColumns && !noRows) {
            // Rows present.
            InsertDeleteRowManipulator *const command = new InsertDeleteRowManipulator(this);
            command->setSheet(sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
        } else {
            // Neither columns, nor rows present.
            ShiftManipulator *const command = new ShiftManipulator(this);
            command->setSheet(sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
            command->setDirection(ShiftManipulator::ShiftBottom);
        }
    }
    // Shift cells right.
    if (m_insertMode == ShiftCellsRight) {
        // Cases:
        // Same as for ShiftCellsDown,
        // except that clearing and inserting are exchanged for cases 2 and 3.
        // Shifting a column to the right is the same as column insertion.
        // Shifting a row to the right is the same as clearing the row.
        if ((!noColumns && !noRows) || (noColumns && !noRows)) {
            // Everything or only rows present.
            DeleteCommand *const command = new DeleteCommand(this);
            command->setSheet(m_sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
            command->setMode(DeleteCommand::OnlyCells);
        } else if (!noColumns && noRows) {
            // Columns present.
            InsertDeleteColumnManipulator *const command = new InsertDeleteColumnManipulator(this);
            command->setSheet(sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
        } else {
            // Neither columns, nor rows present.
            ShiftManipulator *const command = new ShiftManipulator(this);
            command->setSheet(sheet);
            command->add(Region(pasteArea.x(), pasteArea.y(), pasteWidth, pasteHeight, sheet));
            command->setDirection(ShiftManipulator::ShiftRight);
        }
    }

    // This command will collect as many cell loads as possible in the iteration.
    PasteCellCommand *pasteCellCommand = 0;

    KoXmlElement e = root.firstChild().toElement(); // "columns", "rows" or "cell"
    for (; !e.isNull(); e = e.nextSibling().toElement()) {
        // If the element is not a cell, unset the pasteCellCommand pointer.
        // If existing, it is attached as child commnand, so no leaking here.
        if (e.tagName() != "cell") {
            pasteCellCommand = 0;
        }

        // entire columns given
        if (e.tagName() == "columns" && !sheet->isProtected()) {
            const int number = e.attribute("count").toInt();
            if (m_insertMode == NoInsertion) {
                // Clear the existing content; not the column style.
                DeleteCommand *const command = new DeleteCommand(this);
                command->setSheet(m_sheet);
                const int col = e.attribute("column").toInt();
                const int cols = qMax(pasteArea.width(), number);
                const Region region(col + xOffset, 1, cols, KS_rowMax, m_sheet);
                command->add(region);
                command->setMode(DeleteCommand::OnlyCells);
            }

            // Set the column style.
            ColumnFormat columnFormat;
            columnFormat.setSheet(sheet);
            KoXmlElement c = e.firstChild().toElement();
            for (; !c.isNull(); c = c.nextSibling().toElement()) {
                if (c.tagName() != "column") {
                    continue;
                }
                if (columnFormat.load(c, xOffset, m_pasteMode)) {
                    const int col = columnFormat.column();
                    const int cols = qMax(pasteArea.width(), number);
                    for (int coff = 0; col - xOffset + coff <= cols; coff += number) {
                        ColumnStyleCommand *const command = new ColumnStyleCommand(this);
                        command->setSheet(m_sheet);
                        command->add(Region(col + coff, 1, 1, 1, m_sheet));
                        command->setTemplate(columnFormat);
                    }
                }
            }
        }

        // entire rows given
        if (e.tagName() == "rows" && !sheet->isProtected()) {
            const int number = e.attribute("count").toInt();
            if (m_insertMode == NoInsertion) {
                // Clear the existing content; not the row style.
                DeleteCommand *const command = new DeleteCommand(this);
                command->setSheet(m_sheet);
                const int row = e.attribute("row").toInt();
                const int rows = qMax(pasteArea.height(), number);
                const Region region(1, row + yOffset, KS_colMax, rows, m_sheet);
                command->add(region);
                command->setMode(DeleteCommand::OnlyCells);
            }

            // Set the row style.
            RowFormat rowFormat;
            rowFormat.setSheet(sheet);
            KoXmlElement c = e.firstChild().toElement();
            for (; !c.isNull(); c = c.nextSibling().toElement()) {
                if (c.tagName() != "row") {
                    continue;
                }
                if (rowFormat.load(c, yOffset, m_pasteMode)) {
                    const int row = rowFormat.row();
                    const int rows = qMax(pasteArea.height(), number);
                    for (int roff = 0; row - yOffset + roff <= rows; roff += number) {
                        RowStyleCommand *const command = new RowStyleCommand(this);
                        command->setSheet(m_sheet);
                        command->add(Region(1, rowFormat.row(), 1, 1, m_sheet));
                        command->setTemplate(rowFormat);
                    }
                }
            }
        }

        if (e.tagName() == "cell") {
            // Create a new PasteCellCommand, if necessary.
            if (!pasteCellCommand) {
                pasteCellCommand = new PasteCellCommand(this);
                pasteCellCommand->setSheet(m_sheet);
                pasteCellCommand->m_pasteMode = m_pasteMode;
                pasteCellCommand->m_pasteOperation = m_operation;
                pasteCellCommand->m_pasteFC = m_pasteFC;
            }

            // Source cell location:
            const int row = e.attribute("row").toInt();
            const int col = e.attribute("column").toInt();

            // tile the selection with the clipboard contents
            for (int roff = 0; row + roff <= pasteHeight; roff += sourceHeight) {
                for (int coff = 0; col + coff <= pasteWidth; coff += sourceWidth) {
                    kDebug(36005) << "cell at" << (col + xOffset + coff) << ',' << (row + yOffset + roff)
                    << " with roff,coff=" << roff << ',' << coff
                    << ", xOffset:" << xOffset << ", yOffset:" << yOffset << endl;

                    // Destination cell:
                    const Cell cell(sheet, col + xOffset + coff, row + yOffset + roff);
                    // Do nothing, if the sheet and the cell are protected.
                    if (sheet->isProtected() && !cell.style().notProtected()) {
                        continue;
                    }
                    // Add the destination cell and the XML element itself.
                    pasteCellCommand->addXmlElement(cell, e);
                }
            }
        }
    }
    return true;
}
Exemplo n.º 21
0
Arquivo: Doc.cpp Projeto: KDE/calligra
bool Doc::loadXML(const KoXmlDocument& doc, KoStore*)
{
    QPointer<KoUpdater> updater;
    if (progressUpdater()) {
        updater = progressUpdater()->startSubtask(1, "KSpread::Doc::loadXML");
        updater->setProgress(0);
    }

    d->spellListIgnoreAll.clear();
    // <spreadsheet>
    KoXmlElement spread = doc.documentElement();

    if (spread.attribute("mime") != "application/x-kspread" && spread.attribute("mime") != "application/vnd.kde.kspread") {
        setErrorMessage(i18n("Invalid document. Expected mimetype application/x-kspread or application/vnd.kde.kspread, got %1" , spread.attribute("mime")));
        return false;
    }

    bool ok = false;
    int version = spread.attribute("syntaxVersion").toInt(&ok);
    map()->setSyntaxVersion(ok ? version : 0);
    if (map()->syntaxVersion() > CURRENT_SYNTAX_VERSION) {
        int ret = KMessageBox::warningContinueCancel(
                      0, i18n("This document was created with a newer version of Calligra Sheets (syntax version: %1)\n"
                              "When you open it with this version of Calligra Sheets, some information may be lost.", map()->syntaxVersion()),
                      i18n("File Format Mismatch"), KStandardGuiItem::cont());
        if (ret == KMessageBox::Cancel) {
            setErrorMessage("USER_CANCELED");
            return false;
        }
    }

    // <locale>
    KoXmlElement loc = spread.namedItem("locale").toElement();
    if (!loc.isNull())
        static_cast<Localization*>(map()->calculationSettings()->locale())->load(loc);

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

    KoXmlElement defaults = spread.namedItem("defaults").toElement();
    if (!defaults.isNull()) {
        double dim = defaults.attribute("row-height").toDouble(&ok);
        if (!ok)
            return false;
        map()->setDefaultRowHeight(dim);

        dim = defaults.attribute("col-width").toDouble(&ok);

        if (!ok)
            return false;

        map()->setDefaultColumnWidth(dim);
    }

    KoXmlElement ignoreAll = spread.namedItem("SPELLCHECKIGNORELIST").toElement();
    if (!ignoreAll.isNull()) {
        KoXmlElement spellWord = spread.namedItem("SPELLCHECKIGNORELIST").toElement();

        spellWord = spellWord.firstChild().toElement();
        while (!spellWord.isNull()) {
            if (spellWord.tagName() == "SPELLCHECKIGNOREWORD") {
                d->spellListIgnoreAll.append(spellWord.attribute("word"));
            }
            spellWord = spellWord.nextSibling().toElement();
        }
    }

    if (updater) updater->setProgress(40);
    // In case of reload (e.g. from konqueror)
    qDeleteAll(map()->sheetList());
    map()->sheetList().clear();

    KoXmlElement styles = spread.namedItem("styles").toElement();
    if (!styles.isNull()) {
        if (!map()->styleManager()->loadXML(styles)) {
            setErrorMessage(i18n("Styles cannot be loaded."));
            return false;
        }
    }

    // <map>
    KoXmlElement mymap = spread.namedItem("map").toElement();
    if (mymap.isNull()) {
        setErrorMessage(i18n("Invalid document. No map tag."));
        return false;
    }
    if (!map()->loadXML(mymap)) {
        return false;
    }

    // named areas
    const KoXmlElement areaname = spread.namedItem("areaname").toElement();
    if (!areaname.isNull())
        map()->namedAreaManager()->loadXML(areaname);

    //Backwards compatibility with older versions for paper layout
    if (map()->syntaxVersion() < 1) {
        KoXmlElement paper = spread.namedItem("paper").toElement();
        if (!paper.isNull()) {
            loadPaper(paper);
        }
    }

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

    KoXmlElement element(spread.firstChild().toElement());
    while (!element.isNull()) {
        QString tagName(element.tagName());

        if (tagName != "locale" && tagName != "map" && tagName != "styles"
                && tagName != "SPELLCHECKIGNORELIST" && tagName != "areaname"
                && tagName != "paper") {
            // belongs to a plugin, load it and save it for later use
            QDomDocument doc;
            KoXml::asQDomElement(doc, element);
            d->savedDocParts[ tagName ] = doc;
        }

        element = element.nextSibling().toElement();
    }

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

    return true;
}
Exemplo n.º 22
0
void SvgParser::applyFilter(KoShape *shape)
{
    SvgGraphicsContext *gc = m_context.currentGC();
    if (! gc)
        return;

    if (gc->filterId.isEmpty())
        return;

    SvgFilterHelper *filter = findFilter(gc->filterId);
    if (! filter)
        return;

    KoXmlElement content = filter->content();

    // parse filter region
    QRectF bound(shape->position(), shape->size());
    // work on bounding box without viewbox tranformation applied
    // so user space coordinates of bounding box and filter region match up
    bound = gc->viewboxTransform.inverted().mapRect(bound);

    QRectF filterRegion(filter->position(bound), filter->size(bound));

    // convert filter region to boundingbox units
    QRectF objectFilterRegion;
    objectFilterRegion.setTopLeft(SvgUtil::userSpaceToObject(filterRegion.topLeft(), bound));
    objectFilterRegion.setSize(SvgUtil::userSpaceToObject(filterRegion.size(), bound));

    KoFilterEffectLoadingContext context(m_context.xmlBaseDir());
    context.setShapeBoundingBox(bound);
    // enable units conversion
    context.enableFilterUnitsConversion(filter->filterUnits() == SvgFilterHelper::UserSpaceOnUse);
    context.enableFilterPrimitiveUnitsConversion(filter->primitiveUnits() == SvgFilterHelper::UserSpaceOnUse);

    KoFilterEffectRegistry *registry = KoFilterEffectRegistry::instance();

    KoFilterEffectStack *filterStack = 0;

    QSet<QString> stdInputs;
    stdInputs << "SourceGraphic" << "SourceAlpha";
    stdInputs << "BackgroundImage" << "BackgroundAlpha";
    stdInputs << "FillPaint" << "StrokePaint";

    QMap<QString, KoFilterEffect*> inputs;

    // create the filter effects and add them to the shape
    for (KoXmlNode n = content.firstChild(); !n.isNull(); n = n.nextSibling()) {
        KoXmlElement primitive = n.toElement();
        KoFilterEffect *filterEffect = registry->createFilterEffectFromXml(primitive, context);
        if (!filterEffect) {
            debugFlake << "filter effect" << primitive.tagName() << "is not implemented yet";
            continue;
        }

        const QString input = primitive.attribute("in");
        if (!input.isEmpty()) {
            filterEffect->setInput(0, input);
        }
        const QString output = primitive.attribute("result");
        if (!output.isEmpty()) {
            filterEffect->setOutput(output);
        }

        QRectF subRegion;
        // parse subregion
        if (filter->primitiveUnits() == SvgFilterHelper::UserSpaceOnUse) {
            const QString xa = primitive.attribute("x");
            const QString ya = primitive.attribute("y");
            const QString wa = primitive.attribute("width");
            const QString ha = primitive.attribute("height");

            if (xa.isEmpty() || ya.isEmpty() || wa.isEmpty() || ha.isEmpty()) {
                bool hasStdInput = false;
                bool isFirstEffect = filterStack == 0;
                // check if one of the inputs is a standard input
                foreach(const QString &input, filterEffect->inputs()) {
                    if ((isFirstEffect && input.isEmpty()) || stdInputs.contains(input)) {
                        hasStdInput = true;
                        break;
                    }
                }
                if (hasStdInput || primitive.tagName() == "feImage") {
                    // default to 0%, 0%, 100%, 100%
                    subRegion.setTopLeft(QPointF(0, 0));
                    subRegion.setSize(QSizeF(1, 1));
                } else {
                    // defaults to bounding rect of all referenced nodes
                    foreach(const QString &input, filterEffect->inputs()) {
                        if (!inputs.contains(input))
                            continue;

                        KoFilterEffect *inputFilter = inputs[input];
                        if (inputFilter)
                            subRegion |= inputFilter->filterRect();
                    }
                }
            } else {
                const qreal x = parseUnitX(xa);
                const qreal y = parseUnitY(ya);
                const qreal w = parseUnitX(wa);
                const qreal h = parseUnitY(ha);
                subRegion.setTopLeft(SvgUtil::userSpaceToObject(QPointF(x, y), bound));
                subRegion.setSize(SvgUtil::userSpaceToObject(QSizeF(w, h), bound));
            }
        } else {