mathmlimport.cxx 102 KB
Newer Older
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
19 20 21 22 23 24 25


/*todo: Change characters and tcharacters to accumulate the characters together
into one string, xml parser hands them to us line by line rather than all in
one go*/

#include <com/sun/star/xml/sax/InputSource.hpp>
26
#include <com/sun/star/xml/sax/Parser.hpp>
27
#include <com/sun/star/xml/sax/XFastParser.hpp>
28 29
#include <com/sun/star/document/XDocumentProperties.hpp>
#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
Stephan Bergmann's avatar
Stephan Bergmann committed
30
#include <com/sun/star/packages/WrongPasswordException.hpp>
31 32 33 34 35 36
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/uno/Any.h>

37
#include <comphelper/fileformat.h>
38 39 40
#include <comphelper/genericpropertyset.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/servicehelper.hxx>
41
#include <comphelper/propertysetinfo.hxx>
42
#include <o3tl/make_unique.hxx>
43
#include <rtl/character.hxx>
44
#include <sal/log.hxx>
45 46
#include <sfx2/frame.hxx>
#include <sfx2/docfile.hxx>
47
#include <sfx2/sfxsids.hrc>
48
#include <osl/diagnose.h>
49
#include <svtools/sfxecode.hxx>
50
#include <svl/itemset.hxx>
51
#include <svl/stritem.hxx>
52
#include <unotools/streamwrap.hxx>
53
#include <sax/tools/converter.hxx>
54
#include <xmloff/DocumentSettingsContext.hxx>
55 56 57 58 59
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include <xmloff/xmlmetai.hxx>
60 61
#include <svx/dialmgr.hxx>
#include <svx/strings.hrc>
62
#include <tools/diagnose_ex.h>
63 64 65

#include <memory>

66
#include "mathmlattr.hxx"
67
#include "mathmlimport.hxx"
68
#include "register.hxx"
69
#include <document.hxx>
70 71
#include <smdll.hxx>
#include <unomodel.hxx>
72 73 74 75 76 77 78 79 80 81 82
#include <utility.hxx>

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;


83
#define IMPORT_SVC_NAME "com.sun.star.xml.XMLImportFilter"
84

85 86 87 88 89 90 91 92 93 94 95 96
namespace {

SmNode* popOrZero(SmNodeStack& rStack)
{
    if (rStack.empty())
        return nullptr;
    auto pTmp = std::move(rStack.front());
    rStack.pop_front();
    return pTmp.release();
}

}
97

98
ErrCode SmXMLImportWrapper::Import(SfxMedium &rMedium)
99
{
100
    ErrCode nError = ERRCODE_SFX_DOLOADFAILED;
101

102
    uno::Reference<uno::XComponentContext> xContext( comphelper::getProcessComponentContext() );
103 104 105

    //Make a model component from our SmModel
    uno::Reference< lang::XComponent > xModelComp( xModel, uno::UNO_QUERY );
106
    OSL_ENSURE( xModelComp.is(), "XMLReader::Read: got no model" );
107 108 109 110

    // try to get an XStatusIndicator from the Medium
    uno::Reference<task::XStatusIndicator> xStatusIndicator;

Takeshi Abe's avatar
Takeshi Abe committed
111
    bool bEmbedded = false;
112
    uno::Reference <lang::XUnoTunnel> xTunnel(xModel,uno::UNO_QUERY);
113 114 115 116
    SmModel *pModel = reinterpret_cast<SmModel *>
        (xTunnel->getSomething(SmModel::getUnoTunnelId()));

    SmDocShell *pDocShell = pModel ?
117
            static_cast<SmDocShell*>(pModel->GetObjectShell()) : nullptr;
118 119
    if (pDocShell)
    {
120
        OSL_ENSURE( pDocShell->GetMedium() == &rMedium,
121
                "different SfxMedium found" );
122

123 124 125 126 127 128 129
        SfxItemSet* pSet = rMedium.GetItemSet();
        if (pSet)
        {
            const SfxUnoAnyItem* pItem = static_cast<const SfxUnoAnyItem*>(
                pSet->GetItem(SID_PROGRESS_STATUSBAR_CONTROL) );
            if (pItem)
                pItem->GetValue() >>= xStatusIndicator;
130 131
        }

132
        if ( SfxObjectCreateMode::EMBEDDED == pDocShell->GetCreateMode() )
Takeshi Abe's avatar
Takeshi Abe committed
133
            bEmbedded = true;
134 135 136 137
    }

    comphelper::PropertyMapEntry aInfoMap[] =
    {
138
        { OUString("PrivateData"), 0,
139
              cppu::UnoType<XInterface>::get(),
140
              beans::PropertyAttribute::MAYBEVOID, 0 },
141
        { OUString("BaseURI"), 0,
142
              ::cppu::UnoType<OUString>::get(),
143
              beans::PropertyAttribute::MAYBEVOID, 0 },
144
        { OUString("StreamRelPath"), 0,
145
              ::cppu::UnoType<OUString>::get(),
146
              beans::PropertyAttribute::MAYBEVOID, 0 },
147
        { OUString("StreamName"), 0,
148
              ::cppu::UnoType<OUString>::get(),
149
              beans::PropertyAttribute::MAYBEVOID, 0 },
150
        { OUString(), 0, css::uno::Type(), 0, 0 }
151 152 153 154 155 156
    };
    uno::Reference< beans::XPropertySet > xInfoSet(
                comphelper::GenericPropertySet_CreateInstance(
                            new comphelper::PropertySetInfo( aInfoMap ) ) );

    // Set base URI
157
    OUString const baseURI(rMedium.GetBaseURL());
158 159 160
    // needed for relative URLs; but it's OK to import e.g. MathML from the
    // clipboard without one
    SAL_INFO_IF(baseURI.isEmpty(), "starmath", "SmXMLImportWrapper: no base URL");
161
    xInfoSet->setPropertyValue("BaseURI", makeAny(baseURI));
162 163 164 165 166 167 168 169

    sal_Int32 nSteps=3;
    if ( !(rMedium.IsStorage()))
        nSteps = 1;

    sal_Int32 nProgressRange(nSteps);
    if (xStatusIndicator.is())
    {
170
        xStatusIndicator->start(SvxResId(RID_SVXSTR_DOC_LOAD), nProgressRange);
171 172 173 174 175 176 177 178 179 180 181
    }

    nSteps=0;
    if (xStatusIndicator.is())
        xStatusIndicator->setValue(nSteps++);

    if ( rMedium.IsStorage())
    {
        // TODO/LATER: handle the case of embedded links gracefully
        if ( bEmbedded ) // && !rMedium.GetStorage()->IsRoot() )
        {
182
            OUString aName( "dummyObjName" );
183 184 185 186 187 188 189 190
            if ( rMedium.GetItemSet() )
            {
                const SfxStringItem* pDocHierarchItem = static_cast<const SfxStringItem*>(
                    rMedium.GetItemSet()->GetItem(SID_DOC_HIERARCHICALNAME) );
                if ( pDocHierarchItem )
                    aName = pDocHierarchItem->GetValue();
            }

191
            if ( !aName.isEmpty() )
192
            {
193
                xInfoSet->setPropertyValue("StreamRelPath", makeAny(aName));
194 195 196
            }
        }

Takeshi Abe's avatar
Takeshi Abe committed
197
        bool bOASIS = ( SotStorage::GetVersion( rMedium.GetStorage() ) > SOFFICE_FILEFORMAT_60 );
198 199 200
        if (xStatusIndicator.is())
            xStatusIndicator->setValue(nSteps++);

201
        auto nWarn = ReadThroughComponent(
202
            rMedium.GetStorage(), xModelComp, "meta.xml", "Meta.xml",
203
            xContext, xInfoSet,
204 205 206 207 208 209 210 211 212
                (bOASIS ? "com.sun.star.comp.Math.XMLOasisMetaImporter"
                        : "com.sun.star.comp.Math.XMLMetaImporter") );

        if ( nWarn != ERRCODE_IO_BROKENPACKAGE )
        {
            if (xStatusIndicator.is())
                xStatusIndicator->setValue(nSteps++);

            nWarn = ReadThroughComponent(
213
                rMedium.GetStorage(), xModelComp, "settings.xml", nullptr,
214
                xContext, xInfoSet,
215 216 217 218 219 220 221 222 223 224
                (bOASIS ? "com.sun.star.comp.Math.XMLOasisSettingsImporter"
                        : "com.sun.star.comp.Math.XMLSettingsImporter" ) );

            if ( nWarn != ERRCODE_IO_BROKENPACKAGE )
            {
                if (xStatusIndicator.is())
                    xStatusIndicator->setValue(nSteps++);

                nError = ReadThroughComponent(
                    rMedium.GetStorage(), xModelComp, "content.xml", "Content.xml",
225
                    xContext, xInfoSet, "com.sun.star.comp.Math.XMLImporter" );
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
            }
            else
                nError = ERRCODE_IO_BROKENPACKAGE;
        }
        else
            nError = ERRCODE_IO_BROKENPACKAGE;
    }
    else
    {
        Reference<io::XInputStream> xInputStream =
            new utl::OInputStreamWrapper(rMedium.GetInStream());

        if (xStatusIndicator.is())
            xStatusIndicator->setValue(nSteps++);

        nError = ReadThroughComponent( xInputStream, xModelComp,
242
            xContext, xInfoSet, "com.sun.star.comp.Math.XMLImporter", false );
243 244 245 246 247 248 249 250 251
    }

    if (xStatusIndicator.is())
        xStatusIndicator->end();
    return nError;
}


