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