summaryrefslogtreecommitdiffstats
path: root/oox/source/vml/vmlshapecontext.cxx
blob: 3141cb3aad68f0223097e52550ae2dd121fd2f2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * 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 .
 */

#include <sal/config.h>

#include <string_view>

#include <oox/vml/vmlshapecontext.hxx>

#include <oox/core/xmlfilterbase.hxx>
#include <oox/helper/attributelist.hxx>
#include <oox/helper/helper.hxx>
#include <oox/token/namespaces.hxx>
#include <oox/token/tokens.hxx>
#include <oox/vml/vmldrawing.hxx>
#include <oox/vml/vmlshape.hxx>
#include <oox/vml/vmlshapecontainer.hxx>
#include <oox/vml/vmltextboxcontext.hxx>

#include <osl/diagnose.h>
#include <filter/msfilter/escherex.hxx>
#include <o3tl/string_view.hxx>

namespace oox::vml {

using namespace ::com::sun::star;

using ::oox::core::ContextHandler2;
using ::oox::core::ContextHandler2Helper;
using ::oox::core::ContextHandlerRef;

namespace {

/** Returns the boolean value from the specified VML attribute (if present).
 */
OptValue< bool > lclDecodeBool( const AttributeList& rAttribs, sal_Int32 nToken )
{
    OptValue< OUString > oValue = rAttribs.getString( nToken );
    if( oValue.has() ) return OptValue< bool >( ConversionHelper::decodeBool( oValue.get() ) );
    return OptValue< bool >();
}

/** Returns the percentage value from the specified VML attribute (if present).
    The value will be normalized (1.0 is returned for 100%).
 */
OptValue< double > lclDecodePercent( const AttributeList& rAttribs, sal_Int32 nToken, double fDefValue )
{
    OptValue< OUString > oValue = rAttribs.getString( nToken );
    if( oValue.has() ) return OptValue< double >( ConversionHelper::decodePercent( oValue.get(), fDefValue ) );
    return OptValue< double >();
}

/** #119750# Special method for opacity; it *should* be a percentage value, but there are cases
    where a value relative to 0xffff (65536) is used, ending with an 'f'
 */
OptValue< double > lclDecodeOpacity( const AttributeList& rAttribs, sal_Int32 nToken, double fDefValue )
{
    OptValue< OUString > oValue = rAttribs.getString( nToken );
    double fRetval(fDefValue);

    if( oValue.has() )
    {
        const OUString& aString(oValue.get());
        const sal_Int32 nLength(aString.getLength());

        if(nLength > 0)
        {
            if(aString.endsWith("f"))
            {
                fRetval = std::clamp(aString.toDouble() / 65536.0, 0.0, 1.0);
            }
            else
            {
                fRetval = ConversionHelper::decodePercent( aString, fDefValue );
            }
        }
    }

    return OptValue< double >(fRetval);
}

/** Returns the integer value pair from the specified VML attribute (if present).
 */
OptValue< Int32Pair > lclDecodeInt32Pair( const AttributeList& rAttribs, sal_Int32 nToken )
{
    OptValue< OUString > oValue = rAttribs.getString( nToken );
    OptValue< Int32Pair > oRetValue;
    if( oValue.has() )
    {
        std::u16string_view aValue1, aValue2;
        ConversionHelper::separatePair( aValue1, aValue2, oValue.get(), ',' );
        oRetValue = Int32Pair( o3tl::toInt32(aValue1), o3tl::toInt32(aValue2) );
    }
    return oRetValue;
}

/** Returns the percentage pair from the specified VML attribute (if present).
 */
OptValue< DoublePair > lclDecodePercentPair( const AttributeList& rAttribs, sal_Int32 nToken )
{
    OptValue< OUString > oValue = rAttribs.getString( nToken );
    OptValue< DoublePair > oRetValue;
    if( oValue.has() )
    {
        std::u16string_view aValue1, aValue2;
        ConversionHelper::separatePair( aValue1, aValue2, oValue.get(), ',' );
        oRetValue = DoublePair(
            ConversionHelper::decodePercent( aValue1, 0.0 ),
            ConversionHelper::decodePercent( aValue2, 0.0 ) );
    }
    return oRetValue;
}

/** Returns the boolean value from the passed string of an attribute in the x:
    namespace (VML for spreadsheets). Supported values: f, t, False, True.
    @param bDefaultForEmpty  Default value for the empty string.
 */
bool lclDecodeVmlxBool( std::u16string_view rValue, bool bDefaultForEmpty )
{
    if( rValue.empty() ) return bDefaultForEmpty;
    sal_Int32 nToken = AttributeConversion::decodeToken( rValue );
    // anything else than 't' or 'True' is considered to be false, as specified
    return (nToken == XML_t) || (nToken == XML_True);
}

} // namespace

ShapeLayoutContext::ShapeLayoutContext( ContextHandler2Helper const & rParent, Drawing& rDrawing ) :
    ContextHandler2( rParent ),
    mrDrawing( rDrawing )
{
}

ContextHandlerRef ShapeLayoutContext::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
    switch( nElement )
    {
        case O_TOKEN( idmap ):
        {
            OUString aBlockIds = rAttribs.getString( XML_data, OUString() );
            sal_Int32 nIndex = 0;
            while( nIndex >= 0 )
            {
                std::u16string_view aToken = o3tl::trim(o3tl::getToken(aBlockIds, 0, ' ', nIndex ));
                if( !aToken.empty() )
                    mrDrawing.registerBlockId( o3tl::toInt32(aToken) );
            }
        }
        break;
    }
    return nullptr;
}