/// read a component (file + filter version)
252
ErrCode SmXMLImportWrapper::ReadThroughComponent(
253 254
    const Reference<io::XInputStream>& xInputStream,
    const Reference<XComponent>& xModelComponent,
255 256
    Reference<uno::XComponentContext> const & rxContext,
    Reference<beans::XPropertySet> const & rPropSet,
257
    const sal_Char* pFilterName,
Noel Grandin's avatar
Noel Grandin committed
258
    bool bEncrypted )
259
{
260
    ErrCode nError = ERRCODE_SFX_DOLOADFAILED;
261 262
    OSL_ENSURE(xInputStream.is(), "input stream missing");
    OSL_ENSURE(xModelComponent.is(), "document missing");
263
    OSL_ENSURE(rxContext.is(), "factory missing");
264
    OSL_ENSURE(nullptr != pFilterName,"I need a service name for the component!");
265 266 267 268 269 270

    // prepare ParserInputSrouce
    xml::sax::InputSource aParserInput;
    aParserInput.aInputStream = xInputStream;

    // get parser
271
    Reference< xml::sax::XParser > xParser = xml::sax::Parser::create(rxContext);
272 273 274 275 276 277

    Sequence<Any> aArgs( 1 );
    aArgs[0] <<= rPropSet;

    // get filter
    Reference< xml::sax::XDocumentHandler > xFilter(
278 279
        rxContext->getServiceManager()->createInstanceWithArgumentsAndContext(
            OUString::createFromAscii(pFilterName), aArgs, rxContext),
280
        UNO_QUERY );
281
    OSL_ENSURE( xFilter.is(), "Can't instantiate filter component." );
282 283 284 285 286 287 288 289 290 291
    if ( !xFilter.is() )
        return nError;

    // connect parser and filter
    xParser->setDocumentHandler( xFilter );

    // connect model and filter
    Reference < XImporter > xImporter( xFilter, UNO_QUERY );
    xImporter->setTargetDocument( xModelComponent );

292 293 294
    uno::Reference< xml::sax::XFastParser > xFastParser = dynamic_cast<
                            xml::sax::XFastParser* >( xFilter.get() );

295 296 297
    // finally, parser the stream
    try
    {
298 299 300 301
        if( xFastParser.is() )
            xFastParser->parseStream( aParserInput );
        else
            xParser->parseStream( aParserInput );
302

303
        uno::Reference<lang::XUnoTunnel> xFilterTunnel( xFilter, uno::UNO_QUERY );
304 305 306 307
        SmXMLImport *pFilter = reinterpret_cast< SmXMLImport * >(
                sal::static_int_cast< sal_uIntPtr >(
                xFilterTunnel->getSomething( SmXMLImport::getUnoTunnelId() )));
        if ( pFilter && pFilter->GetSuccess() )
308
            nError = ERRCODE_NONE;
309
    }
310
    catch (const xml::sax::SAXParseException& r)
311 312 313
    {
        // sax parser sends wrapped exceptions,
        // try to find the original one
314
        xml::sax::SAXException aSaxEx = *static_cast<const xml::sax::SAXException*>(&r);
Takeshi Abe's avatar
Takeshi Abe committed
315
        bool bTryChild = true;
316 317 318 319 320 321 322

        while( bTryChild )
        {
            xml::sax::SAXException aTmp;
            if ( aSaxEx.WrappedException >>= aTmp )
                aSaxEx = aTmp;
            else
Takeshi Abe's avatar
Takeshi Abe committed
323
                bTryChild = false;
324 325 326 327 328 329 330 331 332
        }

        packages::zip::ZipIOException aBrokenPackage;
        if ( aSaxEx.WrappedException >>= aBrokenPackage )
            return ERRCODE_IO_BROKENPACKAGE;

        if ( bEncrypted )
            nError = ERRCODE_SFX_WRONGPASSWORD;
    }
333
    catch (const xml::sax::SAXException& r)
334 335 336 337 338 339 340 341
    {
        packages::zip::ZipIOException aBrokenPackage;
        if ( r.WrappedException >>= aBrokenPackage )
            return ERRCODE_IO_BROKENPACKAGE;

        if ( bEncrypted )
            nError = ERRCODE_SFX_WRONGPASSWORD;
    }
342
    catch (const packages::zip::ZipIOException&)
343 344 345
    {
        nError = ERRCODE_IO_BROKENPACKAGE;
    }
346 347 348 349
    catch (const io::IOException&)
    {
    }
    catch (const std::range_error&)
350 351 352 353 354 355 356
    {
    }

    return nError;
}


