Exemplo n.º 1
0
bool KoDocumentInfo::loadAuthorInfo(const KoXmlElement &e)
{
    KoXmlNode n = e.namedItem("author").firstChild();
    for (; !n.isNull(); n = n.nextSibling()) {
        KoXmlElement e = n.toElement();
        if (e.isNull())
            continue;

        if (e.tagName() == "full-name")
            setActiveAuthorInfo("creator", e.text().trimmed());
        else
            setActiveAuthorInfo(e.tagName(), e.text().trimmed());
    }

    return true;
}
Exemplo n.º 2
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.º 3
0
void KoChangeTracker::loadOdfChanges(const KoXmlElement& element)
{
    if (element.namespaceURI() == KoXmlNS::text) {
        KoXmlElement tag;
        forEachElement(tag, element) {
            if (! tag.isNull()) {
                const QString localName = tag.localName();
                if (localName == "changed-region") {
                    KoChangeTrackerElement *changeElement = 0;
                    KoXmlElement region;
                    forEachElement(region, tag) {
                        if (!region.isNull()) {
                            if (region.localName() == "insertion") {
                                changeElement = new KoChangeTrackerElement(kundo2_noi18n(tag.attributeNS(KoXmlNS::text,"id")),KoGenChange::InsertChange);
                            } else if (region.localName() == "format-change") {
                                changeElement = new KoChangeTrackerElement(kundo2_noi18n(tag.attributeNS(KoXmlNS::text,"id")),KoGenChange::FormatChange);
                            } else if (region.localName() == "deletion") {
                                changeElement = new KoChangeTrackerElement(kundo2_noi18n(tag.attributeNS(KoXmlNS::text,"id")),KoGenChange::DeleteChange);
                            }
                            KoXmlElement metadata = region.namedItemNS(KoXmlNS::office,"change-info").toElement();
                            if (!metadata.isNull()) {
                                KoXmlElement date = metadata.namedItem("dc:date").toElement();
                                if (!date.isNull()) {
                                    changeElement->setDate(date.text());
                                }
                                KoXmlElement creator = metadata.namedItem("dc:creator").toElement();
                                if (!date.isNull()) {
                                    changeElement->setCreator(creator.text());
                                }
                                //TODO load comments
/*                              KoXmlElement extra = metadata.namedItem("dc-").toElement();
                                if (!date.isNull()) {
                                    kDebug() << "creator: " << creator.text();
                                    changeElement->setCreator(creator.text());
                                }*/
                            }
                            changeElement->setEnabled(d->recordChanges);
                            d->changes.insert( d->changeId, changeElement);
                            d->loadedChanges.insert(tag.attributeNS(KoXmlNS::text,"id"), d->changeId++);
                        }
                    }
                }
            }
        }
Exemplo n.º 4
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.º 5
0
bool KPrDeclarations::loadOdf(const KoXmlElement &body, KoPALoadingContext &context)
{
    Q_UNUSED(context);

    KoXmlElement element;
    forEachElement( element, body ) {
        if (element.namespaceURI() == KoXmlNS::presentation) {
            if (element.tagName() == "header-decl") {
                const QString name = element.attributeNS(KoXmlNS::presentation, "name", QString());
                m_declarations[Header].insert(name, element.text());
            }
            else if(element.tagName() == "footer-decl") {
                const QString name = element.attributeNS(KoXmlNS::presentation, "name", QString());
                m_declarations[Footer].insert(name, element.text());
            }
            else if(element.tagName() == "date-time-decl") {
                QMap<QString, QVariant> data;
                const QString name = element.attributeNS(KoXmlNS::presentation, "name", QString());
                data["fixed"] = element.attributeNS(KoXmlNS::presentation, "source", "fixed") == "fixed";

                QString styleName = element.attributeNS(KoXmlNS::style, "data-style-name", "");
                if (!styleName.isEmpty()) {
                    KoOdfStylesReader::DataFormatsMap::const_iterator it = context.odfLoadingContext().stylesReader().dataFormats().constFind(styleName);
                    if (it != context.odfLoadingContext().stylesReader().dataFormats().constEnd()) {

                        QString formatString = (*it).first.prefix + (*it).first.formatStr + (*it).first.suffix;
                        data["format"] = formatString;
                    }
                }
                else {
                    data["format"] = QString("");
                    data["fixed value"] = element.text();
                }

                m_declarations[DateTime].insert(name, data);
            }
        }
        else if (element.tagName() == "page" && element.namespaceURI() == KoXmlNS::draw) {
            break;
        }
    }
    return true;
}
Exemplo n.º 6
0
bool KoDocumentInfo::loadOasisAuthorInfo(const KoXmlNode &metaDoc)
{
    KoXmlElement e = KoXml::namedItemNS(metaDoc, KoXmlNS::dc, "creator");
    if (!e.isNull() && !e.text().isEmpty())
        setActiveAuthorInfo("creator", e.text());

    KoXmlNode n = metaDoc.firstChild();
    for (; !n.isNull(); n = n.nextSibling()) {
        if (!n.isElement())
            continue;

        KoXmlElement e = n.toElement();
        if (!(e.namespaceURI() == KoXmlNS::meta &&
                e.localName() == "user-defined" && !e.text().isEmpty()))
            continue;

        QString name = e.attributeNS(KoXmlNS::meta, "name", QString());
        setActiveAuthorInfo(name, e.text());
    }

    return true;
}
Exemplo n.º 7
0
bool PageVariable::loadOdf(const KoXmlElement & element, KoShapeLoadingContext & context)
{
    Q_UNUSED(context);
    const QString localName(element.localName());
    if (localName == "page-count") {
        m_type = PageCount;

        m_numberFormat.loadOdf(element);
    } else if (localName == "page-number") {
        m_type = PageNumber;

        // The text:select-page attribute is used to display the number of the previous or the following
        // page rather than the number of the current page.
        QString pageselect = element.attributeNS(KoXmlNS::text, "select-page", QString());
        if (pageselect == "previous")
            m_pageselect = KoTextPage::PreviousPage;
        else if (pageselect == "next")
            m_pageselect = KoTextPage::NextPage;
        else // "current"
            m_pageselect = KoTextPage::CurrentPage;

        // The value of a page number field can be adjusted by a specified number, allowing the display
        // of page numbers of following or preceding pages. The adjustment amount is specified using
        // the text:page-adjust attribute.
        m_pageadjust = element.attributeNS(KoXmlNS::text, "page-adjust", QString()).toInt();

        m_numberFormat.loadOdf(element);

        // The text:fixed attribute specifies whether or not the value of a field element is fixed. If
        // the value of a field is fixed, the value of the field element to which this attribute is
        // attached is preserved in all future edits of the document. If the value of the field is not
        // fixed, the value of the field may be replaced by a new value when the document is edited.
        m_fixed = element.attributeNS(KoXmlNS::text, "fixed", QString()) == "true";
    } else if (localName == "page-continuation-string") {
        m_type = PageContinuation;

        // This attribute specifies whether to check for a previous or next page and if the page exists, the
        // continuation text is printed.
        QString pageselect = element.attributeNS(KoXmlNS::text, "select-page", QString());
        if (pageselect == "previous")
            m_pageselect = KoTextPage::PreviousPage;
        else if (pageselect == "next")
            m_pageselect = KoTextPage::NextPage;
        else
            m_pageselect = KoTextPage::CurrentPage;

        // The text to display
        m_continuation = element.text();
    }
    return true;
}
Exemplo n.º 8
0
// helper method
QString KoOasisSettings::Items::findConfigItem(const KoXmlElement& element,
        const QString& item, bool* ok) const
{
    KoXmlElement it;
    forEachElement(it, element) {
        if (it.localName() == "config-item" &&
                it.namespaceURI() == m_settings->m_configNsUri &&
                it.attributeNS(m_settings->m_configNsUri, "name", QString()) == item) {
            *ok = true;
            return it.text();
        }
    }
    *ok = false;
    return QString();
}
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("Calligra")) {
                    d->generatorType = Calligra;
                }
                // NeoOffice is a port of OpenOffice to Mac OS X
                else if (d->generator.startsWith("OpenOffice.org") || d->generator.startsWith("NeoOffice") ||
                         d->generator.startsWith("LibreOffice") || d->generator.startsWith("StarOffice") ||
                         d->generator.startsWith("Lotus Symphony")) {
                    d->generatorType = OpenOffice;
                }
                else if (d->generator.startsWith("MicrosoftOffice")) {
                    d->generatorType = MicrosoftOffice;
                }
            }
        }
    }
    d->metaXmlParsed = true;

    d->store->popDirectory();
}
Exemplo n.º 10
0
bool CommentShape::loadOdf(const KoXmlElement& element, KoShapeLoadingContext& context)
{
    loadOdfAttributes(element, context, OdfPosition);

    KoXmlElement child;
    forEachElement(child, element)
    {
        if(child.namespaceURI() == KoXmlNS::dc) {
            if(child.localName() == "creator") {
                m_creator = child.text();
                QStringList creatorNames = m_creator.split(' ');
                QString initials;
                if(KoApplication::isLeftToRight()) {
                    foreach(const QString& name, creatorNames) {
                        initials += name.left(1);
                    }
                }
                else {
                    foreach(const QString& name, creatorNames) {
                        initials += name.right(1);
                    }
                }
Exemplo n.º 11
0
void Validity::loadOdfValidation(Cell* const cell, const QString& validationName,
                                 OdfLoadingContext& tableContext)
{
    KoXmlElement element = tableContext.validities.value(validationName);
    Validity validity;
    if (element.hasAttributeNS(KoXmlNS::table, "condition")) {
        QString valExpression = element.attributeNS(KoXmlNS::table, "condition", QString());
        kDebug(36003) << " element.attribute( table:condition )" << valExpression;
        //Condition ::= ExtendedTrueCondition | TrueFunction 'and' TrueCondition
        //TrueFunction ::= cell-content-is-whole-number() | cell-content-is-decimal-number() | cell-content-is-date() | cell-content-is-time()
        //ExtendedTrueCondition ::= ExtendedGetFunction | cell-content-text-length() Operator Value
        //TrueCondition ::= GetFunction | cell-content() Operator Value
        //GetFunction ::= cell-content-is-between(Value, Value) | cell-content-is-not-between(Value, Value)
        //ExtendedGetFunction ::= cell-content-text-length-is-between(Value, Value) | cell-content-text-length-is-not-between(Value, Value)
        //Operator ::= '<' | '>' | '<=' | '>=' | '=' | '!='
        //Value ::= NumberValue | String | Formula
        //A Formula is a formula without an equals (=) sign at the beginning. See section 8.1.3 for more information.
        //A String comprises one or more characters surrounded by quotation marks.
        //A NumberValue is a whole or decimal number. It must not contain comma separators for numbers of 1000 or greater.

        //ExtendedTrueCondition
        if (valExpression.contains("cell-content-text-length()")) {
            //"cell-content-text-length()>45"
            valExpression = valExpression.remove("oooc:cell-content-text-length()");
            kDebug(36003) << " valExpression = :" << valExpression;
            setRestriction(Validity::TextLength);

            loadOdfValidationCondition(valExpression, cell->sheet()->map()->parser());
        } else if (valExpression.contains("cell-content-is-text()")) {
            setRestriction(Validity::Text);
        }
        //cell-content-text-length-is-between(Value, Value) | cell-content-text-length-is-not-between(Value, Value) | cell-content-is-in-list( StringList )
        else if (valExpression.contains("cell-content-text-length-is-between")) {
            setRestriction(Validity::TextLength);
            setCondition(Conditional::Between);
            valExpression = valExpression.remove("oooc:cell-content-text-length-is-between(");
            kDebug(36003) << " valExpression :" << valExpression;
            valExpression = valExpression.remove(')');
            QStringList listVal = valExpression.split(',', QString::SkipEmptyParts);
            loadOdfValidationValue(listVal, cell->sheet()->map()->parser());
        } else if (valExpression.contains("cell-content-text-length-is-not-between")) {
            setRestriction(Validity::TextLength);
            setCondition(Conditional::Different);
            valExpression = valExpression.remove("oooc:cell-content-text-length-is-not-between(");
            kDebug(36003) << " valExpression :" << valExpression;
            valExpression = valExpression.remove(')');
            kDebug(36003) << " valExpression :" << valExpression;
            QStringList listVal = valExpression.split(',', QString::SkipEmptyParts);
            loadOdfValidationValue(listVal, cell->sheet()->map()->parser());
        } else if (valExpression.contains("cell-content-is-in-list(")) {
            setRestriction(Validity::List);
            valExpression = valExpression.remove("oooc:cell-content-is-in-list(");
            kDebug(36003) << " valExpression :" << valExpression;
            valExpression = valExpression.remove(')');
            setValidityList(valExpression.split(';',  QString::SkipEmptyParts));

        }
        //TrueFunction ::= cell-content-is-whole-number() | cell-content-is-decimal-number() | cell-content-is-date() | cell-content-is-time()
        else {
            if (valExpression.contains("cell-content-is-whole-number()")) {
                setRestriction(Validity::Number);
                valExpression = valExpression.remove("oooc:cell-content-is-whole-number() and ");
            } else if (valExpression.contains("cell-content-is-decimal-number()")) {
                setRestriction(Validity::Integer);
                valExpression = valExpression.remove("oooc:cell-content-is-decimal-number() and ");
            } else if (valExpression.contains("cell-content-is-date()")) {
                setRestriction(Validity::Date);
                valExpression = valExpression.remove("oooc:cell-content-is-date() and ");
            } else if (valExpression.contains("cell-content-is-time()")) {
                setRestriction(Validity::Time);
                valExpression = valExpression.remove("oooc:cell-content-is-time() and ");
            }
            kDebug(36003) << "valExpression :" << valExpression;

            if (valExpression.contains("cell-content()")) {
                valExpression = valExpression.remove("cell-content()");
                loadOdfValidationCondition(valExpression, cell->sheet()->map()->parser());
            }
            //GetFunction ::= cell-content-is-between(Value, Value) | cell-content-is-not-between(Value, Value)
            //for the moment we support just int/double value, not text/date/time :(
            if (valExpression.contains("cell-content-is-between(")) {
                valExpression = valExpression.remove("cell-content-is-between(");
                valExpression = valExpression.remove(')');
                QStringList listVal = valExpression.split(',', QString::SkipEmptyParts);
                loadOdfValidationValue(listVal, cell->sheet()->map()->parser());
                setCondition(Conditional::Between);
            }
            if (valExpression.contains("cell-content-is-not-between(")) {
                valExpression = valExpression.remove("cell-content-is-not-between(");
                valExpression = valExpression.remove(')');
                QStringList listVal = valExpression.split(',', QString::SkipEmptyParts);
                loadOdfValidationValue(listVal, cell->sheet()->map()->parser());
                setCondition(Conditional::Different);
            }
        }
    }
    if (element.hasAttributeNS(KoXmlNS::table, "allow-empty-cell")) {
        kDebug(36003) << " element.hasAttribute( table:allow-empty-cell ) :" << element.hasAttributeNS(KoXmlNS::table, "allow-empty-cell");
        setAllowEmptyCell(((element.attributeNS(KoXmlNS::table, "allow-empty-cell", QString()) == "true") ? true : false));
    }
    if (element.hasAttributeNS(KoXmlNS::table, "base-cell-address")) {
        //todo what is it ?
    }

    KoXmlElement help = KoXml::namedItemNS(element, KoXmlNS::table, "help-message");
    if (!help.isNull()) {
        if (help.hasAttributeNS(KoXmlNS::table, "title")) {
            kDebug(36003) << "help.attribute( table:title ) :" << help.attributeNS(KoXmlNS::table, "title", QString());
            setTitleInfo(help.attributeNS(KoXmlNS::table, "title", QString()));
        }
        if (help.hasAttributeNS(KoXmlNS::table, "display")) {
            kDebug(36003) << "help.attribute( table:display ) :" << help.attributeNS(KoXmlNS::table, "display", QString());
            setDisplayValidationInformation(((help.attributeNS(KoXmlNS::table, "display", QString()) == "true") ? true : false));
        }
        KoXmlElement attrText = KoXml::namedItemNS(help, KoXmlNS::text, "p");
        if (!attrText.isNull()) {
            kDebug(36003) << "help text :" << attrText.text();
            setMessageInfo(attrText.text());
        }
    }

    KoXmlElement error = KoXml::namedItemNS(element, KoXmlNS::table, "error-message");
    if (!error.isNull()) {
        if (error.hasAttributeNS(KoXmlNS::table, "title"))
            setTitle(error.attributeNS(KoXmlNS::table, "title", QString()));
        if (error.hasAttributeNS(KoXmlNS::table, "message-type")) {
            QString str = error.attributeNS(KoXmlNS::table, "message-type", QString());
            if (str == "warning")
                setAction(Validity::Warning);
            else if (str == "information")
                setAction(Validity::Information);
            else if (str == "stop")
                setAction(Validity::Stop);
            else
                kDebug(36003) << "validation : message type unknown  :" << str;
        }

        if (error.hasAttributeNS(KoXmlNS::table, "display")) {
            kDebug(36003) << " display message :" << error.attributeNS(KoXmlNS::table, "display", QString());
            setDisplayMessage((error.attributeNS(KoXmlNS::table, "display", QString()) == "true"));
        }
        KoXmlElement attrText = KoXml::namedItemNS(error, KoXmlNS::text, "p");
        if (!attrText.isNull())
            setMessage(attrText.text());
    }
    cell->setValidity(validity);
}
Exemplo n.º 12
0
bool Validity::loadXML(Cell* const cell, const KoXmlElement& validityElement)
{
    ValueParser *const parser = cell->sheet()->map()->parser();
    bool ok = false;
    KoXmlElement param = validityElement.namedItem("param").toElement();
    if (!param.isNull()) {
        if (param.hasAttribute("cond")) {
            d->cond = (Conditional::Type) param.attribute("cond").toInt(&ok);
            if (!ok)
                return false;
        }
        if (param.hasAttribute("action")) {
            d->action = (Action) param.attribute("action").toInt(&ok);
            if (!ok)
                return false;
        }
        if (param.hasAttribute("allow")) {
            d->restriction = (Restriction) param.attribute("allow").toInt(&ok);
            if (!ok)
                return false;
        }
        if (param.hasAttribute("valmin")) {
            d->minValue = parser->tryParseNumber(param.attribute("valmin"), &ok);
            if (!ok)
                return false;
        }
        if (param.hasAttribute("valmax")) {
            d->maxValue = parser->tryParseNumber(param.attribute("valmax"), &ok);
            if (!ok)
                return false;
        }
        if (param.hasAttribute("displaymessage")) {
            d->displayMessage = (bool)param.attribute("displaymessage").toInt();
        }
        if (param.hasAttribute("displayvalidationinformation")) {
            d->displayValidationInformation = (bool)param.attribute("displayvalidationinformation").toInt();
        }
        if (param.hasAttribute("allowemptycell")) {
            d->allowEmptyCell = (bool)param.attribute("allowemptycell").toInt();
        }
        if (param.hasAttribute("listvalidity")) {
            d->listValidity = param.attribute("listvalidity").split(';', QString::SkipEmptyParts);
        }
    }
    KoXmlElement inputTitle = validityElement.namedItem("inputtitle").toElement();
    if (!inputTitle.isNull()) {
        d->titleInfo = inputTitle.text();
    }
    KoXmlElement inputMessage = validityElement.namedItem("inputmessage").toElement();
    if (!inputMessage.isNull()) {
        d->messageInfo = inputMessage.text();
    }

    KoXmlElement titleElement = validityElement.namedItem("title").toElement();
    if (!titleElement.isNull()) {
        d->title = titleElement.text();
    }
    KoXmlElement messageElement = validityElement.namedItem("message").toElement();
    if (!messageElement.isNull()) {
        d->message = messageElement.text();
    }
    KoXmlElement timeMinElement = validityElement.namedItem("timemin").toElement();
    if (!timeMinElement.isNull()) {
        d->minValue = parser->tryParseTime(timeMinElement.text());
    }
    KoXmlElement timeMaxElement = validityElement.namedItem("timemax").toElement();
    if (!timeMaxElement.isNull()) {
        d->maxValue = parser->tryParseTime(timeMaxElement.text());
    }
    KoXmlElement dateMinElement = validityElement.namedItem("datemin").toElement();
    if (!dateMinElement.isNull()) {
        d->minValue = parser->tryParseTime(dateMinElement.text());
    }
    KoXmlElement dateMaxElement = validityElement.namedItem("datemax").toElement();
    if (!dateMaxElement.isNull()) {
        d->maxValue = parser->tryParseTime(dateMaxElement.text());
    }
    return true;
}
Exemplo n.º 13
0
bool ChartShape::Private::loadOdfLabel(KoShape *label, KoXmlElement &labelElement, KoShapeLoadingContext &context)
{
    TextLabelData *labelData = qobject_cast<TextLabelData*>(label->userData());
    if (!labelData)
        return false;

    // Following will always return false cause KoTextShapeData::loadOdf will try to load
    // a frame while our text:p is not within a frame. So, let's just not call loadOdf then...
    //label->loadOdf(labelElement, context);

    // 1. set the text
    KoXmlElement  pElement = KoXml::namedItemNS(labelElement, KoXmlNS::text, "p");

    QTextDocument* doc = labelData->document();
    doc->setPlainText(pElement.text());

    // 2. set the position
    QPointF pos = label->position();
    bool posChanged = false;
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "x")) {
        pos.setX(KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "x", QString())));
        posChanged = true;
    }
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "y")) {
        pos.setY(KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "y", QString())));
        posChanged = true;
    }
    if (posChanged) {
        label->setPosition(pos);
    }

    // 3. set the styles
    if (labelElement.hasAttributeNS(KoXmlNS::chart, "style-name")) {
        KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
        styleStack.clear();
        context.odfLoadingContext().fillStyleStack(labelElement, KoXmlNS::chart, "style-name", "chart");

        styleStack.setTypeProperties("chart");
        if (styleStack.hasProperty(KoXmlNS::style, "rotation-angle")) {
            qreal rotationAngle = 360 - KoUnit::parseValue(styleStack.property(KoXmlNS::style, "rotation-angle"));
            label->rotate(rotationAngle);
        }

        styleStack.setTypeProperties("text");

        if (styleStack.hasProperty(KoXmlNS::fo, "font-size")) {
            const qreal fontSize = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "font-size"));
            QFont font = doc->defaultFont();
            font.setPointSizeF(fontSize);
            doc->setDefaultFont(font);
        }

        if (styleStack.hasProperty(KoXmlNS::fo, "font-family")) {
            const QString fontFamily = styleStack.property(KoXmlNS::fo, "font-family");
            QFont font = doc->defaultFont();
            font.setFamily(fontFamily);
            doc->setDefaultFont(font);
        }
    }

    // 4. set the size
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "width")
        && labelElement.hasAttributeNS(KoXmlNS::svg, "height"))
    {
        const qreal width = KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "width"));
        const qreal height = KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "height"));
        label->setSize(QSizeF(width, height));
    } else {
        QSizeF size = shape->size();
        QRect r = QFontMetrics(doc->defaultFont()).boundingRect(
                        labelData->shapeMargins().left, labelData->shapeMargins().top,
                        qMax(CM_TO_POINT(5), qreal(size.width() - pos.x() * 2.0 - labelData->shapeMargins().right)),
                        qMax(CM_TO_POINT(0.6), qreal(size.height() - labelData->shapeMargins().bottom)),
                        Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, doc->toPlainText());
        label->setSize(r.size());
    }

    return true;
}
Exemplo n.º 14
0
bool ChartTableModel::loadOdf( const KoXmlElement &tableElement,
                               KoShapeLoadingContext &context )
{
    Q_UNUSED( context );

    setRowCount( 0 );
    setColumnCount( 0 );

    ///const QDomNode &node = tableElement.asQDomNode( QDomDocument() );

    //QTextStream stream(stdout);
    //stream << node;

    // FIXME: Rewrite this without the for loop.  I think there can
    //        only be one table-rows and one table-header-rows element
    //        in each table.
    int           row = 0;
    KoXmlElement  n;
    int           found = false;
    forEachElement ( n, tableElement ) {
        if ( n.namespaceURI() != KoXmlNS::table )
            continue;

        if ( n.localName() == "table-rows"
             || n.localName() == "table-header-rows" )
        {
            found = true;

            KoXmlElement  _n;
            forEachElement ( _n, n ) {

                // Must be a table:table-row, else go to next element.
                if ( _n.namespaceURI() != KoXmlNS::table
                     || _n.localName() != "table-row" )
                    continue;

                // Add a row to the internal representation.
                setRowCount( rowCount() + 1 );

                // Loop through all cells in a table row.
                int           column = 0;
                KoXmlElement  __n;
                forEachElement ( __n, _n ) {

                    // Must be a table:table-cell, otherwise go to
                    // next element.
                    if ( __n.namespaceURI() == KoXmlNS::table
                         && __n.localName() == "table-cell" )
                    {
//                         continue;

                    // If this row is wider than any previous one,
                    // then add another column.
                    // Is this efficient enough?
                    if ( column >= columnCount() )
                        setColumnCount( columnCount() + 1 );

                    const QString valueType = __n.attributeNS( KoXmlNS::office, "value-type" );

                    QString valueString = __n.attributeNS( KoXmlNS::office, "value" );
                    const KoXmlElement valueElement = __n.namedItemNS( KoXmlNS::text, "p" ).toElement();
                    if ( ( valueElement.isNull() || !valueElement.isElement() ) && valueString.isEmpty() )
                    {
                        qWarning() << "ChartTableModel::loadOdf(): Cell contains no valid <text:p> element, cannnot load cell data.";
                        // Even if it doesn't contain any value, it's still a cell.
                        column++;
                        continue;
                    }

                    // Read the actual value in the cell.
                    QVariant value;
                    if ( valueString.isEmpty() )
                        valueString = valueElement.text();
                    if ( valueType == "float" )
                        value = valueString.toDouble();
                    else if ( valueType == "boolean" )
                        value = (bool)valueString.toInt();
                    else // if ( valueType == "string" )
                        value = valueString;

                    setData( index( row, column ), value );

                    ++column;
                    }

                } // foreach table:table-cell
                ++row;

            } // foreach table:table-row
        }
    }
Exemplo n.º 15
0
void KoBibliographyInfo::loadOdf(KoTextSharedLoadingData *sharedLoadingData, const KoXmlElement& element)
{
    Q_ASSERT(element.localName() == "bibliography-source" && element.namespaceURI() == KoXmlNS::text);

    KoXmlElement p;
    forEachElement(p, element) {
        if (p.namespaceURI() != KoXmlNS::text) {
            continue;
        }

        // first child
        if (p.localName() == "index-title-template") {
            m_indexTitleTemplate.styleName = p.attribute("style-name");
            m_indexTitleTemplate.styleId = styleNameToStyleId(sharedLoadingData, m_indexTitleTemplate.styleName);
            m_indexTitleTemplate.text = p.text();
        // second child
        } else if (p.localName() == "bibliography-entry-template") {
            BibliographyEntryTemplate bibEntryTemplate;
            bibEntryTemplate.styleName = p.attribute("style-name");
            bibEntryTemplate.bibliographyType = p.attribute("bibliography-type");
            bibEntryTemplate.styleId = styleNameToStyleId(sharedLoadingData, bibEntryTemplate.styleName );

            KoXmlElement indexEntry;
            forEachElement(indexEntry, p) {
                if (indexEntry.namespaceURI() != KoXmlNS::text) {
                    continue;
                }

                if (indexEntry.localName() == "index-entry-bibliography") {
                    // use null String if the style name is not present, it means that we inherit it from the parent
                    IndexEntryBibliography * entryBibliography = new IndexEntryBibliography(
                        indexEntry.attribute("style-name", QString())
                    );

                    entryBibliography->dataField = indexEntry.attribute("bibliography-data-field", "article");
                    bibEntryTemplate.indexEntries.append(static_cast<IndexEntry*>(entryBibliography));

                } else if (indexEntry.localName() == "index-entry-span") {
                    IndexEntrySpan * entrySpan = new IndexEntrySpan(indexEntry.attribute("style-name", QString()));
                    entrySpan->text = indexEntry.text();
                    bibEntryTemplate.indexEntries.append(static_cast<IndexEntry*>(entrySpan));

                } else if (indexEntry.localName() == "index-entry-tab-stop") {
                    IndexEntryTabStop * entryTabStop = new IndexEntryTabStop(indexEntry.attribute("style-name", QString()));

                    QString type = indexEntry.attribute("type","right"); // left or right
                    if (type == "left") {
                        entryTabStop->tab.type = QTextOption::LeftTab;
                    } else {
                        entryTabStop->tab.type = QTextOption::RightTab;
                    }
                    entryTabStop->setPosition(indexEntry.attribute("position", QString()));
                    entryTabStop->tab.leaderText = indexEntry.attribute("leader-char",".");
                    bibEntryTemplate.indexEntries.append(static_cast<IndexEntry*>(entryTabStop));
                }
            }
            m_entryTemplate[bibEntryTemplate.bibliographyType] = bibEntryTemplate;

        // third child
        }
    }// forEachElement
Exemplo n.º 16
0
MetaInfo ZefaniaLex::buildIndexFromXmlDoc(KoXmlDocument *xmldoc)
{
    try {

    MetaInfo info;
    int couldBe = 0;//1 = RMac

    Document indexdoc;
    const QString index = indexPath();
    QString fileTitle;
    QString uid;
    QString type;

    QDir dir("/");
    dir.mkpath(index);

    RefText refText;
    refText.setSettings(m_settings);

    IndexWriter* writer = NULL;
    const TCHAR* stop_words[] = { NULL };
    standard::StandardAnalyzer an(stop_words);

    if(IndexReader::indexExists(index.toStdString().c_str())) {
        if(IndexReader::isLocked(index.toStdString().c_str())) {
            myDebug() << "Index was locked... unlocking it.";
            IndexReader::unlock(index.toStdString().c_str());
        }
    }
    writer = new IndexWriter(index.toStdString().c_str() , &an, true);

    writer->setMaxFieldLength(0x7FFFFFFFL);
    writer->setUseCompoundFile(false);

    KoXmlNode item = xmldoc->documentElement().firstChild();
    type = xmldoc->documentElement().toElement().attribute("type", "");

    for(int c = 0; !item.isNull();) {
        QString key = "";
        QString title = "";
        QString trans = "";
        QString pron = "";
        QString desc = "";
        KoXmlElement e = item.toElement();
        if(e.tagName().compare("INFORMATION", Qt::CaseInsensitive) == 0) {
            KoXmlNode title = item.namedItem("subject");
            KoXmlNode identifer = item.namedItem("identifier");

            fileTitle = title.toElement().text();
            uid = identifer.toElement().text();

        } else if(e.tagName().compare("item", Qt::CaseInsensitive) == 0) {
            key = e.attribute("id");
            KoXmlNode details = item.firstChild();
            while(!details.isNull()) {
                KoXmlElement edetails = details.toElement();
                if(edetails.tagName().compare("title", Qt::CaseInsensitive) == 0) {
                    title = edetails.text();
                } else if(edetails.tagName().compare("transliteration", Qt::CaseInsensitive) == 0) {
                    trans = edetails.text();
                } else if(edetails.tagName().compare("pronunciation", Qt::CaseInsensitive) == 0) {
                    KoXmlNode em = details.firstChild();
                    while(!em.isNull()) {
                        if(em.toElement().tagName().compare("em", Qt::CaseInsensitive) == 0)
                            pron = "<em>" + em.toElement().text() + "</em>";
                        em = em.nextSibling();
                    }
                } else if(edetails.tagName().compare("description", Qt::CaseInsensitive) == 0) {
                    KoXmlNode descNode = details.firstChild();
                    while(!descNode.isNull()) {
                        if(descNode.nodeType() == 2) {
                            desc += descNode.toText().data();
                        } else if(descNode.nodeType() == 1) {
                            KoXmlElement descElement = descNode.toElement();
                            if(descElement.tagName().compare("reflink", Qt::CaseInsensitive) == 0) {
                                if(descElement.hasAttribute("mscope")) {
                                    const QString mscope = descElement.attribute("mscope", ";;;");

                                    VerseUrl url;
                                    url.fromMscope(mscope);

                                    desc += " <a href=\"" + url.toString() + "\">" + refText.toString(url) + "</a> ";
                                } else if(descElement.hasAttribute("target")) {
                                    desc += descElement.text();
                                }

                            } else if(descElement.tagName().compare("see", Qt::CaseInsensitive) == 0) {
                                const QString target = descElement.attribute("target", "");
                                //todo: currently we assume target = x-self
                                StrongUrl url;
                                bool ok = url.fromText(descElement.text());
                                if(ok)
                                    desc += " <a href=\"" + url.toString() + "\">" + descElement.text() + "</a> ";
                            }
                        }

                        descNode = descNode.nextSibling();
                    }
                    desc += "<hr />";
                }
                details = details.nextSibling();
            }
            if(couldBe == 0) {
                if(key.toUpper() == "A-APF" || key.toUpper() == "X-NSN" || key.toUpper() == "V-PAP-DPN") {
                    couldBe = 1;
                }
            }
            QString content = "<h3 class='strongTitle'>" + key + " - " + title + "</h3>";
            if(!trans.isEmpty()) {
                content += " (" + trans + ") ";
            }
            if(!pron.isEmpty()) {
                content += " [" + pron + "] ";
            }
            content += "<br />" + desc;
            indexdoc.clear();
#ifdef OBV_USE_WSTRING
            indexdoc.add(*_CLNEW Field(_T("key"), key.toStdWString().c_str(), Field::STORE_YES |  Field::INDEX_TOKENIZED));
            indexdoc.add(*_CLNEW Field(_T("content"), content.toStdWString().c_str(), Field::STORE_YES |  Field::INDEX_TOKENIZED));
#else
            indexdoc.add(*_CLNEW Field(_T("key"), reinterpret_cast<const wchar_t *>(key.utf16()), Field::STORE_YES |  Field::INDEX_TOKENIZED));
            indexdoc.add(*_CLNEW Field(_T("content"), reinterpret_cast<const wchar_t *>(content.utf16()), Field::STORE_YES |  Field::INDEX_TOKENIZED));
#endif
            writer->addDocument(&indexdoc);

        }
        item = item.nextSibling();
        c++;
    }
    writer->setUseCompoundFile(true);
    writer->optimize();

    writer->close();
    delete writer;
    info.setName(fileTitle);
    info.setUID(uid);
    if(type == "x-strong") {
        info.setDefaultModule(OBVCore::DefaultStrongDictModule);
        info.setContent(OBVCore::StrongsContent);
    } else if(type == "x-dictionary") {
        if(couldBe == 1) {
            info.setDefaultModule(OBVCore::DefaultRMACDictModule);
            info.setContent(OBVCore::RMacContent);
        } else {
            info.setDefaultModule(OBVCore::DefaultDictModule);
        }
    }
    return info;
    }
    catch(...) {
        return MetaInfo();
    }
}
Exemplo n.º 17
0
bool KarbonPart::loadOdf(KoOdfReadStore & odfStore)
{
    kDebug(38000) << "Start loading OASIS document..." /*<< doc.toString()*/;

    KoXmlElement contents = odfStore.contentDoc().documentElement();
    kDebug(38000) << "Start loading OASIS document..." << contents.text();
    kDebug(38000) << "Start loading OASIS contents..." << contents.lastChild().localName();
    kDebug(38000) << "Start loading OASIS contents..." << contents.lastChild().namespaceURI();
    kDebug(38000) << "Start loading OASIS contents..." << contents.lastChild().isElement();
    KoXmlElement body(KoXml::namedItemNS(contents, KoXmlNS::office, "body"));
    if (body.isNull()) {
        kDebug(38000) << "No office:body found!";
        setErrorMessage(i18n("Invalid OASIS document. No office:body tag found."));
        return false;
    }

    body = KoXml::namedItemNS(body, KoXmlNS::office, "drawing");
    if (body.isNull()) {
        kDebug(38000) << "No office:drawing found!";
        setErrorMessage(i18n("Invalid OASIS document. No office:drawing tag found."));
        return false;
    }

    KoXmlElement page(KoXml::namedItemNS(body, KoXmlNS::draw, "page"));
    if (page.isNull()) {
        kDebug(38000) << "No office:drawing found!";
        setErrorMessage(i18n("Invalid OASIS document. No draw:page tag found."));
        return false;
    }

    KoXmlElement * master = 0;
    if (odfStore.styles().masterPages().contains("Standard"))
        master = odfStore.styles().masterPages().value("Standard");
    else if (odfStore.styles().masterPages().contains("Default"))
        master = odfStore.styles().masterPages().value("Default");
    else if (! odfStore.styles().masterPages().empty())
        master = odfStore.styles().masterPages().begin().value();

    if (master) {
        const QString pageStyleName = master->attributeNS(KoXmlNS::style, "page-layout-name", QString());
        const KoXmlElement *style = odfStore.styles().findStyle(pageStyleName);
        if (style) {
            KoPageLayout layout;
            layout.loadOdf(*style);
            setPageLayout(layout);
        }
    } else {
        kWarning() << "No master page found!";
        return false;
    }

    KoOdfLoadingContext context(odfStore.styles(), odfStore.store());
    KoShapeLoadingContext shapeContext(context, resourceManager());

    d->document.loadOasis(page, shapeContext);

    if (d->document.pageSize().isEmpty()) {
        QSizeF pageSize = d->document.contentRect().united(QRectF(0, 0, 1, 1)).size();
        setPageSize(pageSize);
    }

    loadOasisSettings(odfStore.settingsDoc());

    return true;
}