ClientDataContext::ClientDataContext( ContextHandler2Helper const & rParent,
        ClientData& rClientData, const AttributeList& rAttribs ) :
    ContextHandler2( rParent ),
    mrClientData( rClientData )
{
    mrClientData.mnObjType = rAttribs.getToken( XML_ObjectType, XML_TOKEN_INVALID );
}

ContextHandlerRef ClientDataContext::onCreateContext( sal_Int32 /*nElement*/, const AttributeList& /*rAttribs*/ )
{
    if( isRootElement() )
    {
        maElementText.clear();
        return this;
    }
    return nullptr;
}

void ClientDataContext::onCharacters( const OUString& rChars )
{
    /*  Empty but existing elements have special meaning, e.g. 'true'. Collect
        existing text and convert it in onEndElement(). */
    maElementText = rChars;
}

void ClientDataContext::onEndElement()
{
    switch( getCurrentElement() )
    {
        case VMLX_TOKEN( Anchor ):      mrClientData.maAnchor = maElementText;                                          break;
        case VMLX_TOKEN( FmlaMacro ):   mrClientData.maFmlaMacro = maElementText;                                       break;
        case VMLX_TOKEN( FmlaPict ):    mrClientData.maFmlaPict = maElementText;                                        break;
        case VMLX_TOKEN( FmlaLink ):    mrClientData.maFmlaLink = maElementText;                                        break;
        case VMLX_TOKEN( FmlaRange ):   mrClientData.maFmlaRange = maElementText;                                       break;
        case VMLX_TOKEN( FmlaGroup ):   mrClientData.maFmlaGroup = maElementText;                                       break;
        case VMLX_TOKEN( TextHAlign ):  mrClientData.mnTextHAlign = AttributeConversion::decodeToken( maElementText );  break;
        case VMLX_TOKEN( TextVAlign ):  mrClientData.mnTextVAlign = AttributeConversion::decodeToken( maElementText );  break;
        case VMLX_TOKEN( Column ):      mrClientData.mnCol = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Row ):         mrClientData.mnRow = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Checked ):     mrClientData.mnChecked = maElementText.toInt32();                               break;
        case VMLX_TOKEN( DropStyle ):   mrClientData.mnDropStyle = AttributeConversion::decodeToken( maElementText );   break;
        case VMLX_TOKEN( DropLines ):   mrClientData.mnDropLines = maElementText.toInt32();                             break;
        case VMLX_TOKEN( Val ):         mrClientData.mnVal = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Min ):         mrClientData.mnMin = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Max ):         mrClientData.mnMax = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Inc ):         mrClientData.mnInc = maElementText.toInt32();                                   break;
        case VMLX_TOKEN( Page ):        mrClientData.mnPage = maElementText.toInt32();                                  break;
        case VMLX_TOKEN( SelType ):     mrClientData.mnSelType = AttributeConversion::decodeToken( maElementText );     break;
        case VMLX_TOKEN( VTEdit ):      mrClientData.mnVTEdit = maElementText.toInt32();                                break;
        case VMLX_TOKEN( PrintObject ): mrClientData.mbPrintObject = lclDecodeVmlxBool( maElementText, true );          break;
        case VMLX_TOKEN( Visible ):     mrClientData.mbVisible = lclDecodeVmlxBool( maElementText, true );              break;
        case VMLX_TOKEN( DDE ):         mrClientData.mbDde = lclDecodeVmlxBool( maElementText, true );                  break;
        case VMLX_TOKEN( NoThreeD ):    mrClientData.mbNo3D = lclDecodeVmlxBool( maElementText, true );                 break;
        case VMLX_TOKEN( NoThreeD2 ):   mrClientData.mbNo3D2 = lclDecodeVmlxBool( maElementText, true );                break;
        case VMLX_TOKEN( MultiLine ):   mrClientData.mbMultiLine = lclDecodeVmlxBool( maElementText, true );            break;
        case VMLX_TOKEN( VScroll ):     mrClientData.mbVScroll = lclDecodeVmlxBool( maElementText, true );              break;
        case VMLX_TOKEN( SecretEdit ):  mrClientData.mbSecretEdit = lclDecodeVmlxBool( maElementText, true );           break;
    }
}