357
ErrCode SmXMLImportWrapper::ReadThroughComponent(
358
    const uno::Reference< embed::XStorage >& xStorage,
359
    const Reference<XComponent>& xModelComponent,
360 361
    const sal_Char* pStreamName,
    const sal_Char* pCompatibilityStreamName,
362 363
    Reference<uno::XComponentContext> const & rxContext,
    Reference<beans::XPropertySet> const & rPropSet,
364 365
    const sal_Char* pFilterName )
{
366
    OSL_ENSURE(xStorage.is(), "Need storage!");
367
    OSL_ENSURE(nullptr != pStreamName, "Please, please, give me a name!");
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

    // open stream (and set parser input)
    OUString sStreamName = OUString::createFromAscii(pStreamName);
    uno::Reference < container::XNameAccess > xAccess( xStorage, uno::UNO_QUERY );
    if ( !xAccess->hasByName(sStreamName) || !xStorage->isStreamElement(sStreamName) )
    {
        // stream name not found! Then try the compatibility name.
        // do we even have an alternative name?
        if ( pCompatibilityStreamName )
            sStreamName = OUString::createFromAscii(pCompatibilityStreamName);
    }

    // get input stream
    try
    {
        uno::Reference < io::XStream > xEventsStream = xStorage->openStreamElement( sStreamName, embed::ElementModes::READ );

        // determine if stream is encrypted or not
        uno::Reference < beans::XPropertySet > xProps( xEventsStream, uno::UNO_QUERY );
387
        Any aAny = xProps->getPropertyValue( "Encrypted" );
Noel Grandin's avatar
Noel Grandin committed
388
        bool bEncrypted = false;
389
        if ( aAny.getValueType() == cppu::UnoType<bool>::get() )
390 391 392 393 394
            aAny >>= bEncrypted;

        // set Base URL
        if ( rPropSet.is() )
        {
395
            rPropSet->setPropertyValue( "StreamName", makeAny( sStreamName ) );
396 397 398 399
        }


        Reference < io::XInputStream > xStream = xEventsStream->getInputStream();
400
        return ReadThroughComponent( xStream, xModelComponent, rxContext, rPropSet, pFilterName, bEncrypted );
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    }
    catch ( packages::WrongPasswordException& )
    {
        return ERRCODE_SFX_WRONGPASSWORD;
    }
    catch( packages::zip::ZipIOException& )
    {
        return ERRCODE_IO_BROKENPACKAGE;
    }
    catch ( uno::Exception& )
    {
    }

    return ERRCODE_SFX_DOLOADFAILED;
}

417

418
SmXMLImport::SmXMLImport(
419
    const css::uno::Reference< css::uno::XComponentContext >& rContext,
420
    OUString const & implementationName, SvXMLImportFlags nImportFlags)
421
:   SvXMLImport(rContext, implementationName, nImportFlags),
422 423
    bSuccess(false),
    nParseDepth(0)
424 425 426
{
}

427 428 429 430 431
namespace
{
    class theSmXMLImportUnoTunnelId : public rtl::Static< UnoTunnelIdInit, theSmXMLImportUnoTunnelId> {};
}

432 433
const uno::Sequence< sal_Int8 > & SmXMLImport::getUnoTunnelId() throw()
{
434
    return theSmXMLImportUnoTunnelId::get().getSeq();
435 436
}

437 438 439
extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface*
Math_XMLImporter_get_implementation(uno::XComponentContext* pCtx,
                                    uno::Sequence<uno::Any> const& /*rSeq*/)
440
{
441 442
    return cppu::acquire(
        new SmXMLImport(pCtx, "com.sun.star.comp.Math.XMLImporter", SvXMLImportFlags::ALL));
443 444
}

445 446 447
extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface*
Math_XMLOasisMetaImporter_get_implementation(uno::XComponentContext* pCtx,
                                             uno::Sequence<uno::Any> const& /*rSeq*/)
448
{
449 450
    return cppu::acquire(new SmXMLImport(pCtx, "com.sun.star.comp.Math.XMLOasisMetaImporter",
                                         SvXMLImportFlags::META));
451 452
}

453
OUString SmXMLImportSettings_getImplementationName() throw()
454
{
455
    return OUString( "com.sun.star.comp.Math.XMLOasisSettingsImporter" );
456 457
}

458
uno::Sequence< OUString > SmXMLImportSettings_getSupportedServiceNames()
459 460
        throw()
{
461
    return uno::Sequence<OUString>{ IMPORT_SVC_NAME };
462 463
}

