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 
21 #include <pdfiprocessor.hxx>
22 #include <xmlemitter.hxx>
23 #include <pdfihelper.hxx>
24 #include <imagecontainer.hxx>
25 #include "style.hxx"
26 #include "drawtreevisiting.hxx"
27 #include <genericelements.hxx>
28 
29 #include <basegfx/polygon/b2dpolypolygontools.hxx>
30 #include <osl/diagnose.h>
31 #include <com/sun/star/i18n/BreakIterator.hpp>
32 #include <com/sun/star/i18n/CharacterClassification.hpp>
33 #include <com/sun/star/i18n/ScriptType.hpp>
34 #include <com/sun/star/i18n/DirectionProperty.hpp>
35 
36 #include <string.h>
37 
38 using namespace ::com::sun::star;
39 using namespace ::com::sun::star::lang;
40 using namespace ::com::sun::star::i18n;
41 using namespace ::com::sun::star::uno;
42 
43 namespace pdfi
44 {
45 
GetBreakIterator()46 const Reference< XBreakIterator >& DrawXmlOptimizer::GetBreakIterator()
47 {
48     if ( !mxBreakIter.is() )
49     {
50         Reference< XComponentContext > xContext( m_rProcessor.m_xContext, uno::UNO_SET_THROW );
51         mxBreakIter = BreakIterator::create(xContext);
52     }
53     return mxBreakIter;
54 }
55 
GetCharacterClassification()56 const Reference< XCharacterClassification >& DrawXmlEmitter::GetCharacterClassification()
57 {
58     if ( !mxCharClass.is() )
59     {
60         Reference< XComponentContext > xContext( m_rEmitContext.m_xContext, uno::UNO_SET_THROW );
61         mxCharClass = CharacterClassification::create(xContext);
62     }
63     return mxCharClass;
64 }
65 
visit(HyperlinkElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)66 void DrawXmlEmitter::visit( HyperlinkElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&   )
67 {
68     if( elem.Children.empty() )
69         return;
70 
71     const char* pType = dynamic_cast<DrawElement*>(elem.Children.front().get()) ? "draw:a" : "text:a";
72 
73     PropertyMap aProps;
74     aProps[ "xlink:type" ] = "simple";
75     aProps[ "xlink:href" ] = elem.URI;
76     aProps[ "office:target-frame-name" ] = "_blank";
77     aProps[ "xlink:show" ] = "new";
78 
79     m_rEmitContext.rEmitter.beginTag( pType, aProps );
80     auto this_it = elem.Children.begin();
81     while( this_it != elem.Children.end() && this_it->get() != &elem )
82     {
83         (*this_it)->visitedBy( *this, this_it );
84         ++this_it;
85     }
86     m_rEmitContext.rEmitter.endTag( pType );
87 }
88 
visit(TextElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)89 void DrawXmlEmitter::visit( TextElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&   )
90 {
91     if( elem.Text.isEmpty() )
92         return;
93 
94     OUString strSpace(u' ');
95     OUString strNbSpace(u'\x00A0');
96     OUString tabSpace(u'\x0009');
97     PropertyMap aProps;
98     if( elem.StyleId != -1 )
99     {
100         aProps[ OUString( "text:style-name"  ) ] =
101             m_rEmitContext.rStyles.getStyleName( elem.StyleId );
102     }
103 
104     OUString str(elem.Text.getStr());
105 
106     // Check for RTL
107     bool isRTL = false;
108     Reference< i18n::XCharacterClassification > xCC( GetCharacterClassification() );
109     if( xCC.is() )
110     {
111         for(int i=1; i< elem.Text.getLength(); i++)
112         {
113             css::i18n::DirectionProperty nType = static_cast<css::i18n::DirectionProperty>(xCC->getCharacterDirection( str, i ));
114             if ( nType == css::i18n::DirectionProperty_RIGHT_TO_LEFT           ||
115                  nType == css::i18n::DirectionProperty_RIGHT_TO_LEFT_ARABIC    ||
116                  nType == css::i18n::DirectionProperty_RIGHT_TO_LEFT_EMBEDDING ||
117                  nType == css::i18n::DirectionProperty_RIGHT_TO_LEFT_OVERRIDE
118                 )
119                 isRTL = true;
120         }
121     }
122 
123     if (isRTL)  // If so, reverse string
124         str = PDFIProcessor::mirrorString( str );
125 
126     m_rEmitContext.rEmitter.beginTag( "text:span", aProps );
127 
128     for(int i=0; i< elem.Text.getLength(); i++)
129     {
130         OUString strToken=  str.copy(i,1) ;
131         if( strSpace == strToken || strNbSpace == strToken )
132         {
133             aProps[ "text:c" ] = "1";
134             m_rEmitContext.rEmitter.beginTag( "text:s", aProps );
135             m_rEmitContext.rEmitter.endTag( "text:s");
136         }
137         else
138         {
139             if( tabSpace == strToken )
140             {
141                 m_rEmitContext.rEmitter.beginTag( "text:tab", aProps );
142                 m_rEmitContext.rEmitter.endTag( "text:tab");
143             }
144             else
145             {
146                 m_rEmitContext.rEmitter.write( strToken );
147             }
148         }
149     }
150 
151     auto this_it = elem.Children.begin();
152     while( this_it != elem.Children.end() && this_it->get() != &elem )
153     {
154         (*this_it)->visitedBy( *this, this_it );
155         ++this_it;
156     }
157 
158     m_rEmitContext.rEmitter.endTag( "text:span" );
159 }
160 
visit(ParagraphElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)161 void DrawXmlEmitter::visit( ParagraphElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&   )
162 {
163     PropertyMap aProps;
164     if( elem.StyleId != -1 )
165     {
166         aProps[ "text:style-name" ] = m_rEmitContext.rStyles.getStyleName( elem.StyleId );
167     }
168     const char* pTagType = "text:p";
169     if( elem.Type == ParagraphElement::Headline )
170         pTagType = "text:h";
171     m_rEmitContext.rEmitter.beginTag( pTagType, aProps );
172 
173     auto this_it = elem.Children.begin();
174     while( this_it != elem.Children.end() && this_it->get() != &elem )
175     {
176         (*this_it)->visitedBy( *this, this_it );
177         ++this_it;
178     }
179 
180     m_rEmitContext.rEmitter.endTag( pTagType );
181 }
182 
fillFrameProps(DrawElement & rElem,PropertyMap & rProps,const EmitContext & rEmitContext,bool bWasTransformed)183 void DrawXmlEmitter::fillFrameProps( DrawElement&       rElem,
184                                      PropertyMap&       rProps,
185                                      const EmitContext& rEmitContext,
186                                      bool               bWasTransformed
187                                      )
188 {
189     rProps[ "draw:z-index" ] = OUString::number( rElem.ZOrder );
190     rProps[ "draw:style-name"] = rEmitContext.rStyles.getStyleName( rElem.StyleId );
191 
192     if (rElem.IsForText)
193         rProps["draw:text-style-name"] = rEmitContext.rStyles.getStyleName(rElem.TextStyleId);
194 
195     const GraphicsContext& rGC =
196         rEmitContext.rProcessor.getGraphicsContext( rElem.GCId );
197 
198     if (bWasTransformed)
199     {
200         rProps[ "svg:x" ]       = convertPixelToUnitString(rElem.x);
201         rProps[ "svg:y" ]       = convertPixelToUnitString(rElem.y);
202         rProps[ "svg:width" ]   = convertPixelToUnitString(rElem.w);
203         rProps[ "svg:height" ]  = convertPixelToUnitString(rElem.h);
204     }
205     else
206     {
207         OUStringBuffer aBuf(256);
208 
209         basegfx::B2DHomMatrix mat(rGC.Transformation);
210 
211         if (rElem.MirrorVertical)
212         {
213             basegfx::B2DHomMatrix mat2;
214             mat2.translate(0, -0.5);
215             mat2.scale(1, -1);
216             mat2.translate(0, 0.5);
217             mat = mat * mat2;
218         }
219 
220         double scale = convPx2mm(100);
221         mat.scale(scale, scale);
222 
223         aBuf.append("matrix(");
224         aBuf.append(mat.get(0, 0));
225         aBuf.append(' ');
226         aBuf.append(mat.get(1, 0));
227         aBuf.append(' ');
228         aBuf.append(mat.get(0, 1));
229         aBuf.append(' ');
230         aBuf.append(mat.get(1, 1));
231         aBuf.append(' ');
232         aBuf.append(mat.get(0, 2));
233         aBuf.append(' ');
234         aBuf.append(mat.get(1, 2));
235         aBuf.append(")");
236 
237         rProps["draw:transform"] = aBuf.makeStringAndClear();
238     }
239 }
240 
visit(FrameElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)241 void DrawXmlEmitter::visit( FrameElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&   )
242 {
243     if( elem.Children.empty() )
244         return;
245 
246     bool bTextBox = (dynamic_cast<ParagraphElement*>(elem.Children.front().get()) != nullptr);
247     PropertyMap aFrameProps;
248     fillFrameProps( elem, aFrameProps, m_rEmitContext, false );
249     m_rEmitContext.rEmitter.beginTag( "draw:frame", aFrameProps );
250     if( bTextBox )
251         m_rEmitContext.rEmitter.beginTag( "draw:text-box", PropertyMap() );
252 
253     auto this_it = elem.Children.begin();
254     while( this_it != elem.Children.end() && this_it->get() != &elem )
255     {
256         (*this_it)->visitedBy( *this, this_it );
257         ++this_it;
258     }
259 
260     if( bTextBox )
261         m_rEmitContext.rEmitter.endTag( "draw:text-box" );
262     m_rEmitContext.rEmitter.endTag( "draw:frame" );
263 }
264 
visit(PolyPolyElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)265 void DrawXmlEmitter::visit( PolyPolyElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
266 {
267     elem.updateGeometry();
268     /* note:
269      *   aw recommends using 100dth of mm in all respects since the xml import
270      *   (a) is buggy (see issue 37213)
271      *   (b) is optimized for 100dth of mm and does not scale itself then,
272      *       this does not gain us speed but makes for smaller rounding errors since
273      *       the xml importer coordinates are integer based
274      */
275     for (sal_uInt32 i = 0; i< elem.PolyPoly.count(); i++)
276     {
277         basegfx::B2DPolygon b2dPolygon =  elem.PolyPoly.getB2DPolygon( i );
278 
279         for ( sal_uInt32 j = 0; j< b2dPolygon.count(); j++ )
280         {
281             basegfx::B2DPoint point;
282             basegfx::B2DPoint nextPoint;
283             point = b2dPolygon.getB2DPoint( j );
284 
285             basegfx::B2DPoint prevPoint = b2dPolygon.getPrevControlPoint( j ) ;
286 
287             point.setX( convPx2mmPrec2( point.getX() )*100.0 );
288             point.setY( convPx2mmPrec2( point.getY() )*100.0 );
289 
290             if ( b2dPolygon.isPrevControlPointUsed( j ) )
291             {
292                 prevPoint.setX( convPx2mmPrec2( prevPoint.getX() )*100.0 );
293                 prevPoint.setY( convPx2mmPrec2( prevPoint.getY() )*100.0 );
294             }
295 
296             if ( b2dPolygon.isNextControlPointUsed( j ) )
297             {
298                 nextPoint = b2dPolygon.getNextControlPoint( j ) ;
299                 nextPoint.setX( convPx2mmPrec2( nextPoint.getX() )*100.0 );
300                 nextPoint.setY( convPx2mmPrec2( nextPoint.getY() )*100.0 );
301             }
302 
303             b2dPolygon.setB2DPoint( j, point );
304 
305             if ( b2dPolygon.isPrevControlPointUsed( j ) )
306                 b2dPolygon.setPrevControlPoint( j , prevPoint ) ;
307 
308             if ( b2dPolygon.isNextControlPointUsed( j ) )
309                 b2dPolygon.setNextControlPoint( j , nextPoint ) ;
310         }
311 
312         elem.PolyPoly.setB2DPolygon( i, b2dPolygon );
313     }
314 
315     PropertyMap aProps;
316     // PDFIProcessor transforms geometrical objects, not images and text
317     // so we need to tell fillFrameProps here that the transformation for
318     // a PolyPolyElement was already applied (aside from translation)
319     fillFrameProps( elem, aProps, m_rEmitContext, true );
320     OUStringBuffer aBuf( 64 );
321     aBuf.append( "0 0 " );
322     aBuf.append( convPx2mmPrec2(elem.w)*100.0 );
323     aBuf.append( ' ' );
324     aBuf.append( convPx2mmPrec2(elem.h)*100.0 );
325     aProps[ "svg:viewBox" ] = aBuf.makeStringAndClear();
326     aProps[ "svg:d" ]       = basegfx::utils::exportToSvgD( elem.PolyPoly, false, true, false );
327 
328     m_rEmitContext.rEmitter.beginTag( "draw:path", aProps );
329     m_rEmitContext.rEmitter.endTag( "draw:path" );
330 }
331 
visit(ImageElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)332 void DrawXmlEmitter::visit( ImageElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
333 {
334     PropertyMap aImageProps;
335     m_rEmitContext.rEmitter.beginTag( "draw:image", aImageProps );
336     m_rEmitContext.rEmitter.beginTag( "office:binary-data", PropertyMap() );
337     m_rEmitContext.rImages.writeBase64EncodedStream( elem.Image, m_rEmitContext);
338     m_rEmitContext.rEmitter.endTag( "office:binary-data" );
339     m_rEmitContext.rEmitter.endTag( "draw:image" );
340 }
341 
visit(PageElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)342 void DrawXmlEmitter::visit( PageElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&   )
343 {
344     PropertyMap aPageProps;
345     aPageProps[ "draw:master-page-name" ] = m_rEmitContext.rStyles.getStyleName( elem.StyleId );
346 
347     m_rEmitContext.rEmitter.beginTag("draw:page", aPageProps);
348 
349     if( m_rEmitContext.xStatusIndicator.is() )
350         m_rEmitContext.xStatusIndicator->setValue( elem.PageNumber );
351 
352     auto this_it = elem.Children.begin();
353     while( this_it != elem.Children.end() && this_it->get() != &elem )
354     {
355         (*this_it)->visitedBy( *this, this_it );
356         ++this_it;
357     }
358 
359     m_rEmitContext.rEmitter.endTag("draw:page");
360 }
361 
visit(DocumentElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)362 void DrawXmlEmitter::visit( DocumentElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&)
363 {
364     m_rEmitContext.rEmitter.beginTag( "office:body", PropertyMap() );
365     m_rEmitContext.rEmitter.beginTag( m_bWriteDrawDocument ? "office:drawing" : "office:presentation",
366                                       PropertyMap() );
367 
368     auto this_it = elem.Children.begin();
369     while( this_it != elem.Children.end() && this_it->get() != &elem )
370     {
371         (*this_it)->visitedBy( *this, this_it );
372         ++this_it;
373     }
374 
375     m_rEmitContext.rEmitter.endTag( m_bWriteDrawDocument ? "office:drawing" : "office:presentation" );
376     m_rEmitContext.rEmitter.endTag( "office:body" );
377 }
378 
379 
visit(HyperlinkElement &,const std::list<std::unique_ptr<Element>>::const_iterator &)380 void DrawXmlOptimizer::visit( HyperlinkElement&, const std::list< std::unique_ptr<Element> >::const_iterator& )
381 {
382 }
383 
visit(TextElement &,const std::list<std::unique_ptr<Element>>::const_iterator &)384 void DrawXmlOptimizer::visit( TextElement&, const std::list< std::unique_ptr<Element> >::const_iterator&)
385 {
386 }
387 
visit(FrameElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)388 void DrawXmlOptimizer::visit( FrameElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
389 {
390     elem.applyToChildren(*this);
391 }
392 
visit(ImageElement &,const std::list<std::unique_ptr<Element>>::const_iterator &)393 void DrawXmlOptimizer::visit( ImageElement&, const std::list< std::unique_ptr<Element> >::const_iterator& )
394 {
395 }
396 
visit(PolyPolyElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator & elemIt)397 void DrawXmlOptimizer::visit( PolyPolyElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& elemIt )
398 {
399     /* note: optimize two consecutive PolyPolyElements that
400      *  have the same path but one of which is a stroke while
401      *     the other is a fill
402      */
403     if( !elem.Parent )
404         return;
405 
406     // find following PolyPolyElement in parent's children list
407     if( elemIt == elem.Parent->Children.end() )
408         return;
409     auto next_it = elemIt;
410     ++next_it;
411     if( next_it == elem.Parent->Children.end() )
412         return;
413 
414     PolyPolyElement* pNext = dynamic_cast<PolyPolyElement*>(next_it->get());
415     // TODO(F2): this comparison fails for OOo-generated polygons with beziers.
416     if( !pNext || pNext->PolyPoly != elem.PolyPoly )
417         return;
418 
419     const GraphicsContext& rNextGC =
420                    m_rProcessor.getGraphicsContext( pNext->GCId );
421     const GraphicsContext& rThisGC =
422                    m_rProcessor.getGraphicsContext( elem.GCId );
423 
424     if( !(rThisGC.BlendMode      == rNextGC.BlendMode &&
425          rThisGC.Flatness       == rNextGC.Flatness &&
426          rThisGC.Transformation == rNextGC.Transformation &&
427          rThisGC.Clip           == rNextGC.Clip &&
428          rThisGC.FillColor.Red  == rNextGC.FillColor.Red &&
429          rThisGC.FillColor.Green== rNextGC.FillColor.Green &&
430          rThisGC.FillColor.Blue == rNextGC.FillColor.Blue &&
431          rThisGC.FillColor.Alpha== rNextGC.FillColor.Alpha &&
432          pNext->Action          == PATH_STROKE &&
433          (elem.Action == PATH_FILL || elem.Action == PATH_EOFILL)) )
434         return;
435 
436     GraphicsContext aGC = rThisGC;
437     aGC.LineJoin  = rNextGC.LineJoin;
438     aGC.LineCap   = rNextGC.LineCap;
439     aGC.LineWidth = rNextGC.LineWidth;
440     aGC.MiterLimit= rNextGC.MiterLimit;
441     aGC.DashArray = rNextGC.DashArray;
442     aGC.LineColor = rNextGC.LineColor;
443     elem.GCId = m_rProcessor.getGCId( aGC );
444 
445     elem.Action |= pNext->Action;
446 
447     elem.Children.splice( elem.Children.end(), pNext->Children );
448     elem.Parent->Children.erase(next_it);
449 }
450 
visit(ParagraphElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)451 void DrawXmlOptimizer::visit( ParagraphElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
452 {
453     optimizeTextElements( elem );
454 
455     elem.applyToChildren(*this);
456 }
457 
visit(PageElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)458 void DrawXmlOptimizer::visit( PageElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
459 {
460     if( m_rProcessor.getStatusIndicator().is() )
461         m_rProcessor.getStatusIndicator()->setValue( elem.PageNumber );
462 
463     // resolve hyperlinks
464     elem.resolveHyperlinks();
465 
466     elem.resolveFontStyles( m_rProcessor ); // underlines and such
467 
468     // FIXME: until hyperlinks and font effects are adjusted for
469     // geometrical search handle them before sorting
470     PDFIProcessor::sortElements( &elem );
471 
472     // find paragraphs in text
473     ParagraphElement* pCurPara = nullptr;
474     std::list< std::unique_ptr<Element> >::iterator page_element, next_page_element;
475     next_page_element = elem.Children.begin();
476     double fCurLineHeight = 0.0; // average height of text items in current para
477     int nCurLineElements = 0; // number of line contributing elements in current para
478     double line_left = elem.w, line_right = 0.0;
479     double column_width = elem.w*0.75; // estimate text width
480     // TODO: guess columns
481     while( next_page_element != elem.Children.end() )
482     {
483         page_element = next_page_element++;
484         ParagraphElement* pPagePara = dynamic_cast<ParagraphElement*>(page_element->get());
485         if( pPagePara )
486         {
487             pCurPara = pPagePara;
488             // adjust line height and text items
489             fCurLineHeight = 0.0;
490             nCurLineElements = 0;
491             for( const auto& rxChild : pCurPara->Children )
492             {
493                 TextElement* pTestText = dynamic_cast<TextElement*>(rxChild.get());
494                 if( pTestText )
495                 {
496                     fCurLineHeight = (fCurLineHeight*double(nCurLineElements) + pTestText->h)/double(nCurLineElements+1);
497                     nCurLineElements++;
498                 }
499             }
500             continue;
501         }
502 
503         HyperlinkElement* pLink = dynamic_cast<HyperlinkElement*>(page_element->get());
504         DrawElement* pDraw = dynamic_cast<DrawElement*>(page_element->get());
505         if( ! pDraw && pLink && ! pLink->Children.empty() )
506             pDraw = dynamic_cast<DrawElement*>(pLink->Children.front().get() );
507         if( pDraw )
508         {
509             // insert small drawing objects as character, else leave them page bound
510 
511             bool bInsertToParagraph = false;
512             // first check if this is either inside the paragraph
513             if( pCurPara && pDraw->y < pCurPara->y + pCurPara->h )
514             {
515                 if( pDraw->h < fCurLineHeight * 1.5 )
516                 {
517                     bInsertToParagraph = true;
518                     fCurLineHeight = (fCurLineHeight*double(nCurLineElements) + pDraw->h)/double(nCurLineElements+1);
519                     nCurLineElements++;
520                     // mark draw element as character
521                     pDraw->isCharacter = true;
522                 }
523             }
524             // or perhaps the draw element begins a new paragraph
525             else if( next_page_element != elem.Children.end() )
526             {
527                 TextElement* pText = dynamic_cast<TextElement*>(next_page_element->get());
528                 if( ! pText )
529                 {
530                     ParagraphElement* pPara = dynamic_cast<ParagraphElement*>(next_page_element->get());
531                     if( pPara && ! pPara->Children.empty() )
532                         pText = dynamic_cast<TextElement*>(pPara->Children.front().get());
533                 }
534                 if( pText && // check there is a text
535                     pDraw->h < pText->h*1.5 && // and it is approx the same height
536                     // and either upper or lower edge of pDraw is inside text's vertical range
537                     ( ( pDraw->y >= pText->y && pDraw->y <= pText->y+pText->h ) ||
538                       ( pDraw->y+pDraw->h >= pText->y && pDraw->y+pDraw->h <= pText->y+pText->h )
539                       )
540                     )
541                 {
542                     bInsertToParagraph = true;
543                     fCurLineHeight = pDraw->h;
544                     nCurLineElements = 1;
545                     line_left = pDraw->x;
546                     line_right = pDraw->x + pDraw->w;
547                     // begin a new paragraph
548                     pCurPara = nullptr;
549                     // mark draw element as character
550                     pDraw->isCharacter = true;
551                 }
552             }
553 
554             if( ! bInsertToParagraph )
555             {
556                 pCurPara = nullptr;
557                 continue;
558             }
559         }
560 
561         TextElement* pText = dynamic_cast<TextElement*>(page_element->get());
562         if( ! pText && pLink && ! pLink->Children.empty() )
563             pText = dynamic_cast<TextElement*>(pLink->Children.front().get());
564         if( pText )
565         {
566             Element* pGeo = pLink ? static_cast<Element*>(pLink) :
567                                     static_cast<Element*>(pText);
568             if( pCurPara )
569             {
570                 // there was already a text element, check for a new paragraph
571                 if( nCurLineElements > 0 )
572                 {
573                     // if the new text is significantly distant from the paragraph
574                     // begin a new paragraph
575                     if( pGeo->y > pCurPara->y + pCurPara->h + fCurLineHeight*0.5  )
576                         pCurPara = nullptr; // insert new paragraph
577                     else if( pGeo->y > (pCurPara->y+pCurPara->h - fCurLineHeight*0.05) )
578                     {
579                         // new paragraph if either the last line of the paragraph
580                         // was significantly shorter than the paragraph as a whole
581                         if( (line_right - line_left) < pCurPara->w*0.75 )
582                             pCurPara = nullptr;
583                         // or the last line was significantly smaller than the column width
584                         else if( (line_right - line_left) < column_width*0.75 )
585                             pCurPara = nullptr;
586                     }
587                 }
588 
589 
590             }
591 
592 
593             // update line height/width
594             if( pCurPara )
595             {
596                 fCurLineHeight = (fCurLineHeight*double(nCurLineElements) + pGeo->h)/double(nCurLineElements+1);
597                 nCurLineElements++;
598                 if( pGeo->x < line_left )
599                     line_left = pGeo->x;
600                 if( pGeo->x+pGeo->w > line_right )
601                     line_right = pGeo->x+pGeo->w;
602             }
603             else
604             {
605                 fCurLineHeight = pGeo->h;
606                 nCurLineElements = 1;
607                 line_left = pGeo->x;
608                 line_right = pGeo->x + pGeo->w;
609             }
610         }
611 
612 
613         // move element to current paragraph
614         if (! pCurPara )  // new paragraph, insert one
615         {
616             pCurPara = ElementFactory::createParagraphElement( nullptr );
617             // set parent
618             pCurPara->Parent = &elem;
619             //insert new paragraph before current element
620             page_element = elem.Children.insert( page_element, std::unique_ptr<Element>(pCurPara) );
621             // forward iterator to current element again
622             ++ page_element;
623             // update next_element which is now invalid
624             next_page_element = page_element;
625             ++ next_page_element;
626         }
627         Element* pCurEle = page_element->get();
628         Element::setParent( page_element, pCurPara );
629         OSL_ENSURE( !pText || pCurEle == pText || pCurEle == pLink, "paragraph child list in disorder" );
630         if( pText || pDraw )
631             pCurPara->updateGeometryWith( pCurEle );
632     }
633 
634     // process children
635     elem.applyToChildren(*this);
636 }
637 
isSpaces(TextElement * pTextElem)638 static bool isSpaces(TextElement* pTextElem)
639 {
640     for (sal_Int32 i = 0; i != pTextElem->Text.getLength(); ++i) {
641         if (pTextElem->Text[i] != ' ') {
642             return false;
643         }
644     }
645     return true;
646 }
647 
notTransformed(const GraphicsContext & GC)648 static bool notTransformed(const GraphicsContext& GC)
649 {
650     return
651         rtl::math::approxEqual(GC.Transformation.get(0,0), 100.00) &&
652         GC.Transformation.get(1,0) == 0.00 &&
653         GC.Transformation.get(0,1) == 0.00 &&
654         rtl::math::approxEqual(GC.Transformation.get(1,1), -100.00);
655 }
656 
optimizeTextElements(Element & rParent)657 void DrawXmlOptimizer::optimizeTextElements(Element& rParent)
658 {
659     if( rParent.Children.empty() ) // this should not happen
660     {
661         OSL_FAIL( "empty paragraph optimized" );
662         return;
663     }
664 
665     // concatenate child elements with same font id
666     auto next = rParent.Children.begin();
667     auto it = next++;
668 
669     while( next != rParent.Children.end() )
670     {
671         bool bConcat = false;
672         TextElement* pCur = dynamic_cast<TextElement*>(it->get());
673 
674         if( pCur )
675         {
676             TextElement* pNext = dynamic_cast<TextElement*>(next->get());
677             bool isComplex = false;
678             OUString str(pCur->Text.getStr());
679             for(int i=0; i< str.getLength(); i++)
680             {
681                 sal_Int16 nType = GetBreakIterator()->getScriptType( str, i );
682                 if (nType == css::i18n::ScriptType::COMPLEX)
683                     isComplex = true;
684             }
685             bool bPara = strspn("ParagraphElement", typeid(rParent).name());
686             ParagraphElement* pPara = dynamic_cast<ParagraphElement*>(&rParent);
687             if (bPara && pPara && isComplex)
688                 pPara->bRtl = true;
689             if( pNext )
690             {
691                 const GraphicsContext& rCurGC = m_rProcessor.getGraphicsContext( pCur->GCId );
692                 const GraphicsContext& rNextGC = m_rProcessor.getGraphicsContext( pNext->GCId );
693 
694                 // line and space optimization; works only in strictly horizontal mode
695 
696                 // concatenate consecutive text elements unless there is a
697                 // font or text color or matrix change, leave a new span in that case
698                 if( (pCur->FontId == pNext->FontId || isSpaces(pNext)) &&
699                     rCurGC.FillColor.Red == rNextGC.FillColor.Red &&
700                     rCurGC.FillColor.Green == rNextGC.FillColor.Green &&
701                     rCurGC.FillColor.Blue == rNextGC.FillColor.Blue &&
702                     rCurGC.FillColor.Alpha == rNextGC.FillColor.Alpha &&
703                     (rCurGC.Transformation == rNextGC.Transformation || notTransformed(rNextGC))
704                     )
705                 {
706                     pCur->updateGeometryWith( pNext );
707                     // append text to current element
708                     pCur->Text.append( pNext->Text );
709 
710                     str = pCur->Text.getStr();
711                     for(int i=0; i< str.getLength(); i++)
712                     {
713                         sal_Int16 nType = GetBreakIterator()->getScriptType( str, i );
714                         if (nType == css::i18n::ScriptType::COMPLEX)
715                             isComplex = true;
716                     }
717                     if (bPara && pPara && isComplex)
718                         pPara->bRtl = true;
719                     // append eventual children to current element
720                     // and clear children (else the children just
721                     // appended to pCur would be destroyed)
722                     pCur->Children.splice( pCur->Children.end(), pNext->Children );
723                     // get rid of the now useless element
724                     rParent.Children.erase( next );
725                     bConcat = true;
726                 }
727             }
728         }
729         else if( dynamic_cast<HyperlinkElement*>(it->get()) )
730             optimizeTextElements( **it );
731         if ( bConcat )
732             next = it;
733         else
734             ++it;
735         ++next;
736     }
737 }
738 
visit(DocumentElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)739 void DrawXmlOptimizer::visit( DocumentElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&)
740 {
741     elem.applyToChildren(*this);
742 }
743 
744 
visit(PolyPolyElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)745 void DrawXmlFinalizer::visit( PolyPolyElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
746 {
747     // xxx TODO copied from DrawElement
748     const GraphicsContext& rGC = m_rProcessor.getGraphicsContext(elem.GCId );
749 
750     PropertyMap aProps;
751     aProps[ "style:family" ] = "graphic";
752     aProps[ "style:parent-style-name" ] = "standard";
753     // generate standard graphic style if necessary
754     m_rStyleContainer.getStandardStyleId( "graphic" );
755 
756     PropertyMap aGCProps;
757     if (elem.Action & PATH_STROKE)
758     {
759         double scale = GetAverageTransformationScale(rGC.Transformation);
760         if (rGC.DashArray.size() < 2)
761         {
762             aGCProps[ "draw:stroke" ] = "solid";
763         }
764         else
765         {
766             PropertyMap props;
767             FillDashStyleProps(props, rGC.DashArray, scale);
768             StyleContainer::Style style("draw:stroke-dash", props);
769 
770             aGCProps[ "draw:stroke" ] = "dash";
771             aGCProps[ "draw:stroke-dash" ] =
772                 m_rStyleContainer.getStyleName(
773                 m_rStyleContainer.getStyleId(style));
774         }
775 
776         aGCProps[ "svg:stroke-color" ] = getColorString(rGC.LineColor);
777         if (rGC.LineColor.Alpha != 1.0)
778             aGCProps["svg:stroke-opacity"] = getPercentString(rGC.LineColor.Alpha * 100.0);
779         aGCProps[ "svg:stroke-width" ] = convertPixelToUnitString(rGC.LineWidth * scale);
780         aGCProps[ "draw:stroke-linejoin" ] = rGC.GetLineJoinString();
781         aGCProps[ "svg:stroke-linecap" ] = rGC.GetLineCapString();
782     }
783     else
784     {
785         aGCProps[ "draw:stroke" ] = "none";
786     }
787 
788     // TODO(F1): check whether stuff could be emulated by gradient/bitmap/hatch
789     if( elem.Action & (PATH_FILL | PATH_EOFILL) )
790     {
791         aGCProps[ "draw:fill" ]   = "solid";
792         aGCProps[ "draw:fill-color" ] = getColorString(rGC.FillColor);
793         if (rGC.FillColor.Alpha != 1.0)
794             aGCProps["draw:opacity"] = getPercentString(rGC.FillColor.Alpha * 100.0);
795     }
796     else
797     {
798         aGCProps[ "draw:fill" ] = "none";
799     }
800 
801     StyleContainer::Style aStyle( "style:style", aProps );
802     StyleContainer::Style aSubStyle( "style:graphic-properties", aGCProps );
803     aStyle.SubStyles.push_back( &aSubStyle );
804 
805     elem.StyleId = m_rStyleContainer.getStyleId( aStyle );
806 }
807 
visit(HyperlinkElement &,const std::list<std::unique_ptr<Element>>::const_iterator &)808 void DrawXmlFinalizer::visit( HyperlinkElement&, const std::list< std::unique_ptr<Element> >::const_iterator& )
809 {
810 }
811 
SetFontsizeProperties(PropertyMap & props,double fontSize)812 static void SetFontsizeProperties(PropertyMap& props, double fontSize)
813 {
814     OUString aFSize = OUString::number(fontSize * 72 / PDFI_OUTDEV_RESOLUTION) + "pt";
815     props["fo:font-size"] = aFSize;
816     props["style:font-size-asian"] = aFSize;
817     props["style:font-size-complex"] = aFSize;
818 }
819 
visit(TextElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)820 void DrawXmlFinalizer::visit( TextElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
821 {
822     const FontAttributes& rFont = m_rProcessor.getFont( elem.FontId );
823     PropertyMap aProps;
824     aProps[ "style:family" ] = "text";
825 
826     PropertyMap aFontProps;
827 
828     // family name
829     aFontProps[ "fo:font-family" ] = rFont.familyName;
830     aFontProps[ "style:font-family-complex" ] = rFont.familyName;
831 
832     // bold
833     if( rFont.isBold )
834     {
835         aFontProps[ "fo:font-weight" ]         = "bold";
836         aFontProps[ "fo:font-weight-asian" ]   = "bold";
837         aFontProps[ "style:font-weight-complex" ] = "bold";
838     }
839     // italic
840     if( rFont.isItalic )
841     {
842         aFontProps[ "fo:font-style" ]         = "italic";
843         aFontProps[ "fo:font-style-asian" ]   = "italic";
844         aFontProps[ "style:font-style-complex" ] = "italic";
845     }
846     // underline
847     if( rFont.isUnderline )
848     {
849         aFontProps[ "style:text-underline-style" ]  = "solid";
850         aFontProps[ "style:text-underline-width" ]  = "auto";
851         aFontProps[ "style:text-underline-color" ]  = "font-color";
852     }
853     // outline
854     if( rFont.isOutline )
855     {
856         aFontProps[ "style:text-outline" ]  = "true";
857     }
858 
859     // size
860     SetFontsizeProperties(aFontProps, rFont.size);
861 
862     // color
863     const GraphicsContext& rGC = m_rProcessor.getGraphicsContext( elem.GCId );
864     aFontProps[ "fo:color" ] = getColorString( rFont.isOutline ? rGC.LineColor : rGC.FillColor );
865 
866     // scale
867     double fRotate, fShearX;
868     basegfx::B2DTuple aScale, aTranslation;
869     rGC.Transformation.decompose(aScale, aTranslation, fRotate, fShearX);
870     double textScale = 100 * aScale.getX() / aScale.getY();
871     if (((textScale >= 1) && (textScale <= 99)) ||
872         ((textScale >= 101) && (textScale <= 999)))
873     {
874         aFontProps[ "style:text-scale" ] = getPercentString(textScale);
875     }
876 
877     StyleContainer::Style aStyle( "style:style", aProps );
878     StyleContainer::Style aSubStyle( "style:text-properties", aFontProps );
879     aStyle.SubStyles.push_back( &aSubStyle );
880     elem.StyleId = m_rStyleContainer.getStyleId( aStyle );
881 }
882 
visit(ParagraphElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)883 void DrawXmlFinalizer::visit( ParagraphElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
884 {
885 
886     PropertyMap aProps;
887     aProps[ "style:family" ] = "paragraph";
888     // generate standard paragraph style if necessary
889     m_rStyleContainer.getStandardStyleId( "paragraph" );
890 
891     PropertyMap aParProps;
892 
893     aParProps[ "fo:text-align"]                   = "start";
894     if (elem.bRtl)
895         aParProps[ "style:writing-mode"]                    = "rl-tb";
896     else
897         aParProps[ "style:writing-mode"]                    = "lr-tb";
898 
899     StyleContainer::Style aStyle( "style:style", aProps );
900     StyleContainer::Style aSubStyle( "style:paragraph-properties", aParProps );
901     aStyle.SubStyles.push_back( &aSubStyle );
902 
903     elem.StyleId = m_rStyleContainer.getStyleId( aStyle );
904 
905     elem.applyToChildren(*this);
906 }
907 
visit(FrameElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)908 void DrawXmlFinalizer::visit( FrameElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator&)
909 {
910     PropertyMap props1;
911     props1[ "style:family" ] = "graphic";
912     props1[ "style:parent-style-name" ] = "standard";
913     // generate standard graphic style if necessary
914     m_rStyleContainer.getStandardStyleId( "graphic" );
915 
916     PropertyMap aGCProps;
917 
918     aGCProps[ "draw:stroke" ]                    = "none";
919     aGCProps[ "draw:fill" ]                      = "none";
920     aGCProps[ "draw:auto-grow-height" ]          = "true";
921     aGCProps[ "draw:auto-grow-width" ]           = "true";
922     aGCProps[ "draw:textarea-horizontal-align" ] = "left";
923     aGCProps[ "draw:textarea-vertical-align" ]   = "top";
924     aGCProps[ "fo:min-height"]                   = "0cm";
925     aGCProps[ "fo:min-width"]                    = "0cm";
926     aGCProps[ "fo:padding-top" ]                 = "0cm";
927     aGCProps[ "fo:padding-left" ]                = "0cm";
928     aGCProps[ "fo:padding-right" ]               = "0cm";
929     aGCProps[ "fo:padding-bottom" ]              = "0cm";
930 
931     StyleContainer::Style style1( "style:style", props1 );
932     StyleContainer::Style subStyle1( "style:graphic-properties", aGCProps );
933     style1.SubStyles.push_back(&subStyle1);
934 
935     elem.StyleId = m_rStyleContainer.getStyleId(style1);
936 
937     if (elem.IsForText)
938     {
939         PropertyMap props2;
940         props2["style:family"] = "paragraph";
941 
942         PropertyMap textProps;
943         SetFontsizeProperties(textProps, elem.FontSize);
944 
945         StyleContainer::Style style2("style:style", props2);
946         StyleContainer::Style subStyle2("style:text-properties", textProps);
947         style2.SubStyles.push_back(&subStyle2);
948         elem.TextStyleId = m_rStyleContainer.getStyleId(style2);
949     }
950 
951     elem.applyToChildren(*this);
952 }
953 
visit(ImageElement &,const std::list<std::unique_ptr<Element>>::const_iterator &)954 void DrawXmlFinalizer::visit( ImageElement&, const std::list< std::unique_ptr<Element> >::const_iterator& )
955 {
956 }
957 
visit(PageElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)958 void DrawXmlFinalizer::visit( PageElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
959 {
960     if( m_rProcessor.getStatusIndicator().is() )
961         m_rProcessor.getStatusIndicator()->setValue( elem.PageNumber );
962 
963     // transform from pixel to mm
964     double page_width = convPx2mm( elem.w ), page_height = convPx2mm( elem.h );
965 
966     // calculate page margins out of the relevant children (paragraphs)
967     elem.TopMargin = elem.h;
968     elem.BottomMargin = 0;
969     elem.LeftMargin = elem.w;
970     elem.RightMargin = 0;
971 
972     for( const auto& rxChild : elem.Children )
973     {
974         if( rxChild->x < elem.LeftMargin )
975             elem.LeftMargin = rxChild->x;
976         if( rxChild->y < elem.TopMargin )
977             elem.TopMargin = rxChild->y;
978         if( rxChild->x + rxChild->w > elem.RightMargin )
979             elem.RightMargin = (rxChild->x + rxChild->w);
980         if( rxChild->y + rxChild->h > elem.BottomMargin )
981             elem.BottomMargin = (rxChild->y + rxChild->h);
982     }
983 
984     // transform margins to mm
985     double left_margin     = convPx2mm( elem.LeftMargin );
986     double right_margin    = convPx2mm( elem.RightMargin );
987     double top_margin      = convPx2mm( elem.TopMargin );
988     double bottom_margin   = convPx2mm( elem.BottomMargin );
989 
990     // round left/top margin to nearest mm
991     left_margin     = rtl_math_round( left_margin, 0, rtl_math_RoundingMode_Floor );
992     top_margin      = rtl_math_round( top_margin, 0, rtl_math_RoundingMode_Floor );
993     // round (fuzzy) right/bottom margin to nearest cm
994     right_margin    = rtl_math_round( right_margin, right_margin >= 10 ? -1 : 0, rtl_math_RoundingMode_Floor );
995     bottom_margin   = rtl_math_round( bottom_margin, bottom_margin >= 10 ? -1 : 0, rtl_math_RoundingMode_Floor );
996 
997     // set reasonable default in case of way too large margins
998     // e.g. no paragraph case
999     if( left_margin > page_width/2.0 - 10 )
1000         left_margin = 10;
1001     if( right_margin > page_width/2.0 - 10 )
1002         right_margin = 10;
1003     if( top_margin > page_height/2.0 - 10 )
1004         top_margin = 10;
1005     if( bottom_margin > page_height/2.0 - 10 )
1006         bottom_margin = 10;
1007 
1008     // catch the weird cases
1009     if( left_margin < 0 )
1010         left_margin = 0;
1011     if( right_margin < 0 )
1012         right_margin = 0;
1013     if( top_margin < 0 )
1014         top_margin = 0;
1015     if( bottom_margin < 0 )
1016         bottom_margin = 0;
1017 
1018     // widely differing margins are unlikely to be correct
1019     if( right_margin > left_margin*1.5 )
1020         right_margin = left_margin;
1021 
1022     elem.LeftMargin      = convmm2Px( left_margin );
1023     elem.RightMargin     = convmm2Px( right_margin );
1024     elem.TopMargin       = convmm2Px( top_margin );
1025     elem.BottomMargin    = convmm2Px( bottom_margin );
1026 
1027     // get styles for paragraphs
1028     PropertyMap aPageProps;
1029     PropertyMap aPageLayoutProps;
1030     aPageLayoutProps[ "fo:margin-top" ]     =  unitMMString( top_margin );
1031     aPageLayoutProps[ "fo:margin-bottom" ]  =  unitMMString( bottom_margin );
1032     aPageLayoutProps[ "fo:margin-left" ]    =  unitMMString( left_margin );
1033     aPageLayoutProps[ "fo:margin-right" ]   =  unitMMString( right_margin );
1034     aPageLayoutProps[ "fo:page-width" ]     =  unitMMString( page_width );
1035     aPageLayoutProps[ "fo:page-height" ]    =  unitMMString( page_height );
1036     aPageLayoutProps[ "style:print-orientation" ]= elem.w < elem.h ? OUStringLiteral("portrait") : OUStringLiteral("landscape");
1037     aPageLayoutProps[ "style:writing-mode" ]= "lr-tb";
1038 
1039     StyleContainer::Style aStyle( "style:page-layout", aPageProps);
1040     StyleContainer::Style aSubStyle( "style:page-layout-properties", aPageLayoutProps);
1041     aStyle.SubStyles.push_back(&aSubStyle);
1042     sal_Int32 nPageStyle = m_rStyleContainer.impl_getStyleId( aStyle, false );
1043 
1044     // create master page
1045     OUString aMasterPageLayoutName = m_rStyleContainer.getStyleName( nPageStyle );
1046     aPageProps[ "style:page-layout-name" ] = aMasterPageLayoutName;
1047 
1048     StyleContainer::Style aMPStyle( "style:master-page", aPageProps);
1049 
1050     StyleContainer::Style aHeaderStyle( "style:header", PropertyMap() );
1051     StyleContainer::Style aFooterStyle( "style:footer", PropertyMap() );
1052 
1053     elem.StyleId = m_rStyleContainer.impl_getStyleId( aMPStyle,false );
1054 
1055     // create styles for children
1056     elem.applyToChildren(*this);
1057 }
1058 
visit(DocumentElement & elem,const std::list<std::unique_ptr<Element>>::const_iterator &)1059 void DrawXmlFinalizer::visit( DocumentElement& elem, const std::list< std::unique_ptr<Element> >::const_iterator& )
1060 {
1061     elem.applyToChildren(*this);
1062 }
1063 
1064 }
1065 
1066 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
1067