summaryrefslogtreecommitdiff
path: root/oox/source/vml/vmlinputstream.cxx
blob: fb2443aba4c4e526d263e6df54732c10090090b1 (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
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/vml/vmlinputstream.hxx"

#include <map>
#include <rtl/strbuf.hxx>
#include <rtl/strbuf.hxx>
#include "oox/helper/helper.hxx"

namespace oox {
namespace vml {

// ============================================================================

using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;

using ::rtl::OString;
using ::rtl::OStringBuffer;

// ============================================================================

namespace {

inline const sal_Char* lclFindCharacter( const sal_Char* pcBeg, const sal_Char* pcEnd, sal_Char cChar )
{
    sal_Int32 nIndex = rtl_str_indexOfChar_WithLength( pcBeg, static_cast< sal_Int32 >( pcEnd - pcBeg ), cChar );
    return (nIndex < 0) ? pcEnd : (pcBeg + nIndex);
}

inline bool lclIsWhiteSpace( sal_Char cChar )
{
    return (cChar == ' ') || (cChar == '\t') || (cChar == '\n') || (cChar == '\r');
}

const sal_Char* lclFindWhiteSpace( const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    for( ; pcBeg < pcEnd; ++pcBeg )
        if( lclIsWhiteSpace( *pcBeg ) )
            return pcBeg;
    return pcEnd;
}

const sal_Char* lclFindNonWhiteSpace( const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    for( ; pcBeg < pcEnd; ++pcBeg )
        if( !lclIsWhiteSpace( *pcBeg ) )
            return pcBeg;
    return pcEnd;
}

const sal_Char* lclTrimWhiteSpaceFromEnd( const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    while( (pcBeg < pcEnd) && lclIsWhiteSpace( pcEnd[ -1 ] ) )
        --pcEnd;
    return pcEnd;
}

inline void lclAppendToBuffer( OStringBuffer& rBuffer, const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    rBuffer.append( pcBeg, static_cast< sal_Int32 >( pcEnd - pcBeg ) );
}

// ----------------------------------------------------------------------------

void lclProcessAttribs( OStringBuffer& rBuffer, const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    /*  Map attribute names to char-pointer of all attributes. This map is used
        to find multiple occurences of attributes with the same name. The
        mapped pointers are used as map key in the next map below. */
    typedef ::std::map< OString, const sal_Char* > AttributeNameMap;
    AttributeNameMap aAttributeNames;

    /*  Map the char-pointers of all attributes to the full attribute definition
        string. This preserves the original order of the used attributes. */
    typedef ::std::map< const sal_Char*, OString > AttributeDataMap;
    AttributeDataMap aAttributes;

    bool bOk = true;
    const sal_Char* pcNameBeg = pcBeg;
    while( bOk && (pcNameBeg < pcEnd) )
    {
        // pcNameBeg points to begin of attribute name, find equality sign
        const sal_Char* pcEqualSign = lclFindCharacter( pcNameBeg, pcEnd, '=' );
        if( (bOk = pcEqualSign < pcEnd) == true )
        {
            // find end of attribute name (ignore whitespace between name and equality sign)
            const sal_Char* pcNameEnd = lclTrimWhiteSpaceFromEnd( pcNameBeg, pcEqualSign );
            if( (bOk = pcNameBeg < pcNameEnd) == true )
            {
                // find begin of attribute value (must be single or double quote)
                const sal_Char* pcValueBeg = lclFindNonWhiteSpace( pcEqualSign + 1, pcEnd );
                if( (bOk = (pcValueBeg < pcEnd) && ((*pcValueBeg == '\'') || (*pcValueBeg == '"'))) == true )
                {
                    // find end of attribute value (matching quote character)
                    const sal_Char* pcValueEnd = lclFindCharacter( pcValueBeg + 1, pcEnd, *pcValueBeg );
                    if( (bOk = pcValueEnd < pcEnd) == true )
                    {
                        ++pcValueEnd;
                        OString aAttribName( pcNameBeg, static_cast< sal_Int32 >( pcNameEnd - pcNameBeg ) );
                        OString aAttribData( pcNameBeg, static_cast< sal_Int32 >( pcValueEnd - pcNameBeg ) );
                        // search for an existing attribute with the same name
                        AttributeNameMap::iterator aIt = aAttributeNames.find( aAttribName );
                        // remove its definition from the data map
                        if( aIt != aAttributeNames.end() )
                            aAttributes.erase( aIt->second );
                        // insert the attribute into both maps
                        aAttributeNames[ aAttribName ] = pcNameBeg;
                        aAttributes[ pcNameBeg ] = aAttribData;
                        // continue with next attribute (skip whitespace after this attribute)
                        pcNameBeg = pcValueEnd;
                        if( (pcNameBeg < pcEnd) && ((bOk = lclIsWhiteSpace( *pcNameBeg )) == true) )
                            pcNameBeg = lclFindNonWhiteSpace( pcNameBeg + 1, pcEnd );
                    }
                }
            }
        }
    }

    // if no error has occured, build the resulting attribute list
    if( bOk )
        for( AttributeDataMap::iterator aIt = aAttributes.begin(), aEnd = aAttributes.end(); aIt != aEnd; ++aIt )
            rBuffer.append( ' ' ).append( aIt->second );
    // on error, just append the complete passed string
    else
        lclAppendToBuffer( rBuffer, pcBeg, pcEnd );
}

void lclProcessContents( OStringBuffer& rBuffer, const sal_Char* pcBeg, const sal_Char* pcEnd )
{
    /*  MSO has a very weird way to store and handle whitespaces. The stream
        may contain lots of spaces, tabs, and newlines which have to be handled
        as single space character. This will be done in this function.

        If the element text contains a literal line break, it will be stored as
        <br> tag (without matching closing </br> element).

        A single space character following another character is stored
        literally and must not be stipped away here. Example: The element
            <font>abc </font>
        contains the three letters a, b, and c, followed by a space character.

        Consecutive space characters, or a leading single space character, are
        stored in a <span> element. If there are N space characters (N > 1),
        then the <span> element contains exactly (N-1) NBSP characters
        (non-breaking space), followed by a regular space character. Example:
        The element
            <font><span style='mso-spacerun:yes'>\xA0\xA0\xA0 </span></font>
        represents 4 consecutive space characters. Has to be handled by the
        implementation.

        A single space character for its own is stored in an empty element.
        Example: The element
            <font></font>
        represents a single space character. Has to be handled by the
        implementation.
     */

    // skip leading whitespace
    const sal_Char* pcContentsBeg = lclFindNonWhiteSpace( pcBeg, pcEnd );
    while( pcContentsBeg < pcEnd )
    {
        const sal_Char* pcWhitespaceBeg = lclFindWhiteSpace( pcContentsBeg + 1, pcEnd );
        lclAppendToBuffer( rBuffer, pcContentsBeg, pcWhitespaceBeg );
        if( pcWhitespaceBeg < pcEnd )
            rBuffer.append( ' ' );
        pcContentsBeg = lclFindNonWhiteSpace( pcWhitespaceBeg, pcEnd );
    }
}

} // namespace

// ============================================================================

StreamDataContainer::StreamDataContainer( const Reference< XInputStream >& rxInStrm )
{
    if( rxInStrm.is() ) try
    {
        // read all bytes we can read
        rxInStrm->readBytes( maDataSeq, SAL_MAX_INT32 );
    }
    catch( Exception& )
    {
    }

    if( maDataSeq.hasElements() )
    {
        const OString aCDataOpen = CREATE_OSTRING( "<![CDATA[" );
        const OString aCDataClose = CREATE_OSTRING( "]]>" );

        OStringBuffer aBuffer;
        aBuffer.ensureCapacity( maDataSeq.getLength() + 256 );
        const sal_Char* pcCurr = reinterpret_cast< const sal_Char* >( maDataSeq.getConstArray() );
        const sal_Char* pcEnd = pcCurr + maDataSeq.getLength();
        while( pcCurr < pcEnd )
        {
            // look for the next opening angle bracket
            const sal_Char* pcOpen = lclFindCharacter( pcCurr, pcEnd, '<' );

            // copy all characters from current position to opening bracket
            lclProcessContents( aBuffer, pcCurr, pcOpen );

            // nothing to do if no opening bracket has been found
            if( pcOpen < pcEnd )
            {
                // string length from opening bracket to end
                sal_Int32 nLengthToEnd = static_cast< sal_Int32 >( pcEnd - pcOpen );

                // check for CDATA part, starting with '<![CDATA['
                if( rtl_str_compare_WithLength( pcOpen, nLengthToEnd, aCDataOpen.getStr(), aCDataOpen.getLength() ) == 0 )
                {
                    // search the position after the end tag ']]>'
                    sal_Int32 nClosePos = rtl_str_indexOfStr_WithLength( pcOpen, nLengthToEnd, aCDataClose.getStr(), aCDataClose.getLength() );
                    pcCurr = (nClosePos < 0) ? pcEnd : (pcOpen + nClosePos + aCDataClose.getLength());
                    // copy the entire CDATA part
                    lclAppendToBuffer( aBuffer, pcOpen, pcCurr );
                }

                // no CDATA part - process the element starting at pcOpen
                else
                {
                    // look for the next closing angle bracket
                    const sal_Char* pcClose = lclFindCharacter( pcOpen + 1, pcEnd, '>' );
                    // complete element found?
                    if( pcClose < pcEnd )
                    {
                        // continue after closing bracket
                        pcCurr = pcClose + 1;
                        // length of entire element with angle brackets
                        sal_Int32 nElementLen = static_cast< sal_Int32 >( pcCurr - pcOpen );

                        // skip parser instructions: '<![...]>'
                        if( (nElementLen >= 5) && (pcOpen[ 1 ] == '!') && (pcOpen[ 2 ] == '[') && (pcClose[ -1 ] == ']') )
                        {
                            // do nothing
                        }

                        // replace '<br>' element with newline
                        else if( (nElementLen >= 4) && (pcOpen[ 1 ] == 'b') && (pcOpen[ 2 ] == 'r') && (lclFindNonWhiteSpace( pcOpen + 3, pcClose ) == pcClose) )
                        {
                            aBuffer.append( '\n' );
                        }

                        // check start elements and empty elements for repeated attributes
                        else if( pcOpen[ 1 ] != '/' )
                        {
                            // find positions of text content inside brackets, exclude '/' in '<emptyelement/>'
                            const sal_Char* pcContentBeg = pcOpen + 1;
                            bool bIsEmptyElement = pcClose[ -1 ] == '/';
                            const sal_Char* pcContentEnd = bIsEmptyElement ? (pcClose - 1) : pcClose;
                            // append element name to buffer
                            const sal_Char* pcWhiteSpace = lclFindWhiteSpace( pcContentBeg, pcContentEnd );
                            lclAppendToBuffer( aBuffer, pcOpen, pcWhiteSpace );
                            // find begin of attributes, and process all attributes
                            const sal_Char* pcAttribBeg = lclFindNonWhiteSpace( pcWhiteSpace, pcContentEnd );
                            if( pcAttribBeg < pcContentEnd )
                                lclProcessAttribs( aBuffer, pcAttribBeg, pcContentEnd );
                            // close the element
                            if( bIsEmptyElement )
                                aBuffer.append( '/' );
                            aBuffer.append( '>' );
                        }

                        // append end elements without further processing
                        else
                        {
                            lclAppendToBuffer( aBuffer, pcOpen, pcCurr );
                        }
                    }
                    else
                    {
                        // no complete element found, copy all from opening bracket to end
                        lclAppendToBuffer( aBuffer, pcOpen, pcEnd );
                        pcCurr = pcEnd;
                    }
                }
            }
        }

        // set the final data sequence
        maDataSeq = ::comphelper::ByteSequence( reinterpret_cast< const sal_Int8* >( aBuffer.getStr() ), aBuffer.getLength() );
    }
}

// ============================================================================

InputStream::InputStream( const Reference< XInputStream >& rxInStrm ) :
    StreamDataContainer( rxInStrm ),
    ::comphelper::SequenceInputStream( maDataSeq )
{
}

InputStream::~InputStream()
{
}

// ============================================================================

} // namespace vml
} // namespave oox