ShapeContextBase::ShapeContextBase( ContextHandler2Helper const & rParent ) :
    ContextHandler2( rParent )
{
}

ContextHandlerRef ShapeContextBase::createShapeContext( ContextHandler2Helper const & rParent,
        ShapeContainer& rShapes, sal_Int32 nElement, const AttributeList& rAttribs )
{
    switch( nElement )
    {
        case O_TOKEN( shapelayout ):
            return new ShapeLayoutContext( rParent, rShapes.getDrawing() );

        case VML_TOKEN( shapetype ):
            return new ShapeTypeContext( rParent, rShapes.createShapeType(), rAttribs );
        case VML_TOKEN( group ):
            return new GroupShapeContext( rParent, rShapes.createShape< GroupShape >(), rAttribs );
        case VML_TOKEN( shape ):
            if (rAttribs.hasAttribute(XML_path) &&
                    // tdf#122563 skip in the case of empty path
                    !rAttribs.getString(XML_path, "").isEmpty())
                return new ShapeContext( rParent, rShapes.createShape< BezierShape >(), rAttribs );
            else
                return new ShapeContext( rParent, rShapes.createShape< ComplexShape >(), rAttribs );
        case VML_TOKEN( rect ):
            return new RectangleShapeContext( rParent, rAttribs, rShapes.createShape< RectangleShape >() );
        case VML_TOKEN( roundrect ):
            return new ShapeContext( rParent, rShapes.createShape< RectangleShape >(), rAttribs );
        case VML_TOKEN( oval ):
            return new ShapeContext( rParent, rShapes.createShape< EllipseShape >(), rAttribs );
        case VML_TOKEN( polyline ):
            return new ShapeContext( rParent, rShapes.createShape< PolyLineShape >(), rAttribs );
        case VML_TOKEN( line ):
            return new ShapeContext( rParent, rShapes.createShape< LineShape >(), rAttribs );
        case VML_TOKEN( curve ):
            return new ShapeContext( rParent, rShapes.createShape< BezierShape >(), rAttribs );

        // TODO:
        case VML_TOKEN( arc ):
        case VML_TOKEN( diagram ):
        case VML_TOKEN( image ):
            return new ShapeContext( rParent, rShapes.createShape< ComplexShape >(), rAttribs );

        case W_TOKEN(control):
            return new ControlShapeContext( rParent, rShapes, rAttribs );
    }
    return nullptr;
}

