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