464
uno::Reference< uno::XInterface > SmXMLImportSettings_createInstance(
465 466
    const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
{
467
    return static_cast<cppu::OWeakObject*>(new SmXMLImport( comphelper::getComponentContext(rSMgr), SmXMLImportSettings_getImplementationName(), SvXMLImportFlags::SETTINGS ));
468 469 470 471 472 473
}

sal_Int64 SAL_CALL SmXMLImport::getSomething(
    const uno::Sequence< sal_Int8 >&rId )
{
    if ( rId.getLength() == 16 &&
474
        0 == memcmp( getUnoTunnelId().getConstArray(),
475
        rId.getConstArray(), 16 ) )
Luboš Luňák's avatar
Luboš Luňák committed
476
        return sal::static_int_cast< sal_Int64 >(reinterpret_cast< sal_uIntPtr >(this));
477 478 479 480

    return SvXMLImport::getSomething( rId );
}

481
void SmXMLImport::endDocument()
482 483
{
    //Set the resulted tree into the SmDocShell where it belongs
484
    SmNode *pTree = popOrZero(aNodeStack);
485
    if (pTree && pTree->GetType() == SmNodeType::Table)
486 487
    {
        uno::Reference <frame::XModel> xModel = GetModel();
488
        uno::Reference <lang::XUnoTunnel> xTunnel(xModel,uno::UNO_QUERY);
489 490 491 492 493 494 495
        SmModel *pModel = reinterpret_cast<SmModel *>
            (xTunnel->getSomething(SmModel::getUnoTunnelId()));

        if (pModel)
        {
            SmDocShell *pDocShell =
                static_cast<SmDocShell*>(pModel->GetObjectShell());
496
            pDocShell->SetFormulaTree(static_cast<SmTableNode *>(pTree));
497
            if (aText.isEmpty())  //If we picked up no annotation text
498
            {
Caolán McNamara's avatar
Caolán McNamara committed
499
                OUStringBuffer aStrBuf;
500
                // Get text from imported formula
Caolán McNamara's avatar
Caolán McNamara committed
501 502 503
                pTree->CreateTextFromNode(aStrBuf);
                aStrBuf.stripEnd(' ');
                aText = aStrBuf.makeStringAndClear();
504 505 506 507
            }

            // Convert symbol names
            SmParser &rParser = pDocShell->GetParser();
508 509
            bool bVal = rParser.IsImportSymbolNames();
            rParser.SetImportSymbolNames( true );
510
            auto pTmpTree = rParser.Parse( aText );
511
            aText = rParser.GetText();
512
            pTmpTree.reset();
513 514 515 516
            rParser.SetImportSymbolNames( bVal );

            pDocShell->SetText( aText );
        }
517
        OSL_ENSURE(pModel,"So there *was* a uno problem after all");
518

Noel Grandin's avatar
Noel Grandin committed
519
        bSuccess = true;
520 521 522 523 524
    }

    SvXMLImport::endDocument();
}

525

526 527 528 529 530
class SmXMLImportContext: public SvXMLImportContext
{
public:
    SmXMLImportContext( SmXMLImport &rImport, sal_uInt16 nPrfx,
        const OUString& rLName)
531 532 533 534 535 536 537 538 539
        : SvXMLImportContext(rImport, nPrfx, rLName)
    {
        GetSmImport().IncParseDepth();
    }

    virtual ~SmXMLImportContext() override
    {
        GetSmImport().DecParseDepth();
    }
540 541 542

    SmXMLImport& GetSmImport()
    {
Noel Grandin's avatar
Noel Grandin committed
543
        return static_cast<SmXMLImport&>(GetImport());
544 545 546
    }

    virtual void TCharacters(const OUString & /*rChars*/);
547
    virtual void Characters(const OUString &rChars) override;
548
    virtual SvXMLImportContextRef CreateChildContext(sal_uInt16 /*nPrefix*/, const OUString& /*rLocalName*/, const uno::Reference< xml::sax::XAttributeList > & /*xAttrList*/) override;
549 550 551 552 553 554
    virtual void StartElement(const css::uno::Reference<css::xml::sax::XAttributeList>& rAttrList) override
    {
        if (GetSmImport().TooDeep())
            throw std::range_error("too deep");
        SvXMLImportContext::StartElement(rAttrList);
    }
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
};

void SmXMLImportContext::TCharacters(const OUString & /*rChars*/)
{
}

void SmXMLImportContext::Characters(const OUString &rChars)
{
    /*
    Whitespace occurring within the content of token elements is "trimmed"
    from the ends (i.e. all whitespace at the beginning and end of the
    content is removed), and "collapsed" internally (i.e. each sequence of
    1 or more whitespace characters is replaced with one blank character).
    */
    //collapsing not done yet!
    const OUString &rChars2 = rChars.trim();
571
    if (!rChars2.isEmpty())
572 573 574
        TCharacters(rChars2/*.collapse()*/);
}

575
SvXMLImportContextRef SmXMLImportContext::CreateChildContext(sal_uInt16 /*nPrefix*/,
576 577 578
    const OUString& /*rLocalName*/,
    const uno::Reference< xml::sax::XAttributeList > & /*xAttrList*/)
{
579
    return nullptr;
580 581
}

582

583 584 585 586 587 588 589 590
struct SmXMLContext_Helper
{
    sal_Int8 nIsBold;
    sal_Int8 nIsItalic;
    double nFontSize;
    OUString sFontFamily;
    OUString sColor;

591
    SmXMLImportContext & rContext;
592

593
    explicit SmXMLContext_Helper(SmXMLImportContext &rImport)
594 595 596 597 598
        : nIsBold( -1 )
        , nIsItalic( -1 )
        , nFontSize( 0.0 )
        , rContext( rImport )
        {}
599

600
    bool IsFontNodeNeeded() const;
601 602 603 604
    void RetrieveAttrs(const uno::Reference< xml::sax::XAttributeList > &xAttrList );
    void ApplyAttrs();
};

605 606 607 608 609 610 611 612 613
bool SmXMLContext_Helper::IsFontNodeNeeded() const
{
    return nIsBold != -1 ||
        nIsItalic != -1 ||
        nFontSize != 0.0 ||
        !sFontFamily.isEmpty() ||
        !sColor.isEmpty();
}

614 615 616
void SmXMLContext_Helper::RetrieveAttrs(const uno::Reference<
    xml::sax::XAttributeList > & xAttrList )
{
617
    bool bMvFound = false;
618 619 620 621 622 623 624 625 626 627 628 629 630
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0;i<nAttrCount;i++)
    {
        OUString sAttrName = xAttrList->getNameByIndex(i);
        OUString aLocalName;
        sal_uInt16 nPrefix = rContext.GetSmImport().GetNamespaceMap().
            GetKeyByAttrName(sAttrName,&aLocalName);
        OUString sValue = xAttrList->getValueByIndex(i);
        const SvXMLTokenMap &rAttrTokenMap =
            rContext.GetSmImport().GetPresLayoutAttrTokenMap();
        switch(rAttrTokenMap.Get(nPrefix,aLocalName))
        {
            case XML_TOK_FONTWEIGHT:
631
                nIsBold = sal_Int8(sValue == GetXMLToken(XML_BOLD));
632 633
                break;
            case XML_TOK_FONTSTYLE:
634
                nIsItalic = sal_Int8(sValue == GetXMLToken(XML_ITALIC));
635 636
                break;
            case XML_TOK_FONTSIZE:
637
                ::sax::Converter::convertDouble(nFontSize, sValue);
638
                rContext.GetSmImport().GetMM100UnitConverter().
639
                    SetXMLMeasureUnit(util::MeasureUnit::POINT);
640 641 642 643 644 645 646
                if (-1 == sValue.indexOf(GetXMLToken(XML_UNIT_PT)))
                {
                    if (-1 == sValue.indexOf('%'))
                        nFontSize=0.0;
                    else
                    {
                        rContext.GetSmImport().GetMM100UnitConverter().
647
                            SetXMLMeasureUnit(util::MeasureUnit::PERCENT);
648 649 650 651 652 653 654 655 656
                    }
                }
                break;
            case XML_TOK_FONTFAMILY:
                sFontFamily = sValue;
                break;
            case XML_TOK_COLOR:
                sColor = sValue;
                break;
657 658 659
            case XML_TOK_MATHCOLOR:
                sColor = sValue;
                break;
660 661 662
            case XML_TOK_MATHVARIANT:
                bMvFound = true;
                break;
663 664 665 666 667
            default:
                break;
        }
    }

668 669 670 671 672 673 674 675 676
    if (bMvFound)
    {
        // Ignore deprecated attributes fontfamily, fontweight, and fontstyle
        // in favor of mathvariant, as specified in
        // <https://www.w3.org/TR/MathML3/chapter3.html#presm.deprecatt>.
        sFontFamily.clear();
        nIsBold = -1;
        nIsItalic = -1;
    }
677 678 679 680 681 682
}