ShapeTypeContext::ShapeTypeContext(ContextHandler2Helper const & rParent,
        std::shared_ptr<ShapeType> const& pShapeType,
        const AttributeList& rAttribs)
    : ShapeContextBase(rParent)
    , m_pShapeType(pShapeType) // tdf#112311 keep it alive
    , mrTypeModel( pShapeType->getTypeModel() )
{
    // shape identifier and shape name
    bool bHasOspid = rAttribs.hasAttribute( O_TOKEN( spid ) );
    mrTypeModel.maShapeId = rAttribs.getXString( bHasOspid ? O_TOKEN( spid ) : XML_id, OUString() );
    mrTypeModel.maLegacyId = rAttribs.getString( XML_id, OUString() );
    OSL_ENSURE( !mrTypeModel.maShapeId.isEmpty(), "ShapeTypeContext::ShapeTypeContext - missing shape identifier" );
    // builtin shape type identifier
    mrTypeModel.moShapeType = rAttribs.getInteger( O_TOKEN( spt ) );
    // if the o:spid attribute exists, the id attribute contains the user-defined shape name
    if( bHasOspid )
    {
        mrTypeModel.maShapeName = rAttribs.getXString( XML_id, OUString() );
        // get ShapeType and ShapeId from name for compatibility
        static constexpr OUStringLiteral sShapeTypePrefix = u"shapetype_";
        OUString tmp;
        if( mrTypeModel.maShapeName.startsWith( sShapeTypePrefix ) )
        {
            mrTypeModel.maShapeId = mrTypeModel.maShapeName;
            mrTypeModel.moShapeType = o3tl::toInt32(mrTypeModel.maShapeName.subView(sShapeTypePrefix.getLength()));
        }
        else if (mrTypeModel.maShapeName.startsWith("_x0000_t", &tmp))
        {
            mrTypeModel.maShapeId = mrTypeModel.maShapeName;
            mrTypeModel.moShapeType = tmp.toInt32();
        }
    }

    // coordinate system position/size, CSS style
    mrTypeModel.moCoordPos = lclDecodeInt32Pair( rAttribs, XML_coordorigin );
    mrTypeModel.moCoordSize = lclDecodeInt32Pair( rAttribs, XML_coordsize );
    setStyle( rAttribs.getString( XML_style, OUString() ) );
    if( lclDecodeBool( rAttribs, O_TOKEN( hr )).get( false ))
    {   // MSO's handling of o:hr width is nowhere near what the spec says:
        // - o:hrpct is not in % but in 0.1%
        // - if o:hrpct is not given, 100% width is assumed
        // - given width is used only if explicit o:hrpct="0" is given
        OUString hrpct = rAttribs.getString( O_TOKEN( hrpct ), "1000" );
        if( hrpct != "0" )
            mrTypeModel.maWidthPercent = OUString::number( hrpct.toInt32() );
        mrTypeModel.maWrapDistanceLeft = "0";
        mrTypeModel.maWrapDistanceRight = "0";
        mrTypeModel.maPositionHorizontal = rAttribs.getString( O_TOKEN( hralign ), "left" );
        mrTypeModel.moWrapType = "topAndBottom";
    }

    // stroke settings (may be overridden by v:stroke element later)
    mrTypeModel.maStrokeModel.moStroked = lclDecodeBool( rAttribs, XML_stroked );
    mrTypeModel.maStrokeModel.moColor = rAttribs.getString( XML_strokecolor );
    mrTypeModel.maStrokeModel.moWeight = rAttribs.getString( XML_strokeweight );

    // fill settings (may be overridden by v:fill element later)
    mrTypeModel.maFillModel.moFilled = lclDecodeBool( rAttribs, XML_filled );
    mrTypeModel.maFillModel.moColor = rAttribs.getString( XML_fillcolor );

    // For roundrect we may have an arcsize attribute to read
    mrTypeModel.maArcsize = rAttribs.getString(XML_arcsize, OUString());
    // editas
    mrTypeModel.maEditAs = rAttribs.getString(XML_editas, OUString());

    mrTypeModel.maAdjustments = rAttribs.getString(XML_adj, OUString());
}

