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