Coverage Report

Created: 2025-12-31 10:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/xmloff/source/style/GradientStyle.cxx
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This file is part of the LibreOffice project.
4
 *
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/.
8
 *
9
 * This file incorporates work covered by the following license notice:
10
 *
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 .
18
 */
19
20
#include <xmloff/GradientStyle.hxx>
21
22
#include <com/sun/star/awt/Gradient2.hpp>
23
24
#include <comphelper/documentconstants.hxx>
25
#include <rtl/ustrbuf.hxx>
26
#include <rtl/ustring.hxx>
27
#include <sal/log.hxx>
28
#include <sax/tools/converter.hxx>
29
#include <xmloff/xmlement.hxx>
30
#include <xmloff/xmlexp.hxx>
31
#include <xmloff/xmlimp.hxx>
32
#include <xmloff/xmlnamespace.hxx>
33
#include <xmloff/xmltoken.hxx>
34
#include <xmloff/xmluconv.hxx>
35
#include <basegfx/utils/bgradient.hxx>
36
#include <docmodel/uno/UnoGradientTools.hxx>
37
38
using namespace ::com::sun::star;
39
using namespace ::xmloff::token;
40
41
SvXMLEnumMapEntry<awt::GradientStyle> const pXML_GradientStyle_Enum[] =
42
{
43
    { XML_LINEAR,                       awt::GradientStyle_LINEAR },
44
    { XML_GRADIENTSTYLE_AXIAL,          awt::GradientStyle_AXIAL },
45
    { XML_GRADIENTSTYLE_RADIAL,         awt::GradientStyle_RADIAL },
46
    { XML_GRADIENTSTYLE_ELLIPSOID,      awt::GradientStyle_ELLIPTICAL },
47
    { XML_GRADIENTSTYLE_SQUARE,         awt::GradientStyle_SQUARE },
48
    { XML_GRADIENTSTYLE_RECTANGULAR,    awt::GradientStyle_RECT },
49
    { XML_TOKEN_INVALID, awt::GradientStyle(0) }
50
};
51
52
// Import
53
XMLGradientStyleImport::XMLGradientStyleImport(
54
    SvXMLImport& rImp )
55
332
    : m_rImport(rImp)
56
332
{
57
332
}
58
59
void XMLGradientStyleImport::importXML(
60
    const uno::Reference< xml::sax::XFastAttributeList >& xAttrList,
61
    uno::Any& rValue,
62
    OUString& rStrName )