void SmXMLContext_Helper::ApplyAttrs()
{
    SmNodeStack &rNodeStack = rContext.GetSmImport().GetNodeStack();

683
    if (IsFontNodeNeeded())
684 685 686 687 688 689 690 691 692 693 694
    {
        SmToken aToken;
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;

        if (nIsBold != -1)
        {
            if (nIsBold)
                aToken.eType = TBOLD;
            else
                aToken.eType = TNBOLD;
695
            std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
696
            pFontNode->SetSubNodes(nullptr,popOrZero(rNodeStack));
697
            rNodeStack.push_front(std::move(pFontNode));
698 699 700 701 702 703 704
        }
        if (nIsItalic != -1)
        {
            if (nIsItalic)
                aToken.eType = TITALIC;
            else
                aToken.eType = TNITALIC;
705
            std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
706
            pFontNode->SetSubNodes(nullptr,popOrZero(rNodeStack));
707
            rNodeStack.push_front(std::move(pFontNode));
708 709 710 711
        }
        if (nFontSize != 0.0)
        {
            aToken.eType = TSIZE;
712
            std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
713

714 715
            if (util::MeasureUnit::PERCENT == rContext.GetSmImport()
                    .GetMM100UnitConverter().GetXMLMeasureUnit())
716 717
            {
                if (nFontSize < 100.00)
718
                    pFontNode->SetSizeParameter(Fraction(100.00/nFontSize),
719
                        FontSizeType::DIVIDE);
720
                else
721
                    pFontNode->SetSizeParameter(Fraction(nFontSize/100.00),
722
                        FontSizeType::MULTIPLY);
723 724
            }
            else
725
                pFontNode->SetSizeParameter(Fraction(nFontSize),FontSizeType::ABSOLUT);
726

727
            pFontNode->SetSubNodes(nullptr,popOrZero(rNodeStack));
728
            rNodeStack.push_front(std::move(pFontNode));
729
        }
730
        if (!sFontFamily.isEmpty())
731 732 733
        {
            if (sFontFamily.equalsIgnoreAsciiCase(GetXMLToken(XML_FIXED)))
                aToken.eType = TFIXED;
734
            else if (sFontFamily.equalsIgnoreAsciiCase("sans"))
735
                aToken.eType = TSANS;
736
            else if (sFontFamily.equalsIgnoreAsciiCase("serif"))
737 738 739 740 741 742
                aToken.eType = TSERIF;
            else //Just give up, we need to extend our font mechanism to be
                //more general
                return;

            aToken.aText = sFontFamily;
743
            std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
744
            pFontNode->SetSubNodes(nullptr,popOrZero(rNodeStack));
745
            rNodeStack.push_front(std::move(pFontNode));
746
        }
747
        if (!sColor.isEmpty())
748 749 750 751 752
        {
            //Again we can only handle a small set of colours in
            //StarMath for now.
            const SvXMLTokenMap& rTokenMap =
                rContext.GetSmImport().GetColorTokenMap();
753 754
            sal_uInt16 tok = rTokenMap.Get(XML_NAMESPACE_MATH, sColor);
            if (tok != XML_TOK_UNKNOWN)
755
            {
756
                aToken.eType = static_cast<SmTokenType>(tok);
757
                std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
758
                pFontNode->SetSubNodes(nullptr,popOrZero(rNodeStack));
759
                rNodeStack.push_front(std::move(pFontNode));
760 761 762 763 764 765
            }
        }

    }
}

766

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
class SmXMLTokenAttrHelper
{
    SmXMLImportContext& mrContext;
    MathMLMathvariantValue meMv;
    bool mbMvFound;

public:
    SmXMLTokenAttrHelper(SmXMLImportContext& rContext)
        : mrContext(rContext)
        , meMv(MathMLMathvariantValue::Normal)
        , mbMvFound(false)
    {}

    void RetrieveAttrs(const uno::Reference<xml::sax::XAttributeList>& xAttrList);
    void ApplyAttrs(MathMLMathvariantValue eDefaultMv);
};

void SmXMLTokenAttrHelper::RetrieveAttrs(const uno::Reference<xml::sax::XAttributeList>& xAttrList)
{
    if (!xAttrList.is())
        return;
    sal_Int16 nAttrCount = xAttrList->getLength();
    for (sal_Int16 i=0;i<nAttrCount;i++)
    {
        OUString sAttrName = xAttrList->getNameByIndex(i);
        OUString aLocalName;
        sal_uInt16 nPrefix = mrContext.GetSmImport().GetNamespaceMap().
            GetKeyByAttrName(sAttrName, &aLocalName);
        OUString sValue = xAttrList->getValueByIndex(i);
        const SvXMLTokenMap &rAttrTokenMap =
            mrContext.GetSmImport().GetPresLayoutAttrTokenMap();
        switch(rAttrTokenMap.Get(nPrefix, aLocalName))
        {
            case XML_TOK_MATHVARIANT:
801
                if (!GetMathMLMathvariantValue(sValue, meMv))
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
                    SAL_WARN("starmath", "failed to recognize mathvariant: " << sValue);
                mbMvFound = true;
                break;
            default:
                break;
        }
    }
}