ContextHandlerRef ShapeTypeContext::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
    if( isRootElement() ) switch( nElement )
    {
        case VML_TOKEN( stroke ):
            mrTypeModel.maStrokeModel.moStroked.assignIfUsed( lclDecodeBool( rAttribs, XML_on ) );
            mrTypeModel.maStrokeModel.maStartArrow.moArrowType = rAttribs.getToken( XML_startarrow );
            mrTypeModel.maStrokeModel.maStartArrow.moArrowWidth = rAttribs.getToken( XML_startarrowwidth );
            mrTypeModel.maStrokeModel.maStartArrow.moArrowLength = rAttribs.getToken( XML_startarrowlength );
            mrTypeModel.maStrokeModel.maEndArrow.moArrowType = rAttribs.getToken( XML_endarrow );
            mrTypeModel.maStrokeModel.maEndArrow.moArrowWidth = rAttribs.getToken( XML_endarrowwidth );
            mrTypeModel.maStrokeModel.maEndArrow.moArrowLength = rAttribs.getToken( XML_endarrowlength );
            mrTypeModel.maStrokeModel.moColor.assignIfUsed( rAttribs.getString( XML_color ) );
            mrTypeModel.maStrokeModel.moOpacity = lclDecodeOpacity( rAttribs, XML_opacity, 1.0 );
            mrTypeModel.maStrokeModel.moWeight.assignIfUsed( rAttribs.getString( XML_weight ) );
            mrTypeModel.maStrokeModel.moDashStyle = rAttribs.getString( XML_dashstyle );
            mrTypeModel.maStrokeModel.moLineStyle = rAttribs.getToken( XML_linestyle );
            mrTypeModel.maStrokeModel.moEndCap = rAttribs.getToken( XML_endcap );
            mrTypeModel.maStrokeModel.moJoinStyle = rAttribs.getToken( XML_joinstyle );
        break;
        case VML_TOKEN( fill ):
        {
            // in DOCX shapes use r:id for the relationship id
            // in XLSX they use o:relid
            bool bHasORelId = rAttribs.hasAttribute( O_TOKEN(relid) );
            mrTypeModel.maFillModel.moFilled.assignIfUsed( lclDecodeBool( rAttribs, XML_on ) );
            mrTypeModel.maFillModel.moColor.assignIfUsed( rAttribs.getString( XML_color ) );
            mrTypeModel.maFillModel.moOpacity = lclDecodeOpacity( rAttribs, XML_opacity, 1.0 );
            mrTypeModel.maFillModel.moColor2 = rAttribs.getString( XML_color2 );
            mrTypeModel.maFillModel.moOpacity2 = lclDecodeOpacity( rAttribs, XML_opacity2, 1.0 );
            mrTypeModel.maFillModel.moType = rAttribs.getToken( XML_type );
            mrTypeModel.maFillModel.moAngle = rAttribs.getInteger( XML_angle );
            mrTypeModel.maFillModel.moFocus = lclDecodePercent( rAttribs, XML_focus, 0.0 );
            mrTypeModel.maFillModel.moFocusPos = lclDecodePercentPair( rAttribs, XML_focusposition );
            mrTypeModel.maFillModel.moFocusSize = lclDecodePercentPair( rAttribs, XML_focussize );
            mrTypeModel.maFillModel.moBitmapPath = decodeFragmentPath( rAttribs, bHasORelId ? O_TOKEN(relid) : R_TOKEN(id) );
            mrTypeModel.maFillModel.moRotate = lclDecodeBool( rAttribs, XML_rotate );
            break;
        }
        case VML_TOKEN( imagedata ):
        {
            // shapes in docx use r:id for the relationship id
            // in xlsx it they use o:relid
            bool bHasORelId = rAttribs.hasAttribute( O_TOKEN( relid ) );
            mrTypeModel.moGraphicPath = decodeFragmentPath( rAttribs, bHasORelId ? O_TOKEN( relid ) : R_TOKEN( id ) );
            mrTypeModel.moGraphicTitle = rAttribs.getString( O_TOKEN( title ) );

            // Get crop attributes.
            mrTypeModel.moCropBottom = rAttribs.getString(XML_cropbottom);
            mrTypeModel.moCropLeft = rAttribs.getString(XML_cropleft);
            mrTypeModel.moCropRight = rAttribs.getString(XML_cropright);
            mrTypeModel.moCropTop = rAttribs.getString(XML_croptop);

            // Gain / contrast.
            OptValue<OUString> oGain = rAttribs.getString(XML_gain);
            sal_Int32 nGain = 0x10000;
            if (oGain.has() && oGain.get().endsWith("f"))
            {
                nGain = oGain.get().toInt32();
            }
            if (nGain < 0x10000)
            {
                nGain *= 101; // 100 + 1 to round
                nGain /= 0x10000;
                nGain -= 100;
            }
            mrTypeModel.mnGain = nGain;

            // Blacklevel / brightness.
            OptValue<OUString> oBlacklevel = rAttribs.getString(XML_blacklevel);
            sal_Int16 nBlacklevel = 0;
            if (oBlacklevel.has() && oBlacklevel.get().endsWith("f"))
            {
                nBlacklevel = oBlacklevel.get().toInt32();
            }
            if (nBlacklevel != 0)
            {
                nBlacklevel /= 327;
            }
            mrTypeModel.mnBlacklevel = nBlacklevel;
        }
        break;
        case NMSP_vmlWord | XML_wrap:
            mrTypeModel.moWrapAnchorX = rAttribs.getString(XML_anchorx);
            mrTypeModel.moWrapAnchorY = rAttribs.getString(XML_anchory);
            mrTypeModel.moWrapType = rAttribs.getString(XML_type);
            mrTypeModel.moWrapSide = rAttribs.getString(XML_side);
        break;
        case VML_TOKEN( shadow ):
        {
            mrTypeModel.maShadowModel.mbHasShadow = true;
            mrTypeModel.maShadowModel.moShadowOn = lclDecodeBool(rAttribs, XML_on).get(false);
            mrTypeModel.maShadowModel.moColor.assignIfUsed(rAttribs.getString(XML_color));
            mrTypeModel.maShadowModel.moOffset.assignIfUsed(rAttribs.getString(XML_offset));
            mrTypeModel.maShadowModel.moOpacity = lclDecodePercent(rAttribs, XML_opacity, 1.0);
        }
        break;
        case VML_TOKEN( textpath ):
            mrTypeModel.maTextpathModel.moString.assignIfUsed(rAttribs.getString(XML_string));
            mrTypeModel.maTextpathModel.moStyle.assignIfUsed(rAttribs.getString(XML_style));
            mrTypeModel.maTextpathModel.moTrim.assignIfUsed(lclDecodeBool(rAttribs, XML_trim));
        break;
    }
    return nullptr;
}