63
332
{
64
332
    OUString aDisplayName;
65
66
332
    awt::Gradient2 aGradient;
67
332
    aGradient.Style = css::awt::GradientStyle_LINEAR;
68
332
    aGradient.StartColor = 0;
69
332
    aGradient.EndColor = 0;
70
332
    aGradient.Angle = 0;
71
332
    aGradient.Border = 0;
72
332
    aGradient.XOffset = 0;
73
332
    aGradient.YOffset = 0;
74
332
    aGradient.StartIntensity = 100;
75
332
    aGradient.EndIntensity = 100;
76
332
    aGradient.StepCount = 0;
77
78
332
    for (auto &aIter : sax_fastparser::castToFastAttributeList( xAttrList ))
79
2.67k
    {
80
2.67k
        sal_Int32 nTmpValue(0);
81
82
2.67k
        switch( aIter.getToken() )
83
2.67k
        {
84
324
        case XML_ELEMENT(DRAW, XML_NAME):
85
324
            rStrName = aIter.toString();
86
324
            break;
87
86
        case XML_ELEMENT(DRAW, XML_DISPLAY_NAME):
88
86
            aDisplayName = aIter.toString();
89
86
            break;
90
326
        case XML_ELEMENT(DRAW, XML_STYLE):
91
326
            SvXMLUnitConverter::convertEnum( aGradient.Style, aIter.toView(), pXML_GradientStyle_Enum );
92
326
            break;
93
0
        case XML_ELEMENT(DRAW, XML_CX):
94
0
            ::sax::Converter::convertPercent( nTmpValue, aIter.toView() );
95
0
            aGradient.XOffset = static_cast< sal_Int16 >( nTmpValue );
96
0
            break;
97
0
        case XML_ELEMENT(DRAW, XML_CY):
98
0
            ::sax::Converter::convertPercent( nTmpValue, aIter.toView() );
99
0
            aGradient.YOffset = static_cast< sal_Int16 >( nTmpValue );
100
0
            break;
101
323
        case XML_ELEMENT(DRAW, XML_START_COLOR):
102
323
            ::sax::Converter::convertColor(aGradient.StartColor, aIter.toView());
103
323
            break;
104
315
        case XML_ELEMENT(DRAW, XML_END_COLOR):
105
315
            ::sax::Converter::convertColor(aGradient.EndColor, aIter.toView());
106
315
            break;
107
314
        case XML_ELEMENT(DRAW, XML_START_INTENSITY):
108
314
            ::sax::Converter::convertPercent( nTmpValue, aIter.toView() );
109
314
            aGradient.StartIntensity = static_cast< sal_Int16 >( nTmpValue );
110
314
            break;
111
314
        case XML_ELEMENT(DRAW, XML_END_INTENSITY):
112
314
            ::sax::Converter::convertPercent( nTmpValue, aIter.toView() );
113
314
            aGradient.EndIntensity = static_cast< sal_Int16 >( nTmpValue );
114
314
            break;
115
312
        case XML_ELEMENT(DRAW, XML_GRADIENT_ANGLE):
116
312
            {
117
312
                auto const cmp12(m_rImport.GetODFVersion().compareTo(ODFVER_012_TEXT));
118
                // tdf#89475 try to detect borked OOo angles
119
312
                bool const bIsWrongOOo10thDegAngle(
120
312
                    (cmp12 < 0)
121
124
                    || (cmp12 == 0
122
115
                        && (m_rImport.isGeneratorVersionOlderThan(SvXMLImport::AOO_4x,
123
115
                                                                  SvXMLImport::LO_7x)
124
                            // also for AOO 4.x, assume there won't ever be a 4.2
125
9
                            || m_rImport.getGeneratorVersion() == SvXMLImport::AOO_4x)));
126
312
                sal_Int16 nAngle;
127
312
                bool const bSuccess = ::sax::Converter::convert10thDegAngle(
128
312
                    nAngle, aIter.toView(), bIsWrongOOo10thDegAngle);
129
312
                if (bSuccess)
130
308
                { // limit to valid range [0..3600[
131
308
                    nAngle = nAngle % 3600;
132
308
                    if (nAngle < 0)
133
20
                        nAngle += 3600;
134
308
                    aGradient.Angle = nAngle;
135
308
                }
136
312
                SAL_INFO_IF(!bSuccess, "xmloff.style", "failed to import draw:angle");
137
312
            }
138
312
            break;
139
312
        case XML_ELEMENT(DRAW, XML_BORDER):
140
311
            ::sax::Converter::convertPercent( nTmpValue, aIter.toView() );
141
311
            aGradient.Border = static_cast< sal_Int16 >( nTmpValue );
142
311
            break;
143
144
54
        default:
145
54
            XMLOFF_WARN_UNKNOWN("xmloff.style", aIter);
146
2.67k
        }
147
2.67k
    }
148
149
332
    rValue <<= aGradient;
150
151
332
    if( !aDisplayName.isEmpty() )
152
86
    {
153
86
        m_rImport.AddStyleDisplayName( XmlStyleFamily::SD_GRADIENT_ID, rStrName,
154
86
                                     aDisplayName );
155
86
        rStrName = aDisplayName;
156
86
    }
157
332
}
158
159
XMLGradientStopContext::XMLGradientStopContext(
160
    SvXMLImport& rImport, sal_Int32 nElement,
161
    const uno::Reference< xml::sax::XFastAttributeList >& xAttrList,
162
    std::vector<awt::ColorStop>& rColorStopVec)