void SmXMLTokenAttrHelper::ApplyAttrs(MathMLMathvariantValue eDefaultMv)
{
    assert( eDefaultMv == MathMLMathvariantValue::Normal ||
            eDefaultMv == MathMLMathvariantValue::Italic );

    std::vector<SmTokenType> vVariant;
    MathMLMathvariantValue eMv = mbMvFound ? meMv : eDefaultMv;
    switch(eMv)
    {
        case MathMLMathvariantValue::Normal:
            vVariant.push_back(TNITALIC);
            break;
        case MathMLMathvariantValue::Bold:
            vVariant.push_back(TBOLD);
            break;
        case MathMLMathvariantValue::Italic:
            // nothing to do
            break;
        case MathMLMathvariantValue::BoldItalic:
            vVariant.push_back(TITALIC);
            vVariant.push_back(TBOLD);
            break;
        case MathMLMathvariantValue::DoubleStruck:
            // TODO
            break;
        case MathMLMathvariantValue::BoldFraktur:
            // TODO: Fraktur
            vVariant.push_back(TBOLD);
            break;
        case MathMLMathvariantValue::Script:
            // TODO
            break;
        case MathMLMathvariantValue::BoldScript:
            // TODO: Script
            vVariant.push_back(TBOLD);
            break;
        case MathMLMathvariantValue::Fraktur:
            // TODO
            break;
        case MathMLMathvariantValue::SansSerif:
            vVariant.push_back(TSANS);
            break;
        case MathMLMathvariantValue::BoldSansSerif:
            vVariant.push_back(TSANS);
            vVariant.push_back(TBOLD);
            break;
        case MathMLMathvariantValue::SansSerifItalic:
            vVariant.push_back(TITALIC);
            vVariant.push_back(TSANS);
            break;
        case MathMLMathvariantValue::SansSerifBoldItalic:
            vVariant.push_back(TITALIC);
            vVariant.push_back(TBOLD);
            vVariant.push_back(TSANS);
            break;
        case MathMLMathvariantValue::Monospace:
            vVariant.push_back(TFIXED);
            break;
        case MathMLMathvariantValue::Initial:
        case MathMLMathvariantValue::Tailed:
        case MathMLMathvariantValue::Looped:
        case MathMLMathvariantValue::Stretched:
            // TODO
            break;
    }
    if (vVariant.empty())
        return;
    SmNodeStack &rNodeStack = mrContext.GetSmImport().GetNodeStack();
    for (auto eType : vVariant)
    {
        SmToken aToken;
        aToken.eType = eType;
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;
        std::unique_ptr<SmFontNode> pFontNode(new SmFontNode(aToken));
        pFontNode->SetSubNodes(nullptr, popOrZero(rNodeStack));
        rNodeStack.push_front(std::move(pFontNode));
    }
}


892 893 894 895 896 897 898
class SmXMLDocContext_Impl : public SmXMLImportContext
{
public:
    SmXMLDocContext_Impl( SmXMLImport &rImport, sal_uInt16 nPrfx,
        const OUString& rLName)
        : SmXMLImportContext(rImport,nPrfx,rLName) {}

899
    virtual SvXMLImportContextRef CreateChildContext(sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > &xAttrList) override;
900

901
    void EndElement() override;
902 903
};

904

905 906 907 908
/*avert thy gaze from the proginator*/
class SmXMLRowContext_Impl : public SmXMLDocContext_Impl
{
protected:
909
    size_t const nElementCount;
910 911 912 913 914

public:
    SmXMLRowContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLDocContext_Impl(rImport,nPrefix,rLName)
915 916 917
        , nElementCount(GetSmImport().GetNodeStack().size())
    {
    }
918

919
    virtual SvXMLImportContextRef CreateChildContext(sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > &xAttrList) override;
920 921

    SvXMLImportContext *StrictCreateChildContext(sal_uInt16 nPrefix,
922
        const OUString& rLocalName);
923

924
    void EndElement() override;
925 926
};

927 928 929 930 931 932 933 934 935
class SmXMLEncloseContext_Impl : public SmXMLRowContext_Impl
{
public:
    // TODO/LATER: convert <menclose notation="horizontalstrike"> into
    // "overstrike{}" and extend the Math syntax to support more notations
    SmXMLEncloseContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

936
    void EndElement() override;
937 938 939 940 941 942 943 944 945
};

void SmXMLEncloseContext_Impl::EndElement()
{
    /*
    <menclose> accepts any number of arguments; if this number is not 1, its
    contents are treated as a single "inferred <mrow>" containing its
    arguments
    */
946
    if (GetSmImport().GetNodeStack().size() - nElementCount != 1)
947 948 949
        SmXMLRowContext_Impl::EndElement();
}

950

951 952 953
class SmXMLFracContext_Impl : public SmXMLRowContext_Impl
{
public:
954
    // TODO/LATER: convert <mfrac bevelled="true"> into "wideslash{}{}"
955 956 957 958
    SmXMLFracContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

959
    void EndElement() override;
960 961
};

962

963 964 965 966 967 968 969
class SmXMLSqrtContext_Impl : public SmXMLRowContext_Impl
{
public:
    SmXMLSqrtContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

970
    void EndElement() override;
971 972
};

973

974 975 976 977 978 979 980
class SmXMLRootContext_Impl : public SmXMLRowContext_Impl
{
public:
    SmXMLRootContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

981
    void EndElement() override;
982 983
};

984

985 986 987 988 989 990 991 992 993 994 995
class SmXMLStyleContext_Impl : public SmXMLRowContext_Impl
{
protected:
    SmXMLContext_Helper aStyleHelper;

public:
    /*Right now the style tag is completely ignored*/
    SmXMLStyleContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName) : SmXMLRowContext_Impl(rImport,nPrefix,rLName),
        aStyleHelper(*this) {}

996 997
    void EndElement() override;
    void StartElement(const uno::Reference< xml::sax::XAttributeList > &xAttrList ) override;
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
};

void SmXMLStyleContext_Impl::StartElement(const uno::Reference<
    xml::sax::XAttributeList > & xAttrList )
{
    aStyleHelper.RetrieveAttrs(xAttrList);
}


void SmXMLStyleContext_Impl::EndElement()
{
    /*
    <mstyle> accepts any number of arguments; if this number is not 1, its
    contents are treated as a single "inferred <mrow>" containing its
    arguments
    */
    SmNodeStack &rNodeStack = GetSmImport().GetNodeStack();
1015
    if (rNodeStack.size() - nElementCount != 1)
1016 1017 1018 1019
        SmXMLRowContext_Impl::EndElement();
    aStyleHelper.ApplyAttrs();
}

1020

1021 1022 1023 1024 1025 1026 1027 1028
class SmXMLPaddedContext_Impl : public SmXMLRowContext_Impl
{
public:
    /*Right now the style tag is completely ignored*/
    SmXMLPaddedContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

1029
    void EndElement() override;
1030 1031 1032 1033 1034 1035 1036 1037 1038
};

void SmXMLPaddedContext_Impl::EndElement()
{
    /*
    <mpadded> accepts any number of arguments; if this number is not 1, its
    contents are treated as a single "inferred <mrow>" containing its
    arguments
    */
1039
    if (GetSmImport().GetNodeStack().size() - nElementCount != 1)
1040 1041 1042
        SmXMLRowContext_Impl::EndElement();
}

1043

1044 1045 1046 1047 1048 1049 1050 1051
class SmXMLPhantomContext_Impl : public SmXMLRowContext_Impl
{
public:
    /*Right now the style tag is completely ignored*/
    SmXMLPhantomContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

1052
    void EndElement() override;
1053 1054 1055 1056 1057 1058 1059 1060 1061
};

