Don't redefine ASN_OCTETSTRING, it's already defined in snmp.h.
[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, *buffer;
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 = buffer = 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, buffer);
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     static int hinter = -1;
468
469     if((ret = LookupEntry(plfsz)) != -1) return ret;
470
471     ret = AllocEntry();
472     entry = glyphsetCache + ret;
473     entry->lfsz = *plfsz;
474     for( format = 0; format < AA_MAXVALUE; format++ ) {
475         assert( !entry->format[format] );
476     }
477
478     if(antialias && plfsz->lf.lfQuality != NONANTIALIASED_QUALITY)
479     {
480         if(hinter == -1)
481         {
482             RASTERIZER_STATUS status;
483             GetRasterizerCaps(&status, sizeof(status));
484             hinter = status.wFlags & WINE_TT_HINTER_ENABLED;
485         }
486         if(!hinter || !get_gasp_flags(physDev, &flags) || flags & GASP_DOGRAY)
487             entry->aa_default = AA_Grey;
488         else
489             entry->aa_default = AA_None;
490     }
491     else
492         entry->aa_default = AA_None;
493
494     return ret;
495 }
496
497 static void dec_ref_cache(int index)
498 {
499     assert(index >= 0);
500     TRACE("dec'ing entry %d to %d\n", index, glyphsetCache[index].count - 1);
501     assert(glyphsetCache[index].count > 0);
502     glyphsetCache[index].count--;
503 }
504
505 static void lfsz_calc_hash(LFANDSIZE *plfsz)
506 {
507   DWORD hash = 0, *ptr;
508   int i;
509
510   hash ^= plfsz->devsize.cx;
511   hash ^= plfsz->devsize.cy;
512   for(i = 0, ptr = (DWORD*)&plfsz->lf; i < 7; i++, ptr++)
513     hash ^= *ptr;
514   for(i = 0, ptr = (DWORD*)&plfsz->lf.lfFaceName; i < LF_FACESIZE/2; i++, ptr++) {
515     WCHAR *pwc = (WCHAR *)ptr;
516     if(!*pwc) break;
517     hash ^= *ptr;
518     pwc++;
519     if(!*pwc) break;
520   }
521   plfsz->hash = hash;
522   return;
523 }
524
525 /***********************************************************************
526  *   X11DRV_XRender_Finalize
527  */
528 void X11DRV_XRender_Finalize(void)
529 {
530     int i;
531
532     EnterCriticalSection(&xrender_cs);
533     for(i = mru; i >= 0; i = glyphsetCache[i].next)
534         FreeEntry(i);
535     LeaveCriticalSection(&xrender_cs);
536 }
537
538
539 /***********************************************************************
540  *   X11DRV_XRender_SelectFont
541  */
542 BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
543 {
544     LFANDSIZE lfsz;
545
546     GetObjectW(hfont, sizeof(lfsz.lf), &lfsz.lf);
547     TRACE("h=%ld w=%ld weight=%ld it=%d charset=%d name=%s\n",
548           lfsz.lf.lfHeight, lfsz.lf.lfWidth, lfsz.lf.lfWeight,
549           lfsz.lf.lfItalic, lfsz.lf.lfCharSet, debugstr_w(lfsz.lf.lfFaceName));
550     lfsz.devsize.cx = X11DRV_XWStoDS( physDev, lfsz.lf.lfWidth );
551     lfsz.devsize.cy = X11DRV_YWStoDS( physDev, lfsz.lf.lfHeight );
552     lfsz_calc_hash(&lfsz);
553
554     EnterCriticalSection(&xrender_cs);
555     if(!physDev->xrender) {
556         physDev->xrender = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
557                                      sizeof(*physDev->xrender));
558         physDev->xrender->cache_index = -1;
559     }
560     else if(physDev->xrender->cache_index != -1)
561         dec_ref_cache(physDev->xrender->cache_index);
562     physDev->xrender->cache_index = GetCacheEntry(physDev, &lfsz);
563     LeaveCriticalSection(&xrender_cs);
564     return 0;
565 }
566
567 /***********************************************************************
568  *   X11DRV_XRender_DeleteDC
569  */
570 void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
571 {
572     wine_tsx11_lock();
573     if(physDev->xrender->tile_pict)
574         pXRenderFreePicture(gdi_display, physDev->xrender->tile_pict);
575
576     if(physDev->xrender->tile_xpm)
577         XFreePixmap(gdi_display, physDev->xrender->tile_xpm);
578
579     if(physDev->xrender->pict) {
580         TRACE("freeing pict = %lx dc = %p\n", physDev->xrender->pict, physDev->hdc);
581         pXRenderFreePicture(gdi_display, physDev->xrender->pict);
582     }
583     wine_tsx11_unlock();
584
585     EnterCriticalSection(&xrender_cs);
586     if(physDev->xrender->cache_index != -1)
587         dec_ref_cache(physDev->xrender->cache_index);
588     LeaveCriticalSection(&xrender_cs);
589
590     HeapFree(GetProcessHeap(), 0, physDev->xrender);
591     physDev->xrender = NULL;
592     return;
593 }
594
595 /***********************************************************************
596  *   X11DRV_XRender_UpdateDrawable
597  *
598  * This gets called from X11DRV_SetDrawable and X11DRV_SelectBitmap.
599  * It deletes the pict when the drawable changes.
600  */
601 void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
602 {
603     if(physDev->xrender->pict) {
604         TRACE("freeing pict %08lx from dc %p drawable %08lx\n", physDev->xrender->pict,
605               physDev->hdc, physDev->drawable);
606         wine_tsx11_lock();
607         XFlush(gdi_display);
608         pXRenderFreePicture(gdi_display, physDev->xrender->pict);
609         wine_tsx11_unlock();
610     }
611     physDev->xrender->pict = 0;
612     return;
613 }
614
615 /************************************************************************
616  *   UploadGlyph
617  *
618  * Helper to ExtTextOut.  Must be called inside xrender_cs
619  */
620 static BOOL UploadGlyph(X11DRV_PDEVICE *physDev, int glyph, AA_Type format)
621 {
622     unsigned int buflen;
623     char *buf;
624     Glyph gid;
625     GLYPHMETRICS gm;
626     XGlyphInfo gi;
627     gsCacheEntry *entry = glyphsetCache + physDev->xrender->cache_index;
628     gsCacheEntryFormat *formatEntry;
629     UINT ggo_format = GGO_GLYPH_INDEX;
630     XRenderPictFormat pf;
631
632     /* If there is nothing for the current type, we create the entry. */
633     if( !entry->format[format] ) {
634         entry->format[format] = HeapAlloc(GetProcessHeap(),
635                                           HEAP_ZERO_MEMORY,
636                                           sizeof(gsCacheEntryFormat));
637     }
638     formatEntry = entry->format[format];
639
640     if(formatEntry->nrealized <= glyph) {
641         formatEntry->nrealized = (glyph / 128 + 1) * 128;
642
643         if (formatEntry->realized)
644             formatEntry->realized = HeapReAlloc(GetProcessHeap(),
645                                       HEAP_ZERO_MEMORY,
646                                       formatEntry->realized,
647                                       formatEntry->nrealized * sizeof(BOOL));
648         else
649             formatEntry->realized = HeapAlloc(GetProcessHeap(),
650                                       HEAP_ZERO_MEMORY,
651                                       formatEntry->nrealized * sizeof(BOOL));
652
653         if(!X11DRV_XRender_Installed) {
654           if (formatEntry->bitmaps)
655             formatEntry->bitmaps = HeapReAlloc(GetProcessHeap(),
656                                       HEAP_ZERO_MEMORY,
657                                       formatEntry->bitmaps,
658                                       formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
659           else
660             formatEntry->bitmaps = HeapAlloc(GetProcessHeap(),
661                                       HEAP_ZERO_MEMORY,
662                                       formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
663
664           if (formatEntry->gis)
665             formatEntry->gis = HeapReAlloc(GetProcessHeap(),
666                                    HEAP_ZERO_MEMORY,
667                                    formatEntry->gis,
668                                    formatEntry->nrealized * sizeof(formatEntry->gis[0]));
669           else
670             formatEntry->gis = HeapAlloc(GetProcessHeap(),
671                                    HEAP_ZERO_MEMORY,
672                                    formatEntry->nrealized * sizeof(formatEntry->gis[0]));
673         }
674     }
675
676     switch(format) {
677     case AA_Grey:
678         ggo_format |= WINE_GGO_GRAY16_BITMAP;
679         break;
680
681     default:
682         ERR("aa = %d - not implemented\n", format);
683     case AA_None:
684         ggo_format |= GGO_BITMAP;
685         break;
686     }
687
688     buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
689                               NULL);
690     if(buflen == GDI_ERROR) {
691         if(format != AA_None) {
692             format = AA_None;
693             entry->aa_default = AA_None;
694             ggo_format &= ~WINE_GGO_GRAY16_BITMAP;
695             ggo_format |= GGO_BITMAP;
696             buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
697                                       NULL);
698         }
699         if(buflen == GDI_ERROR) {
700             ERR("GetGlyphOutlineW failed\n");
701             return FALSE;
702         }
703         TRACE("Turning off antialiasing for this monochrome font\n");
704     }
705
706     if(formatEntry->glyphset == 0 && X11DRV_XRender_Installed) {
707         switch(format) {
708         case AA_Grey:
709             pf.depth = 8;
710             pf.direct.alphaMask = 0xff;
711             break;
712
713         default:
714             ERR("aa = %d - not implemented\n", format);
715         case AA_None:
716             pf.depth = 1;
717             pf.direct.alphaMask = 1;
718             break;
719         }
720
721         pf.type = PictTypeDirect;
722         pf.direct.alpha = 0;
723
724         wine_tsx11_lock();
725         formatEntry->font_format = pXRenderFindFormat(gdi_display,
726                                                 PictFormatType |
727                                                 PictFormatDepth |
728                                                 PictFormatAlpha |
729                                                 PictFormatAlphaMask,
730                                                 &pf, 0);
731
732         formatEntry->glyphset = pXRenderCreateGlyphSet(gdi_display, formatEntry->font_format);
733         wine_tsx11_unlock();
734     }
735
736
737     buf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buflen);
738     GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, buflen, buf, NULL);
739     formatEntry->realized[glyph] = TRUE;
740
741     TRACE("buflen = %d. Got metrics: %dx%d adv=%d,%d origin=%ld,%ld\n",
742           buflen,
743           gm.gmBlackBoxX, gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY,
744           gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
745
746     gi.width = gm.gmBlackBoxX;
747     gi.height = gm.gmBlackBoxY;
748     gi.x = -gm.gmptGlyphOrigin.x;
749     gi.y = gm.gmptGlyphOrigin.y;
750     gi.xOff = gm.gmCellIncX;
751     gi.yOff = gm.gmCellIncY;
752
753     if(TRACE_ON(xrender)) {
754         int pitch, i, j;
755         char output[300];
756         unsigned char *line;
757
758         if(format == AA_None) {
759             pitch = ((gi.width + 31) / 32) * 4;
760             for(i = 0; i < gi.height; i++) {
761                 line = (unsigned char*) buf + i * pitch;
762                 output[0] = '\0';
763                 for(j = 0; j < pitch * 8; j++) {
764                     strcat(output, (line[j / 8] & (1 << (7 - (j % 8)))) ? "#" : " ");
765                 }
766                 strcat(output, "\n");
767                 TRACE(output);
768             }
769         } else {
770             static const char blks[] = " .:;!o*#";
771             char str[2];
772
773             str[1] = '\0';
774             pitch = ((gi.width + 3) / 4) * 4;
775             for(i = 0; i < gi.height; i++) {
776                 line = (unsigned char*) buf + i * pitch;
777                 output[0] = '\0';
778                 for(j = 0; j < pitch; j++) {
779                     str[0] = blks[line[j] >> 5];
780                     strcat(output, str);
781                 }
782                 strcat(output, "\n");
783                 TRACE(output);
784             }
785         }
786     }
787
788     if(formatEntry->glyphset) {
789         if(format == AA_None && BitmapBitOrder(gdi_display) != MSBFirst) {
790             unsigned char *byte = (unsigned char*) buf, c;
791             int i = buflen;
792
793             while(i--) {
794                 c = *byte;
795
796                 /* magic to flip bit order */
797                 c = ((c << 1) & 0xaa) | ((c >> 1) & 0x55);
798                 c = ((c << 2) & 0xcc) | ((c >> 2) & 0x33);
799                 c = ((c << 4) & 0xf0) | ((c >> 4) & 0x0f);
800
801                 *byte++ = c;
802             }
803         }
804         gid = glyph;
805         wine_tsx11_lock();
806         pXRenderAddGlyphs(gdi_display, formatEntry->glyphset, &gid, &gi, 1,
807                           buf, buflen);
808         wine_tsx11_unlock();
809         HeapFree(GetProcessHeap(), 0, buf);
810     } else {
811         formatEntry->bitmaps[glyph] = buf;
812         memcpy(&formatEntry->gis[glyph], &gi, sizeof(gi));
813     }
814     return TRUE;
815 }
816
817 static void SharpGlyphMono(X11DRV_PDEVICE *physDev, INT x, INT y,
818                             void *bitmap, XGlyphInfo *gi)
819 {
820     unsigned char   *srcLine = bitmap, *src;
821     unsigned char   bits, bitsMask;
822     int             width = gi->width;
823     int             stride = ((width + 31) & ~31) >> 3;
824     int             height = gi->height;
825     int             w;
826     int             xspan, lenspan;
827
828     TRACE("%d, %d\n", x, y);
829     x -= gi->x;
830     y -= gi->y;
831     while (height--)
832     {
833         src = srcLine;
834         srcLine += stride;
835         w = width;
836         
837         bitsMask = 0x80;    /* FreeType is always MSB first */
838         bits = *src++;
839         
840         xspan = x;
841         while (w)
842         {
843             if (bits & bitsMask)
844             {
845                 lenspan = 0;
846                 do
847                 {
848                     lenspan++;
849                     if (lenspan == w)
850                         break;
851                     bitsMask = bitsMask >> 1;
852                     if (!bitsMask)
853                     {
854                         bits = *src++;
855                         bitsMask = 0x80;
856                     }
857                 } while (bits & bitsMask);
858                 XFillRectangle (gdi_display, physDev->drawable, 
859                                 physDev->gc, xspan, y, lenspan, 1);
860                 xspan += lenspan;
861                 w -= lenspan;
862             }
863             else
864             {
865                 do
866                 {
867                     w--;
868                     xspan++;
869                     if (!w)
870                         break;
871                     bitsMask = bitsMask >> 1;
872                     if (!bitsMask)
873                     {
874                         bits = *src++;
875                         bitsMask = 0x80;
876                     }
877                 } while (!(bits & bitsMask));
878             }
879         }
880         y++;
881     }
882 }
883
884 static void SharpGlyphGray(X11DRV_PDEVICE *physDev, INT x, INT y,
885                             void *bitmap, XGlyphInfo *gi)
886 {
887     unsigned char   *srcLine = bitmap, *src, bits;
888     int             width = gi->width;
889     int             stride = ((width + 3) & ~3);
890     int             height = gi->height;
891     int             w;
892     int             xspan, lenspan;
893
894     x -= gi->x;
895     y -= gi->y;
896     while (height--)
897     {
898         src = srcLine;
899         srcLine += stride;
900         w = width;
901         
902         bits = *src++;
903         xspan = x;
904         while (w)
905         {
906             if (bits >= 0x80)
907             {
908                 lenspan = 0;
909                 do
910                 {
911                     lenspan++;
912                     if (lenspan == w)
913                         break;
914                     bits = *src++;
915                 } while (bits >= 0x80);
916                 XFillRectangle (gdi_display, physDev->drawable, 
917                                 physDev->gc, xspan, y, lenspan, 1);
918                 xspan += lenspan;
919                 w -= lenspan;
920             }
921             else
922             {
923                 do
924                 {
925                     w--;
926                     xspan++;
927                     if (!w)
928                         break;
929                     bits = *src++;
930                 } while (bits < 0x80);
931             }
932         }
933         y++;
934     }
935 }
936
937
938 static void ExamineBitfield (DWORD mask, int *shift, int *len)
939 {
940     int s, l;
941
942     s = 0;
943     while ((mask & 1) == 0)
944     {
945         mask >>= 1;
946         s++;
947     }
948     l = 0;
949     while ((mask & 1) == 1)
950     {
951         mask >>= 1;
952         l++;
953     }
954     *shift = s;
955     *len = l;
956 }
957
958 static DWORD GetField (DWORD pixel, int shift, int len)
959 {
960     pixel = pixel & (((1 << (len)) - 1) << shift);
961     pixel = pixel << (32 - (shift + len)) >> 24;
962     while (len < 8)
963     {
964         pixel |= (pixel >> len);
965         len <<= 1;
966     }
967     return pixel;
968 }
969
970
971 static DWORD PutField (DWORD pixel, int shift, int len)
972 {
973     shift = shift - (8 - len);
974     if (len <= 8)
975         pixel &= (((1 << len) - 1) << (8 - len));
976     if (shift < 0)
977         pixel >>= -shift;
978     else
979         pixel <<= shift;
980     return pixel;
981 }
982
983 static void SmoothGlyphGray(XImage *image, int x, int y, void *bitmap, XGlyphInfo *gi,
984                             int color)
985 {
986     int             r_shift, r_len;
987     int             g_shift, g_len;
988     int             b_shift, b_len;
989     BYTE            *maskLine, *mask, m;
990     int             maskStride;
991     DWORD           pixel;
992     int             width, height;
993     int             w, tx;
994     BYTE            src_r, src_g, src_b;
995
996     x -= gi->x;
997     y -= gi->y;
998     width = gi->width;
999     height = gi->height;
1000
1001     maskLine = (unsigned char *) bitmap;
1002     maskStride = (width + 3) & ~3;
1003
1004     ExamineBitfield (image->red_mask, &r_shift, &r_len);
1005     ExamineBitfield (image->green_mask, &g_shift, &g_len);
1006     ExamineBitfield (image->blue_mask, &b_shift, &b_len);
1007
1008     src_r = GetField(color, r_shift, r_len);
1009     src_g = GetField(color, g_shift, g_len);
1010     src_b = GetField(color, b_shift, b_len);
1011     
1012     for(; height--; y++)
1013     {
1014         mask = maskLine;
1015         maskLine += maskStride;
1016         w = width;
1017         tx = x;
1018
1019         if(y < 0) continue;
1020         if(y >= image->height) break;
1021
1022         for(; w--; tx++)
1023         {
1024             if(tx >= image->width) break;
1025
1026             m = *mask++;
1027             if(tx < 0) continue;
1028
1029             if (m == 0xff)
1030                 XPutPixel (image, tx, y, color);
1031             else if (m)
1032             {
1033                 BYTE r, g, b;
1034
1035                 pixel = XGetPixel (image, tx, y);
1036
1037                 r = GetField(pixel, r_shift, r_len);
1038                 r = ((BYTE)~m * (WORD)r + (BYTE)m * (WORD)src_r) >> 8;
1039                 g = GetField(pixel, g_shift, g_len);
1040                 g = ((BYTE)~m * (WORD)g + (BYTE)m * (WORD)src_g) >> 8;
1041                 b = GetField(pixel, b_shift, b_len);
1042                 b = ((BYTE)~m * (WORD)b + (BYTE)m * (WORD)src_b) >> 8;
1043
1044                 pixel = (PutField (r, r_shift, r_len) |
1045                          PutField (g, g_shift, g_len) |
1046                          PutField (b, b_shift, b_len));
1047                 XPutPixel (image, tx, y, pixel);
1048             }
1049         }
1050     }
1051 }
1052
1053 static int XRenderErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
1054 {
1055     return 1;
1056 }
1057
1058 /***********************************************************************
1059  *   X11DRV_XRender_ExtTextOut
1060  */
1061 BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
1062                                 const RECT *lprect, LPCWSTR wstr, UINT count,
1063                                 const INT *lpDx )
1064 {
1065     XRenderColor col;
1066     RGNDATA *data;
1067     XGCValues xgcval;
1068     int render_op = PictOpOver;
1069     gsCacheEntry *entry;
1070     gsCacheEntryFormat *formatEntry;
1071     BOOL retv = FALSE;
1072     HDC hdc = physDev->hdc;
1073     int textPixel, backgroundPixel;
1074     HRGN saved_region = 0;
1075     BOOL disable_antialias = FALSE;
1076     AA_Type antialias = AA_None;
1077     DIBSECTION bmp;
1078     unsigned int idx;
1079     double cosEsc, sinEsc;
1080     LOGFONTW lf;
1081
1082     /* Do we need to disable antialiasing because of palette mode? */
1083     if( !physDev->bitmap || GetObjectW( physDev->bitmap->hbitmap, sizeof(bmp), &bmp ) != sizeof(bmp) ) {
1084         TRACE("bitmap is not a DIB\n");
1085     }
1086     else if (bmp.dsBmih.biBitCount <= 8) {
1087         TRACE("Disabling antialiasing\n");
1088         disable_antialias = TRUE;
1089     }
1090
1091     xgcval.function = GXcopy;
1092     xgcval.background = physDev->backgroundPixel;
1093     xgcval.fill_style = FillSolid;
1094     wine_tsx11_lock();
1095     XChangeGC( gdi_display, physDev->gc, GCFunction | GCBackground | GCFillStyle, &xgcval );
1096     wine_tsx11_unlock();
1097
1098     X11DRV_LockDIBSection( physDev, DIB_Status_GdiMod, FALSE );
1099
1100     if(physDev->depth == 1) {
1101         if((physDev->textPixel & 0xffffff) == 0) {
1102             textPixel = 0;
1103             backgroundPixel = 1;
1104         } else {
1105             textPixel = 1;
1106             backgroundPixel = 0;
1107         }
1108     } else {
1109         textPixel = physDev->textPixel;
1110         backgroundPixel = physDev->backgroundPixel;
1111     }
1112
1113     if(flags & ETO_OPAQUE)
1114     {
1115         wine_tsx11_lock();
1116         XSetForeground( gdi_display, physDev->gc, backgroundPixel );
1117         XFillRectangle( gdi_display, physDev->drawable, physDev->gc,
1118                         physDev->org.x + lprect->left, physDev->org.y + lprect->top,
1119                         lprect->right - lprect->left, lprect->bottom - lprect->top );
1120         wine_tsx11_unlock();
1121     }
1122
1123     if(count == 0)
1124     {
1125         retv = TRUE;
1126         goto done_unlock;
1127     }
1128
1129     
1130     GetObjectW(GetCurrentObject(physDev->hdc, OBJ_FONT), sizeof(lf), &lf);
1131     if(lf.lfEscapement != 0) {
1132         cosEsc = cos(lf.lfEscapement * M_PI / 1800);
1133         sinEsc = sin(lf.lfEscapement * M_PI / 1800);
1134     } else {
1135         cosEsc = 1;
1136         sinEsc = 0;
1137     }
1138
1139     if (flags & ETO_CLIPPED)
1140     {
1141         HRGN clip_region;
1142
1143         clip_region = CreateRectRgnIndirect( lprect );
1144         /* make a copy of the current device region */
1145         saved_region = CreateRectRgn( 0, 0, 0, 0 );
1146         CombineRgn( saved_region, physDev->region, 0, RGN_COPY );
1147         X11DRV_SetDeviceClipping( physDev, saved_region, clip_region );
1148         DeleteObject( clip_region );
1149     }
1150
1151     if(X11DRV_XRender_Installed) {
1152         if(!physDev->xrender->pict) {
1153             XRenderPictureAttributes pa;
1154             pa.subwindow_mode = IncludeInferiors;
1155
1156             wine_tsx11_lock();
1157             physDev->xrender->pict = pXRenderCreatePicture(gdi_display,
1158                                                            physDev->drawable,
1159                                                            (physDev->depth == 1) ?
1160                                                            mono_format : screen_format,
1161                                                            CPSubwindowMode, &pa);
1162             wine_tsx11_unlock();
1163
1164             TRACE("allocing pict = %lx dc = %p drawable = %08lx\n",
1165                   physDev->xrender->pict, hdc, physDev->drawable);
1166         } else {
1167             TRACE("using existing pict = %lx dc = %p drawable = %08lx\n",
1168                   physDev->xrender->pict, hdc, physDev->drawable);
1169         }
1170
1171         if ((data = X11DRV_GetRegionData( physDev->region, 0 )))
1172         {
1173             wine_tsx11_lock();
1174             pXRenderSetPictureClipRectangles( gdi_display, physDev->xrender->pict,
1175                                               physDev->org.x, physDev->org.y,
1176                                               (XRectangle *)data->Buffer, data->rdh.nCount );
1177             wine_tsx11_unlock();
1178             HeapFree( GetProcessHeap(), 0, data );
1179         }
1180     }
1181
1182     if(X11DRV_XRender_Installed) {
1183         /* Create a 1x1 pixmap to tile over the font mask */
1184         if(!physDev->xrender->tile_xpm) {
1185             XRenderPictureAttributes pa;
1186
1187             XRenderPictFormat *format = (physDev->depth == 1) ? mono_format : screen_format;
1188             wine_tsx11_lock();
1189             physDev->xrender->tile_xpm = XCreatePixmap(gdi_display,
1190                                                        physDev->drawable,
1191                                                        1, 1,
1192                                                        format->depth);
1193             pa.repeat = True;
1194             physDev->xrender->tile_pict = pXRenderCreatePicture(gdi_display,
1195                                                                 physDev->xrender->tile_xpm,
1196                                                                 format,
1197                                                                 CPRepeat, &pa);
1198             wine_tsx11_unlock();
1199             TRACE("Created pixmap of depth %d\n", format->depth);
1200             /* init lastTextColor to something different from textPixel */
1201             physDev->xrender->lastTextColor = ~physDev->textPixel;
1202
1203         }
1204
1205         if(physDev->textPixel != physDev->xrender->lastTextColor) {
1206             if(physDev->depth != 1) {
1207                 /* Map 0 -- 0xff onto 0 -- 0xffff */
1208                 int             r_shift, r_len;
1209                 int             g_shift, g_len;
1210                 int             b_shift, b_len;
1211
1212                 ExamineBitfield (visual->red_mask, &r_shift, &r_len );
1213                 ExamineBitfield (visual->green_mask, &g_shift, &g_len);
1214                 ExamineBitfield (visual->blue_mask, &b_shift, &b_len);
1215
1216                 col.red = GetField(physDev->textPixel, r_shift, r_len);
1217                 col.red |= col.red << 8;
1218                 col.green = GetField(physDev->textPixel, g_shift, g_len);
1219                 col.green |= col.green << 8;
1220                 col.blue = GetField(physDev->textPixel, b_shift, b_len);
1221                 col.blue |= col.blue << 8;
1222                 col.alpha = 0x0;
1223             } else { /* for a 1bpp bitmap we always need a 1 in the tile */
1224                 col.red = col.green = col.blue = 0;
1225                 col.alpha = 0xffff;
1226             }
1227             wine_tsx11_lock();
1228             pXRenderFillRectangle(gdi_display, PictOpSrc,
1229                                   physDev->xrender->tile_pict,
1230                                   &col, 0, 0, 1, 1);
1231             wine_tsx11_unlock();
1232             physDev->xrender->lastTextColor = physDev->textPixel;
1233         }
1234
1235         /* FIXME the mapping of Text/BkColor onto 1 or 0 needs investigation.
1236          */
1237         if((physDev->depth == 1) && (textPixel == 0))
1238             render_op = PictOpOutReverse; /* This gives us 'black' text */
1239     }
1240
1241     EnterCriticalSection(&xrender_cs);
1242     entry = glyphsetCache + physDev->xrender->cache_index;
1243     if( disable_antialias == FALSE )
1244         antialias = entry->aa_default;
1245     formatEntry = entry->format[antialias];
1246
1247     for(idx = 0; idx < count; idx++) {
1248         if( !formatEntry ) {
1249             UploadGlyph(physDev, wstr[idx], antialias);
1250             formatEntry = entry->format[antialias];
1251         } else if( wstr[idx] >= formatEntry->nrealized || formatEntry->realized[wstr[idx]] == FALSE) {
1252             UploadGlyph(physDev, wstr[idx], antialias);
1253         }
1254     }
1255     assert(formatEntry);
1256
1257     TRACE("Writing %s at %ld,%ld\n", debugstr_wn(wstr,count),
1258           physDev->org.x + x, physDev->org.y + y);
1259
1260     if(X11DRV_XRender_Installed) {
1261         wine_tsx11_lock();
1262         if(!lpDx)
1263             pXRenderCompositeString16(gdi_display, render_op,
1264                                       physDev->xrender->tile_pict,
1265                                       physDev->xrender->pict,
1266                                       formatEntry->font_format, formatEntry->glyphset,
1267                                       0, 0, physDev->org.x + x, physDev->org.y + y,
1268                                       wstr, count);
1269         else {
1270             INT offset = 0, xoff = 0, yoff = 0;
1271             for(idx = 0; idx < count; idx++) {
1272                 pXRenderCompositeString16(gdi_display, render_op,
1273                                           physDev->xrender->tile_pict,
1274                                           physDev->xrender->pict,
1275                                           formatEntry->font_format, formatEntry->glyphset,
1276                                           0, 0, physDev->org.x + x + xoff,
1277                                           physDev->org.y + y + yoff,
1278                                           wstr + idx, 1);
1279                 offset += lpDx[idx];
1280                 xoff = offset * cosEsc;
1281                 yoff = offset * -sinEsc;
1282             }
1283         }
1284         wine_tsx11_unlock();
1285
1286     } else {
1287         INT offset = 0, xoff = 0, yoff = 0;
1288         wine_tsx11_lock();
1289         XSetForeground( gdi_display, physDev->gc, textPixel );
1290
1291         if(antialias == AA_None) {
1292             for(idx = 0; idx < count; idx++) {
1293                 SharpGlyphMono(physDev, physDev->org.x + x + xoff,
1294                                physDev->org.y + y + yoff,
1295                                formatEntry->bitmaps[wstr[idx]],
1296                                &formatEntry->gis[wstr[idx]]);
1297                 if(lpDx) {
1298                     offset += lpDx[idx];
1299                     xoff = offset * cosEsc;
1300                     yoff = offset * -sinEsc;
1301                 } else {
1302                     xoff += formatEntry->gis[wstr[idx]].xOff;
1303                     yoff += formatEntry->gis[wstr[idx]].yOff;
1304                 }
1305             }
1306         } else if(physDev->depth == 1) {
1307             for(idx = 0; idx < count; idx++) {
1308                 SharpGlyphGray(physDev, physDev->org.x + x + xoff,
1309                                physDev->org.y + y + yoff,
1310                                formatEntry->bitmaps[wstr[idx]],
1311                                &formatEntry->gis[wstr[idx]]);
1312                 if(lpDx) {
1313                     offset += lpDx[idx];
1314                     xoff = offset * cosEsc;
1315                     yoff = offset * -sinEsc;
1316                 } else {
1317                     xoff += formatEntry->gis[wstr[idx]].xOff;
1318                     yoff += formatEntry->gis[wstr[idx]].yOff;
1319                 }
1320                     
1321             }
1322         } else {
1323             XImage *image;
1324             unsigned int w, h, dummy_uint;
1325             Window dummy_window;
1326             int dummy_int;
1327             int image_x, image_y, image_off_x, image_off_y, image_w, image_h;
1328             RECT extents = {0, 0, 0, 0};
1329             POINT cur = {0, 0};
1330             
1331             
1332             XGetGeometry(gdi_display, physDev->drawable, &dummy_window, &dummy_int, &dummy_int,
1333                          &w, &h, &dummy_uint, &dummy_uint);
1334             TRACE("drawable %dx%d\n", w, h);
1335
1336             for(idx = 0; idx < count; idx++) {
1337                 if(extents.left > cur.x - formatEntry->gis[wstr[idx]].x)
1338                     extents.left = cur.x - formatEntry->gis[wstr[idx]].x;
1339                 if(extents.top > cur.y - formatEntry->gis[wstr[idx]].y)
1340                     extents.top = cur.y - formatEntry->gis[wstr[idx]].y;
1341                 if(extents.right < cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width)
1342                     extents.right = cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width;
1343                 if(extents.bottom < cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height)
1344                     extents.bottom = cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height;
1345                 if(lpDx) {
1346                     offset += lpDx[idx];
1347                     cur.x = offset * cosEsc;
1348                     cur.y = offset * -sinEsc;
1349                 } else {
1350                     cur.x += formatEntry->gis[wstr[idx]].xOff;
1351                     cur.y += formatEntry->gis[wstr[idx]].yOff;
1352                 }
1353             }
1354             TRACE("glyph extents %ld,%ld - %ld,%ld drawable x,y %ld,%ld\n", extents.left, extents.top,
1355                   extents.right, extents.bottom, physDev->org.x + x, physDev->org.y + y);
1356
1357             if(physDev->org.x + x + extents.left >= 0) {
1358                 image_x = physDev->org.x + x + extents.left;
1359                 image_off_x = 0;
1360             } else {
1361                 image_x = 0;
1362                 image_off_x = physDev->org.x + x + extents.left;
1363             }
1364             if(physDev->org.y + y + extents.top >= 0) {
1365                 image_y = physDev->org.y + y + extents.top;
1366                 image_off_y = 0;
1367             } else {
1368                 image_y = 0;
1369                 image_off_y = physDev->org.y + y + extents.top;
1370             }
1371             if(physDev->org.x + x + extents.right < w)
1372                 image_w = physDev->org.x + x + extents.right - image_x;
1373             else
1374                 image_w = w - image_x;
1375             if(physDev->org.y + y + extents.bottom < h)
1376                 image_h = physDev->org.y + y + extents.bottom - image_y;
1377             else
1378                 image_h = h - image_y;
1379
1380             if(image_w <= 0 || image_h <= 0) goto no_image;
1381
1382             X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1383             image = XGetImage(gdi_display, physDev->drawable,
1384                               image_x, image_y, image_w, image_h,
1385                               AllPlanes, ZPixmap);
1386             X11DRV_check_error();
1387
1388             TRACE("XGetImage(%p, %x, %d, %d, %d, %d, %lx, %x) depth = %d rets %p\n",
1389                   gdi_display, (int)physDev->drawable, image_x, image_y,
1390                   image_w, image_h, AllPlanes, ZPixmap,
1391                   physDev->depth, image);
1392             if(!image) {
1393                 Pixmap xpm = XCreatePixmap(gdi_display, physDev->drawable, image_w, image_h,
1394                                            physDev->depth);
1395                 GC gc;
1396                 XGCValues gcv;
1397
1398                 gcv.graphics_exposures = False;
1399                 gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
1400                 XCopyArea(gdi_display, physDev->drawable, xpm, gc, image_x, image_y,
1401                           image_w, image_h, 0, 0);
1402                 XFreeGC(gdi_display, gc);
1403                 X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1404                 image = XGetImage(gdi_display, xpm, 0, 0, image_w, image_h, AllPlanes,
1405                                   ZPixmap);
1406                 X11DRV_check_error();
1407                 XFreePixmap(gdi_display, xpm);
1408             }
1409             if(!image) goto no_image;
1410
1411             image->red_mask = visual->red_mask;
1412             image->green_mask = visual->green_mask;
1413             image->blue_mask = visual->blue_mask;
1414
1415             offset = xoff = yoff = 0;
1416             for(idx = 0; idx < count; idx++) {
1417                 SmoothGlyphGray(image, xoff + image_off_x - extents.left,
1418                                 yoff + image_off_y - extents.top,
1419                                 formatEntry->bitmaps[wstr[idx]],
1420                                 &formatEntry->gis[wstr[idx]],
1421                                 physDev->textPixel);
1422                 if(lpDx) {
1423                     offset += lpDx[idx];
1424                     xoff = offset * cosEsc;
1425                     yoff = offset * -sinEsc;
1426                 } else {
1427                     xoff += formatEntry->gis[wstr[idx]].xOff;
1428                     yoff += formatEntry->gis[wstr[idx]].yOff;
1429                 }
1430             }
1431             XPutImage(gdi_display, physDev->drawable, physDev->gc, image, 0, 0,
1432                       image_x, image_y, image_w, image_h);
1433             XDestroyImage(image);
1434         }
1435     no_image:
1436         wine_tsx11_unlock();
1437     }
1438     LeaveCriticalSection(&xrender_cs);
1439
1440     if (flags & ETO_CLIPPED)
1441     {
1442         /* restore the device region */
1443         X11DRV_SetDeviceClipping( physDev, saved_region, 0 );
1444         DeleteObject( saved_region );
1445     }
1446
1447     retv = TRUE;
1448
1449 done_unlock:
1450     X11DRV_UnlockDIBSection( physDev, TRUE );
1451     return retv;
1452 }
1453
1454 /******************************************************************************
1455  * AlphaBlend         (x11drv.@)
1456  */
1457 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1458                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1459                        BLENDFUNCTION blendfn)
1460 {
1461     XRenderPictureAttributes pa;
1462     XRenderPictFormat *src_format;
1463     XRenderPictFormat argb32_templ = {
1464         0,                          /* id */
1465         PictTypeDirect,             /* type */
1466         32,                         /* depth */
1467         {                           /* direct */
1468             16,                     /* direct.red */
1469             0xff,                   /* direct.redMask */
1470             8,                      /* direct.green */
1471             0xff,                   /* direct.greenMask */
1472             0,                      /* direct.blue */
1473             0xff,                   /* direct.blueMask */
1474             24,                     /* direct.alpha */
1475             0xff,                   /* direct.alphaMask */
1476         },
1477         0,                          /* colormap */
1478     };
1479     unsigned long argb32_templ_mask = 
1480         PictFormatType |
1481         PictFormatDepth |
1482         PictFormatRed |
1483         PictFormatRedMask |
1484         PictFormatGreen |
1485         PictFormatGreenMask |
1486         PictFormatBlue |
1487         PictFormatBlueMask |
1488         PictFormatAlpha |
1489         PictFormatAlphaMask;
1490
1491     Picture dst_pict, src_pict;
1492     Pixmap xpm;
1493     DIBSECTION dib;
1494     XImage *image;
1495     GC gc;
1496     XGCValues gcv;
1497     BYTE *dstbits, *data;
1498     int y, y2;
1499     POINT pts[2];
1500     BOOL top_down = FALSE;
1501     RGNDATA *rgndata;
1502
1503     if(!X11DRV_XRender_Installed) {
1504         FIXME("Unable to AlphaBlend without Xrender\n");
1505         return FALSE;
1506     }
1507     pts[0].x = xDst;
1508     pts[0].y = yDst;
1509     pts[1].x = xDst + widthDst;
1510     pts[1].y = yDst + heightDst;
1511     LPtoDP(devDst->hdc, pts, 2);
1512     xDst      = pts[0].x;
1513     yDst      = pts[0].y;
1514     widthDst  = pts[1].x - pts[0].x;
1515     heightDst = pts[1].y - pts[0].y;
1516
1517     pts[0].x = xSrc;
1518     pts[0].y = ySrc;
1519     pts[1].x = xSrc + widthSrc;
1520     pts[1].y = ySrc + heightSrc;
1521     LPtoDP(devSrc->hdc, pts, 2);
1522     xSrc      = pts[0].x;
1523     ySrc      = pts[0].y;
1524     widthSrc  = pts[1].x - pts[0].x;
1525     heightSrc = pts[1].y - pts[0].y;
1526
1527 #ifndef HAVE_XRENDERSETPICTURETRANSFORM
1528     if(widthDst != widthSrc || heightDst != heightSrc)
1529 #else
1530     if(!pXRenderSetPictureTransform)
1531 #endif
1532     {
1533         FIXME("Unable to Stretch, XRenderSetPictureTransform is currently required\n");
1534         return FALSE;
1535     }
1536
1537     if (!devSrc->bitmap || GetObjectW( devSrc->bitmap->hbitmap, sizeof(dib), &dib ) != sizeof(dib))
1538     {
1539         FIXME("not a dibsection\n");
1540         return FALSE;
1541     }
1542
1543     if(dib.dsBm.bmBitsPixel != 32) {
1544         FIXME("not a 32 bpp dibsection\n");
1545         return FALSE;
1546     }
1547     dstbits = data = HeapAlloc(GetProcessHeap(), 0, heightSrc * widthSrc * 4);
1548
1549     if(dib.dsBmih.biHeight < 0) { /* top-down dib */
1550         top_down = TRUE;
1551         dstbits += widthSrc * (heightSrc - 1) * 4;
1552         y2 = ySrc;
1553         y = y2 + heightSrc;
1554     }
1555     else
1556     {
1557         y = dib.dsBmih.biHeight - ySrc - 1;
1558         y2 = y - heightSrc;
1559     }
1560     for(; y > y2; y--) {
1561         memcpy(dstbits, (char *)dib.dsBm.bmBits + y * dib.dsBm.bmWidthBytes + xSrc * 4,
1562                widthSrc * 4);
1563         dstbits += (top_down ? -1 : 1) * widthSrc * 4;
1564     }
1565
1566     wine_tsx11_lock();
1567     image = XCreateImage(gdi_display, visual, 32, ZPixmap, 0,
1568                          (char*) data, widthSrc, heightSrc, 32, widthSrc * 4);
1569
1570     /*
1571       Avoid using XRenderFindStandardFormat as older libraries don't have it
1572       src_format = pXRenderFindStandardFormat(gdi_display, PictStandardARGB32);
1573     */
1574     src_format = pXRenderFindFormat(gdi_display, argb32_templ_mask, &argb32_templ, 0);
1575
1576     TRACE("src_format %p\n", src_format);
1577
1578     pa.subwindow_mode = IncludeInferiors;
1579
1580     /* FIXME use devDst->xrender->pict ? */
1581     dst_pict = pXRenderCreatePicture(gdi_display,
1582                                      devDst->drawable,
1583                                      (devDst->depth == 1) ?
1584                                      mono_format : screen_format,
1585                                      CPSubwindowMode, &pa);
1586     TRACE("dst_pict %08lx\n", dst_pict);
1587     TRACE("src_drawable = %08lx\n", devSrc->drawable);
1588     xpm = XCreatePixmap(gdi_display,
1589                         devSrc->drawable,
1590                         widthSrc, heightSrc, 32);
1591     gcv.graphics_exposures = False;
1592     gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
1593     TRACE("xpm = %08lx\n", xpm);
1594     XPutImage(gdi_display, xpm, gc, image, 0, 0, 0, 0, widthSrc, heightSrc);
1595
1596     src_pict = pXRenderCreatePicture(gdi_display,
1597                                      xpm, src_format,
1598                                      CPSubwindowMode, &pa);
1599     TRACE("src_pict %08lx\n", src_pict);
1600
1601     if ((rgndata = X11DRV_GetRegionData( devDst->region, 0 )))
1602     {
1603         pXRenderSetPictureClipRectangles( gdi_display, dst_pict,
1604                                           devDst->org.x, devDst->org.y,
1605                                           (XRectangle *)rgndata->Buffer, 
1606                                           rgndata->rdh.nCount );
1607         HeapFree( GetProcessHeap(), 0, rgndata );
1608     }
1609
1610 #ifdef HAVE_XRENDERSETPICTURETRANSFORM
1611     if(widthDst != widthSrc || heightDst != heightSrc) {
1612         double xscale = widthSrc/(double)widthDst;
1613         double yscale = heightSrc/(double)heightDst;
1614         XTransform xform = {{
1615             { XDoubleToFixed(xscale), XDoubleToFixed(0), XDoubleToFixed(0) },
1616             { XDoubleToFixed(0), XDoubleToFixed(yscale), XDoubleToFixed(0) },
1617             { XDoubleToFixed(0), XDoubleToFixed(0), XDoubleToFixed(1) }
1618         }};
1619         pXRenderSetPictureTransform(gdi_display, src_pict, &xform);
1620     }
1621 #endif
1622     pXRenderComposite(gdi_display, PictOpOver, src_pict, 0, dst_pict,
1623                       0, 0, 0, 0,
1624                       xDst + devDst->org.x, yDst + devDst->org.y, widthDst, heightDst);
1625
1626
1627     pXRenderFreePicture(gdi_display, src_pict);
1628     XFreePixmap(gdi_display, xpm);
1629     XFreeGC(gdi_display, gc);
1630     pXRenderFreePicture(gdi_display, dst_pict);
1631     image->data = NULL;
1632     XDestroyImage(image);
1633
1634     wine_tsx11_unlock();
1635     HeapFree(GetProcessHeap(), 0, data);
1636     return TRUE;
1637 }
1638
1639 #else /* HAVE_X11_EXTENSIONS_XRENDER_H */
1640
1641 void X11DRV_XRender_Init(void)
1642 {
1643     TRACE("XRender support not compiled in.\n");
1644     return;
1645 }
1646
1647 void X11DRV_XRender_Finalize(void)
1648 {
1649 }
1650
1651 BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
1652 {
1653   assert(0);
1654   return FALSE;
1655 }
1656
1657 void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
1658 {
1659   assert(0);
1660   return;
1661 }
1662
1663 BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
1664                                 const RECT *lprect, LPCWSTR wstr, UINT count,
1665                                 const INT *lpDx )
1666 {
1667   assert(0);
1668   return FALSE;
1669 }
1670
1671 void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
1672 {
1673   assert(0);
1674   return;
1675 }
1676
1677 /******************************************************************************
1678  * AlphaBlend         (x11drv.@)
1679  */
1680 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1681                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1682                        BLENDFUNCTION blendfn)
1683 {
1684   FIXME("not supported - XRENDER headers were missing at compile time\n");
1685   return FALSE;
1686 }
1687
1688 #endif /* HAVE_X11_EXTENSIONS_XRENDER_H */