163
0
:   SvXMLImportContext(rImport)
164
0
{
165
0
    if(nElement != XML_ELEMENT(LO_EXT, xmloff::token::XML_GRADIENT_STOP))
166
0
        return;
167
168
0
    double fOffset = -1.0;
169
0
    OUString sColorType;
170
0
    OUString sColorValue;
171
    // First collect all attributes
172
0
    for (auto &aIter : sax_fastparser::castToFastAttributeList(xAttrList))
173
0
    {
174
0
        switch(aIter.getToken())
175
0
        {
176
0
        case XML_ELEMENT(SVG, xmloff::token::XML_OFFSET): // needed??
177
0
        case XML_ELEMENT(SVG_COMPAT, xmloff::token::XML_OFFSET):
178
0
            if (!::sax::Converter::convertDouble(fOffset, aIter.toView()))
179
0
                return;
180
0
            break;
181
0
        case XML_ELEMENT(LO_EXT, xmloff::token::XML_COLOR_VALUE):
182
0
            sColorValue = aIter.toString();
183
0
            if (sColorValue.isEmpty())
184
0
                return;
185
0
            break;
186
0
        case XML_ELEMENT(LO_EXT, xmloff::token::XML_COLOR_TYPE):
187
0
            sColorType = aIter.toString();
188
0
            if (sColorType.isEmpty())
189
0
                return;
190
0
            break;
191
0
        default:
192
0
            XMLOFF_WARN_UNKNOWN("xmloff.style", aIter);
193
0
        }
194
0
    }
195
196
    // As of LO 7.6.0 only "rgb" is implemented.
197
0
    if (sColorType != u"rgb")
198
0
        return;
199
200
    // Type "rgb" requires kind color-value="#rrggbb".
201
0
    ::Color aColor;
202
0
    if (!::sax::Converter::convertColor(aColor, sColorValue))
203
0
        return;
204
205
    // All attribute values OK. Generate ColorStop.
206
0
    css::rendering::RGBColor aRGBColor;
207
0
    aRGBColor.Red = aColor.GetRed() / 255.0;
208
0
    aRGBColor.Green = aColor.GetGreen() / 255.0;
209
0
    aRGBColor.Blue = aColor.GetBlue() / 255.0;
210
211
0
    awt::ColorStop aColorStop;
212
0
    aColorStop.StopOffset = fOffset;
213
0
    aColorStop.StopColor = aRGBColor;
214
0
    rColorStopVec.push_back(aColorStop);
215
0
}
216
217
XMLGradientStopContext::~XMLGradientStopContext()
218
0
{
219
0
}
220
221
// Export
222
223
XMLGradientStyleExport::XMLGradientStyleExport(
224
    SvXMLExport& rExp )
225
3
    : m_rExport(rExp)
226
3
{
227
3
}
228
229
void XMLGradientStyleExport::exportXML(
230
    const OUString& rStrName,
231
    const uno::Any& rValue )
232
18
{
233
18
    if( rStrName.isEmpty() )
234
0
        return;
235
236
18
    if (!rValue.has<css::awt::Gradient2>() && !rValue.has<css::awt::Gradient>())
237
0
        return;
238
239
18
    basegfx::BGradient aGradient = model::gradient::getFromAny(rValue);
240
241
    // Export of axial gradient to OOXML produces a symmetrical linear multi-color gradient. Import
242
    // does not regenerate it as 'axial' because that is not needed for MCGR. For export to ODF we
243
    // try to regenerate 'axial' for to get a better compatibility with LO versions before MCGR.
244
18
    aGradient.tryToConvertToAxial();
245
246
    // MCGR: For better compatibility with LO versions before MCGR, try
247
    // to re-create a 'border' value based on the existing gradient stops.
248
    // With MCGR we do not need 'border' anymore in quite some cases since
249
    // no Start/EndColor at 0.0 resp. 1.0 is explicitly needed. Since we
250
    // (unfortunately need to) internally continue to support border
251
    // anyways it does no harm to fallback to use the border value - if
252
    // there is an equivalent representation as this helper checks for.
253
    // For exports that do not support 'border' this will be adapted as
254
    // needed (see tryToApplyBorder()).
255
18
    aGradient.tryToRecreateBorder(nullptr);
256
257
18
    OUString aStrValue;
258
18
    OUStringBuffer aOut;
259
260
    // Style
261
18
    if( !SvXMLUnitConverter::convertEnum( aOut, aGradient.GetGradientStyle(), pXML_GradientStyle_Enum ) )
262
0
        return;
263
264
    // Name
265
18
    bool bEncoded = false;
266
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME,
267
18
                          m_rExport.EncodeStyleName( rStrName,
268
18
                                                    &bEncoded ) );
269
18
    if( bEncoded )
270
12
        m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME,
271
12
                                rStrName );
272
273
18
    aStrValue = aOut.makeStringAndClear();
274
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_STYLE, aStrValue );
275
276
    // Center x/y
277
18
    if( aGradient.GetGradientStyle() != awt::GradientStyle_LINEAR &&
278
3
        aGradient.GetGradientStyle() != awt::GradientStyle_AXIAL   )
279
3
    {
280
3
        ::sax::Converter::convertPercent(aOut, aGradient.GetXOffset());
281
3
        aStrValue = aOut.makeStringAndClear();
282
3
        m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CX, aStrValue );
283
3
        ::sax::Converter::convertPercent(aOut, aGradient.GetYOffset());
284
3
        aStrValue = aOut.makeStringAndClear();
285
3
        m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CY, aStrValue );
286
3
    }
287
288
    // prep Start/EndColor, default black
289
18
    basegfx::BColor aStartColor;
290
18
    basegfx::BColor aEndColor;
291
292
18
    if (!aGradient.GetColorStops().empty())
293
18
    {
294
18
        aStartColor = aGradient.GetColorStops().front().getStopColor();
295
18
        aEndColor = aGradient.GetColorStops().back().getStopColor();
296
18
    }