void SmXMLPhantomContext_Impl::EndElement()
{
    /*
    <mphantom> accepts any number of arguments; if this number is not 1, its
    contents are treated as a single "inferred <mrow>" containing its
    arguments
    */
1062
    if (GetSmImport().GetNodeStack().size() - nElementCount != 1)
1063 1064 1065 1066 1067 1068 1069
        SmXMLRowContext_Impl::EndElement();

    SmToken aToken;
    aToken.cMathChar = '\0';
    aToken.nLevel = 5;
    aToken.eType = TPHANTOM;

1070
    std::unique_ptr<SmFontNode> pPhantom(new SmFontNode(aToken));
1071
    SmNodeStack &rNodeStack = GetSmImport().GetNodeStack();
1072
    pPhantom->SetSubNodes(nullptr,popOrZero(rNodeStack));
1073
    rNodeStack.push_front(std::move(pPhantom));
1074 1075
}

1076

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
class SmXMLFencedContext_Impl : public SmXMLRowContext_Impl
{
protected:
    sal_Unicode cBegin;
    sal_Unicode cEnd;

public:
    SmXMLFencedContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName),
        cBegin('('), cEnd(')') {}

1089 1090
    void StartElement(const uno::Reference< xml::sax::XAttributeList > & xAttrList ) override;
    void EndElement() override;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
};


void SmXMLFencedContext_Impl::StartElement(const uno::Reference<
    xml::sax::XAttributeList > & xAttrList )
{
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0;i<nAttrCount;i++)
    {
        OUString sAttrName = xAttrList->getNameByIndex(i);
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName(sAttrName,&aLocalName);
        OUString sValue = xAttrList->getValueByIndex(i);
        const SvXMLTokenMap &rAttrTokenMap =
            GetSmImport().GetFencedAttrTokenMap();
        switch(rAttrTokenMap.Get(nPrefix,aLocalName))
        {
            //temp, starmath cannot handle multichar brackets (I think)
            case XML_TOK_OPEN:
                cBegin = sValue[0];
                break;
            case XML_TOK_CLOSE:
                cEnd = sValue[0];
                break;
            default:
                /*Go to superclass*/
                break;
        }
    }
}


void SmXMLFencedContext_Impl::EndElement()
{
    SmToken aToken;
    aToken.cMathChar = '\0';
Ivan Timofeev's avatar
Ivan Timofeev committed
1128
    aToken.aText = ",";
1129 1130 1131 1132
    aToken.nLevel = 5;

    aToken.eType = TLPARENT;
    aToken.cMathChar = cBegin;
1133
    std::unique_ptr<SmStructureNode> pSNode(new SmBraceNode(aToken));
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    SmNode *pLeft = new SmMathSymbolNode(aToken);

    aToken.cMathChar = cEnd;
    aToken.eType = TRPARENT;
    SmNode *pRight = new SmMathSymbolNode(aToken);

    SmNodeArray aRelationArray;
    SmNodeStack &rNodeStack = GetSmImport().GetNodeStack();

    aToken.cMathChar = '\0';
    aToken.eType = TIDENT;

1146
    auto i = rNodeStack.size() - nElementCount;
1147 1148
    if (rNodeStack.size() - nElementCount > 1)
        i += rNodeStack.size() - 1 - nElementCount;
1149
    aRelationArray.resize(i);
1150
    while (rNodeStack.size() > nElementCount)
1151
    {
1152 1153
        auto pNode = std::move(rNodeStack.front());
        rNodeStack.pop_front();
1154
        aRelationArray[--i] = pNode.release();
1155
        if (i > 1 && rNodeStack.size() > 1)
1156 1157 1158 1159 1160
            aRelationArray[--i] = new SmGlyphSpecialNode(aToken);
    }

    SmToken aDummy;
    SmStructureNode *pBody = new SmExpressionNode(aDummy);
1161
    pBody->SetSubNodes(std::move(aRelationArray));
1162 1163 1164


    pSNode->SetSubNodes(pLeft,pBody,pRight);
1165
    pSNode->SetScaleMode(SmScaleMode::Height);
1166
    GetSmImport().GetNodeStack().push_front(std::move(pSNode));
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
}


class SmXMLErrorContext_Impl : public SmXMLRowContext_Impl
{
public:
    SmXMLErrorContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLRowContext_Impl(rImport,nPrefix,rLName) {}

1177
    void EndElement() override;
1178 1179 1180 1181 1182 1183 1184
};

void SmXMLErrorContext_Impl::EndElement()
{
    /*Right now the error tag is completely ignored, what
     can I do with it in starmath, ?, maybe we need a
     report window ourselves, do a test for validity of
Andrea Gelmini's avatar
Andrea Gelmini committed
1185
     the xml input, use mirrors, and then generate
1186 1187 1188 1189
     the markup inside the merror with a big red colour
     of something. For now just throw them all away.
     */
    SmNodeStack &rNodeStack = GetSmImport().GetNodeStack();
1190
    while (rNodeStack.size() > nElementCount)
1191
    {
1192
        rNodeStack.pop_front();
1193 1194 1195
    }
}

1196

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
class SmXMLNumberContext_Impl : public SmXMLImportContext
{
protected:
    SmToken aToken;

public:
    SmXMLNumberContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLImportContext(rImport,nPrefix,rLName)
    {
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;
        aToken.eType = TNUMBER;
    }

1212
    virtual void TCharacters(const OUString &rChars) override;
1213

1214
    void EndElement() override;
1215 1216 1217 1218 1219 1220 1221 1222 1223
};

void SmXMLNumberContext_Impl::TCharacters(const OUString &rChars)
{
    aToken.aText = rChars;
}

void SmXMLNumberContext_Impl::EndElement()
{
1224
    GetSmImport().GetNodeStack().push_front(o3tl::make_unique<SmTextNode>(aToken,FNT_NUMBER));
1225 1226
}

1227

1228 1229
class SmXMLAnnotationContext_Impl : public SmXMLImportContext
{
Takeshi Abe's avatar
Takeshi Abe committed
1230
    bool bIsStarMath;
1231 1232 1233 1234

public:
    SmXMLAnnotationContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
Takeshi Abe's avatar
Takeshi Abe committed
1235
        : SmXMLImportContext(rImport,nPrefix,rLName), bIsStarMath(false) {}
1236

1237
    virtual void Characters(const OUString &rChars) override;
1238

1239
    void StartElement(const uno::Reference<xml::sax::XAttributeList > & xAttrList ) override;
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
};