OptValue< OUString > ShapeTypeContext::decodeFragmentPath( const AttributeList& rAttribs, sal_Int32 nToken ) const
{
    OptValue< OUString > oFragmentPath;
    OptValue< OUString > oRelId = rAttribs.getString( nToken );
    if( oRelId.has() )
        oFragmentPath = getFragmentPathFromRelId( oRelId.get() );
    return oFragmentPath;
}

void ShapeTypeContext::setStyle( std::u16string_view rStyle )
{
    sal_Int32 nIndex = 0;
    while( nIndex >= 0 )
    {
        std::u16string_view aName, aValue;
        if( ConversionHelper::separatePair( aName, aValue, o3tl::getToken(rStyle, 0, ';', nIndex ), ':' ) )
        {
            if( aName == u"position" )      mrTypeModel.maPosition = aValue;
            else if( aName == u"z-index" )        mrTypeModel.maZIndex = aValue;
            else if( aName == u"left" )           mrTypeModel.maLeft = aValue;
            else if( aName == u"top" )            mrTypeModel.maTop = aValue;
            else if( aName == u"width" )          mrTypeModel.maWidth = aValue;
            else if( aName == u"height" )         mrTypeModel.maHeight = aValue;
            else if( aName == u"margin-left" )    mrTypeModel.maMarginLeft = aValue;
            else if( aName == u"margin-top" )     mrTypeModel.maMarginTop = aValue;
            else if( aName == u"mso-position-vertical-relative" )  mrTypeModel.maPositionVerticalRelative = aValue;
            else if( aName == u"mso-position-horizontal-relative" )  mrTypeModel.maPositionHorizontalRelative = aValue;
            else if( aName == u"mso-position-horizontal" ) mrTypeModel.maPositionHorizontal = aValue;
            else if( aName == u"mso-position-vertical" ) mrTypeModel.maPositionVertical = aValue;
            else if( aName == u"mso-width-percent" ) mrTypeModel.maWidthPercent = aValue;
            else if( aName == u"mso-width-relative" ) mrTypeModel.maWidthRelative = aValue;
            else if( aName == u"mso-height-percent" ) mrTypeModel.maHeightPercent = aValue;
            else if( aName == u"mso-height-relative" ) mrTypeModel.maHeightRelative = aValue;
            else if( aName == u"mso-fit-shape-to-text" )           mrTypeModel.mbAutoHeight = true;
            else if( aName == u"rotation" )       mrTypeModel.maRotation = aValue;
            else if( aName == u"flip" )       mrTypeModel.maFlip = aValue;
            else if( aName == u"visibility" )
                mrTypeModel.mbVisible = aValue != u"hidden";
            else if( aName == u"mso-wrap-style" ) mrTypeModel.maWrapStyle = aValue;
            else if ( aName == u"v-text-anchor" ) mrTypeModel.maVTextAnchor = aValue;
            else if ( aName == u"mso-wrap-distance-left" ) mrTypeModel.maWrapDistanceLeft = aValue;
            else if ( aName == u"mso-wrap-distance-right" ) mrTypeModel.maWrapDistanceRight = aValue;
            else if ( aName == u"mso-wrap-distance-top" ) mrTypeModel.maWrapDistanceTop = aValue;
            else if ( aName == u"mso-wrap-distance-bottom" ) mrTypeModel.maWrapDistanceBottom = aValue;
        }
    }
}

ShapeContext::ShapeContext(ContextHandler2Helper const& rParent,
                           const std::shared_ptr<ShapeBase>& pShape, const AttributeList& rAttribs)
    : ShapeTypeContext(rParent, pShape, rAttribs)
    , mrShape(*pShape)
    , mrShapeModel(pShape->getShapeModel())
{
    // collect shape specific attributes
    mrShapeModel.maType = rAttribs.getXString( XML_type, OUString() );
    // polyline path
    setPoints( rAttribs.getString( XML_points, OUString() ) );
    // line start and end positions
    setFrom(rAttribs.getString(XML_from, OUString()));
    setTo(rAttribs.getString(XML_to, OUString()));
    setControl1(rAttribs.getString(XML_control1, OUString()));
    setControl2(rAttribs.getString(XML_control2, OUString()));
    setVmlPath(rAttribs.getString(XML_path, OUString()));
    setHyperlink(rAttribs.getString(XML_href, OUString()));
}

