Use a more portable scheme for storing the name of a critical
[wine] / dlls / x11drv / xrender.c
1 /*
2  * Functions to use the XRender extension
3  *
4  * Copyright 2001, 2002 Huw D M Davies for CodeWeavers
5  *
6  * Some parts also:
7  * Copyright 2000 Keith Packard, member of The XFree86 Project, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <assert.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "wownt32.h"
34 #include "x11drv.h"
35 #include "gdi.h"
36 #include "wine/library.h"
37 #include "wine/unicode.h"
38 #include "wine/debug.h"
39
40 static BOOL X11DRV_XRender_Installed = FALSE;
41 int using_client_side_fonts = FALSE;
42
43 WINE_DEFAULT_DEBUG_CHANNEL(xrender);
44
45 #ifdef HAVE_X11_EXTENSIONS_XRENDER_H
46
47 #include <X11/Xlib.h>
48 #include <X11/extensions/Xrender.h>
49
50 static XRenderPictFormat *screen_format; /* format of screen */
51 static XRenderPictFormat *mono_format; /* format of mono bitmap */
52
53 typedef struct
54 {
55     LOGFONTW lf;
56     SIZE     devsize;  /* size in device coords */
57     DWORD    hash;
58 } LFANDSIZE;
59
60 #define INITIAL_REALIZED_BUF_SIZE 128
61
62 typedef enum { AA_None = 0, AA_Grey, AA_RGB, AA_BGR, AA_VRGB, AA_VBGR, AA_MAXVALUE } AA_Type;
63
64 typedef struct
65 {
66     GlyphSet glyphset;
67     XRenderPictFormat *font_format;
68     int nrealized;
69     BOOL *realized;
70     void **bitmaps;
71     XGlyphInfo *gis;
72 } gsCacheEntryFormat;
73
74 typedef struct
75 {
76     LFANDSIZE lfsz;
77     AA_Type aa_default;
78     gsCacheEntryFormat * format[AA_MAXVALUE];
79     INT count;
80     INT next;
81 } gsCacheEntry;
82
83 struct tagXRENDERINFO
84 {
85     int                cache_index;
86     Picture            pict;
87     Picture            tile_pict;
88     Pixmap             tile_xpm;
89     COLORREF           lastTextColor;
90 };
91
92
93 static gsCacheEntry *glyphsetCache = NULL;
94 static DWORD glyphsetCacheSize = 0;
95 static INT lastfree = -1;
96 static INT mru = -1;
97
98 #define INIT_CACHE_SIZE 10
99
100 static int antialias = 1;
101
102 /* some default values just in case */
103 #ifndef SONAME_LIBX11
104 #define SONAME_LIBX11 "libX11.so"
105 #endif
106 #ifndef SONAME_LIBXEXT
107 #define SONAME_LIBXEXT "libXext.so"
108 #endif
109 #ifndef SONAME_LIBXRENDER
110 #define SONAME_LIBXRENDER "libXrender.so"
111 #endif
112
113 static void *xrender_handle;
114
115 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
116 MAKE_FUNCPTR(XRenderAddGlyphs)
117 MAKE_FUNCPTR(XRenderComposite)
118 MAKE_FUNCPTR(XRenderCompositeString8)
119 MAKE_FUNCPTR(XRenderCompositeString16)
120 MAKE_FUNCPTR(XRenderCompositeString32)
121 MAKE_FUNCPTR(XRenderCreateGlyphSet)
122 MAKE_FUNCPTR(XRenderCreatePicture)
123 MAKE_FUNCPTR(XRenderFillRectangle)
124 MAKE_FUNCPTR(XRenderFindFormat)
125 MAKE_FUNCPTR(XRenderFindVisualFormat)
126 MAKE_FUNCPTR(XRenderFreeGlyphSet)
127 MAKE_FUNCPTR(XRenderFreePicture)
128 MAKE_FUNCPTR(XRenderSetPictureClipRectangles)
129 #ifdef HAVE_XRENDERSETPICTURETRANSFORM
130 MAKE_FUNCPTR(XRenderSetPictureTransform)
131 #endif
132 MAKE_FUNCPTR(XRenderQueryExtension)
133 #undef MAKE_FUNCPTR
134
135 static CRITICAL_SECTION xrender_cs;
136 static CRITICAL_SECTION_DEBUG critsect_debug =
137 {
138     0, 0, &xrender_cs,
139     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
140       0, 0, { (DWORD_PTR)(__FILE__ ": xrender_cs") }
141 };
142 static CRITICAL_SECTION xrender_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
143
144
145 /***********************************************************************
146  *   X11DRV_XRender_Init
147  *
148  * Let's see if our XServer has the extension available
149  *
150  */
151 void X11DRV_XRender_Init(void)
152 {
153     int error_base, event_base, i;
154     XRenderPictFormat pf;
155
156     if (client_side_with_render &&
157         wine_dlopen(SONAME_LIBX11, RTLD_NOW|RTLD_GLOBAL, NULL, 0) &&
158         wine_dlopen(SONAME_LIBXEXT, RTLD_NOW|RTLD_GLOBAL, NULL, 0) && 
159         (xrender_handle = wine_dlopen(SONAME_LIBXRENDER, RTLD_NOW, NULL, 0)))
160     {
161
162 #define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(xrender_handle, #f, NULL, 0)) == NULL) goto sym_not_found;
163 LOAD_FUNCPTR(XRenderAddGlyphs)
164 LOAD_FUNCPTR(XRenderComposite)
165 LOAD_FUNCPTR(XRenderCompositeString8)
166 LOAD_FUNCPTR(XRenderCompositeString16)
167 LOAD_FUNCPTR(XRenderCompositeString32)
168 LOAD_FUNCPTR(XRenderCreateGlyphSet)
169 LOAD_FUNCPTR(XRenderCreatePicture)
170 LOAD_FUNCPTR(XRenderFillRectangle)
171 LOAD_FUNCPTR(XRenderFindFormat)
172 LOAD_FUNCPTR(XRenderFindVisualFormat)
173 LOAD_FUNCPTR(XRenderFreeGlyphSet)
174 LOAD_FUNCPTR(XRenderFreePicture)
175 LOAD_FUNCPTR(XRenderSetPictureClipRectangles)
176 LOAD_FUNCPTR(XRenderQueryExtension)
177 #undef LOAD_FUNCPTR
178 #ifdef HAVE_XRENDERSETPICTURETRANSFORM
179 #define LOAD_OPTIONAL_FUNCPTR(f) p##f = wine_dlsym(xrender_handle, #f, NULL, 0);
180 LOAD_OPTIONAL_FUNCPTR(XRenderSetPictureTransform)
181 #undef LOAD_OPTIONAL_FUNCPTR
182 #endif
183
184
185         wine_tsx11_lock();
186         if(pXRenderQueryExtension(gdi_display, &event_base, &error_base)) {
187             X11DRV_XRender_Installed = TRUE;
188             TRACE("Xrender is up and running error_base = %d\n", error_base);
189             screen_format = pXRenderFindVisualFormat(gdi_display, visual);
190             if(!screen_format)
191             {
192                 /* Xrender doesn't like DirectColor visuals, try to find a TrueColor one instead */
193                 if (visual->class == DirectColor)
194                 {
195                     XVisualInfo info;
196                     if (XMatchVisualInfo( gdi_display, DefaultScreen(gdi_display),
197                                           screen_depth, TrueColor, &info ))
198                     {
199                         screen_format = pXRenderFindVisualFormat(gdi_display, info.visual);
200                         if (screen_format) visual = info.visual;
201                     }
202                 }
203             }
204             if(!screen_format) /* This fails in buggy versions of libXrender.so */
205             {
206                 wine_tsx11_unlock();
207                 WINE_MESSAGE(
208                     "Wine has detected that you probably have a buggy version\n"
209                     "of libXrender.so .  Because of this client side font rendering\n"
210                     "will be disabled.  Please upgrade this library.\n");
211                 X11DRV_XRender_Installed = FALSE;
212                 return;
213             }
214             pf.type = PictTypeDirect;
215             pf.depth = 1;
216             pf.direct.alpha = 0;
217             pf.direct.alphaMask = 1;
218             mono_format = pXRenderFindFormat(gdi_display, PictFormatType |
219                                              PictFormatDepth | PictFormatAlpha |
220                                              PictFormatAlphaMask, &pf, 0);
221             if(!mono_format) {
222                 ERR("mono_format == NULL?\n");
223                 X11DRV_XRender_Installed = FALSE;
224             }
225         }
226         wine_tsx11_unlock();
227     }
228
229 sym_not_found:
230     if(X11DRV_XRender_Installed || client_side_with_core)
231     {
232         glyphsetCache = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
233                                   sizeof(*glyphsetCache) * INIT_CACHE_SIZE);
234
235         glyphsetCacheSize = INIT_CACHE_SIZE;
236         lastfree = 0;
237         for(i = 0; i < INIT_CACHE_SIZE; i++) {
238           glyphsetCache[i].next = i + 1;
239           glyphsetCache[i].count = -1;
240         }
241         glyphsetCache[i-1].next = -1;
242         using_client_side_fonts = 1;
243
244         if(!X11DRV_XRender_Installed) {
245             TRACE("Xrender is not available on your XServer, client side rendering with the core protocol instead.\n");
246             if(screen_depth <= 8 || !client_side_antialias_with_core)
247                 antialias = 0;
248         } else {
249             if(screen_depth <= 8 || !client_side_antialias_with_render)
250                 antialias = 0;
251         }
252     }
253     else TRACE("Using X11 core fonts\n");
254 }
255
256 static BOOL fontcmp(LFANDSIZE *p1, LFANDSIZE *p2)
257 {
258   if(p1->hash != p2->hash) return TRUE;
259   if(memcmp(&p1->devsize, &p2->devsize, sizeof(p1->devsize))) return TRUE;
260   if(memcmp(&p1->lf, &p2->lf, offsetof(LOGFONTW, lfFaceName))) return TRUE;
261   return strcmpW(p1->lf.lfFaceName, p2->lf.lfFaceName);
262 }
263
264 #if 0
265 static void walk_cache(void)
266 {
267   int i;
268
269   EnterCriticalSection(&xrender_cs);
270   for(i=mru; i >= 0; i = glyphsetCache[i].next)
271     TRACE("item %d\n", i);
272   LeaveCriticalSection(&xrender_cs);
273 }
274 #endif
275
276 static int LookupEntry(LFANDSIZE *plfsz)
277 {
278   int i, prev_i = -1;
279
280   for(i = mru; i >= 0; i = glyphsetCache[i].next) {
281     TRACE("%d\n", i);
282     if(glyphsetCache[i].count == -1) { /* reached free list so stop */
283       i = -1;
284       break;
285     }
286
287     if(!fontcmp(&glyphsetCache[i].lfsz, plfsz)) {
288       glyphsetCache[i].count++;
289       if(prev_i >= 0) {
290         glyphsetCache[prev_i].next = glyphsetCache[i].next;
291         glyphsetCache[i].next = mru;
292         mru = i;
293       }
294       TRACE("found font in cache %d\n", i);
295       return i;
296     }
297     prev_i = i;
298   }
299   TRACE("font not in cache\n");
300   return -1;
301 }
302
303 static void FreeEntry(int entry)
304 {
305     int i, format;
306   
307     for(format = 0; format < AA_MAXVALUE; format++) {
308         gsCacheEntryFormat * formatEntry;
309
310         if( !glyphsetCache[entry].format[format] )
311             continue;
312
313         formatEntry = glyphsetCache[entry].format[format];
314
315         if(formatEntry->glyphset) {
316             wine_tsx11_lock();
317             pXRenderFreeGlyphSet(gdi_display, formatEntry->glyphset);
318             wine_tsx11_unlock();
319             formatEntry->glyphset = 0;
320         }
321         if(formatEntry->nrealized) {
322             HeapFree(GetProcessHeap(), 0, formatEntry->realized);
323             formatEntry->realized = NULL;
324             if(formatEntry->bitmaps) {
325                 for(i = 0; i < formatEntry->nrealized; i++)
326                     if(formatEntry->bitmaps[i])
327                         HeapFree(GetProcessHeap(), 0, formatEntry->bitmaps[i]);
328                 HeapFree(GetProcessHeap(), 0, formatEntry->bitmaps);
329                 formatEntry->bitmaps = NULL;
330                 HeapFree(GetProcessHeap(), 0, formatEntry->gis);
331                 formatEntry->gis = NULL;
332             }
333             formatEntry->nrealized = 0;
334         }
335
336         HeapFree(GetProcessHeap(), 0, formatEntry);
337         glyphsetCache[entry].format[format] = NULL;
338     }
339 }
340
341 static int AllocEntry(void)
342 {
343   int best = -1, prev_best = -1, i, prev_i = -1;
344
345   if(lastfree >= 0) {
346     assert(glyphsetCache[lastfree].count == -1);
347     glyphsetCache[lastfree].count = 1;
348     best = lastfree;
349     lastfree = glyphsetCache[lastfree].next;
350     assert(best != mru);
351     glyphsetCache[best].next = mru;
352     mru = best;
353
354     TRACE("empty space at %d, next lastfree = %d\n", mru, lastfree);
355     return mru;
356   }
357
358   for(i = mru; i >= 0; i = glyphsetCache[i].next) {
359     if(glyphsetCache[i].count == 0) {
360       best = i;
361       prev_best = prev_i;
362     }
363     prev_i = i;
364   }
365
366   if(best >= 0) {
367     TRACE("freeing unused glyphset at cache %d\n", best);
368     FreeEntry(best);
369     glyphsetCache[best].count = 1;
370     if(prev_best >= 0) {
371       glyphsetCache[prev_best].next = glyphsetCache[best].next;
372       glyphsetCache[best].next = mru;
373       mru = best;
374     } else {
375       assert(mru == best);
376     }
377     return mru;
378   }
379
380   TRACE("Growing cache\n");
381   
382   if (glyphsetCache)
383     glyphsetCache = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
384                               glyphsetCache,
385                               (glyphsetCacheSize + INIT_CACHE_SIZE)
386                               * sizeof(*glyphsetCache));
387   else
388     glyphsetCache = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
389                               (glyphsetCacheSize + INIT_CACHE_SIZE)
390                               * sizeof(*glyphsetCache));
391
392   for(best = i = glyphsetCacheSize; i < glyphsetCacheSize + INIT_CACHE_SIZE;
393       i++) {
394     glyphsetCache[i].next = i + 1;
395     glyphsetCache[i].count = -1;
396   }
397   glyphsetCache[i-1].next = -1;
398   glyphsetCacheSize += INIT_CACHE_SIZE;
399
400   lastfree = glyphsetCache[best].next;
401   glyphsetCache[best].count = 1;
402   glyphsetCache[best].next = mru;
403   mru = best;
404   TRACE("new free cache slot at %d\n", mru);
405   return mru;
406 }
407
408 static int GetCacheEntry(LFANDSIZE *plfsz)
409 {
410     int ret;
411     int format;
412     gsCacheEntry *entry;
413
414     if((ret = LookupEntry(plfsz)) != -1) return ret;
415
416     ret = AllocEntry();
417     entry = glyphsetCache + ret;
418     entry->lfsz = *plfsz;
419     for( format = 0; format < AA_MAXVALUE; format++ ) {
420         assert( !entry->format[format] );
421     }
422
423     if(antialias && plfsz->lf.lfQuality != NONANTIALIASED_QUALITY)
424         entry->aa_default = AA_Grey;
425     else
426         entry->aa_default = AA_None;
427
428     return ret;
429 }
430
431 static void dec_ref_cache(int index)
432 {
433     assert(index >= 0);
434     TRACE("dec'ing entry %d to %d\n", index, glyphsetCache[index].count - 1);
435     assert(glyphsetCache[index].count > 0);
436     glyphsetCache[index].count--;
437 }
438
439 static void lfsz_calc_hash(LFANDSIZE *plfsz)
440 {
441   DWORD hash = 0, *ptr;
442   int i;
443
444   hash ^= plfsz->devsize.cx;
445   hash ^= plfsz->devsize.cy;
446   for(i = 0, ptr = (DWORD*)&plfsz->lf; i < 7; i++, ptr++)
447     hash ^= *ptr;
448   for(i = 0, ptr = (DWORD*)&plfsz->lf.lfFaceName; i < LF_FACESIZE/2; i++, ptr++) {
449     WCHAR *pwc = (WCHAR *)ptr;
450     if(!*pwc) break;
451     hash ^= *ptr;
452     pwc++;
453     if(!*pwc) break;
454   }
455   plfsz->hash = hash;
456   return;
457 }
458
459 /***********************************************************************
460  *   X11DRV_XRender_Finalize
461  */
462 void X11DRV_XRender_Finalize(void)
463 {
464     int i;
465
466     EnterCriticalSection(&xrender_cs);
467     for(i = mru; i >= 0; i = glyphsetCache[i].next)
468         FreeEntry(i);
469     LeaveCriticalSection(&xrender_cs);
470 }
471
472
473 /***********************************************************************
474  *   X11DRV_XRender_SelectFont
475  */
476 BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
477 {
478     LFANDSIZE lfsz;
479
480     GetObjectW(hfont, sizeof(lfsz.lf), &lfsz.lf);
481     TRACE("h=%ld w=%ld weight=%ld it=%d charset=%d name=%s\n",
482           lfsz.lf.lfHeight, lfsz.lf.lfWidth, lfsz.lf.lfWeight,
483           lfsz.lf.lfItalic, lfsz.lf.lfCharSet, debugstr_w(lfsz.lf.lfFaceName));
484     lfsz.devsize.cx = X11DRV_XWStoDS( physDev, lfsz.lf.lfWidth );
485     lfsz.devsize.cy = X11DRV_YWStoDS( physDev, lfsz.lf.lfHeight );
486     lfsz_calc_hash(&lfsz);
487
488     EnterCriticalSection(&xrender_cs);
489     if(!physDev->xrender) {
490         physDev->xrender = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
491                                      sizeof(*physDev->xrender));
492         physDev->xrender->cache_index = -1;
493     }
494     else if(physDev->xrender->cache_index != -1)
495         dec_ref_cache(physDev->xrender->cache_index);
496     physDev->xrender->cache_index = GetCacheEntry(&lfsz);
497     LeaveCriticalSection(&xrender_cs);
498     return 0;
499 }
500
501 /***********************************************************************
502  *   X11DRV_XRender_DeleteDC
503  */
504 void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
505 {
506     wine_tsx11_lock();
507     if(physDev->xrender->tile_pict)
508         pXRenderFreePicture(gdi_display, physDev->xrender->tile_pict);
509
510     if(physDev->xrender->tile_xpm)
511         XFreePixmap(gdi_display, physDev->xrender->tile_xpm);
512
513     if(physDev->xrender->pict) {
514         TRACE("freeing pict = %lx dc = %p\n", physDev->xrender->pict, physDev->hdc);
515         pXRenderFreePicture(gdi_display, physDev->xrender->pict);
516     }
517     wine_tsx11_unlock();
518
519     EnterCriticalSection(&xrender_cs);
520     if(physDev->xrender->cache_index != -1)
521         dec_ref_cache(physDev->xrender->cache_index);
522     LeaveCriticalSection(&xrender_cs);
523
524     HeapFree(GetProcessHeap(), 0, physDev->xrender);
525     physDev->xrender = NULL;
526     return;
527 }
528
529 /***********************************************************************
530  *   X11DRV_XRender_UpdateDrawable
531  *
532  * This gets called from X11DRV_SetDrawable and X11DRV_SelectBitmap.
533  * It deletes the pict when the drawable changes.
534  */
535 void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
536 {
537     if(physDev->xrender->pict) {
538         TRACE("freeing pict %08lx from dc %p drawable %08lx\n", physDev->xrender->pict,
539               physDev->hdc, physDev->drawable);
540         wine_tsx11_lock();
541         XFlush(gdi_display);
542         pXRenderFreePicture(gdi_display, physDev->xrender->pict);
543         wine_tsx11_unlock();
544     }
545     physDev->xrender->pict = 0;
546     return;
547 }
548
549 /************************************************************************
550  *   UploadGlyph
551  *
552  * Helper to ExtTextOut.  Must be called inside xrender_cs
553  */
554 static BOOL UploadGlyph(X11DRV_PDEVICE *physDev, int glyph, AA_Type format)
555 {
556     unsigned int buflen;
557     char *buf;
558     Glyph gid;
559     GLYPHMETRICS gm;
560     XGlyphInfo gi;
561     gsCacheEntry *entry = glyphsetCache + physDev->xrender->cache_index;
562     gsCacheEntryFormat *formatEntry;
563     UINT ggo_format = GGO_GLYPH_INDEX;
564     XRenderPictFormat pf;
565
566     /* If there is nothing for the current type, we create the entry. */
567     if( !entry->format[format] ) {
568         entry->format[format] = HeapAlloc(GetProcessHeap(),
569                                           HEAP_ZERO_MEMORY,
570                                           sizeof(gsCacheEntryFormat));
571     }
572     formatEntry = entry->format[format];
573
574     if(formatEntry->nrealized <= glyph) {
575         formatEntry->nrealized = (glyph / 128 + 1) * 128;
576
577         if (formatEntry->realized)
578             formatEntry->realized = HeapReAlloc(GetProcessHeap(),
579                                       HEAP_ZERO_MEMORY,
580                                       formatEntry->realized,
581                                       formatEntry->nrealized * sizeof(BOOL));
582         else
583             formatEntry->realized = HeapAlloc(GetProcessHeap(),
584                                       HEAP_ZERO_MEMORY,
585                                       formatEntry->nrealized * sizeof(BOOL));
586
587         if(!X11DRV_XRender_Installed) {
588           if (formatEntry->bitmaps)
589             formatEntry->bitmaps = HeapReAlloc(GetProcessHeap(),
590                                       HEAP_ZERO_MEMORY,
591                                       formatEntry->bitmaps,
592                                       formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
593           else
594             formatEntry->bitmaps = HeapAlloc(GetProcessHeap(),
595                                       HEAP_ZERO_MEMORY,
596                                       formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
597
598           if (formatEntry->gis)
599             formatEntry->gis = HeapReAlloc(GetProcessHeap(),
600                                    HEAP_ZERO_MEMORY,
601                                    formatEntry->gis,
602                                    formatEntry->nrealized * sizeof(formatEntry->gis[0]));
603           else
604             formatEntry->gis = HeapAlloc(GetProcessHeap(),
605                                    HEAP_ZERO_MEMORY,
606                                    formatEntry->nrealized * sizeof(formatEntry->gis[0]));
607         }
608     }
609
610     switch(format) {
611     case AA_Grey:
612         ggo_format |= WINE_GGO_GRAY16_BITMAP;
613         break;
614
615     default:
616         ERR("aa = %d - not implemented\n", format);
617     case AA_None:
618         ggo_format |= GGO_BITMAP;
619         break;
620     }
621
622     buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
623                               NULL);
624     if(buflen == GDI_ERROR) {
625         if(format != AA_None) {
626             format = AA_None;
627             entry->aa_default = AA_None;
628             ggo_format &= ~WINE_GGO_GRAY16_BITMAP;
629             ggo_format |= GGO_BITMAP;
630             buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
631                                       NULL);
632         }
633         if(buflen == GDI_ERROR) {
634             ERR("GetGlyphOutlineW failed\n");
635             return FALSE;
636         }
637         TRACE("Turning off antialiasing for this monochrome font\n");
638     }
639
640     if(formatEntry->glyphset == 0 && X11DRV_XRender_Installed) {
641         switch(format) {
642         case AA_Grey:
643             pf.depth = 8;
644             pf.direct.alphaMask = 0xff;
645             break;
646
647         default:
648             ERR("aa = %d - not implemented\n", format);
649         case AA_None:
650             pf.depth = 1;
651             pf.direct.alphaMask = 1;
652             break;
653         }
654
655         pf.type = PictTypeDirect;
656         pf.direct.alpha = 0;
657
658         wine_tsx11_lock();
659         formatEntry->font_format = pXRenderFindFormat(gdi_display,
660                                                 PictFormatType |
661                                                 PictFormatDepth |
662                                                 PictFormatAlpha |
663                                                 PictFormatAlphaMask,
664                                                 &pf, 0);
665
666         formatEntry->glyphset = pXRenderCreateGlyphSet(gdi_display, formatEntry->font_format);
667         wine_tsx11_unlock();
668     }
669
670
671     buf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buflen);
672     GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, buflen, buf, NULL);
673     formatEntry->realized[glyph] = TRUE;
674
675     TRACE("buflen = %d. Got metrics: %dx%d adv=%d,%d origin=%ld,%ld\n",
676           buflen,
677           gm.gmBlackBoxX, gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY,
678           gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
679
680     gi.width = gm.gmBlackBoxX;
681     gi.height = gm.gmBlackBoxY;
682     gi.x = -gm.gmptGlyphOrigin.x;
683     gi.y = gm.gmptGlyphOrigin.y;
684     gi.xOff = gm.gmCellIncX;
685     gi.yOff = gm.gmCellIncY;
686
687     if(TRACE_ON(xrender)) {
688         int pitch, i, j;
689         char output[300];
690         unsigned char *line;
691
692         if(format == AA_None) {
693             pitch = ((gi.width + 31) / 32) * 4;
694             for(i = 0; i < gi.height; i++) {
695                 line = (unsigned char*) buf + i * pitch;
696                 output[0] = '\0';
697                 for(j = 0; j < pitch * 8; j++) {
698                     strcat(output, (line[j / 8] & (1 << (7 - (j % 8)))) ? "#" : " ");
699                 }
700                 strcat(output, "\n");
701                 TRACE(output);
702             }
703         } else {
704             static const char blks[] = " .:;!o*#";
705             char str[2];
706
707             str[1] = '\0';
708             pitch = ((gi.width + 3) / 4) * 4;
709             for(i = 0; i < gi.height; i++) {
710                 line = (unsigned char*) buf + i * pitch;
711                 output[0] = '\0';
712                 for(j = 0; j < pitch; j++) {
713                     str[0] = blks[line[j] >> 5];
714                     strcat(output, str);
715                 }
716                 strcat(output, "\n");
717                 TRACE(output);
718             }
719         }
720     }
721
722     if(formatEntry->glyphset) {
723         if(format == AA_None && BitmapBitOrder(gdi_display) != MSBFirst) {
724             unsigned char *byte = (unsigned char*) buf, c;
725             int i = buflen;
726
727             while(i--) {
728                 c = *byte;
729
730                 /* magic to flip bit order */
731                 c = ((c << 1) & 0xaa) | ((c >> 1) & 0x55);
732                 c = ((c << 2) & 0xcc) | ((c >> 2) & 0x33);
733                 c = ((c << 4) & 0xf0) | ((c >> 4) & 0x0f);
734
735                 *byte++ = c;
736             }
737         }
738         gid = glyph;
739         wine_tsx11_lock();
740         pXRenderAddGlyphs(gdi_display, formatEntry->glyphset, &gid, &gi, 1,
741                           buf, buflen);
742         wine_tsx11_unlock();
743         HeapFree(GetProcessHeap(), 0, buf);
744     } else {
745         formatEntry->bitmaps[glyph] = buf;
746         memcpy(&formatEntry->gis[glyph], &gi, sizeof(gi));
747     }
748     return TRUE;
749 }
750
751 static void SharpGlyphMono(X11DRV_PDEVICE *physDev, INT x, INT y,
752                             void *bitmap, XGlyphInfo *gi)
753 {
754     unsigned char   *srcLine = bitmap, *src;
755     unsigned char   bits, bitsMask;
756     int             width = gi->width;
757     int             stride = ((width + 31) & ~31) >> 3;
758     int             height = gi->height;
759     int             w;
760     int             xspan, lenspan;
761
762     TRACE("%d, %d\n", x, y);
763     x -= gi->x;
764     y -= gi->y;
765     while (height--)
766     {
767         src = srcLine;
768         srcLine += stride;
769         w = width;
770         
771         bitsMask = 0x80;    /* FreeType is always MSB first */
772         bits = *src++;
773         
774         xspan = x;
775         while (w)
776         {
777             if (bits & bitsMask)
778             {
779                 lenspan = 0;
780                 do
781                 {
782                     lenspan++;
783                     if (lenspan == w)
784                         break;
785                     bitsMask = bitsMask >> 1;
786                     if (!bitsMask)
787                     {
788                         bits = *src++;
789                         bitsMask = 0x80;
790                     }
791                 } while (bits & bitsMask);
792                 XFillRectangle (gdi_display, physDev->drawable, 
793                                 physDev->gc, xspan, y, lenspan, 1);
794                 xspan += lenspan;
795                 w -= lenspan;
796             }
797             else
798             {
799                 do
800                 {
801                     w--;
802                     xspan++;
803                     if (!w)
804                         break;
805                     bitsMask = bitsMask >> 1;
806                     if (!bitsMask)
807                     {
808                         bits = *src++;
809                         bitsMask = 0x80;
810                     }
811                 } while (!(bits & bitsMask));
812             }
813         }
814         y++;
815     }
816 }
817
818 static void SharpGlyphGray(X11DRV_PDEVICE *physDev, INT x, INT y,
819                             void *bitmap, XGlyphInfo *gi)
820 {
821     unsigned char   *srcLine = bitmap, *src, bits;
822     int             width = gi->width;
823     int             stride = ((width + 3) & ~3);
824     int             height = gi->height;
825     int             w;
826     int             xspan, lenspan;
827
828     x -= gi->x;
829     y -= gi->y;
830     while (height--)
831     {
832         src = srcLine;
833         srcLine += stride;
834         w = width;
835         
836         bits = *src++;
837         xspan = x;
838         while (w)
839         {
840             if (bits >= 0x80)
841             {
842                 lenspan = 0;
843                 do
844                 {
845                     lenspan++;
846                     if (lenspan == w)
847                         break;
848                     bits = *src++;
849                 } while (bits >= 0x80);
850                 XFillRectangle (gdi_display, physDev->drawable, 
851                                 physDev->gc, xspan, y, lenspan, 1);
852                 xspan += lenspan;
853                 w -= lenspan;
854             }
855             else
856             {
857                 do
858                 {
859                     w--;
860                     xspan++;
861                     if (!w)
862                         break;
863                     bits = *src++;
864                 } while (bits < 0x80);
865             }
866         }
867         y++;
868     }
869 }
870
871
872 static void ExamineBitfield (DWORD mask, int *shift, int *len)
873 {
874     int s, l;
875
876     s = 0;
877     while ((mask & 1) == 0)
878     {
879         mask >>= 1;
880         s++;
881     }
882     l = 0;
883     while ((mask & 1) == 1)
884     {
885         mask >>= 1;
886         l++;
887     }
888     *shift = s;
889     *len = l;
890 }
891
892 static DWORD GetField (DWORD pixel, int shift, int len)
893 {
894     pixel = pixel & (((1 << (len)) - 1) << shift);
895     pixel = pixel << (32 - (shift + len)) >> 24;
896     while (len < 8)
897     {
898         pixel |= (pixel >> len);
899         len <<= 1;
900     }
901     return pixel;
902 }
903
904
905 static DWORD PutField (DWORD pixel, int shift, int len)
906 {
907     shift = shift - (8 - len);
908     if (len <= 8)
909         pixel &= (((1 << len) - 1) << (8 - len));
910     if (shift < 0)
911         pixel >>= -shift;
912     else
913         pixel <<= shift;
914     return pixel;
915 }
916
917 static void SmoothGlyphGray(XImage *image, int x, int y, void *bitmap, XGlyphInfo *gi,
918                             int color)
919 {
920     int             r_shift, r_len;
921     int             g_shift, g_len;
922     int             b_shift, b_len;
923     BYTE            *maskLine, *mask, m;
924     int             maskStride;
925     DWORD           pixel;
926     int             width, height;
927     int             w, tx;
928     BYTE            src_r, src_g, src_b;
929
930     x -= gi->x;
931     y -= gi->y;
932     width = gi->width;
933     height = gi->height;
934
935     maskLine = (unsigned char *) bitmap;
936     maskStride = (width + 3) & ~3;
937
938     ExamineBitfield (image->red_mask, &r_shift, &r_len);
939     ExamineBitfield (image->green_mask, &g_shift, &g_len);
940     ExamineBitfield (image->blue_mask, &b_shift, &b_len);
941
942     src_r = GetField(color, r_shift, r_len);
943     src_g = GetField(color, g_shift, g_len);
944     src_b = GetField(color, b_shift, b_len);
945     
946     for(; height--; y++)
947     {
948         mask = maskLine;
949         maskLine += maskStride;
950         w = width;
951         tx = x;
952
953         if(y < 0) continue;
954         if(y >= image->height) break;
955
956         for(; w--; tx++)
957         {
958             if(tx >= image->width) break;
959
960             m = *mask++;
961             if(tx < 0) continue;
962
963             if (m == 0xff)
964                 XPutPixel (image, tx, y, color);
965             else if (m)
966             {
967                 BYTE r, g, b;
968
969                 pixel = XGetPixel (image, tx, y);
970
971                 r = GetField(pixel, r_shift, r_len);
972                 r = ((BYTE)~m * (WORD)r + (BYTE)m * (WORD)src_r) >> 8;
973                 g = GetField(pixel, g_shift, g_len);
974                 g = ((BYTE)~m * (WORD)g + (BYTE)m * (WORD)src_g) >> 8;
975                 b = GetField(pixel, b_shift, b_len);
976                 b = ((BYTE)~m * (WORD)b + (BYTE)m * (WORD)src_b) >> 8;
977
978                 pixel = (PutField (r, r_shift, r_len) |
979                          PutField (g, g_shift, g_len) |
980                          PutField (b, b_shift, b_len));
981                 XPutPixel (image, tx, y, pixel);
982             }
983         }
984     }
985 }
986
987 static int XRenderErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
988 {
989     return 1;
990 }
991
992 /***********************************************************************
993  *   X11DRV_XRender_ExtTextOut
994  */
995 BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
996                                 const RECT *lprect, LPCWSTR wstr, UINT count,
997                                 const INT *lpDx )
998 {
999     XRenderColor col;
1000     RGNDATA *data;
1001     XGCValues xgcval;
1002     int render_op = PictOpOver;
1003     gsCacheEntry *entry;
1004     gsCacheEntryFormat *formatEntry;
1005     BOOL retv = FALSE;
1006     HDC hdc = physDev->hdc;
1007     int textPixel, backgroundPixel;
1008     HRGN saved_region = 0;
1009     BOOL disable_antialias = FALSE;
1010     AA_Type antialias = AA_None;
1011     DIBSECTION bmp;
1012     unsigned int idx;
1013     double cosEsc, sinEsc;
1014     LOGFONTW lf;
1015
1016     /* Do we need to disable antialiasing because of palette mode? */
1017     if( !physDev->bitmap || GetObjectW( physDev->bitmap->hbitmap, sizeof(bmp), &bmp ) != sizeof(bmp) ) {
1018         TRACE("bitmap is not a DIB\n");
1019     }
1020     else if (bmp.dsBmih.biBitCount <= 8) {
1021         TRACE("Disabling antialiasing\n");
1022         disable_antialias = TRUE;
1023     }
1024
1025     xgcval.function = GXcopy;
1026     xgcval.background = physDev->backgroundPixel;
1027     xgcval.fill_style = FillSolid;
1028     wine_tsx11_lock();
1029     XChangeGC( gdi_display, physDev->gc, GCFunction | GCBackground | GCFillStyle, &xgcval );
1030     wine_tsx11_unlock();
1031
1032     X11DRV_LockDIBSection( physDev, DIB_Status_GdiMod, FALSE );
1033
1034     if(physDev->depth == 1) {
1035         if((physDev->textPixel & 0xffffff) == 0) {
1036             textPixel = 0;
1037             backgroundPixel = 1;
1038         } else {
1039             textPixel = 1;
1040             backgroundPixel = 0;
1041         }
1042     } else {
1043         textPixel = physDev->textPixel;
1044         backgroundPixel = physDev->backgroundPixel;
1045     }
1046
1047     if(flags & ETO_OPAQUE)
1048     {
1049         wine_tsx11_lock();
1050         XSetForeground( gdi_display, physDev->gc, backgroundPixel );
1051         XFillRectangle( gdi_display, physDev->drawable, physDev->gc,
1052                         physDev->org.x + lprect->left, physDev->org.y + lprect->top,
1053                         lprect->right - lprect->left, lprect->bottom - lprect->top );
1054         wine_tsx11_unlock();
1055     }
1056
1057     if(count == 0)
1058     {
1059         retv = TRUE;
1060         goto done_unlock;
1061     }
1062
1063     
1064     GetObjectW(GetCurrentObject(physDev->hdc, OBJ_FONT), sizeof(lf), &lf);
1065     if(lf.lfEscapement != 0) {
1066         cosEsc = cos(lf.lfEscapement * M_PI / 1800);
1067         sinEsc = sin(lf.lfEscapement * M_PI / 1800);
1068     } else {
1069         cosEsc = 1;
1070         sinEsc = 0;
1071     }
1072
1073     if (flags & ETO_CLIPPED)
1074     {
1075         HRGN clip_region;
1076
1077         clip_region = CreateRectRgnIndirect( lprect );
1078         /* make a copy of the current device region */
1079         saved_region = CreateRectRgn( 0, 0, 0, 0 );
1080         CombineRgn( saved_region, physDev->region, 0, RGN_COPY );
1081         X11DRV_SetDeviceClipping( physDev, saved_region, clip_region );
1082         DeleteObject( clip_region );
1083     }
1084
1085     if(X11DRV_XRender_Installed) {
1086         if(!physDev->xrender->pict) {
1087             XRenderPictureAttributes pa;
1088             pa.subwindow_mode = IncludeInferiors;
1089
1090             wine_tsx11_lock();
1091             physDev->xrender->pict = pXRenderCreatePicture(gdi_display,
1092                                                            physDev->drawable,
1093                                                            (physDev->depth == 1) ?
1094                                                            mono_format : screen_format,
1095                                                            CPSubwindowMode, &pa);
1096             wine_tsx11_unlock();
1097
1098             TRACE("allocing pict = %lx dc = %p drawable = %08lx\n",
1099                   physDev->xrender->pict, hdc, physDev->drawable);
1100         } else {
1101             TRACE("using existing pict = %lx dc = %p drawable = %08lx\n",
1102                   physDev->xrender->pict, hdc, physDev->drawable);
1103         }
1104
1105         if ((data = X11DRV_GetRegionData( physDev->region, 0 )))
1106         {
1107             wine_tsx11_lock();
1108             pXRenderSetPictureClipRectangles( gdi_display, physDev->xrender->pict,
1109                                               physDev->org.x, physDev->org.y,
1110                                               (XRectangle *)data->Buffer, data->rdh.nCount );
1111             wine_tsx11_unlock();
1112             HeapFree( GetProcessHeap(), 0, data );
1113         }
1114     }
1115
1116     if(X11DRV_XRender_Installed) {
1117         /* Create a 1x1 pixmap to tile over the font mask */
1118         if(!physDev->xrender->tile_xpm) {
1119             XRenderPictureAttributes pa;
1120
1121             XRenderPictFormat *format = (physDev->depth == 1) ? mono_format : screen_format;
1122             wine_tsx11_lock();
1123             physDev->xrender->tile_xpm = XCreatePixmap(gdi_display,
1124                                                        physDev->drawable,
1125                                                        1, 1,
1126                                                        format->depth);
1127             pa.repeat = True;
1128             physDev->xrender->tile_pict = pXRenderCreatePicture(gdi_display,
1129                                                                 physDev->xrender->tile_xpm,
1130                                                                 format,
1131                                                                 CPRepeat, &pa);
1132             wine_tsx11_unlock();
1133             TRACE("Created pixmap of depth %d\n", format->depth);
1134             /* init lastTextColor to something different from textPixel */
1135             physDev->xrender->lastTextColor = ~physDev->textPixel;
1136
1137         }
1138
1139         if(physDev->textPixel != physDev->xrender->lastTextColor) {
1140             if(physDev->depth != 1) {
1141                 /* Map 0 -- 0xff onto 0 -- 0xffff */
1142                 int             r_shift, r_len;
1143                 int             g_shift, g_len;
1144                 int             b_shift, b_len;
1145
1146                 ExamineBitfield (visual->red_mask, &r_shift, &r_len );
1147                 ExamineBitfield (visual->green_mask, &g_shift, &g_len);
1148                 ExamineBitfield (visual->blue_mask, &b_shift, &b_len);
1149
1150                 col.red = GetField(physDev->textPixel, r_shift, r_len);
1151                 col.red |= col.red << 8;
1152                 col.green = GetField(physDev->textPixel, g_shift, g_len);
1153                 col.green |= col.green << 8;
1154                 col.blue = GetField(physDev->textPixel, b_shift, b_len);
1155                 col.blue |= col.blue << 8;
1156                 col.alpha = 0x0;
1157             } else { /* for a 1bpp bitmap we always need a 1 in the tile */
1158                 col.red = col.green = col.blue = 0;
1159                 col.alpha = 0xffff;
1160             }
1161             wine_tsx11_lock();
1162             pXRenderFillRectangle(gdi_display, PictOpSrc,
1163                                   physDev->xrender->tile_pict,
1164                                   &col, 0, 0, 1, 1);
1165             wine_tsx11_unlock();
1166             physDev->xrender->lastTextColor = physDev->textPixel;
1167         }
1168
1169         /* FIXME the mapping of Text/BkColor onto 1 or 0 needs investigation.
1170          */
1171         if((physDev->depth == 1) && (textPixel == 0))
1172             render_op = PictOpOutReverse; /* This gives us 'black' text */
1173     }
1174
1175     EnterCriticalSection(&xrender_cs);
1176     entry = glyphsetCache + physDev->xrender->cache_index;
1177     if( disable_antialias == FALSE )
1178         antialias = entry->aa_default;
1179     formatEntry = entry->format[antialias];
1180
1181     for(idx = 0; idx < count; idx++) {
1182         if( !formatEntry ) {
1183             UploadGlyph(physDev, wstr[idx], antialias);
1184             formatEntry = entry->format[antialias];
1185         } else if( wstr[idx] >= formatEntry->nrealized || formatEntry->realized[wstr[idx]] == FALSE) {
1186             UploadGlyph(physDev, wstr[idx], antialias);
1187         }
1188     }
1189     assert(formatEntry);
1190
1191     TRACE("Writing %s at %ld,%ld\n", debugstr_wn(wstr,count),
1192           physDev->org.x + x, physDev->org.y + y);
1193
1194     if(X11DRV_XRender_Installed) {
1195         wine_tsx11_lock();
1196         if(!lpDx)
1197             pXRenderCompositeString16(gdi_display, render_op,
1198                                       physDev->xrender->tile_pict,
1199                                       physDev->xrender->pict,
1200                                       formatEntry->font_format, formatEntry->glyphset,
1201                                       0, 0, physDev->org.x + x, physDev->org.y + y,
1202                                       wstr, count);
1203         else {
1204             INT offset = 0, xoff = 0, yoff = 0;
1205             for(idx = 0; idx < count; idx++) {
1206                 pXRenderCompositeString16(gdi_display, render_op,
1207                                           physDev->xrender->tile_pict,
1208                                           physDev->xrender->pict,
1209                                           formatEntry->font_format, formatEntry->glyphset,
1210                                           0, 0, physDev->org.x + x + xoff,
1211                                           physDev->org.y + y + yoff,
1212                                           wstr + idx, 1);
1213                 offset += lpDx[idx];
1214                 xoff = offset * cosEsc;
1215                 yoff = offset * -sinEsc;
1216             }
1217         }
1218         wine_tsx11_unlock();
1219
1220     } else {
1221         INT offset = 0, xoff = 0, yoff = 0;
1222         wine_tsx11_lock();
1223         XSetForeground( gdi_display, physDev->gc, textPixel );
1224
1225         if(antialias == AA_None) {
1226             for(idx = 0; idx < count; idx++) {
1227                 SharpGlyphMono(physDev, physDev->org.x + x + xoff,
1228                                physDev->org.y + y + yoff,
1229                                formatEntry->bitmaps[wstr[idx]],
1230                                &formatEntry->gis[wstr[idx]]);
1231                 if(lpDx) {
1232                     offset += lpDx[idx];
1233                     xoff = offset * cosEsc;
1234                     yoff = offset * -sinEsc;
1235                 } else {
1236                     xoff += formatEntry->gis[wstr[idx]].xOff;
1237                     yoff += formatEntry->gis[wstr[idx]].yOff;
1238                 }
1239             }
1240         } else if(physDev->depth == 1) {
1241             for(idx = 0; idx < count; idx++) {
1242                 SharpGlyphGray(physDev, physDev->org.x + x + xoff,
1243                                physDev->org.y + y + yoff,
1244                                formatEntry->bitmaps[wstr[idx]],
1245                                &formatEntry->gis[wstr[idx]]);
1246                 if(lpDx) {
1247                     offset += lpDx[idx];
1248                     xoff = offset * cosEsc;
1249                     yoff = offset * -sinEsc;
1250                 } else {
1251                     xoff += formatEntry->gis[wstr[idx]].xOff;
1252                     yoff += formatEntry->gis[wstr[idx]].yOff;
1253                 }
1254                     
1255             }
1256         } else {
1257             XImage *image;
1258             unsigned int w, h, dummy_uint;
1259             Window dummy_window;
1260             int dummy_int;
1261             int image_x, image_y, image_off_x, image_off_y, image_w, image_h;
1262             RECT extents = {0, 0, 0, 0};
1263             POINT cur = {0, 0};
1264             
1265             
1266             XGetGeometry(gdi_display, physDev->drawable, &dummy_window, &dummy_int, &dummy_int,
1267                          &w, &h, &dummy_uint, &dummy_uint);
1268             TRACE("drawable %dx%d\n", w, h);
1269
1270             for(idx = 0; idx < count; idx++) {
1271                 if(extents.left > cur.x - formatEntry->gis[wstr[idx]].x)
1272                     extents.left = cur.x - formatEntry->gis[wstr[idx]].x;
1273                 if(extents.top > cur.y - formatEntry->gis[wstr[idx]].y)
1274                     extents.top = cur.y - formatEntry->gis[wstr[idx]].y;
1275                 if(extents.right < cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width)
1276                     extents.right = cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width;
1277                 if(extents.bottom < cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height)
1278                     extents.bottom = cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height;
1279                 if(lpDx) {
1280                     offset += lpDx[idx];
1281                     cur.x = offset * cosEsc;
1282                     cur.y = offset * -sinEsc;
1283                 } else {
1284                     cur.x += formatEntry->gis[wstr[idx]].xOff;
1285                     cur.y += formatEntry->gis[wstr[idx]].yOff;
1286                 }
1287             }
1288             TRACE("glyph extents %ld,%ld - %ld,%ld drawable x,y %ld,%ld\n", extents.left, extents.top,
1289                   extents.right, extents.bottom, physDev->org.x + x, physDev->org.y + y);
1290
1291             if(physDev->org.x + x + extents.left >= 0) {
1292                 image_x = physDev->org.x + x + extents.left;
1293                 image_off_x = 0;
1294             } else {
1295                 image_x = 0;
1296                 image_off_x = physDev->org.x + x + extents.left;
1297             }
1298             if(physDev->org.y + y + extents.top >= 0) {
1299                 image_y = physDev->org.y + y + extents.top;
1300                 image_off_y = 0;
1301             } else {
1302                 image_y = 0;
1303                 image_off_y = physDev->org.y + y + extents.top;
1304             }
1305             if(physDev->org.x + x + extents.right < w)
1306                 image_w = physDev->org.x + x + extents.right - image_x;
1307             else
1308                 image_w = w - image_x;
1309             if(physDev->org.y + y + extents.bottom < h)
1310                 image_h = physDev->org.y + y + extents.bottom - image_y;
1311             else
1312                 image_h = h - image_y;
1313
1314             if(image_w <= 0 || image_h <= 0) goto no_image;
1315
1316             X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1317             image = XGetImage(gdi_display, physDev->drawable,
1318                               image_x, image_y, image_w, image_h,
1319                               AllPlanes, ZPixmap);
1320             X11DRV_check_error();
1321
1322             TRACE("XGetImage(%p, %x, %d, %d, %d, %d, %lx, %x) depth = %d rets %p\n",
1323                   gdi_display, (int)physDev->drawable, image_x, image_y,
1324                   image_w, image_h, AllPlanes, ZPixmap,
1325                   physDev->depth, image);
1326             if(!image) {
1327                 Pixmap xpm = XCreatePixmap(gdi_display, physDev->drawable, image_w, image_h,
1328                                            physDev->depth);
1329                 GC gc;
1330                 XGCValues gcv;
1331
1332                 gcv.graphics_exposures = False;
1333                 gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
1334                 XCopyArea(gdi_display, physDev->drawable, xpm, gc, image_x, image_y,
1335                           image_w, image_h, 0, 0);
1336                 XFreeGC(gdi_display, gc);
1337                 X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1338                 image = XGetImage(gdi_display, xpm, 0, 0, image_w, image_h, AllPlanes,
1339                                   ZPixmap);
1340                 X11DRV_check_error();
1341                 XFreePixmap(gdi_display, xpm);
1342             }
1343             if(!image) goto no_image;
1344
1345             image->red_mask = visual->red_mask;
1346             image->green_mask = visual->green_mask;
1347             image->blue_mask = visual->blue_mask;
1348
1349             offset = xoff = yoff = 0;
1350             for(idx = 0; idx < count; idx++) {
1351                 SmoothGlyphGray(image, xoff + image_off_x - extents.left,
1352                                 yoff + image_off_y - extents.top,
1353                                 formatEntry->bitmaps[wstr[idx]],
1354                                 &formatEntry->gis[wstr[idx]],
1355                                 physDev->textPixel);
1356                 if(lpDx) {
1357                     offset += lpDx[idx];
1358                     xoff = offset * cosEsc;
1359                     yoff = offset * -sinEsc;
1360                 } else {
1361                     xoff += formatEntry->gis[wstr[idx]].xOff;
1362                     yoff += formatEntry->gis[wstr[idx]].yOff;
1363                 }
1364             }
1365             XPutImage(gdi_display, physDev->drawable, physDev->gc, image, 0, 0,
1366                       image_x, image_y, image_w, image_h);
1367             XDestroyImage(image);
1368         }
1369     no_image:
1370         wine_tsx11_unlock();
1371     }
1372     LeaveCriticalSection(&xrender_cs);
1373
1374     if (flags & ETO_CLIPPED)
1375     {
1376         /* restore the device region */
1377         X11DRV_SetDeviceClipping( physDev, saved_region, 0 );
1378         DeleteObject( saved_region );
1379     }
1380
1381     retv = TRUE;
1382
1383 done_unlock:
1384     X11DRV_UnlockDIBSection( physDev, TRUE );
1385     return retv;
1386 }
1387
1388 /******************************************************************************
1389  * AlphaBlend         (x11drv.@)
1390  */
1391 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1392                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1393                        BLENDFUNCTION blendfn)
1394 {
1395     XRenderPictureAttributes pa;
1396     XRenderPictFormat *src_format;
1397     XRenderPictFormat argb32_templ = {
1398         0,                          /* id */
1399         PictTypeDirect,             /* type */
1400         32,                         /* depth */
1401         {                           /* direct */
1402             16,                     /* direct.red */
1403             0xff,                   /* direct.redMask */
1404             8,                      /* direct.green */
1405             0xff,                   /* direct.greenMask */
1406             0,                      /* direct.blue */
1407             0xff,                   /* direct.blueMask */
1408             24,                     /* direct.alpha */
1409             0xff,                   /* direct.alphaMask */
1410         },
1411         0,                          /* colormap */
1412     };
1413     unsigned long argb32_templ_mask = 
1414         PictFormatType |
1415         PictFormatDepth |
1416         PictFormatRed |
1417         PictFormatRedMask |
1418         PictFormatGreen |
1419         PictFormatGreenMask |
1420         PictFormatBlue |
1421         PictFormatBlueMask |
1422         PictFormatAlpha |
1423         PictFormatAlphaMask;
1424
1425     Picture dst_pict, src_pict;
1426     Pixmap xpm;
1427     DIBSECTION dib;
1428     XImage *image;
1429     GC gc;
1430     XGCValues gcv;
1431     BYTE *dstbits, *data;
1432     int y, y2;
1433     POINT pts[2];
1434     BOOL top_down = FALSE;
1435     RGNDATA *rgndata;
1436
1437     if(!X11DRV_XRender_Installed) {
1438         FIXME("Unable to AlphaBlend without Xrender\n");
1439         return FALSE;
1440     }
1441     pts[0].x = xDst;
1442     pts[0].y = yDst;
1443     pts[1].x = xDst + widthDst;
1444     pts[1].y = yDst + heightDst;
1445     LPtoDP(devDst->hdc, pts, 2);
1446     xDst      = pts[0].x;
1447     yDst      = pts[0].y;
1448     widthDst  = pts[1].x - pts[0].x;
1449     heightDst = pts[1].y - pts[0].y;
1450
1451     pts[0].x = xSrc;
1452     pts[0].y = ySrc;
1453     pts[1].x = xSrc + widthSrc;
1454     pts[1].y = ySrc + heightSrc;
1455     LPtoDP(devSrc->hdc, pts, 2);
1456     xSrc      = pts[0].x;
1457     ySrc      = pts[0].y;
1458     widthSrc  = pts[1].x - pts[0].x;
1459     heightSrc = pts[1].y - pts[0].y;
1460
1461 #ifndef HAVE_XRENDERSETPICTURETRANSFORM
1462     if(widthDst != widthSrc || heightDst != heightSrc)
1463 #else
1464     if(!pXRenderSetPictureTransform)
1465 #endif
1466     {
1467         FIXME("Unable to Stretch, XRenderSetPictureTransform is currently required\n");
1468         return FALSE;
1469     }
1470
1471     if (!devSrc->bitmap || GetObjectW( devSrc->bitmap->hbitmap, sizeof(dib), &dib ) != sizeof(dib))
1472     {
1473         FIXME("not a dibsection\n");
1474         return FALSE;
1475     }
1476
1477     if(dib.dsBm.bmBitsPixel != 32) {
1478         FIXME("not a 32 bpp dibsection\n");
1479         return FALSE;
1480     }
1481     dstbits = data = HeapAlloc(GetProcessHeap(), 0, heightSrc * widthSrc * 4);
1482
1483     if(dib.dsBmih.biHeight < 0) { /* top-down dib */
1484         top_down = TRUE;
1485         dstbits += widthSrc * (heightSrc - 1) * 4;
1486         y2 = ySrc;
1487         y = y2 + heightSrc;
1488     }
1489     else
1490     {
1491         y = dib.dsBmih.biHeight - ySrc - 1;
1492         y2 = y - heightSrc;
1493     }
1494     for(; y > y2; y--) {
1495         memcpy(dstbits, (char *)dib.dsBm.bmBits + y * dib.dsBm.bmWidthBytes + xSrc * 4,
1496                widthSrc * 4);
1497         dstbits += (top_down ? -1 : 1) * widthSrc * 4;
1498     }
1499
1500     wine_tsx11_lock();
1501     image = XCreateImage(gdi_display, visual, 32, ZPixmap, 0,
1502                          (char*) data, widthSrc, heightSrc, 32, widthSrc * 4);
1503
1504     /*
1505       Avoid using XRenderFindStandardFormat as older libraries don't have it
1506       src_format = pXRenderFindStandardFormat(gdi_display, PictStandardARGB32);
1507     */
1508     src_format = pXRenderFindFormat(gdi_display, argb32_templ_mask, &argb32_templ, 0);
1509
1510     TRACE("src_format %p\n", src_format);
1511
1512     pa.subwindow_mode = IncludeInferiors;
1513
1514     /* FIXME use devDst->xrender->pict ? */
1515     dst_pict = pXRenderCreatePicture(gdi_display,
1516                                      devDst->drawable,
1517                                      (devDst->depth == 1) ?
1518                                      mono_format : screen_format,
1519                                      CPSubwindowMode, &pa);
1520     TRACE("dst_pict %08lx\n", dst_pict);
1521     TRACE("src_drawable = %08lx\n", devSrc->drawable);
1522     xpm = XCreatePixmap(gdi_display,
1523                         devSrc->drawable,
1524                         widthSrc, heightSrc, 32);
1525     gcv.graphics_exposures = False;
1526     gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
1527     TRACE("xpm = %08lx\n", xpm);
1528     XPutImage(gdi_display, xpm, gc, image, 0, 0, 0, 0, widthSrc, heightSrc);
1529
1530     src_pict = pXRenderCreatePicture(gdi_display,
1531                                      xpm, src_format,
1532                                      CPSubwindowMode, &pa);
1533     TRACE("src_pict %08lx\n", src_pict);
1534
1535     if ((rgndata = X11DRV_GetRegionData( devDst->region, 0 )))
1536     {
1537         pXRenderSetPictureClipRectangles( gdi_display, dst_pict,
1538                                           devDst->org.x, devDst->org.y,
1539                                           (XRectangle *)rgndata->Buffer, 
1540                                           rgndata->rdh.nCount );
1541         HeapFree( GetProcessHeap(), 0, rgndata );
1542     }
1543
1544 #ifdef HAVE_XRENDERSETPICTURETRANSFORM
1545     if(widthDst != widthSrc || heightDst != heightSrc) {
1546         double xscale = widthSrc/(double)widthDst;
1547         double yscale = heightSrc/(double)heightDst;
1548         XTransform xform = {{
1549             { XDoubleToFixed(xscale), XDoubleToFixed(0), XDoubleToFixed(0) },
1550             { XDoubleToFixed(0), XDoubleToFixed(yscale), XDoubleToFixed(0) },
1551             { XDoubleToFixed(0), XDoubleToFixed(0), XDoubleToFixed(1) }
1552         }};
1553         pXRenderSetPictureTransform(gdi_display, src_pict, &xform);
1554     }
1555 #endif
1556     pXRenderComposite(gdi_display, PictOpOver, src_pict, 0, dst_pict,
1557                       0, 0, 0, 0,
1558                       xDst + devDst->org.x, yDst + devDst->org.y, widthDst, heightDst);
1559
1560
1561     pXRenderFreePicture(gdi_display, src_pict);
1562     XFreePixmap(gdi_display, xpm);
1563     XFreeGC(gdi_display, gc);
1564     pXRenderFreePicture(gdi_display, dst_pict);
1565     image->data = NULL;
1566     XDestroyImage(image);
1567
1568     wine_tsx11_unlock();
1569     HeapFree(GetProcessHeap(), 0, data);
1570     return TRUE;
1571 }
1572
1573 #else /* HAVE_X11_EXTENSIONS_XRENDER_H */
1574
1575 void X11DRV_XRender_Init(void)
1576 {
1577     TRACE("XRender support not compiled in.\n");
1578     return;
1579 }
1580
1581 void X11DRV_XRender_Finalize(void)
1582 {
1583 }
1584
1585 BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
1586 {
1587   assert(0);
1588   return FALSE;
1589 }
1590
1591 void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
1592 {
1593   assert(0);
1594   return;
1595 }
1596
1597 BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
1598                                 const RECT *lprect, LPCWSTR wstr, UINT count,
1599                                 const INT *lpDx, INT breakExtra )
1600 {
1601   assert(0);
1602   return FALSE;
1603 }
1604
1605 void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
1606 {
1607   assert(0);
1608   return;
1609 }
1610
1611 /******************************************************************************
1612  * AlphaBlend         (x11drv.@)
1613  */
1614 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1615                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1616                        BLENDFUNCTION blendfn)
1617 {
1618   FIXME("not supported - XRENDER headers were missing at compile time\n");
1619   return FALSE;
1620 }
1621
1622 #endif /* HAVE_X11_EXTENSIONS_XRENDER_H */