void SmXMLAnnotationContext_Impl::StartElement(const uno::Reference<
    xml::sax::XAttributeList > & xAttrList )
{
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for (sal_Int16 i=0;i<nAttrCount;i++)
    {
        OUString sAttrName = xAttrList->getNameByIndex(i);
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName(sAttrName,&aLocalName);

        OUString sValue = xAttrList->getValueByIndex(i);
        const SvXMLTokenMap &rAttrTokenMap =
            GetSmImport().GetAnnotationAttrTokenMap();
        switch(rAttrTokenMap.Get(nPrefix,aLocalName))
        {
            case XML_TOK_ENCODING:
1259
                bIsStarMath= sValue == "StarMath 5.0";
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
                break;
            default:
                break;
        }
    }
}

void SmXMLAnnotationContext_Impl::Characters(const OUString &rChars)
{
    if (bIsStarMath)
1270
        GetSmImport().SetText( GetSmImport().GetText() + rChars );
1271 1272
}

1273

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
class SmXMLTextContext_Impl : public SmXMLImportContext
{
protected:
    SmToken aToken;

public:
    SmXMLTextContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLImportContext(rImport,nPrefix,rLName)
    {
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;
        aToken.eType = TTEXT;
    }

1289
    virtual void TCharacters(const OUString &rChars) override;
1290

1291
    void EndElement() override;
1292 1293 1294 1295 1296 1297 1298 1299 1300
};

void SmXMLTextContext_Impl::TCharacters(const OUString &rChars)
{
    aToken.aText = rChars;
}

void SmXMLTextContext_Impl::EndElement()
{
1301
    GetSmImport().GetNodeStack().push_front(o3tl::make_unique<SmTextNode>(aToken,FNT_TEXT));
1302 1303
}

1304

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
class SmXMLStringContext_Impl : public SmXMLImportContext
{
protected:
    SmToken aToken;

public:
    SmXMLStringContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
        : SmXMLImportContext(rImport,nPrefix,rLName)
    {
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;
        aToken.eType = TTEXT;
    }

1320
    virtual void TCharacters(const OUString &rChars) override;
1321

1322
    void EndElement() override;
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
};

void SmXMLStringContext_Impl::TCharacters(const OUString &rChars)
{
    /*
    The content of <ms> elements should be rendered with visible "escaping" of
    certain characters in the content, including at least "double quote"
    itself, and preferably whitespace other than individual blanks. The intent
    is for the viewer to see that the expression is a string literal, and to
    see exactly which characters form its content. For example, <ms>double
    quote is "</ms> might be rendered as "double quote is \"".

    Obviously this isn't fully done here.
    */
Ivan Timofeev's avatar
Ivan Timofeev committed
1337
    aToken.aText = "\"" + rChars + "\"";
1338 1339 1340 1341
}

void SmXMLStringContext_Impl::EndElement()
{
1342
    GetSmImport().GetNodeStack().push_front(o3tl::make_unique<SmTextNode>(aToken,FNT_FIXED));
1343 1344
}

1345

1346 1347
class SmXMLIdentifierContext_Impl : public SmXMLImportContext
{
1348
    SmXMLTokenAttrHelper maTokenAttrHelper;
1349 1350 1351 1352 1353 1354
    SmXMLContext_Helper aStyleHelper;
    SmToken aToken;

public:
    SmXMLIdentifierContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
1355 1356 1357
        : SmXMLImportContext(rImport,nPrefix,rLName)
        , maTokenAttrHelper(*this)
        , aStyleHelper(*this)
1358 1359 1360 1361 1362 1363
    {
        aToken.cMathChar = '\0';
        aToken.nLevel = 5;
        aToken.eType = TIDENT;
    }

1364 1365
    void TCharacters(const OUString &rChars) override;
    void StartElement(const uno::Reference< xml::sax::XAttributeList > & xAttrList ) override
1366
    {
1367
        maTokenAttrHelper.RetrieveAttrs(xAttrList);
1368 1369
        aStyleHelper.RetrieveAttrs(xAttrList);
    };
1370
    void EndElement() override;
1371 1372 1373 1374
};

void SmXMLIdentifierContext_Impl::EndElement()
{
1375
    std::unique_ptr<SmTextNode> pNode;
1376 1377
    //we will handle identifier italic/normal here instead of with a standalone
    //font node
Ivan Timofeev's avatar
Ivan Timofeev committed
1378 1379
    if (((aStyleHelper.nIsItalic == -1) && (aToken.aText.getLength() > 1))
        || ((aStyleHelper.nIsItalic == 0) && (aToken.aText.getLength() == 1)))
1380
    {
1381
        pNode.reset(new SmTextNode(aToken,FNT_FUNCTION));
1382 1383 1384 1385
        pNode->GetFont().SetItalic(ITALIC_NONE);
        aStyleHelper.nIsItalic = -1;
    }
    else
1386
        pNode.reset(new SmTextNode(aToken,FNT_VARIABLE));
1387
    if (aStyleHelper.nIsItalic != -1)
1388 1389 1390 1391 1392
    {
        if (aStyleHelper.nIsItalic)
            pNode->GetFont().SetItalic(ITALIC_NORMAL);
        else
            pNode->GetFont().SetItalic(ITALIC_NONE);
1393
        aStyleHelper.nIsItalic = -1;
1394
    }
1395
    GetSmImport().GetNodeStack().push_front(std::move(pNode));
1396 1397 1398 1399 1400
    aStyleHelper.ApplyAttrs();

    maTokenAttrHelper.ApplyAttrs( (aToken.aText.getLength() == 1)
                                  ? MathMLMathvariantValue::Italic
                                  : MathMLMathvariantValue::Normal );
1401 1402 1403 1404 1405 1406 1407
}

void SmXMLIdentifierContext_Impl::TCharacters(const OUString &rChars)
{
    aToken.aText = rChars;
}

1408

1409 1410
class SmXMLOperatorContext_Impl : public SmXMLImportContext
{
1411
    SmXMLTokenAttrHelper maTokenAttrHelper;
Takeshi Abe's avatar
Takeshi Abe committed
1412
    bool bIsStretchy;
1413 1414 1415 1416 1417
    SmToken aToken;

public:
    SmXMLOperatorContext_Impl(SmXMLImport &rImport,sal_uInt16 nPrefix,
        const OUString& rLName)
1418 1419 1420
        : SmXMLImportContext(rImport,nPrefix,rLName)
        , maTokenAttrHelper(*this)
        , bIsStretchy(false)
1421 1422 1423 1424 1425
    {
        aToken.eType = TSPECIAL;
        aToken.nLevel = 5;
    }

1426 1427 1428
    void TCharacters(const OUString &rChars) override;
    void StartElement(const uno::Reference< xml::sax::XAttributeList > &xAttrList ) override;
    void EndElement() override;
1429 1430 1431 1432 1433 1434