ContextHandlerRef ShapeContext::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
    // Excel specific shape client data
    if( isRootElement() ) switch( nElement )
    {
        case VML_TOKEN( textbox ):
        {
            // Calculate the shape type: map both <rect> and <v:shape> with a textbox shape type to
            // a TextShape.
            sal_Int32 nShapeType = 0;
            if (ShapeContainer* pShapeContainer = mrShape.getContainer())
            {
                OUString aType = mrShapeModel.maType;
                if (!aType.isEmpty() && aType[0] == '#')
                {
                    aType = aType.copy(1);
                }
                if (const ShapeType* pShapeType = pShapeContainer->getShapeTypeById(aType))
                {
                    nShapeType = pShapeType->getTypeModel().moShapeType.get();
                }
            }
            mrShapeModel.mbInGroup = (getParentElement() == VML_TOKEN(group));

            // FIXME: the shape with textbox should be used for the next cases
            if (getCurrentElement() == VML_TOKEN(rect) || nShapeType == ESCHER_ShpInst_TextBox)
            {
                if (mrShapeModel.mbInGroup)
                    // FIXME: without this a text will be added into the group-shape instead of its
                    // parent shape
                    dynamic_cast<SimpleShape&>(mrShape).setService("com.sun.star.drawing.TextShape");
                else
                    // FIXME: without this we does not handle some properties like shadow
                    dynamic_cast<SimpleShape&>(mrShape).setService("com.sun.star.text.TextFrame");
            }
            return new TextBoxContext( *this, mrShapeModel.createTextBox(mrShape.getTypeModel()), rAttribs,
                mrShape.getDrawing().getFilter().getGraphicHelper());
        }
        case VMLX_TOKEN( ClientData ):
            // tdf#41466 ActiveX control shapes with a textbox are transformed into a frame
            // (see unit test testActiveXOptionButtonGroup)
            dynamic_cast<SimpleShape&>(mrShape).setService("com.sun.star.text.TextFrame");
            return new ClientDataContext( *this, mrShapeModel.createClientData(), rAttribs );
        case VMLPPT_TOKEN( textdata ):
            // Force RectangleShape, this is ugly :(
            // and is there because of the lines above which change it to TextFrame
            dynamic_cast< SimpleShape& >( mrShape ).setService(
                    "com.sun.star.drawing.RectangleShape");
            mrShapeModel.maLegacyDiagramPath = getFragmentPathFromRelId(rAttribs.getString(XML_id, OUString()));
            break;
        case O_TOKEN( signatureline ):
            mrShapeModel.mbIsSignatureLine = true;
            mrShapeModel.maSignatureId = rAttribs.getString(XML_id, OUString());
            mrShapeModel.maSignatureLineSuggestedSignerName
                = rAttribs.getString(O_TOKEN(suggestedsigner), OUString());
            mrShapeModel.maSignatureLineSuggestedSignerTitle
                = rAttribs.getString(O_TOKEN(suggestedsigner2), OUString());
            mrShapeModel.maSignatureLineSuggestedSignerEmail
                = rAttribs.getString(O_TOKEN(suggestedsigneremail), OUString());
            mrShapeModel.maSignatureLineSigningInstructions
                = rAttribs.getString(O_TOKEN(signinginstructions), OUString());
            mrShapeModel.mbSignatureLineShowSignDate = ConversionHelper::decodeBool(
                rAttribs.getString(XML_showsigndate, "t")); // default is true
            mrShapeModel.mbSignatureLineCanAddComment = ConversionHelper::decodeBool(
                rAttribs.getString(XML_allowcomments, "f")); // default is false
            break;
        case O_TOKEN( lock ):
            // TODO
            break;
    }
    // handle remaining stuff in base class
    return ShapeTypeContext::onCreateContext( nElement, rAttribs );
}