297
298
    // Color start
299
18
    ::sax::Converter::convertColor(aOut, Color(aStartColor));
300
18
    aStrValue = aOut.makeStringAndClear();
301
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_START_COLOR, aStrValue );
302
303
    // Color end
304
18
    ::sax::Converter::convertColor(aOut, Color(aEndColor));
305
18
    aStrValue = aOut.makeStringAndClear();
306
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_END_COLOR, aStrValue );
307
308
    // Intensity start
309
18
    ::sax::Converter::convertPercent(aOut, aGradient.GetStartIntens());
310
18
    aStrValue = aOut.makeStringAndClear();
311
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_START_INTENSITY, aStrValue );
312
313
    // Intensity end
314
18
    ::sax::Converter::convertPercent(aOut, aGradient.GetEndIntens());
315
18
    aStrValue = aOut.makeStringAndClear();
316
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_END_INTENSITY, aStrValue );
317
318
    // Angle
319
18
    if( aGradient.GetGradientStyle() != awt::GradientStyle_RADIAL )
320
18
    {
321
        // true: wrong, but backward compatible with OOo/LO < 4.4
322
        // false: OFFICE-3774 tdf#89475 write valid ODF 1.2 angle; needs LO 4.4 to import
323
18
        bool bIsWrongOOo10thDegAngle(m_rExport.getSaneDefaultVersion() < SvtSaveOptions::ODFSVER_012
324
18
            || m_rExport.getSaneDefaultVersion() == SvtSaveOptions::ODFSVER_012_EXT_COMPAT);
325
18
        ::sax::Converter::convert10thDegAngle(aOut, static_cast<sal_Int16>(aGradient.GetAngle()),
326
18
                                              bIsWrongOOo10thDegAngle);
327
18
        aStrValue = aOut.makeStringAndClear();
328
18
        m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_GRADIENT_ANGLE, aStrValue );
329
18
    }
330
331
    // Border
332
18
    ::sax::Converter::convertPercent( aOut, aGradient.GetBorder() );
333
18
    aStrValue = aOut.makeStringAndClear();
334
18
    m_rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_BORDER, aStrValue );
335
336
    // ctor writes start tag. End-tag is written by destructor at block end.
337
18
    SvXMLElementExport aElem( m_rExport, XML_NAMESPACE_DRAW, XML_GRADIENT,
338
18
                          true, false );
339
340
    // Write child elements <loext:gradient-stop>
341
    // Do not export in standard ODF 1.3 or older.
342
18
    if ((m_rExport.getSaneDefaultVersion() & SvtSaveOptions::ODFSVER_EXTENDED) == 0)
343
0
        return;
344
345
18
    if (aGradient.GetColorStops().empty())
346
0
        return;
347
348
18
    double fPreviousOffset = 0.0;
349
18
    for (const auto& aCandidate : aGradient.GetColorStops())
350
36
    {
351
        // Attribute svg:offset. Make sure offsets are increasing.
352
36
        double fOffset = std::clamp<double>(aCandidate.getStopOffset(), 0.0, 1.0);
353
36
        if (fOffset < fPreviousOffset)
354
0
            fOffset = fPreviousOffset;
355
36
        m_rExport.AddAttribute(XML_NAMESPACE_SVG, XML_OFFSET, OUString::number(fOffset));
356
36
        fPreviousOffset = fOffset;
357
358
        // As of LO 7.6.0 only color-type="rgb" is implemented.
359
36
        m_rExport.AddAttribute(XML_NAMESPACE_LO_EXT, XML_COLOR_TYPE, u"rgb"_ustr);
360
361
        // Attribute loext:color-value, data type color, that is #rrggbb.
362
36
        const basegfx::BColor aDecimalColor(aCandidate.getStopColor());
363
36
        ::Color aToolsColor(std::clamp<sal_uInt8>(std::round(aDecimalColor.getRed() * 255.0), 0, 255),
364
36
                            std::clamp<sal_uInt8>(std::round(aDecimalColor.getGreen() * 255.0), 0, 255),
365
36
                            std::clamp<sal_uInt8>(std::round(aDecimalColor.getBlue() * 255.0), 0, 255));
366
36
        m_rExport.AddAttribute(XML_NAMESPACE_LO_EXT, XML_COLOR_VALUE,
367
36
                             rtl::OUStringChar('#') + aToolsColor.AsRGBHexString());
368
369
        // write gradient stop element
370
36
        SvXMLElementExport aStopElement(m_rExport, XML_NAMESPACE_LO_EXT, XML_GRADIENT_STOP, true, true);
371
36
    }
372
18
}
373
374
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */