1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_canvas.hxx"
26 
27 #include <math.h>
28 
29 #include <canvas/debug.hxx>
30 #include <canvas/verbosetrace.hxx>
31 #include <tools/diagnose_ex.h>
32 
33 #include <vcl/metric.hxx>
34 #include <vcl/virdev.hxx>
35 
36 #ifdef WNT
37 #include <tools/prewin.h>
38 #include <windows.h>
39 #include <tools/postwin.h>
40 #ifdef max
41 #undef max
42 #endif
43 #ifdef min
44 #undef min
45 #endif
46 #endif
47 
48 #ifdef OS2
49 #define INCL_WIN
50 #include <os2.h>
51 #endif
52 
53 #include <vcl/sysdata.hxx>
54 
55 #include <basegfx/matrix/b2dhommatrix.hxx>
56 #include <basegfx/numeric/ftools.hxx>
57 
58 #include <boost/scoped_array.hpp>
59 
60 #include "cairo_textlayout.hxx"
61 #include "cairo_spritecanvas.hxx"
62 
63 #ifdef CAIRO_HAS_QUARTZ_SURFACE
64 # include "cairo_quartz_cairo.hxx"
65 #elif defined CAIRO_HAS_WIN32_SURFACE
66 # include "cairo_win32_cairo.hxx"
67 # include <cairo-win32.h>
68 #elif defined CAIRO_HAS_XLIB_SURFACE
69 # include "cairo_xlib_cairo.hxx"
70 # include <cairo-ft.h>
71 #elif defined CAIRO_HAS_OS2_SURFACE
72 # include "cairo_os2_cairo.hxx"
73 # include <cairo-os2.h>
74 #else
75 # error Native API needed.
76 #endif
77 
78 using namespace ::cairo;
79 using namespace ::com::sun::star;
80 
81 namespace cairocanvas
82 {
83     namespace
84     {
setupLayoutMode(OutputDevice & rOutDev,sal_Int8 nTextDirection)85         void setupLayoutMode( OutputDevice& rOutDev,
86                               sal_Int8		nTextDirection )
87         {
88             // TODO(P3): avoid if already correctly set
89             sal_uLong nLayoutMode;
90             switch( nTextDirection )
91             {
92                 default:
93                     nLayoutMode = 0;
94                     break;
95                 case rendering::TextDirection::WEAK_LEFT_TO_RIGHT:
96                     nLayoutMode = TEXT_LAYOUT_BIDI_LTR;
97                     break;
98                 case rendering::TextDirection::STRONG_LEFT_TO_RIGHT:
99                     nLayoutMode = TEXT_LAYOUT_BIDI_LTR | TEXT_LAYOUT_BIDI_STRONG;
100                     break;
101                 case rendering::TextDirection::WEAK_RIGHT_TO_LEFT:
102                     nLayoutMode = TEXT_LAYOUT_BIDI_RTL;
103                     break;
104                 case rendering::TextDirection::STRONG_RIGHT_TO_LEFT:
105                     nLayoutMode = TEXT_LAYOUT_BIDI_RTL | TEXT_LAYOUT_BIDI_STRONG;
106                     break;
107             }
108 
109             // set calculated layout mode. Origin is always the left edge,
110             // as required at the API spec
111             rOutDev.SetLayoutMode( nLayoutMode | TEXT_LAYOUT_TEXTORIGIN_LEFT );
112         }
113 
compareFallbacks(const SystemGlyphData & rA,const SystemGlyphData & rB)114         bool compareFallbacks(const SystemGlyphData&rA, const SystemGlyphData &rB)
115         {
116             return rA.fallbacklevel < rB.fallbacklevel;
117         }
118     }
119 
TextLayout(const rendering::StringContext & aText,sal_Int8 nDirection,sal_Int64,const CanvasFont::Reference & rFont,const SurfaceProviderRef & rRefDevice)120     TextLayout::TextLayout( const rendering::StringContext& 	aText,
121                             sal_Int8                        	nDirection,
122                             sal_Int64                       	/*nRandomSeed*/,
123                             const CanvasFont::Reference&      	rFont,
124 							const SurfaceProviderRef&			rRefDevice ) :
125         TextLayout_Base( m_aMutex ),
126         maText( aText ),
127         maLogicalAdvancements(),
128         mpFont( rFont ),
129         mpRefDevice( rRefDevice ),
130         mnTextDirection( nDirection )
131     {
132     }
133 
~TextLayout()134     TextLayout::~TextLayout()
135     {
136     }
137 
disposing()138     void SAL_CALL TextLayout::disposing()
139     {
140         ::osl::MutexGuard aGuard( m_aMutex );
141 
142         mpFont.reset();
143         mpRefDevice.clear();
144     }
145 
146     // XTextLayout
queryTextShapes()147     uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > > SAL_CALL TextLayout::queryTextShapes(  ) throw (uno::RuntimeException)
148     {
149         ::osl::MutexGuard aGuard( m_aMutex );
150 
151         // TODO
152         return uno::Sequence< uno::Reference< rendering::XPolyPolygon2D > >();
153     }
154 
queryInkMeasures()155     uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryInkMeasures(  ) throw (uno::RuntimeException)
156     {
157         ::osl::MutexGuard aGuard( m_aMutex );
158 
159         // TODO
160         return uno::Sequence< geometry::RealRectangle2D >();
161     }
162 
queryMeasures()163     uno::Sequence< geometry::RealRectangle2D > SAL_CALL TextLayout::queryMeasures(  ) throw (uno::RuntimeException)
164     {
165         ::osl::MutexGuard aGuard( m_aMutex );
166 
167         // TODO
168         return uno::Sequence< geometry::RealRectangle2D >();
169     }
170 
queryLogicalAdvancements()171     uno::Sequence< double > SAL_CALL TextLayout::queryLogicalAdvancements(  ) throw (uno::RuntimeException)
172     {
173         ::osl::MutexGuard aGuard( m_aMutex );
174 
175         return maLogicalAdvancements;
176     }
177 
applyLogicalAdvancements(const uno::Sequence<double> & aAdvancements)178     void SAL_CALL TextLayout::applyLogicalAdvancements( const uno::Sequence< double >& aAdvancements ) throw (lang::IllegalArgumentException, uno::RuntimeException)
179     {
180         ::osl::MutexGuard aGuard( m_aMutex );
181 
182         if( aAdvancements.getLength() != maText.Length )
183         {
184             OSL_TRACE( "TextLayout::applyLogicalAdvancements(): mismatching number of advancements" );
185             throw lang::IllegalArgumentException();
186         }
187 
188         maLogicalAdvancements = aAdvancements;
189     }
190 
queryTextBounds()191     geometry::RealRectangle2D SAL_CALL TextLayout::queryTextBounds(  ) throw (uno::RuntimeException)
192     {
193         ::osl::MutexGuard aGuard( m_aMutex );
194 
195         OutputDevice* pOutDev = mpRefDevice->getOutputDevice();
196     	if( !pOutDev )
197             return geometry::RealRectangle2D();
198 
199         VirtualDevice aVDev( *pOutDev );
200         aVDev.SetFont( mpFont->getVCLFont() );
201 
202         // need metrics for Y offset, the XCanvas always renders
203         // relative to baseline
204         const ::FontMetric& aMetric( aVDev.GetFontMetric() );
205 
206         setupLayoutMode( aVDev, mnTextDirection );
207 
208         const sal_Int32 nAboveBaseline( -aMetric.GetIntLeading() - aMetric.GetAscent() );
209         const sal_Int32 nBelowBaseline( aMetric.GetDescent() );
210 
211         if( maLogicalAdvancements.getLength() )
212         {
213             return geometry::RealRectangle2D( 0, nAboveBaseline,
214                                               maLogicalAdvancements[ maLogicalAdvancements.getLength()-1 ],
215                                               nBelowBaseline );
216         }
217         else
218         {
219             return geometry::RealRectangle2D( 0, nAboveBaseline,
220                                               aVDev.GetTextWidth(
221                                                   maText.Text,
222                                                   ::canvas::tools::numeric_cast<sal_uInt16>(maText.StartPosition),
223                                                   ::canvas::tools::numeric_cast<sal_uInt16>(maText.Length) ),
224                                               nBelowBaseline );
225         }
226     }
227 
justify(double)228     double SAL_CALL TextLayout::justify( double /*nSize*/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)
229     {
230         ::osl::MutexGuard aGuard( m_aMutex );
231 
232         // TODO
233         return 0.0;
234     }
235 
combinedJustify(const uno::Sequence<uno::Reference<rendering::XTextLayout>> &,double)236     double SAL_CALL TextLayout::combinedJustify( const uno::Sequence< uno::Reference< rendering::XTextLayout > >& /*aNextLayouts*/,
237                                                  double /*nSize*/ ) throw (lang::IllegalArgumentException, uno::RuntimeException)
238     {
239         ::osl::MutexGuard aGuard( m_aMutex );
240 
241         // TODO
242         return 0.0;
243     }
244 
getTextHit(const geometry::RealPoint2D &)245     rendering::TextHit SAL_CALL TextLayout::getTextHit( const geometry::RealPoint2D& /*aHitPoint*/ ) throw (uno::RuntimeException)
246     {
247         ::osl::MutexGuard aGuard( m_aMutex );
248 
249         // TODO
250         return rendering::TextHit();
251     }
252 
getCaret(sal_Int32,sal_Bool)253     rendering::Caret SAL_CALL TextLayout::getCaret( sal_Int32 /*nInsertionIndex*/,
254                                                     sal_Bool /*bExcludeLigatures*/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
255     {
256         ::osl::MutexGuard aGuard( m_aMutex );
257 
258         // TODO
259         return rendering::Caret();
260     }
261 
getNextInsertionIndex(sal_Int32,sal_Int32,sal_Bool)262     sal_Int32 SAL_CALL TextLayout::getNextInsertionIndex( sal_Int32 /*nStartIndex*/,
263                                                           sal_Int32 /*nCaretAdvancement*/,
264                                                           sal_Bool /*bExcludeLigatures*/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
265     {
266         ::osl::MutexGuard aGuard( m_aMutex );
267 
268         // TODO
269         return 0;
270     }
271 
queryVisualHighlighting(sal_Int32,sal_Int32)272     uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryVisualHighlighting( sal_Int32 /*nStartIndex*/,
273                                                                                               sal_Int32 /*nEndIndex*/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
274     {
275         ::osl::MutexGuard aGuard( m_aMutex );
276 
277         // TODO
278         return uno::Reference< rendering::XPolyPolygon2D >();
279     }
280 
queryLogicalHighlighting(sal_Int32,sal_Int32)281     uno::Reference< rendering::XPolyPolygon2D > SAL_CALL TextLayout::queryLogicalHighlighting( sal_Int32 /*nStartIndex*/,
282                                                                                                sal_Int32 /*nEndIndex*/ ) throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
283     {
284         ::osl::MutexGuard aGuard( m_aMutex );
285 
286         // TODO
287         return uno::Reference< rendering::XPolyPolygon2D >();
288     }
289 
getBaselineOffset()290     double SAL_CALL TextLayout::getBaselineOffset(  ) throw (uno::RuntimeException)
291     {
292         ::osl::MutexGuard aGuard( m_aMutex );
293 
294         // TODO
295         return 0.0;
296     }
297 
getMainTextDirection()298     sal_Int8 SAL_CALL TextLayout::getMainTextDirection(  ) throw (uno::RuntimeException)
299     {
300         ::osl::MutexGuard aGuard( m_aMutex );
301 
302         return mnTextDirection;
303     }
304 
getFont()305     uno::Reference< rendering::XCanvasFont > SAL_CALL TextLayout::getFont(  ) throw (uno::RuntimeException)
306     {
307         ::osl::MutexGuard aGuard( m_aMutex );
308 
309         return mpFont.getRef();
310     }
311 
getText()312     rendering::StringContext SAL_CALL TextLayout::getText(  ) throw (uno::RuntimeException)
313     {
314         ::osl::MutexGuard aGuard( m_aMutex );
315 
316         return maText;
317     }
318 
useFont(Cairo * pCairo)319     void TextLayout::useFont( Cairo* pCairo )
320     {
321 	rendering::FontRequest aFontRequest = mpFont->getFontRequest();
322 	rendering::FontInfo aFontInfo = aFontRequest.FontDescription;
323 
324 	cairo_select_font_face( pCairo, ::rtl::OUStringToOString( aFontInfo.FamilyName, RTL_TEXTENCODING_UTF8 ), CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL );
325 	cairo_set_font_size( pCairo, aFontRequest.CellSize );
326     }
327 
328   /** TextLayout:draw
329    *
330    * This function uses the "toy" api of the cairo library
331    *
332    **/
draw(Cairo * pCairo)333     bool TextLayout::draw( Cairo* pCairo )
334     {
335         ::osl::MutexGuard aGuard( m_aMutex );
336 
337 		::rtl::OUString aSubText = maText.Text.copy( maText.StartPosition, maText.Length );
338 		::rtl::OString aUTF8String = ::rtl::OUStringToOString( aSubText, RTL_TEXTENCODING_UTF8 );
339 
340 		cairo_save( pCairo );
341 		/* move to 0, 0 as cairo_show_text advances current point and current point is not restored by cairo_restore.
342 		   before we were depending on unmodified current point which I believed was preserved by save/restore */
343 		cairo_move_to( pCairo, 0, 0 );
344 		useFont( pCairo );
345 		cairo_show_text( pCairo, aUTF8String.getStr() );
346 		cairo_restore( pCairo );
347 
348         return true;
349     }
350 
351 
352   /**
353    * TextLayout::isCairoRenderable
354    *
355    * Features currently not supported by Cairo (VCL rendering is used as fallback):
356    * - vertical glyphs
357    *
358    * @return true, if text/font can be rendered with cairo
359    **/
isCairoRenderable(SystemFontData aSysFontData) const360     bool TextLayout::isCairoRenderable(SystemFontData aSysFontData) const
361     {
362 #if defined UNX && !defined QUARTZ
363         // is font usable?
364         if (!aSysFontData.nFontId) return false;
365 #endif
366 
367         // vertical glyph rendering is not supported in cairo for now
368         if (aSysFontData.bVerticalCharacterType) {
369             OSL_TRACE(":cairocanvas::TextLayout::isCairoRenderable(): ***************** VERTICAL CHARACTER STYLE!!! ****************");
370             return false;
371         }
372 
373         return true;
374     }
375 
376   /**
377    * TextLayout::draw
378    *
379    * Cairo-based text rendering. Draw text directly on the cairo surface with cairo fonts.
380    * Avoid using VCL VirtualDevices for that, bypassing VCL DrawText functions, when possible
381    *
382    * Note: some text effects are not rendered due to lacking generic canvas or cairo canvas
383    *       implementation. See issues 92657, 92658, 92659, 92660, 97529
384    *
385    * @return true, if successful
386    **/
draw(SurfaceSharedPtr & pSurface,OutputDevice & rOutDev,const Point & rOutpos,const rendering::ViewState & viewState,const rendering::RenderState & renderState) const387     bool TextLayout::draw( SurfaceSharedPtr&             pSurface,
388                            OutputDevice&                 rOutDev,
389                            const Point&                  rOutpos,
390                            const rendering::ViewState&   viewState,
391                            const rendering::RenderState& renderState ) const
392     {
393         ::osl::MutexGuard aGuard( m_aMutex );
394         SystemTextLayoutData aSysLayoutData;
395 #if (defined CAIRO_HAS_WIN32_SURFACE) && (OSL_DEBUG_LEVEL > 1)
396         LOGFONTW logfont;
397 #endif
398         setupLayoutMode( rOutDev, mnTextDirection );
399 
400         // TODO(P2): cache that
401         ::boost::scoped_array< sal_Int32 > aOffsets(new sal_Int32[maLogicalAdvancements.getLength()]);
402 
403         if( maLogicalAdvancements.getLength() )
404         {
405             setupTextOffsets( aOffsets.get(), maLogicalAdvancements, viewState, renderState );
406 
407             // TODO(F3): ensure correct length and termination for DX
408             // array (last entry _must_ contain the overall width)
409         }
410 
411         aSysLayoutData = rOutDev.GetSysTextLayoutData(rOutpos, maText.Text,
412                                                       ::canvas::tools::numeric_cast<sal_uInt16>(maText.StartPosition),
413                                                       ::canvas::tools::numeric_cast<sal_uInt16>(maText.Length),
414                                                       maLogicalAdvancements.getLength() ? aOffsets.get() : NULL);
415 
416         // Sort them so that all glyphs on the same glyph fallback level are consecutive
417         std::sort(aSysLayoutData.rGlyphData.begin(), aSysLayoutData.rGlyphData.end(), compareFallbacks);
418         bool bCairoRenderable = true;
419 
420         //Pull all the fonts we need to render the text
421         typedef std::pair<SystemFontData,int> FontLevel;
422         typedef std::vector<FontLevel> FontLevelVector;
423         FontLevelVector aFontData;
424         SystemGlyphDataVector::const_iterator aIter=aSysLayoutData.rGlyphData.begin();
425         const SystemGlyphDataVector::const_iterator aEnd=aSysLayoutData.rGlyphData.end();
426         for( ; aIter != aEnd; ++aIter )
427         {
428             if( aFontData.empty() || aIter->fallbacklevel != aFontData.back().second )
429             {
430                 aFontData.push_back(FontLevel(rOutDev.GetSysFontData(aIter->fallbacklevel),
431                                               aIter->fallbacklevel));
432                 if( !isCairoRenderable(aFontData.back().first) )
433                 {
434                     bCairoRenderable = false;
435                     OSL_TRACE(":cairocanvas::TextLayout::draw(S,O,p,v,r): VCL FALLBACK %s%s%s%s - %s",
436                               maLogicalAdvancements.getLength() ? "ADV " : "",
437                               aFontData.back().first.bAntialias ? "AA " : "",
438                               aFontData.back().first.bFakeBold ? "FB " : "",
439                               aFontData.back().first.bFakeItalic ? "FI " : "",
440                               ::rtl::OUStringToOString( maText.Text.copy( maText.StartPosition, maText.Length ),
441                                                         RTL_TEXTENCODING_UTF8 ).getStr());
442                     break;
443                 }
444             }
445         }
446 
447         // The ::GetSysTextLayoutData(), i.e. layouting of text to glyphs can change the font being used.
448         // The fallback checks need to be done after final font is known.
449         if (!bCairoRenderable)    // VCL FALLBACKS
450         {
451             if (maLogicalAdvancements.getLength())        // VCL FALLBACK - with glyph advances
452             {
453                 rOutDev.DrawTextArray( rOutpos, maText.Text, aOffsets.get(),
454                                        ::canvas::tools::numeric_cast<sal_uInt16>(maText.StartPosition),
455                                        ::canvas::tools::numeric_cast<sal_uInt16>(maText.Length) );
456                 return true;
457             }
458             else                                               // VCL FALLBACK - without advances
459             {
460                 rOutDev.DrawText( rOutpos, maText.Text,
461                                   ::canvas::tools::numeric_cast<sal_uInt16>(maText.StartPosition),
462                                   ::canvas::tools::numeric_cast<sal_uInt16>(maText.Length) );
463                 return true;
464             }
465         }
466 
467         if (aSysLayoutData.rGlyphData.empty()) return false; //??? false?
468 
469         /**
470          * Setup platform independent glyph vector into cairo-based glyphs vector.
471          **/
472 
473         // Loop through the fonts used and render the matching glyphs for each
474         FontLevelVector::const_iterator aFontDataIter = aFontData.begin();
475         const FontLevelVector::const_iterator aFontDataEnd = aFontData.end();
476         for( ; aFontDataIter != aFontDataEnd; ++aFontDataIter )
477         {
478             const SystemFontData &rSysFontData = aFontDataIter->first;
479 
480             // setup glyphs
481             std::vector<cairo_glyph_t> cairo_glyphs;
482             cairo_glyphs.reserve( 256 );
483 
484             SystemGlyphDataVector::const_iterator aIter=aSysLayoutData.rGlyphData.begin();
485             const SystemGlyphDataVector::const_iterator aEnd=aSysLayoutData.rGlyphData.end();
486             for( ; aIter != aEnd; ++aIter )
487             {
488                 SystemGlyphData systemGlyph = *aIter;
489                 if( systemGlyph.fallbacklevel != aFontDataIter->second )
490                     continue;
491 
492                 cairo_glyph_t aGlyph;
493                 aGlyph.index = systemGlyph.index;
494     #ifdef CAIRO_HAS_WIN32_SURFACE
495                 // Cairo requires standard glyph indexes (ETO_GLYPH_INDEX), while vcl/win/* uses ucs4 chars.
496                 // Convert to standard indexes
497                 aGlyph.index = cairo::ucs4toindex((unsigned int) aGlyph.index, rSysFontData.hFont);
498     #elif defined(CAIRO_HAS_OS2_SURFACE)
499                 // Cairo requires standard glyph indexes (ETO_GLYPH_INDEX), while vcl/os2/* uses codepage chars.
500                 // Convert to standard indexes
501                 ::rtl::OString aFontName = ::rtl::OUStringToOString(
502                             rOutDev.GetFont().GetName(), RTL_TEXTENCODING_UTF8);
503                 aGlyph.index = cairo::ucs4toindex((unsigned int) aGlyph.index, aFontName);
504     #endif
505                 aGlyph.x = systemGlyph.x;
506                 aGlyph.y = systemGlyph.y;
507                 cairo_glyphs.push_back(aGlyph);
508             }
509 
510             if (cairo_glyphs.empty())
511                 continue;
512 
513             /**
514              * Setup font
515              **/
516             cairo_font_face_t* font_face = NULL;
517 
518     #ifdef CAIRO_HAS_QUARTZ_SURFACE
519             // TODO: use cairo_quartz_font_face_create_for_cgfont(cgFont)
520             //       when CGFont (Mac OS X 10.5 API) is provided by the AQUA VCL backend.
521             font_face = cairo_quartz_font_face_create_for_atsu_font_id((ATSUFontID) rSysFontData.aATSUFontID);
522 
523     #elif defined CAIRO_HAS_WIN32_SURFACE
524       #if (OSL_DEBUG_LEVEL > 1)
525             GetObjectW( rSysFontData.hFont, sizeof(logfont), &logfont );
526       #endif
527             // Note: cairo library uses logfont fallbacks when lfEscapement, lfOrientation and lfWidth are not zero.
528             // VCL always has non-zero value for lfWidth
529             font_face = cairo_win32_font_face_create_for_hfont(rSysFontData.hFont);
530 
531     #elif defined CAIRO_HAS_XLIB_SURFACE
532             font_face = cairo_ft_font_face_create_for_ft_face((FT_Face)rSysFontData.nFontId,
533                                                               rSysFontData.nFontFlags);
534     #elif defined CAIRO_HAS_OS2_SURFACE
535             // see below
536     #else
537     # error Native API needed.
538     #endif
539 
540             CairoSharedPtr pSCairo = pSurface->getCairo();
541 
542     #if defined CAIRO_HAS_OS2_SURFACE
543             ::rtl::OString aFontName = ::rtl::OUStringToOString(
544                         rOutDev.GetFont().GetName(), RTL_TEXTENCODING_UTF8);
545             cairo_font_slant_t slant = (rOutDev.GetFont().GetItalic() == ITALIC_NONE ?
546                                             CAIRO_FONT_SLANT_NORMAL : CAIRO_FONT_SLANT_ITALIC);
547             cairo_font_weight_t weight = (rOutDev.GetFont().GetWeight() == WEIGHT_NORMAL ?
548                                               CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
549             // map StarSymbol to OpenSymbol
550             if (aFontName.equals("StarSymbol"))
551                 cairo_select_font_face( pSCairo.get(), "OpenSymbol",
552                                         slant, weight);
553             else
554                 cairo_select_font_face( pSCairo.get(), aFontName,
555                                         slant, weight);
556     #endif
557 
558             if (font_face)
559                 cairo_set_font_face( pSCairo.get(), font_face);
560 
561             // create default font options. cairo_get_font_options() does not retrieve the surface defaults,
562             // only what has been set before with cairo_set_font_options()
563             cairo_font_options_t* options = cairo_font_options_create();
564             if (rSysFontData.bAntialias) {
565                 // CAIRO_ANTIALIAS_GRAY provides more similar result to VCL Canvas,
566                 // so we're not using CAIRO_ANTIALIAS_SUBPIXEL
567                 cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
568             }
569             cairo_set_font_options( pSCairo.get(), options);
570 
571             // Font color
572             Color mTextColor = rOutDev.GetTextColor();
573             cairo_set_source_rgb(pSCairo.get(),
574                                  mTextColor.GetRed()/255.0,
575                                  mTextColor.GetGreen()/255.0,
576                                  mTextColor.GetBlue()/255.0);
577 
578             // Font rotation and scaling
579             cairo_matrix_t m;
580             Font aFont = rOutDev.GetFont();
581             FontMetric aMetric( rOutDev.GetFontMetric(aFont) );
582             long nWidth = 0;
583 
584             // width calculation is deep magic and platform/font dependent.
585             // width == 0 means no scaling, and usually width == height means the same.
586             // Other values mean horizontal scaling (narrow or stretching)
587             // see issue #101566
588 
589             //proper scale calculation across platforms
590             if (aFont.GetWidth() == 0) {
591                 nWidth = aFont.GetHeight();
592             } else {
593                 // any scaling needs to be relative to the platform-dependent definition
594                 // of height of the font
595                 nWidth = aFont.GetWidth() * aFont.GetHeight() / aMetric.GetHeight();
596             }
597 
598             cairo_matrix_init_identity(&m);
599 
600             if (aSysLayoutData.orientation) cairo_matrix_rotate(&m, (3600 - aSysLayoutData.orientation) * M_PI / 1800.0);
601 
602             cairo_matrix_scale(&m, nWidth, aFont.GetHeight());
603 
604             //faux italics
605             if (rSysFontData.bFakeItalic) m.xy = -m.xx * 0x6000L / 0x10000L;
606 
607             cairo_set_font_matrix(pSCairo.get(), &m);
608 
609             OSL_TRACE("\r\n:cairocanvas::TextLayout::draw(S,O,p,v,r): Size:(%d,%d), W:%d->%d, Pos (%d,%d), G(%d,%d,%d) %s%s%s%s || Name:%s - %s",
610                       aFont.GetWidth(),
611                       aFont.GetHeight(),
612                       aMetric.GetWidth(),
613                       nWidth,
614                       (int) rOutpos.X(),
615                       (int) rOutpos.Y(),
616                       cairo_glyphs[0].index, cairo_glyphs[1].index, cairo_glyphs[2].index,
617                       maLogicalAdvancements.getLength() ? "ADV " : "",
618                       rSysFontData.bAntialias ? "AA " : "",
619                       rSysFontData.bFakeBold ? "FB " : "",
620                       rSysFontData.bFakeItalic ? "FI " : "",
621     #if (defined CAIRO_HAS_WIN32_SURFACE) && (OSL_DEBUG_LEVEL > 1)
622                       ::rtl::OUStringToOString( reinterpret_cast<const sal_Unicode*> (logfont.lfFaceName), RTL_TEXTENCODING_UTF8 ).getStr(),
623     #else
624                       ::rtl::OUStringToOString( aFont.GetName(), RTL_TEXTENCODING_UTF8 ).getStr(),
625     #endif
626                       ::rtl::OUStringToOString( maText.Text.copy( maText.StartPosition, maText.Length ),
627                                                 RTL_TEXTENCODING_UTF8 ).getStr()
628                 );
629 
630             cairo_show_glyphs(pSCairo.get(), &cairo_glyphs[0], cairo_glyphs.size());
631 
632             //faux bold
633             if (rSysFontData.bFakeBold) {
634                 double bold_dx = 0.5 * sqrt( 0.7 * aFont.GetHeight() );
635                 int total_steps = 2 * ((int) (bold_dx + 0.5));
636 
637                 // loop to draw the text for every half pixel of displacement
638                 for (int nSteps = 0; nSteps < total_steps; nSteps++) {
639                     for(int nGlyphIdx = 0; nGlyphIdx < (int) cairo_glyphs.size(); nGlyphIdx++) {
640                         cairo_glyphs[nGlyphIdx].x += bold_dx * nSteps / total_steps;
641                     }
642                     cairo_show_glyphs(pSCairo.get(), &cairo_glyphs[0], cairo_glyphs.size());
643                 }
644                 OSL_TRACE(":cairocanvas::TextLayout::draw(S,O,p,v,r): FAKEBOLD - dx:%d", (int) bold_dx);
645             }
646 
647             cairo_restore( pSCairo.get() );
648             if (font_face)
649                 cairo_font_face_destroy(font_face);
650         }
651         return true;
652     }
653 
654 
655     namespace
656     {
657         class OffsetTransformer
658         {
659         public:
OffsetTransformer(const::basegfx::B2DHomMatrix & rMat)660             OffsetTransformer( const ::basegfx::B2DHomMatrix& rMat ) :
661                 maMatrix( rMat )
662             {
663             }
664 
operator ()(const double & rOffset)665             sal_Int32 operator()( const double& rOffset )
666             {
667                 // This is an optimization of the normal rMat*[x,0]
668                 // transformation of the advancement vector (in x
669                 // direction), followed by a length calculation of the
670                 // resulting vector: advancement' =
671                 // ||rMat*[x,0]||. Since advancements are vectors, we
672                 // can ignore translational components, thus if [x,0],
673                 // it follows that rMat*[x,0]=[x',0] holds. Thus, we
674                 // just have to calc the transformation of the x
675                 // component.
676 
677                 // TODO(F2): Handle non-horizontal advancements!
678                 return ::basegfx::fround( hypot(maMatrix.get(0,0)*rOffset,
679 												maMatrix.get(1,0)*rOffset) );
680             }
681 
682         private:
683             ::basegfx::B2DHomMatrix maMatrix;
684         };
685     }
686 
setupTextOffsets(sal_Int32 * outputOffsets,const uno::Sequence<double> & inputOffsets,const rendering::ViewState & viewState,const rendering::RenderState & renderState) const687     void TextLayout::setupTextOffsets( sal_Int32*						outputOffsets,
688                                        const uno::Sequence< double >& 	inputOffsets,
689                                        const rendering::ViewState& 		viewState,
690                                        const rendering::RenderState& 	renderState		) const
691     {
692         ENSURE_OR_THROW( outputOffsets!=NULL,
693                           "TextLayout::setupTextOffsets offsets NULL" );
694 
695         ::basegfx::B2DHomMatrix aMatrix;
696 
697         ::canvas::tools::mergeViewAndRenderTransform(aMatrix,
698                                                      viewState,
699                                                      renderState);
700 
701         // fill integer offsets
702         ::std::transform( const_cast< uno::Sequence< double >& >(inputOffsets).getConstArray(),
703                           const_cast< uno::Sequence< double >& >(inputOffsets).getConstArray()+inputOffsets.getLength(),
704                           outputOffsets,
705                           OffsetTransformer( aMatrix ) );
706     }
707 
708 #define SERVICE_NAME "com.sun.star.rendering.TextLayout"
709 #define IMPLEMENTATION_NAME "CairoCanvas::TextLayout"
710 
getImplementationName()711     ::rtl::OUString SAL_CALL TextLayout::getImplementationName() throw( uno::RuntimeException )
712     {
713         return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );
714     }
715 
supportsService(const::rtl::OUString & ServiceName)716     sal_Bool SAL_CALL TextLayout::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )
717     {
718         return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
719     }
720 
getSupportedServiceNames()721     uno::Sequence< ::rtl::OUString > SAL_CALL TextLayout::getSupportedServiceNames()  throw( uno::RuntimeException )
722     {
723         uno::Sequence< ::rtl::OUString > aRet(1);
724         aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
725 
726         return aRet;
727     }
728 }
729