void ShapeContext::setPoints(std::u16string_view rPoints)
{
    mrShapeModel.maPoints.clear();
    sal_Int32 nIndex = 0;

    while (nIndex >= 0)
    {
        sal_Int32 nX = ConversionHelper::decodeMeasureToTwip(
            mrShape.getDrawing().getFilter().getGraphicHelper(), o3tl::getToken(rPoints, 0, ',', nIndex),
            0, true, true);
        sal_Int32 nY = ConversionHelper::decodeMeasureToTwip(
            mrShape.getDrawing().getFilter().getGraphicHelper(), o3tl::getToken(rPoints, 0, ',', nIndex),
            0, false, true);
        mrShapeModel.maPoints.emplace_back(nX, nY);
    }
    // VML polyline has no size in its style attribute. Word writes the size to attribute
    // coordsize with values in twip but without unit. For others we get size from points.
    if (!mrShape.getTypeModel().maWidth.isEmpty() || !mrShape.getTypeModel().maHeight.isEmpty())
        return;

    if (mrShape.getTypeModel().moCoordSize.has())
    {
        double fWidth = mrShape.getTypeModel().moCoordSize.get().first;
        fWidth = o3tl::convert(fWidth, o3tl::Length::twip, o3tl::Length::pt);
        double fHeight = mrShape.getTypeModel().moCoordSize.get().second;
        fHeight = o3tl::convert(fHeight, o3tl::Length::twip, o3tl::Length::pt);
        mrShape.getTypeModel().maWidth = OUString::number(fWidth) + "pt";
        mrShape.getTypeModel().maHeight = OUString::number(fHeight) + "pt";
    }
    else if (mrShapeModel.maPoints.size())
    {
        double fMinX = mrShapeModel.maPoints[0].X;
        double fMaxX = mrShapeModel.maPoints[0].X;
        double fMinY = mrShapeModel.maPoints[0].Y;
        double fMaxY = mrShapeModel.maPoints[0].Y;
        for (const auto& rPoint : mrShapeModel.maPoints)
        {
            if (rPoint.X < fMinX)
                fMinX = rPoint.X;
            else if (rPoint.X > fMaxX)
                fMaxX = rPoint.X;
            if (rPoint.Y < fMinY)
                fMinY = rPoint.Y;
            else if (rPoint.Y > fMaxY)
                fMaxY = rPoint.Y;
        }
        mrShape.getTypeModel().maWidth
            = OUString::number(
                  o3tl::convert(fMaxX - fMinX, o3tl::Length::twip, o3tl::Length::pt))
              + "pt";
        mrShape.getTypeModel().maHeight
            = OUString::number(
                  o3tl::convert(fMaxY - fMinY, o3tl::Length::twip, o3tl::Length::pt))
              + "pt";
        // Set moCoordSize, otherwise default (1000,1000) is used.
        mrShape.getTypeModel().moCoordSize.set(
            Int32Pair(basegfx::fround(fMaxX - fMinX), basegfx::fround(fMaxY - fMinY)));
    }
}

void ShapeContext::setFrom( const OUString& rPoints )
{
    if (!rPoints.isEmpty())
        mrShapeModel.maFrom = rPoints;
}

void ShapeContext::setTo( const OUString& rPoints )
{
    if (!rPoints.isEmpty())
        mrShapeModel.maTo = rPoints;
}

void ShapeContext::setControl1( const OUString& rPoints )
{
    if (!rPoints.isEmpty())
        mrShapeModel.maControl1 = rPoints;
}

void ShapeContext::setControl2( const OUString& rPoints )
{
    if (!rPoints.isEmpty())
        mrShapeModel.maControl2 = rPoints;
}
void ShapeContext::setVmlPath( const OUString& rPath )
{
    if (!rPath.isEmpty())
        mrShapeModel.maVmlPath = rPath;
}

void ShapeContext::setHyperlink( const OUString& rHyperlink )
{
    if (!rHyperlink.isEmpty())
        mrShapeModel.maHyperlink = rHyperlink;
}

GroupShapeContext::GroupShapeContext(ContextHandler2Helper const& rParent,
                                     const std::shared_ptr<GroupShape>& pShape,
                                     const AttributeList& rAttribs)
    : ShapeContext(rParent, pShape, rAttribs)
    , mrShapes(pShape->getChildren())
{
}

ContextHandlerRef GroupShapeContext::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
    // try to create a context of an embedded shape
    ContextHandlerRef xContext = createShapeContext( *this, mrShapes, nElement, rAttribs );
    // handle remaining stuff of this shape in base class
    return xContext ? xContext : ShapeContext::onCreateContext( nElement, rAttribs );
}

RectangleShapeContext::RectangleShapeContext(ContextHandler2Helper const& rParent,
                                             const AttributeList& rAttribs,
                                             const std::shared_ptr<RectangleShape>& pShape)
    : ShapeContext(rParent, pShape, rAttribs)
{
}

ContextHandlerRef RectangleShapeContext::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
    // The parent class's context is fine
    return ShapeContext::onCreateContext( nElement, rAttribs );
}

ControlShapeContext::ControlShapeContext( ::oox::core::ContextHandler2Helper const & rParent, ShapeContainer& rShapes, const AttributeList& rAttribs )
    : ShapeContextBase (rParent)
{
    ::oox::vml::ControlInfo aInfo;
    aInfo.maShapeId = rAttribs.getXString( W_TOKEN( shapeid ), OUString() );
    aInfo.maFragmentPath = getFragmentPathFromRelId(rAttribs.getString( R_TOKEN(id), OUString() ));
    aInfo.maName = rAttribs.getString( W_TOKEN( name ), OUString() );
    aInfo.mbTextContentShape = true;
    rShapes.getDrawing().registerControl(aInfo);
}

} // namespace oox

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */