Bump version to 24.04.3.4
[LibreOffice.git] / oox / source / vml / vmlformatting.cxx
blob5fb422e63b9df544b9e6c629d1ef90afca06fda3
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include <cstdlib>
24 #include <oox/vml/vmlformatting.hxx>
26 #include <com/sun/star/beans/PropertyValue.hpp>
27 #include <com/sun/star/beans/XPropertySet.hpp>
28 #include <com/sun/star/drawing/XShape.hpp>
29 #include <com/sun/star/drawing/EnhancedCustomShapeTextPathMode.hpp>
30 #include <com/sun/star/table/ShadowFormat.hpp>
31 #include <com/sun/star/text/XTextRange.hpp>
33 #include <o3tl/float_int_conversion.hxx>
34 #include <o3tl/unit_conversion.hxx>
35 #include <rtl/strbuf.hxx>
36 #include <sal/log.hxx>
37 #include <osl/diagnose.h>
38 #include <oox/drawingml/color.hxx>
39 #include <oox/drawingml/drawingmltypes.hxx>
40 #include <drawingml/fillproperties.hxx>
41 #include <drawingml/lineproperties.hxx>
42 #include <oox/drawingml/shapepropertymap.hxx>
43 #include <oox/helper/attributelist.hxx>
44 #include <oox/helper/graphichelper.hxx>
45 #include <oox/token/properties.hxx>
46 #include <oox/token/tokens.hxx>
47 #include <svx/svdtrans.hxx>
48 #include <comphelper/propertysequence.hxx>
49 #include <o3tl/string_view.hxx>
50 #include <svx/xbitmap.hxx>
51 #include <vcl/BitmapTools.hxx>
52 #include <vcl/virdev.hxx>
54 namespace oox::vml {
56 using namespace ::com::sun::star;
57 using namespace ::com::sun::star::geometry;
59 using ::oox::drawingml::Color;
60 using ::oox::drawingml::FillProperties;
61 using ::oox::drawingml::LineArrowProperties;
62 using ::oox::drawingml::LineProperties;
63 using ::oox::drawingml::ShapePropertyMap;
64 using ::com::sun::star::awt::Point;
65 using ::com::sun::star::drawing::PolygonFlags;
66 using ::com::sun::star::drawing::PolygonFlags_NORMAL;
67 using ::com::sun::star::drawing::PolygonFlags_CONTROL;
69 namespace {
71 bool lclExtractDouble( double& orfValue, size_t& ornEndPos, std::u16string_view aValue )
73 // extract the double value and find start position of unit characters
74 rtl_math_ConversionStatus eConvStatus = rtl_math_ConversionStatus_Ok;
75 sal_Int32 nEndPos;
76 orfValue = ::rtl::math::stringToDouble( aValue, '.', '\0', &eConvStatus, &nEndPos );
77 ornEndPos = nEndPos;
78 return eConvStatus == rtl_math_ConversionStatus_Ok;
81 } // namespace
83 bool ConversionHelper::separatePair( std::u16string_view& orValue1, std::u16string_view& orValue2,
84 std::u16string_view rValue, sal_Unicode cSep )
86 size_t nSepPos = rValue.find( cSep );
87 if( nSepPos != std::u16string_view::npos )
89 orValue1 = o3tl::trim(rValue.substr( 0, nSepPos ));
90 orValue2 = o3tl::trim(rValue.substr( nSepPos + 1 ));
92 else
94 orValue1 = o3tl::trim(rValue);
95 orValue2 = std::u16string_view();
97 return !orValue1.empty() && !orValue2.empty();
100 bool ConversionHelper::decodeBool( std::u16string_view rValue )
102 sal_Int32 nToken = AttributeConversion::decodeToken( rValue );
103 // anything else than 't' or 'true' is considered to be false, as specified
104 return (nToken == XML_t) || (nToken == XML_true);
107 double ConversionHelper::decodePercent( std::u16string_view rValue, double fDefValue )
109 if( rValue.empty() )
110 return fDefValue;
112 double fValue = 0.0;
113 size_t nEndPos = 0;
114 if( !lclExtractDouble( fValue, nEndPos, rValue ) )
115 return fDefValue;
117 if( nEndPos == rValue.size() )
118 return fValue;
120 if( (nEndPos + 1 == rValue.size()) && (rValue[ nEndPos ] == '%') )
121 return fValue / 100.0;
123 if( (nEndPos + 1 == rValue.size()) && (rValue[ nEndPos ] == 'f') )
124 return fValue / 65536.0;
126 OSL_FAIL( "ConversionHelper::decodePercent - unknown measure unit" );
127 return fDefValue;
130 Degree100 ConversionHelper::decodeRotation( std::u16string_view rValue )
132 if( rValue.empty() )
133 return 0_deg100;
135 double fValue = 0.0;
136 double fRotation = 0.0;
137 size_t nEndPos = 0;
138 if( !lclExtractDouble(fValue, nEndPos, rValue) )
139 return 0_deg100;
141 if( nEndPos == rValue.size() )
142 fRotation = fValue;
143 else if( (nEndPos + 2 == rValue.size()) && (rValue[nEndPos] == 'f') && (rValue[nEndPos+1] == 'd') )
144 fRotation = fValue / 65536.0;
145 else
147 OSL_FAIL("ConversionHelper::decodeRotation - unknown measure unit");
148 return 0_deg100;
151 return NormAngle36000(Degree100(static_cast<sal_Int32>(fRotation * -100)));
154 sal_Int64 ConversionHelper::decodeMeasureToEmu( const GraphicHelper& rGraphicHelper,
155 std::u16string_view rValue, sal_Int32 nRefValue, bool bPixelX, bool bDefaultAsPixel )
157 // default for missing values is 0
158 if( rValue.empty() )
159 return 0;
161 // TODO: according to spec, value may contain "auto"
162 if ( rValue == u"auto" )
164 OSL_FAIL( "ConversionHelper::decodeMeasureToEmu - special value 'auto' must be handled by caller" );
165 return nRefValue;
168 // extract the double value and find start position of unit characters
169 double fValue = 0.0;
170 size_t nEndPos = 0;
171 if( !lclExtractDouble( fValue, nEndPos, rValue ) || (fValue == 0.0) )
172 return 0;
174 // process trailing unit, convert to EMU
175 std::u16string_view aUnit;
176 if( (0 < nEndPos) && (nEndPos < rValue.size()) )
177 aUnit = rValue.substr( nEndPos );
178 else if( bDefaultAsPixel )
179 aUnit = u"px";
180 // else default is EMU
182 if( aUnit.size() == 2 )
184 sal_Unicode cChar1 = aUnit[ 0 ];
185 sal_Unicode cChar2 = aUnit[ 1 ];
186 if ((cChar1 == 'i') && (cChar2 == 'n'))
187 fValue = o3tl::convert(fValue, o3tl::Length::in, o3tl::Length::emu);
188 else if ((cChar1 == 'c') && (cChar2 == 'm'))
189 fValue = o3tl::convert(fValue, o3tl::Length::cm, o3tl::Length::emu);
190 else if ((cChar1 == 'm') && (cChar2 == 'm'))
191 fValue = o3tl::convert(fValue, o3tl::Length::mm, o3tl::Length::emu);
192 else if ((cChar1 == 'p') && (cChar2 == 't'))
193 fValue = o3tl::convert(fValue, o3tl::Length::pt, o3tl::Length::emu);
194 else if ((cChar1 == 'p') && (cChar2 == 'c'))
195 fValue = o3tl::convert(fValue, o3tl::Length::pc, o3tl::Length::emu);
196 else if( (cChar1 == 'p') && (cChar2 == 'x') ) // 1 pixel, dependent on output device
197 fValue = o3tl::convert(bPixelX ? rGraphicHelper.convertScreenPixelXToHmm(fValue)
198 : rGraphicHelper.convertScreenPixelYToHmm(fValue),
199 o3tl::Length::mm100, o3tl::Length::emu);
201 else if( (aUnit.size() == 1) && (aUnit[ 0 ] == '%') )
203 fValue *= nRefValue / 100.0;
205 else if( bDefaultAsPixel || !aUnit.empty() ) // default as EMU and no unit -> do nothing
207 OSL_FAIL( "ConversionHelper::decodeMeasureToEmu - unknown measure unit" );
208 fValue = nRefValue;
210 return o3tl::saturating_cast< sal_Int64 >( fValue + 0.5 );
213 sal_Int32 ConversionHelper::decodeMeasureToHmm( const GraphicHelper& rGraphicHelper,
214 std::u16string_view rValue, sal_Int32 nRefValue, bool bPixelX, bool bDefaultAsPixel )
216 return ::oox::drawingml::convertEmuToHmm( decodeMeasureToEmu( rGraphicHelper, rValue, nRefValue, bPixelX, bDefaultAsPixel ) );
219 sal_Int32 ConversionHelper::decodeMeasureToTwip(const GraphicHelper& rGraphicHelper,
220 std::u16string_view rValue, sal_Int32 nRefValue,
221 bool bPixelX, bool bDefaultAsPixel)
223 return ::o3tl::convert(
224 decodeMeasureToEmu(rGraphicHelper, rValue, nRefValue, bPixelX, bDefaultAsPixel),
225 o3tl::Length::emu, o3tl::Length::twip);
228 Color ConversionHelper::decodeColor( const GraphicHelper& rGraphicHelper,
229 const std::optional< OUString >& roVmlColor, const std::optional< double >& roVmlOpacity,
230 ::Color nDefaultRgb, ::Color nPrimaryRgb )
232 Color aDmlColor;
234 // convert opacity
235 const sal_Int32 DML_FULL_OPAQUE = ::oox::drawingml::MAX_PERCENT;
236 double fOpacity = roVmlOpacity.value_or( 1.0 );
237 sal_Int32 nOpacity = getLimitedValue< sal_Int32, double >( fOpacity * DML_FULL_OPAQUE, 0, DML_FULL_OPAQUE );
238 if( nOpacity < DML_FULL_OPAQUE )
239 aDmlColor.addTransformation( XML_alpha, nOpacity );
241 // color attribute not present - set passed default color
242 if( !roVmlColor.has_value() )
244 aDmlColor.setSrgbClr( nDefaultRgb );
245 return aDmlColor;
248 // separate leading color name or RGB value from following palette index
249 std::u16string_view aColorName, aColorIndex;
250 separatePair( aColorName, aColorIndex, roVmlColor.value(), ' ' );
252 // RGB colors in the format '#RRGGBB'
253 if( (aColorName.size() == 7) && (aColorName[ 0 ] == '#') )
255 aDmlColor.setSrgbClr( o3tl::toUInt32(aColorName.substr( 1 ), 16) );
256 return aDmlColor;
259 // RGB colors in the format '#RGB'
260 if( (aColorName.size() == 4) && (aColorName[ 0 ] == '#') )
262 sal_Int32 nR = o3tl::toUInt32(aColorName.substr( 1, 1 ), 16 ) * 0x11;
263 sal_Int32 nG = o3tl::toUInt32(aColorName.substr( 2, 1 ), 16 ) * 0x11;
264 sal_Int32 nB = o3tl::toUInt32(aColorName.substr( 3, 1 ), 16 ) * 0x11;
265 aDmlColor.setSrgbClr( (nR << 16) | (nG << 8) | nB );
266 return aDmlColor;
269 /* Predefined color names or system color names (resolve to RGB to detect
270 valid color name). */
271 sal_Int32 nColorToken = AttributeConversion::decodeToken( aColorName );
272 ::Color nRgbValue = Color::getVmlPresetColor( nColorToken, API_RGB_TRANSPARENT );
273 if( nRgbValue == API_RGB_TRANSPARENT )
274 nRgbValue = rGraphicHelper.getSystemColor( nColorToken );
275 if( nRgbValue != API_RGB_TRANSPARENT )
277 aDmlColor.setSrgbClr( nRgbValue );
278 return aDmlColor;
281 // try palette colors enclosed in brackets
282 if( (aColorIndex.size() >= 3) && (aColorIndex[ 0 ] == '[') && (aColorIndex[ aColorIndex.size() - 1 ] == ']') )
284 aDmlColor.setPaletteClr( o3tl::toInt32(aColorIndex.substr( 1, aColorIndex.size() - 2 )) );
285 return aDmlColor;
288 // try fill gradient modificator 'fill <modifier>(<amount>)'
289 if( (nPrimaryRgb != API_RGB_TRANSPARENT) && (nColorToken == XML_fill) )
291 size_t nOpenParen = aColorIndex.find( '(' );
292 size_t nCloseParen = aColorIndex.find( ')' );
293 if( nOpenParen != std::u16string_view::npos && nCloseParen != std::u16string_view::npos &&
294 (2 <= nOpenParen) && (nOpenParen + 1 < nCloseParen) && (nCloseParen + 1 == aColorIndex.size()) )
296 sal_Int32 nModToken = XML_TOKEN_INVALID;
297 switch( AttributeConversion::decodeToken( aColorIndex.substr( 0, nOpenParen ) ) )
299 case XML_darken: nModToken = XML_shade;break;
300 case XML_lighten: nModToken = XML_tint;
302 sal_Int32 nValue = o3tl::toInt32(aColorIndex.substr( nOpenParen + 1, nCloseParen - nOpenParen - 1 ));
303 if( (nModToken != XML_TOKEN_INVALID) && (0 <= nValue) && (nValue < 255) )
305 /* Simulate this modifier color by a color with related transformation.
306 The modifier amount has to be converted from the range [0;255] to
307 percentage [0;100000] used by DrawingML. */
308 aDmlColor.setSrgbClr( nPrimaryRgb );
309 aDmlColor.addTransformation( nModToken, static_cast< sal_Int32 >( nValue * ::oox::drawingml::MAX_PERCENT / 255 ) );
310 return aDmlColor;
315 OSL_FAIL( OStringBuffer( "lclGetColor - invalid VML color name '" +
316 OUStringToOString( roVmlColor.value(), RTL_TEXTENCODING_ASCII_US ) + "'" ).getStr() );
317 aDmlColor.setSrgbClr( nDefaultRgb );
318 return aDmlColor;
321 void ConversionHelper::decodeVmlPath( ::std::vector< ::std::vector< Point > >& rPointLists, ::std::vector< ::std::vector< PolygonFlags > >& rFlagLists, std::u16string_view rPath )
323 ::std::vector< sal_Int32 > aCoordList;
324 Point aCurrentPoint;
325 sal_Int32 nTokenStart = 0;
326 sal_Int32 nTokenLen = 0;
327 sal_Int32 nParamCount = 0;
328 bool bCommand = false;
329 enum VML_State { START, MOVE_REL, MOVE_ABS, BEZIER_REL, BEZIER_ABS,
330 LINE_REL, LINE_ABS, CLOSE, END, UNSUPPORTED };
331 VML_State state = START;
333 rPointLists.emplace_back( );
334 rFlagLists.emplace_back( );
336 for ( size_t i = 0; i < rPath.size(); i++ )
338 // Keep track of current integer token
339 if ( ( rPath[ i ] >= '0' && rPath[ i ] <= '9' ) || rPath[ i ] == '-' )
340 nTokenLen++;
341 else if ( rPath[ i ] != ' ' )
343 // Store coordinate from current token
344 if ( state != START && state != UNSUPPORTED )
346 if ( nTokenLen > 0 )
347 aCoordList.push_back( o3tl::toInt32(rPath.substr( nTokenStart, nTokenLen )) );
348 else
349 aCoordList.push_back( 0 );
350 nTokenLen = 0;
353 if (rPath[ i ] == ',' )
355 nParamCount--;
358 // Upon finding the next command code, deal with stored
359 // coordinates for previous command and reset parameters counter if needed.
360 // See http://www.w3.org/TR/NOTE-VML#_Toc416858382 for params count reference
361 if ( rPath[ i ] != ',' || nParamCount == 0 )
363 switch ( state )
365 case MOVE_REL:
366 aCoordList.resize(2, 0); // 2* params -> param count reset
367 if ( !rPointLists.empty() && !rPointLists.back().empty() )
369 rPointLists.emplace_back( );
370 rFlagLists.emplace_back( );
372 rPointLists.back().emplace_back( aCoordList[ 0 ], aCoordList[ 1 ] );
373 rFlagLists.back().push_back( PolygonFlags_NORMAL );
374 aCurrentPoint = rPointLists.back().back();
375 nParamCount = 2;
376 break;
378 case MOVE_ABS:
379 aCoordList.resize(2, 0); // 2 params -> no param count reset
380 if ( !rPointLists.empty() && !rPointLists.back().empty() )
382 rPointLists.emplace_back( );
383 rFlagLists.emplace_back( );
385 rPointLists.back().emplace_back( (aCoordList[ 0 ]), aCoordList[ 1 ] );
386 rFlagLists.back().push_back( PolygonFlags_NORMAL );
387 aCurrentPoint = rPointLists.back().back();
388 break;
390 case BEZIER_REL:
391 aCoordList.resize(6, 0); // 6* params -> param count reset
392 rPointLists.back().emplace_back( aCurrentPoint.X + aCoordList[ 0 ],
393 aCurrentPoint.Y + aCoordList[ 1 ] );
394 rPointLists.back().emplace_back( aCurrentPoint.X + aCoordList[ 2 ],
395 aCurrentPoint.Y + aCoordList[ 3 ] );
396 rPointLists.back().emplace_back( aCurrentPoint.X + aCoordList[ 4 ],
397 aCurrentPoint.Y + aCoordList[ 5 ] );
398 rFlagLists.back().push_back( PolygonFlags_CONTROL );
399 rFlagLists.back().push_back( PolygonFlags_CONTROL );
400 rFlagLists.back().push_back( PolygonFlags_NORMAL );
401 aCurrentPoint = rPointLists.back().back();
402 nParamCount = 6;
403 break;
405 case BEZIER_ABS:
406 aCoordList.resize(6, 0); // 6* params -> param count reset
407 rPointLists.back().emplace_back( aCoordList[ 0 ], aCoordList[ 1 ] );
408 rPointLists.back().emplace_back( aCoordList[ 2 ], aCoordList[ 3 ] );
409 rPointLists.back().emplace_back( aCoordList[ 4 ], aCoordList[ 5 ] );
410 rFlagLists.back().push_back( PolygonFlags_CONTROL );
411 rFlagLists.back().push_back( PolygonFlags_CONTROL );
412 rFlagLists.back().push_back( PolygonFlags_NORMAL );
413 aCurrentPoint = rPointLists.back().back();
414 nParamCount = 6;
415 break;
417 case LINE_REL:
418 aCoordList.resize(2, 0); // 2* params -> param count reset
419 rPointLists.back().emplace_back( aCurrentPoint.X + aCoordList[ 0 ],
420 aCurrentPoint.Y + aCoordList[ 1 ] );
421 rFlagLists.back().push_back( PolygonFlags_NORMAL );
422 aCurrentPoint = rPointLists.back().back();
423 nParamCount = 2;
424 break;
426 case LINE_ABS:
427 aCoordList.resize(2, 0); // 2* params -> param count reset
428 rPointLists.back().emplace_back( aCoordList[ 0 ], (aCoordList.size() > 1 ? aCoordList[ 1 ] : 0) );
429 rFlagLists.back().push_back( PolygonFlags_NORMAL );
430 aCurrentPoint = rPointLists.back().back();
431 nParamCount = 2;
432 break;
434 case CLOSE: // 0 param
435 SAL_WARN_IF(rPointLists.back().empty() || rFlagLists.back().empty(), "oox", "empty pointlists at close");
436 if (!rPointLists.back().empty() && !rFlagLists.back().empty())
438 rPointLists.back().push_back( rPointLists.back()[ 0 ] );
439 rFlagLists.back().push_back( rFlagLists.back()[ 0 ] );
440 aCurrentPoint = rPointLists.back().back();
442 break;
444 case END: // 0 param
445 rPointLists.emplace_back( );
446 rFlagLists.emplace_back( );
447 break;
449 case START:
450 case UNSUPPORTED:
451 break;
454 aCoordList.clear();
457 // Allow two-char commands to peek ahead to the next character
458 sal_Unicode nextChar = '\0';
459 if (i+1 < rPath.size())
460 nextChar = rPath[i+1];
462 // Move to relevant state upon finding a command
463 bCommand = true;
464 switch ( rPath[ i ] )
466 // Single-character commands
467 case 't': // rmoveto
468 state = MOVE_REL; nParamCount = 2; break;
469 case 'm': // moveto
470 state = MOVE_ABS; nParamCount = 2; break;
471 case 'v': // rcurveto
472 state = BEZIER_REL; nParamCount = 6; break;
473 case 'c': // curveto
474 state = BEZIER_ABS; nParamCount = 6; break;
475 case 'r': // rlineto
476 state = LINE_REL; nParamCount = 2; break;
477 case 'l': // lineto
478 state = LINE_ABS; nParamCount = 2; break;
479 case 'x': // close
480 state = CLOSE; break;
481 case 'e': // end
482 state = END; break;
484 // Two-character commands
485 case 'n':
487 switch ( nextChar )
489 case 'f': // nf - nofill
490 case 's': // ns - nostroke
491 state = UNSUPPORTED; i++; break;
493 break;
495 case 'a': // Elliptical curves
497 switch ( nextChar )
499 case 'e': // ae - angleellipseto
500 case 'l': // al - angleellipse
501 state = UNSUPPORTED; i++; break;
502 case 't': // at - arcto
503 case 'r': // ar - arc
504 state = UNSUPPORTED; i++; break;
506 break;
508 case 'w': // Clockwise elliptical arcs
510 switch ( nextChar )
512 case 'a': // wa - clockwisearcto
513 case 'r': // wr - clockwisearc
514 state = UNSUPPORTED; i++; break;
516 break;
518 case 'q':
520 switch ( nextChar )
522 case 'x': // qx - ellipticalquadrantx
523 case 'y': // qy - ellipticalquadranty
524 state = UNSUPPORTED; i++; break;
525 case 'b': // qb - quadraticbezier
526 state = UNSUPPORTED; i++; break;
528 break;
530 case 'h': // behaviour extensions
532 switch ( nextChar )
534 case 'a': // ha - AutoLine
535 case 'b': // hb - AutoCurve
536 case 'c': // hc - CornerLine
537 case 'd': // hd - CornerCurve
538 case 'e': // he - SmoothLine
539 case 'f': // hf - SmoothCurve
540 case 'g': // hg - SymmetricLine
541 case 'h': // hh - SymmetricCurve
542 case 'i': // hi - Freeform
543 state = UNSUPPORTED; i++; break;
545 break;
547 default:
548 bCommand = false;
549 break;
552 if (bCommand) nTokenLen = 0;
553 nTokenStart = i+1;
558 namespace {
560 sal_Int64 lclGetEmu( const GraphicHelper& rGraphicHelper, const std::optional< OUString >& roValue, sal_Int64 nDefValue )
562 return roValue.has_value() ? ConversionHelper::decodeMeasureToEmu( rGraphicHelper, roValue.value(), 0, false, false ) : nDefValue;
565 void lclGetDmlLineDash( std::optional< sal_Int32 >& oroPresetDash, LineProperties::DashStopVector& orCustomDash, const std::optional< OUString >& roDashStyle )
567 if( !roDashStyle.has_value() )
568 return;
570 const OUString& rDashStyle = roDashStyle.value();
571 switch( AttributeConversion::decodeToken( rDashStyle ) )
573 case XML_solid: oroPresetDash = XML_solid; return;
574 case XML_shortdot: oroPresetDash = XML_sysDot; return;
575 case XML_shortdash: oroPresetDash = XML_sysDash; return;
576 case XML_shortdashdot: oroPresetDash = XML_sysDashDot; return;
577 case XML_shortdashdotdot: oroPresetDash = XML_sysDashDotDot; return;
578 case XML_dot: oroPresetDash = XML_dot; return;
579 case XML_dash: oroPresetDash = XML_dash; return;
580 case XML_dashdot: oroPresetDash = XML_dashDot; return;
581 case XML_longdash: oroPresetDash = XML_lgDash; return;
582 case XML_longdashdot: oroPresetDash = XML_lgDashDot; return;
583 case XML_longdashdotdot: oroPresetDash = XML_lgDashDotDot; return;
585 // try to convert user-defined dash style
586 default:
588 ::std::vector< sal_Int32 > aValues;
589 sal_Int32 nIndex = 0;
590 while( nIndex >= 0 )
591 aValues.push_back( o3tl::toInt32(o3tl::getToken(rDashStyle, 0, ' ', nIndex )) );
592 size_t nPairs = aValues.size() / 2; // ignore last value if size is odd
593 for( size_t nPairIdx = 0; nPairIdx < nPairs; ++nPairIdx )
594 orCustomDash.emplace_back( aValues[ 2 * nPairIdx ], aValues[ 2 * nPairIdx + 1 ] );
599 sal_Int32 lclGetDmlArrowType( const std::optional< sal_Int32 >& roArrowType )
601 if( roArrowType.has_value() ) switch( roArrowType.value() )
603 case XML_none: return XML_none;
604 case XML_block: return XML_triangle;
605 case XML_classic: return XML_stealth;
606 case XML_diamond: return XML_diamond;
607 case XML_oval: return XML_oval;
608 case XML_open: return XML_arrow;
610 return XML_none;
613 sal_Int32 lclGetDmlArrowWidth( const std::optional< sal_Int32 >& roArrowWidth )
615 if( roArrowWidth.has_value() ) switch( roArrowWidth.value() )
617 case XML_narrow: return XML_sm;
618 case XML_medium: return XML_med;
619 case XML_wide: return XML_lg;
621 return XML_med;
624 sal_Int32 lclGetDmlArrowLength( const std::optional< sal_Int32 >& roArrowLength )
626 if( roArrowLength.has_value() ) switch( roArrowLength.value() )
628 case XML_short: return XML_sm;
629 case XML_medium: return XML_med;
630 case XML_long: return XML_lg;
632 return XML_med;
635 void lclConvertArrow( LineArrowProperties& orArrowProp, const StrokeArrowModel& rStrokeArrow )
637 orArrowProp.moArrowType = lclGetDmlArrowType( rStrokeArrow.moArrowType );
638 orArrowProp.moArrowWidth = lclGetDmlArrowWidth( rStrokeArrow.moArrowWidth );
639 orArrowProp.moArrowLength = lclGetDmlArrowLength( rStrokeArrow.moArrowLength );
642 sal_Int32 lclGetDmlLineCompound( const std::optional< sal_Int32 >& roLineStyle )
644 if( roLineStyle.has_value() ) switch( roLineStyle.value() )
646 case XML_single: return XML_sng;
647 case XML_thinThin: return XML_dbl;
648 case XML_thinThick: return XML_thinThick;
649 case XML_thickThin: return XML_thickThin;
650 case XML_thickBetweenThin: return XML_tri;
652 return XML_sng;
655 sal_Int32 lclGetDmlLineCap( const std::optional< sal_Int32 >& roEndCap )
657 if( roEndCap.has_value() ) switch( roEndCap.value() )
659 case XML_flat: return XML_flat;
660 case XML_square: return XML_sq;
661 case XML_round: return XML_rnd;
663 return XML_flat; // different defaults in VML (flat) and DrawingML (square)
666 sal_Int32 lclGetDmlLineJoint( const std::optional< sal_Int32 >& roJoinStyle )
668 if( roJoinStyle.has_value() ) switch( roJoinStyle.value() )
670 case XML_round: return XML_round;
671 case XML_bevel: return XML_bevel;
672 case XML_miter: return XML_miter;
674 return XML_round;
677 } // namespace
679 void StrokeArrowModel::assignUsed( const StrokeArrowModel& rSource )
681 assignIfUsed( moArrowType, rSource.moArrowType );
682 assignIfUsed( moArrowWidth, rSource.moArrowWidth );
683 assignIfUsed( moArrowLength, rSource.moArrowLength );
686 void StrokeModel::assignUsed( const StrokeModel& rSource )
688 assignIfUsed( moStroked, rSource.moStroked );
689 maStartArrow.assignUsed( rSource.maStartArrow );
690 maEndArrow.assignUsed( rSource.maEndArrow );
691 assignIfUsed( moColor, rSource.moColor );
692 assignIfUsed( moOpacity, rSource.moOpacity );
693 assignIfUsed( moWeight, rSource.moWeight );
694 assignIfUsed( moDashStyle, rSource.moDashStyle );
695 assignIfUsed( moLineStyle, rSource.moLineStyle );
696 assignIfUsed( moEndCap, rSource.moEndCap );
697 assignIfUsed( moJoinStyle, rSource.moJoinStyle );
700 void StrokeModel::pushToPropMap( ShapePropertyMap& rPropMap, const GraphicHelper& rGraphicHelper ) const
702 /* Convert VML line formatting to DrawingML line formatting and let the
703 DrawingML code do the hard work. */
704 LineProperties aLineProps;
706 if( moStroked.value_or( true ) )
708 aLineProps.maLineFill.moFillType = XML_solidFill;
709 lclConvertArrow( aLineProps.maStartArrow, maStartArrow );
710 lclConvertArrow( aLineProps.maEndArrow, maEndArrow );
711 aLineProps.maLineFill.maFillColor = ConversionHelper::decodeColor( rGraphicHelper, moColor, moOpacity, API_RGB_BLACK );
712 aLineProps.moLineWidth = getLimitedValue< sal_Int32, sal_Int64 >( lclGetEmu( rGraphicHelper, moWeight, 1 ), 0, SAL_MAX_INT32 );
713 lclGetDmlLineDash( aLineProps.moPresetDash, aLineProps.maCustomDash, moDashStyle );
714 aLineProps.moLineCompound = lclGetDmlLineCompound( moLineStyle );
715 aLineProps.moLineCap = lclGetDmlLineCap( moEndCap );
716 aLineProps.moLineJoint = lclGetDmlLineJoint( moJoinStyle );
718 else
720 aLineProps.maLineFill.moFillType = XML_noFill;
723 aLineProps.pushToPropMap( rPropMap, rGraphicHelper );
726 void FillModel::assignUsed( const FillModel& rSource )
728 assignIfUsed( moFilled, rSource.moFilled );
729 assignIfUsed( moColor, rSource.moColor );
730 assignIfUsed( moOpacity, rSource.moOpacity );
731 assignIfUsed( moColor2, rSource.moColor2 );
732 assignIfUsed( moOpacity2, rSource.moOpacity2 );
733 assignIfUsed( moType, rSource.moType );
734 assignIfUsed( moAngle, rSource.moAngle );
735 assignIfUsed( moFocus, rSource.moFocus );
736 assignIfUsed( moFocusPos, rSource.moFocusPos );
737 assignIfUsed( moFocusSize, rSource.moFocusSize );
738 assignIfUsed( moBitmapPath, rSource.moBitmapPath );
739 assignIfUsed( moRotate, rSource.moRotate );
742 static void lcl_setGradientStop( std::multimap< double, Color >& rMap, const double fKey, const Color& rValue ) {
743 auto aElement = rMap.find( fKey );
745 if (aElement != rMap.end())
746 aElement->second = rValue;
747 else
748 rMap.emplace( fKey, rValue );
751 void FillModel::pushToPropMap( ShapePropertyMap& rPropMap, const GraphicHelper& rGraphicHelper ) const
753 /* Convert VML fill formatting to DrawingML fill formatting and let the
754 DrawingML code do the hard work. */
755 FillProperties aFillProps;
757 if( moFilled.value_or( true ) )
759 sal_Int32 nFillType = moType.value_or( XML_solid );
760 switch( nFillType )
762 case XML_gradient:
763 case XML_gradientRadial:
765 aFillProps.moFillType = XML_gradFill;
766 aFillProps.maGradientProps.moRotateWithShape = moRotate.value_or( false );
767 double fFocus = moFocus.value_or( 0.0 );
769 // prepare colors
770 Color aColor1 = ConversionHelper::decodeColor( rGraphicHelper, moColor, moOpacity, API_RGB_WHITE );
771 Color aColor2 = ConversionHelper::decodeColor( rGraphicHelper, moColor2, moOpacity2, API_RGB_WHITE, aColor1.getColor( rGraphicHelper ) );
773 // type XML_gradient is linear or axial gradient
774 if( nFillType == XML_gradient )
776 // normalize angle to range [0;360) degrees
777 sal_Int32 nVmlAngle = getIntervalValue< sal_Int32, sal_Int32 >( moAngle.value_or( 0 ), 0, 360 );
779 // focus of -50% or 50% is axial gradient
780 // so approximate anything with a similar focus by using LO's axial gradient,
781 // (otherwise drop the radial aspect; linear gradient becomes the closest match)
782 if( ((-0.75 <= fFocus) && (fFocus <= -0.25)) || ((0.25 <= fFocus) && (fFocus <= 0.75)) )
784 /* According to spec, a focus of positive 50% is outer-to-inner,
785 and -50% is inner-to-outer (color to color2).
786 If the angle was provided as a negative,
787 then the colors are also (again) reversed. */
788 bool bOuterToInner = fFocus > 0.0;
789 if (moAngle.value_or(0) < 0)
790 bOuterToInner = !bOuterToInner;
792 // simulate axial gradient by 3-step DrawingML gradient
793 const Color& rOuterColor = bOuterToInner ? aColor1 : aColor2;
794 const Color& rInnerColor = bOuterToInner ? aColor2 : aColor1;
796 // add in order of offset
797 lcl_setGradientStop( aFillProps.maGradientProps.maGradientStops, 0.0, rOuterColor);
798 lcl_setGradientStop( aFillProps.maGradientProps.maGradientStops, 0.5, rInnerColor);
799 lcl_setGradientStop( aFillProps.maGradientProps.maGradientStops, 1.0, rOuterColor);
801 else // focus of -100%, 0%, and 100% is linear gradient
803 // LO linear gradients: top == start, but for MSO bottom == start == moColor
804 bool bSwapColors = true;
806 /* According to spec, a focus of -100% or 100% swaps the
807 start and stop colors, effectively reversing the gradient.
808 If the angle was provided as a negative,
809 then the colors are also (again) reversed. */
810 if( fFocus < -0.5 || fFocus > 0.5 )
811 bSwapColors = !bSwapColors;
812 if (moAngle.value_or(0) < 0)
813 bSwapColors = !bSwapColors;
815 const Color& rStartColor = bSwapColors ? aColor2 : aColor1;
816 const Color& rEndColor = bSwapColors ? aColor1 : aColor2;
817 // set the start and stop colors
818 lcl_setGradientStop(aFillProps.maGradientProps.maGradientStops, 0.0,
819 rStartColor);
820 lcl_setGradientStop(aFillProps.maGradientProps.maGradientStops, 1.0,
821 rEndColor);
824 // VML counts counterclockwise from bottom, DrawingML clockwise from left
825 sal_Int32 nDmlAngle = NormAngle360(90 - nVmlAngle);
826 aFillProps.maGradientProps.moShadeAngle = nDmlAngle * ::oox::drawingml::PER_DEGREE;
828 else // XML_gradientRadial is rectangular gradient
830 aFillProps.maGradientProps.moGradientPath = XML_rect;
831 // convert VML focus position and size to DrawingML fill-to-rect
832 DoublePair aFocusPos = moFocusPos.value_or( DoublePair( 0.0, 0.0 ) );
833 DoublePair aFocusSize = moFocusSize.value_or( DoublePair( 0.0, 0.0 ) );
834 double fLeft = getLimitedValue< double, double >( aFocusPos.first, 0.0, 1.0 );
835 double fTop = getLimitedValue< double, double >( aFocusPos.second, 0.0, 1.0 );
836 double fRight = getLimitedValue< double, double >( fLeft + aFocusSize.first, fLeft, 1.0 );
837 double fBottom = getLimitedValue< double, double >( fTop + aFocusSize.second, fTop, 1.0 );
838 aFillProps.maGradientProps.moFillToRect = IntegerRectangle2D(
839 static_cast< sal_Int32 >( fLeft * ::oox::drawingml::MAX_PERCENT ),
840 static_cast< sal_Int32 >( fTop * ::oox::drawingml::MAX_PERCENT ),
841 static_cast< sal_Int32 >( (1.0 - fRight) * ::oox::drawingml::MAX_PERCENT ),
842 static_cast< sal_Int32 >( (1.0 - fBottom) * ::oox::drawingml::MAX_PERCENT ) );
844 // set the start and stop colors (focus of 0% means outer-to-inner)
845 bool bOuterToInner = (-0.5 <= fFocus) && (fFocus <= 0.5);
846 lcl_setGradientStop( aFillProps.maGradientProps.maGradientStops, 0.0, bOuterToInner ? aColor2 : aColor1 );
847 lcl_setGradientStop( aFillProps.maGradientProps.maGradientStops, 1.0, bOuterToInner ? aColor1 : aColor2 );
850 break;
852 case XML_pattern:
853 case XML_tile:
854 case XML_frame:
856 if( moBitmapPath.has_value() && !moBitmapPath.value().isEmpty() )
858 aFillProps.maBlipProps.mxFillGraphic = rGraphicHelper.importEmbeddedGraphic(moBitmapPath.value());
859 if (aFillProps.maBlipProps.mxFillGraphic.is())
861 if (nFillType == XML_pattern)
863 // VML provides an 8x8 black(background) and white(foreground) pattern
864 // along with specified background(color2) and foreground(color) colors,
865 // while LO needs the color applied directly to the pattern.
866 const Graphic aGraphic(aFillProps.maBlipProps.mxFillGraphic);
867 ::Color nBackColor;
868 ::Color nPixelColor;
869 bool bIs8x8 = vcl::bitmap::isHistorical8x8(aGraphic.GetBitmapEx(),
870 nBackColor, nPixelColor);
871 if (bIs8x8)
873 nBackColor
874 = ConversionHelper::decodeColor(rGraphicHelper, moColor2,
875 moOpacity2, API_RGB_WHITE)
876 .getColor(rGraphicHelper);
877 // Documentation says undefined == white; observation says lightgray
878 nPixelColor
879 = ConversionHelper::decodeColor(rGraphicHelper, moColor,
880 moOpacity, COL_LIGHTGRAY)
881 .getColor(rGraphicHelper);
883 XOBitmap aXOB(aGraphic.GetBitmapEx());
884 aXOB.Bitmap2Array();
885 // LO uses the first pixel's color to represent background pixels
886 if (aXOB.GetBackgroundColor() == COL_WHITE)
888 // White always represents the foreground in VML => swap
889 aXOB.SetPixelColor(nBackColor);
890 aXOB.SetBackgroundColor(nPixelColor);
892 else
894 assert(aXOB.GetBackgroundColor() == COL_BLACK);
895 aXOB.SetPixelColor(nPixelColor);
896 aXOB.SetBackgroundColor(nBackColor);
898 aXOB.Array2Bitmap();
900 Graphic aLOPattern(aXOB.GetBitmap());
901 aLOPattern.setOriginURL(aGraphic.getOriginURL());
902 aFillProps.maBlipProps.mxFillGraphic = aLOPattern.GetXGraphic();
906 aFillProps.moFillType = XML_blipFill;
907 aFillProps.maBlipProps.moBitmapMode = (nFillType == XML_frame) ? XML_stretch : XML_tile;
908 break; // do not break if bitmap is missing, but run to XML_solid instead
912 [[fallthrough]]; // to XML_solid in case of missing bitmap path intended!
914 case XML_solid:
915 default:
917 aFillProps.moFillType = XML_solidFill;
918 // fill color (default is white)
919 aFillProps.maFillColor = ConversionHelper::decodeColor( rGraphicHelper, moColor, moOpacity, API_RGB_WHITE );
923 else
925 aFillProps.moFillType = XML_noFill;
928 aFillProps.pushToPropMap( rPropMap, rGraphicHelper );
931 ShadowModel::ShadowModel()
932 : mbHasShadow(false)
936 void ShadowModel::pushToPropMap(ShapePropertyMap& rPropMap, const GraphicHelper& rGraphicHelper) const
938 if (!mbHasShadow || (moShadowOn.has_value() && !moShadowOn.value()))
939 return;
941 drawingml::Color aColor = ConversionHelper::decodeColor(rGraphicHelper, moColor, moOpacity, API_RGB_GRAY);
942 // nOffset* is in mm100, default value is 35 twips, see DffPropertyReader::ApplyAttributes() in msfilter.
943 sal_Int32 nOffsetX = 62, nOffsetY = 62;
944 if (moOffset.has_value())
946 std::u16string_view aOffsetX, aOffsetY;
947 ConversionHelper::separatePair(aOffsetX, aOffsetY, moOffset.value(), ',');
948 if (!aOffsetX.empty())
949 nOffsetX = ConversionHelper::decodeMeasureToHmm(rGraphicHelper, aOffsetX, 0, false, false );
950 if (!aOffsetY.empty())
951 nOffsetY = ConversionHelper::decodeMeasureToHmm(rGraphicHelper, aOffsetY, 0, false, false );
954 table::ShadowFormat aFormat;
955 aFormat.Color = sal_Int32(aColor.getColor(rGraphicHelper));
956 aFormat.Location = nOffsetX < 0
957 ? nOffsetY < 0 ? table::ShadowLocation_TOP_LEFT : table::ShadowLocation_BOTTOM_LEFT
958 : nOffsetY < 0 ? table::ShadowLocation_TOP_RIGHT : table::ShadowLocation_BOTTOM_RIGHT;
959 // The width of the shadow is the average of the x and y values, see SwWW8ImplReader::MatchSdrItemsIntoFlySet().
960 aFormat.ShadowWidth = ((std::abs(nOffsetX) + std::abs(nOffsetY)) / 2);
961 rPropMap.setProperty(PROP_ShadowFormat, aFormat);
964 TextpathModel::TextpathModel()
968 static beans::PropertyValue lcl_createTextpathProps()
970 uno::Sequence<beans::PropertyValue> aTextpathPropSeq( comphelper::InitPropertySequence({
971 { "TextPath", uno::Any(true) },
972 { "TextPathMode", uno::Any(drawing::EnhancedCustomShapeTextPathMode_SHAPE) },
973 { "ScaleX", uno::Any(false) },
974 { "SameLetterHeights", uno::Any(false) }
975 }));
977 beans::PropertyValue aRet;
978 aRet.Name = "TextPath";
979 aRet.Value <<= aTextpathPropSeq;
980 return aRet;
983 void TextpathModel::pushToPropMap(ShapePropertyMap& rPropMap, const uno::Reference<drawing::XShape>& xShape, const GraphicHelper& rGraphicHelper) const
985 OUString sFont = "";
987 if (moString.has_value())
989 uno::Reference<text::XTextRange> xTextRange(xShape, uno::UNO_QUERY);
990 xTextRange->setString(moString.value());
992 uno::Reference<beans::XPropertySet> xPropertySet(xShape, uno::UNO_QUERY);
993 uno::Sequence<beans::PropertyValue> aGeomPropSeq = xPropertySet->getPropertyValue("CustomShapeGeometry").get< uno::Sequence<beans::PropertyValue> >();
994 bool bFound = false;
995 for (beans::PropertyValue& rProp : asNonConstRange(aGeomPropSeq))
997 if (rProp.Name == "TextPath")
999 bFound = true;
1000 rProp = lcl_createTextpathProps();
1003 if (!bFound)
1005 sal_Int32 nSize = aGeomPropSeq.getLength();
1006 aGeomPropSeq.realloc(nSize+1);
1007 aGeomPropSeq.getArray()[nSize] = lcl_createTextpathProps();
1009 rPropMap.setAnyProperty(PROP_CustomShapeGeometry, uno::Any(aGeomPropSeq));
1011 if (moStyle.has_value())
1013 OUString aStyle = moStyle.value_or(OUString());
1015 sal_Int32 nIndex = 0;
1016 while( nIndex >= 0 )
1018 std::u16string_view aName, aValue;
1019 if (ConversionHelper::separatePair(aName, aValue, o3tl::getToken(aStyle, 0, ';', nIndex), ':'))
1021 if (aName == u"font-family")
1023 // remove " (first, and last character)
1024 if (aValue.size() > 2)
1025 aValue = aValue.substr(1, aValue.size() - 2);
1027 uno::Reference<beans::XPropertySet> xPropertySet(xShape, uno::UNO_QUERY);
1028 xPropertySet->setPropertyValue("CharFontName", uno::Any(OUString(aValue)));
1029 sFont = aValue;
1031 else if (aName == u"font-size")
1033 std::optional<OUString> aOptString {OUString(aValue)};
1034 float nSize = drawingml::convertEmuToPoints(lclGetEmu(rGraphicHelper, aOptString, 1));
1036 uno::Reference<beans::XPropertySet> xPropertySet(xShape, uno::UNO_QUERY);
1037 xPropertySet->setPropertyValue("CharHeight", uno::Any(nSize));
1042 if (moTrim.has_value() && moTrim.value())
1043 return;
1045 OUString sText = moString.value_or("");
1046 ScopedVclPtrInstance<VirtualDevice> pDevice;
1047 vcl::Font aFont = pDevice->GetFont();
1048 aFont.SetFamilyName(sFont);
1049 aFont.SetFontSize(Size(0, 96));
1050 pDevice->SetFont(aFont);
1052 auto nTextWidth = pDevice->GetTextWidth(sText);
1053 if (nTextWidth)
1055 sal_Int32 nNewHeight = (static_cast<double>(pDevice->GetTextHeight()) / nTextWidth) * xShape->getSize().Width;
1056 xShape->setSize(awt::Size(xShape->getSize().Width, nNewHeight));
1060 } // namespace oox
1062 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */