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     {
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 
114         bool compareFallbacks(const SystemGlyphData&rA, const SystemGlyphData &rB)
115         {
116             return rA.fallbacklevel < rB.fallbacklevel;
117         }
118     }
119 
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 
134     TextLayout::~TextLayout()
135     {
136     }
137 
138     void SAL_CALL TextLayout::disposing()
139     {
140         ::osl::MutexGuard aGuard( m_aMutex );
141 
142         mpFont.reset();
143         mpRefDevice.clear();
144     }
145 
146     // XTextLayout
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 
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 
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 
171     uno::Sequence< double > SAL_CALL TextLayout::queryLogicalAdvancements(  ) throw (uno::RuntimeException)
172     {
173         ::osl::MutexGuard aGuard( m_aMutex );
174 
175         return maLogicalAdvancements;
176     }
177 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
298     sal_Int8 SAL_CALL TextLayout::getMainTextDirection(  ) throw (uno::RuntimeException)
299     {
300         ::osl::MutexGuard aGuard( m_aMutex );
301 
302         return mnTextDirection;
303     }
304 
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 
312     rendering::StringContext SAL_CALL TextLayout::getText(  ) throw (uno::RuntimeException)
313     {
314         ::osl::MutexGuard aGuard( m_aMutex );
315 
316         return maText;
317     }
318 
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    **/
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    **/
360     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    **/
387     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             cairo_select_font_face( pSCairo.get(), aFontName,
550                                     slant, weight);
551     #endif
552 
553             if (font_face)
554                 cairo_set_font_face( pSCairo.get(), font_face);
555 
556             // create default font options. cairo_get_font_options() does not retrieve the surface defaults,
557             // only what has been set before with cairo_set_font_options()
558             cairo_font_options_t* options = cairo_font_options_create();
559             if (rSysFontData.bAntialias) {
560                 // CAIRO_ANTIALIAS_GRAY provides more similar result to VCL Canvas,
561                 // so we're not using CAIRO_ANTIALIAS_SUBPIXEL
562                 cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
563             }
564             cairo_set_font_options( pSCairo.get(), options);
565 
566             // Font color
567             Color mTextColor = rOutDev.GetTextColor();
568             cairo_set_source_rgb(pSCairo.get(),
569                                  mTextColor.GetRed()/255.0,
570                                  mTextColor.GetGreen()/255.0,
571                                  mTextColor.GetBlue()/255.0);
572 
573             // Font rotation and scaling
574             cairo_matrix_t m;
575             Font aFont = rOutDev.GetFont();
576             FontMetric aMetric( rOutDev.GetFontMetric(aFont) );
577             long nWidth = 0;
578 
579             // width calculation is deep magic and platform/font dependent.
580             // width == 0 means no scaling, and usually width == height means the same.
581             // Other values mean horizontal scaling (narrow or stretching)
582             // see issue #101566
583 
584             //proper scale calculation across platforms
585             if (aFont.GetWidth() == 0) {
586                 nWidth = aFont.GetHeight();
587             } else {
588                 // any scaling needs to be relative to the platform-dependent definition
589                 // of height of the font
590                 nWidth = aFont.GetWidth() * aFont.GetHeight() / aMetric.GetHeight();
591             }
592 
593             cairo_matrix_init_identity(&m);
594 
595             if (aSysLayoutData.orientation) cairo_matrix_rotate(&m, (3600 - aSysLayoutData.orientation) * M_PI / 1800.0);
596 
597             cairo_matrix_scale(&m, nWidth, aFont.GetHeight());
598 
599             //faux italics
600             if (rSysFontData.bFakeItalic) m.xy = -m.xx * 0x6000L / 0x10000L;
601 
602             cairo_set_font_matrix(pSCairo.get(), &m);
603 
604             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",
605                       aFont.GetWidth(),
606                       aFont.GetHeight(),
607                       aMetric.GetWidth(),
608                       nWidth,
609                       (int) rOutpos.X(),
610                       (int) rOutpos.Y(),
611                       cairo_glyphs[0].index, cairo_glyphs[1].index, cairo_glyphs[2].index,
612                       maLogicalAdvancements.getLength() ? "ADV " : "",
613                       rSysFontData.bAntialias ? "AA " : "",
614                       rSysFontData.bFakeBold ? "FB " : "",
615                       rSysFontData.bFakeItalic ? "FI " : "",
616     #if (defined CAIRO_HAS_WIN32_SURFACE) && (OSL_DEBUG_LEVEL > 1)
617                       ::rtl::OUStringToOString( reinterpret_cast<const sal_Unicode*> (logfont.lfFaceName), RTL_TEXTENCODING_UTF8 ).getStr(),
618     #else
619                       ::rtl::OUStringToOString( aFont.GetName(), RTL_TEXTENCODING_UTF8 ).getStr(),
620     #endif
621                       ::rtl::OUStringToOString( maText.Text.copy( maText.StartPosition, maText.Length ),
622                                                 RTL_TEXTENCODING_UTF8 ).getStr()
623                 );
624 
625             cairo_show_glyphs(pSCairo.get(), &cairo_glyphs[0], cairo_glyphs.size());
626 
627             //faux bold
628             if (rSysFontData.bFakeBold) {
629                 double bold_dx = 0.5 * sqrt( 0.7 * aFont.GetHeight() );
630                 int total_steps = 2 * ((int) (bold_dx + 0.5));
631 
632                 // loop to draw the text for every half pixel of displacement
633                 for (int nSteps = 0; nSteps < total_steps; nSteps++) {
634                     for(int nGlyphIdx = 0; nGlyphIdx < (int) cairo_glyphs.size(); nGlyphIdx++) {
635                         cairo_glyphs[nGlyphIdx].x += bold_dx * nSteps / total_steps;
636                     }
637                     cairo_show_glyphs(pSCairo.get(), &cairo_glyphs[0], cairo_glyphs.size());
638                 }
639                 OSL_TRACE(":cairocanvas::TextLayout::draw(S,O,p,v,r): FAKEBOLD - dx:%d", (int) bold_dx);
640             }
641 
642             cairo_restore( pSCairo.get() );
643             if (font_face)
644                 cairo_font_face_destroy(font_face);
645         }
646         return true;
647     }
648 
649 
650     namespace
651     {
652         class OffsetTransformer
653         {
654         public:
655             OffsetTransformer( const ::basegfx::B2DHomMatrix& rMat ) :
656                 maMatrix( rMat )
657             {
658             }
659 
660             sal_Int32 operator()( const double& rOffset )
661             {
662                 // This is an optimization of the normal rMat*[x,0]
663                 // transformation of the advancement vector (in x
664                 // direction), followed by a length calculation of the
665                 // resulting vector: advancement' =
666                 // ||rMat*[x,0]||. Since advancements are vectors, we
667                 // can ignore translational components, thus if [x,0],
668                 // it follows that rMat*[x,0]=[x',0] holds. Thus, we
669                 // just have to calc the transformation of the x
670                 // component.
671 
672                 // TODO(F2): Handle non-horizontal advancements!
673                 return ::basegfx::fround( hypot(maMatrix.get(0,0)*rOffset,
674 												maMatrix.get(1,0)*rOffset) );
675             }
676 
677         private:
678             ::basegfx::B2DHomMatrix maMatrix;
679         };
680     }
681 
682     void TextLayout::setupTextOffsets( sal_Int32*						outputOffsets,
683                                        const uno::Sequence< double >& 	inputOffsets,
684                                        const rendering::ViewState& 		viewState,
685                                        const rendering::RenderState& 	renderState		) const
686     {
687         ENSURE_OR_THROW( outputOffsets!=NULL,
688                           "TextLayout::setupTextOffsets offsets NULL" );
689 
690         ::basegfx::B2DHomMatrix aMatrix;
691 
692         ::canvas::tools::mergeViewAndRenderTransform(aMatrix,
693                                                      viewState,
694                                                      renderState);
695 
696         // fill integer offsets
697         ::std::transform( const_cast< uno::Sequence< double >& >(inputOffsets).getConstArray(),
698                           const_cast< uno::Sequence< double >& >(inputOffsets).getConstArray()+inputOffsets.getLength(),
699                           outputOffsets,
700                           OffsetTransformer( aMatrix ) );
701     }
702 
703 #define SERVICE_NAME "com.sun.star.rendering.TextLayout"
704 #define IMPLEMENTATION_NAME "CairoCanvas::TextLayout"
705 
706     ::rtl::OUString SAL_CALL TextLayout::getImplementationName() throw( uno::RuntimeException )
707     {
708         return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );
709     }
710 
711     sal_Bool SAL_CALL TextLayout::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )
712     {
713         return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
714     }
715 
716     uno::Sequence< ::rtl::OUString > SAL_CALL TextLayout::getSupportedServiceNames()  throw( uno::RuntimeException )
717     {
718         uno::Sequence< ::rtl::OUString > aRet(1);
719         aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
720 
721         return aRet;
722     }
723 }
724