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