Store the pixmap depth and the DIBSECTION pointer in the phys bitmap
[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     HBITMAP hBitmap = GetCurrentObject( physDev->hdc, OBJ_BITMAP );
1037     if( GetObjectW( hBitmap, sizeof(bmp), &bmp ) != sizeof(bmp) ) {
1038         TRACE("bitmap is not a DIB\n");
1039     }
1040     else if (bmp.dsBmih.biBitCount <= 8) {
1041         TRACE("Disabling antialiasing\n");
1042         disable_antialias = TRUE;
1043     }
1044
1045     TRACE("%p, %d, %d, %08x, %p, %s, %d, %p)\n", hdc, x, y, flags,
1046           lprect, debugstr_wn(wstr, count), count, lpDx);
1047
1048     if(flags & ETO_GLYPH_INDEX)
1049         glyphs = (const WORD*)wstr;
1050     else {
1051         glyphs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
1052         GetGlyphIndicesW(hdc, wstr, count, (WORD*)glyphs, 0);
1053     }
1054
1055     if(lprect)
1056       TRACE("rect: %ld,%ld - %ld,%ld\n", lprect->left, lprect->top, lprect->right,
1057             lprect->bottom);
1058     TRACE("align = %x bkmode = %x mapmode = %x\n", align, GetBkMode(hdc), GetMapMode(hdc));
1059
1060     if(align & TA_UPDATECP)
1061     {
1062         GetCurrentPositionEx( hdc, &pt );
1063         x = pt.x;
1064         y = pt.y;
1065     }
1066
1067     GetTextMetricsW(hdc, &tm);
1068     GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(lf), &lf);
1069
1070     if(!(tm.tmPitchAndFamily & TMPF_VECTOR)) /* Non-scalable fonts shouldn't be rotated */
1071         lf.lfEscapement = 0;
1072
1073     if(lf.lfEscapement != 0) {
1074         cosEsc = cos(lf.lfEscapement * M_PI / 1800);
1075         sinEsc = sin(lf.lfEscapement * M_PI / 1800);
1076     } else {
1077         cosEsc = 1;
1078         sinEsc = 0;
1079     }
1080
1081     if(flags & (ETO_CLIPPED | ETO_OPAQUE)) {
1082         if(!lprect) {
1083             if(flags & ETO_CLIPPED) goto done;
1084             GetTextExtentPointI(hdc, glyphs, count, &sz);
1085             done_extents = TRUE;
1086             rc.left = x;
1087             rc.top = y;
1088             rc.right = x + sz.cx;
1089             rc.bottom = y + sz.cy;
1090         } else {
1091             rc = *lprect;
1092         }
1093
1094         LPtoDP(hdc, (POINT*)&rc, 2);
1095
1096         if(rc.left > rc.right) {INT tmp = rc.left; rc.left = rc.right; rc.right = tmp;}
1097         if(rc.top > rc.bottom) {INT tmp = rc.top; rc.top = rc.bottom; rc.bottom = tmp;}
1098     }
1099
1100     xgcval.function = GXcopy;
1101     xgcval.background = physDev->backgroundPixel;
1102     xgcval.fill_style = FillSolid;
1103     wine_tsx11_lock();
1104     XChangeGC( gdi_display, physDev->gc, GCFunction | GCBackground | GCFillStyle, &xgcval );
1105     wine_tsx11_unlock();
1106
1107     X11DRV_LockDIBSection( physDev, DIB_Status_GdiMod, FALSE );
1108
1109     if(physDev->depth == 1) {
1110         if((physDev->textPixel & 0xffffff) == 0) {
1111             textPixel = 0;
1112             backgroundPixel = 1;
1113         } else {
1114             textPixel = 1;
1115             backgroundPixel = 0;
1116         }
1117     } else {
1118         textPixel = physDev->textPixel;
1119         backgroundPixel = physDev->backgroundPixel;
1120     }
1121
1122     if(flags & ETO_OPAQUE) {
1123         wine_tsx11_lock();
1124         XSetForeground( gdi_display, physDev->gc, backgroundPixel );
1125         XFillRectangle( gdi_display, physDev->drawable, physDev->gc,
1126                         physDev->org.x + rc.left, physDev->org.y + rc.top,
1127                         rc.right - rc.left, rc.bottom - rc.top );
1128         wine_tsx11_unlock();
1129     }
1130
1131     if(count == 0) {
1132         retv =  TRUE;
1133         goto done_unlock;
1134     }
1135
1136     pt.x = x;
1137     pt.y = y;
1138     LPtoDP(hdc, &pt, 1);
1139     x = pt.x;
1140     y = pt.y;
1141
1142     TRACE("real x,y %d,%d\n", x, y);
1143
1144     char_extra = GetTextCharacterExtra(hdc);
1145     if(char_extra || breakExtra) {
1146         UINT i;
1147         SIZE tmpsz;
1148         deltas = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
1149         for(i = 0; i < count; i++) {
1150             if(lpDx)
1151                 deltas[i] = lpDx[i] + char_extra;
1152             else {
1153                 GetTextExtentPointI(hdc, glyphs + i, 1, &tmpsz);
1154                 deltas[i] = tmpsz.cx;
1155             }
1156             
1157             if (breakExtra && wstr[i] == tm.tmBreakChar) {
1158                 deltas[i] = deltas[i] + breakExtra;
1159             }
1160         }
1161     } else if(lpDx)
1162         deltas = (INT*)lpDx;
1163
1164     if(deltas) {
1165         width = 0;
1166         for(idx = 0; idx < count; idx++)
1167             width += deltas[idx];
1168     } else {
1169         if(!done_extents) {
1170             GetTextExtentPointI(hdc, glyphs, count, &sz);
1171             done_extents = TRUE;
1172         }
1173         width = sz.cx;
1174     }
1175     width = X11DRV_XWStoDS(physDev, width);
1176     xwidth = width * cosEsc;
1177     ywidth = width * sinEsc;
1178
1179     tm.tmAscent = abs(X11DRV_YWStoDS(physDev, tm.tmAscent));
1180     tm.tmDescent = abs(X11DRV_YWStoDS(physDev, tm.tmDescent));
1181     switch( align & (TA_LEFT | TA_RIGHT | TA_CENTER) ) {
1182     case TA_LEFT:
1183         if (align & TA_UPDATECP) {
1184             pt.x = x + xwidth;
1185             pt.y = y - ywidth;
1186             DPtoLP(hdc, &pt, 1);
1187             MoveToEx(hdc, pt.x, pt.y, NULL);
1188         }
1189         break;
1190
1191     case TA_CENTER:
1192         x -= xwidth / 2;
1193         y += ywidth / 2;
1194         break;
1195
1196     case TA_RIGHT:
1197         x -= xwidth;
1198         y += ywidth;
1199         if (align & TA_UPDATECP) {
1200             pt.x = x;
1201             pt.y = y;
1202             DPtoLP(hdc, &pt, 1);
1203             MoveToEx(hdc, pt.x, pt.y, NULL);
1204         }
1205         break;
1206     }
1207
1208     switch( align & (TA_TOP | TA_BOTTOM | TA_BASELINE) ) {
1209     case TA_TOP:
1210         y += tm.tmAscent * cosEsc;
1211         x += tm.tmAscent * sinEsc;
1212         break;
1213
1214     case TA_BOTTOM:
1215         y -= tm.tmDescent * cosEsc;
1216         x -= tm.tmDescent * sinEsc;
1217         break;
1218
1219     case TA_BASELINE:
1220         break;
1221     }
1222
1223     if (flags & ETO_CLIPPED)
1224     {
1225         HRGN clip_region;
1226         RECT clip_rect = *lprect;
1227
1228         LPtoDP( hdc, (POINT *)&clip_rect, 2 );
1229         clip_region = CreateRectRgnIndirect( &clip_rect );
1230         /* make a copy of the current device region */
1231         saved_region = CreateRectRgn( 0, 0, 0, 0 );
1232         CombineRgn( saved_region, physDev->region, 0, RGN_COPY );
1233         X11DRV_SetDeviceClipping( physDev, saved_region, clip_region );
1234         DeleteObject( clip_region );
1235     }
1236
1237     if(X11DRV_XRender_Installed) {
1238         if(!physDev->xrender->pict) {
1239             XRenderPictureAttributes pa;
1240             pa.subwindow_mode = IncludeInferiors;
1241
1242             wine_tsx11_lock();
1243             physDev->xrender->pict = pXRenderCreatePicture(gdi_display,
1244                                                            physDev->drawable,
1245                                                            (physDev->depth == 1) ?
1246                                                            mono_format : screen_format,
1247                                                            CPSubwindowMode, &pa);
1248             wine_tsx11_unlock();
1249
1250             TRACE("allocing pict = %lx dc = %p drawable = %08lx\n",
1251                   physDev->xrender->pict, hdc, physDev->drawable);
1252         } else {
1253             TRACE("using existing pict = %lx dc = %p drawable = %08lx\n",
1254                   physDev->xrender->pict, hdc, physDev->drawable);
1255         }
1256
1257         if ((data = X11DRV_GetRegionData( physDev->region, 0 )))
1258         {
1259             wine_tsx11_lock();
1260             pXRenderSetPictureClipRectangles( gdi_display, physDev->xrender->pict,
1261                                               physDev->org.x, physDev->org.y,
1262                                               (XRectangle *)data->Buffer, data->rdh.nCount );
1263             wine_tsx11_unlock();
1264             HeapFree( GetProcessHeap(), 0, data );
1265         }
1266     }
1267
1268     if(GetBkMode(hdc) != TRANSPARENT) {
1269         if(!((flags & ETO_CLIPPED) && (flags & ETO_OPAQUE))) {
1270             if(!(flags & ETO_OPAQUE) || x < rc.left || x + width >= rc.right ||
1271                y - tm.tmAscent < rc.top || y + tm.tmDescent >= rc.bottom) {
1272                 wine_tsx11_lock();
1273                 XSetForeground( gdi_display, physDev->gc, backgroundPixel );
1274                 XFillRectangle( gdi_display, physDev->drawable, physDev->gc,
1275                                 physDev->org.x + x, physDev->org.y + y - tm.tmAscent,
1276                                 width, tm.tmAscent + tm.tmDescent );
1277                 wine_tsx11_unlock();
1278             }
1279         }
1280     }
1281
1282     if(X11DRV_XRender_Installed) {
1283         /* Create a 1x1 pixmap to tile over the font mask */
1284         if(!physDev->xrender->tile_xpm) {
1285             XRenderPictureAttributes pa;
1286
1287             XRenderPictFormat *format = (physDev->depth == 1) ? mono_format : screen_format;
1288             wine_tsx11_lock();
1289             physDev->xrender->tile_xpm = XCreatePixmap(gdi_display,
1290                                                        physDev->drawable,
1291                                                        1, 1,
1292                                                        format->depth);
1293             pa.repeat = True;
1294             physDev->xrender->tile_pict = pXRenderCreatePicture(gdi_display,
1295                                                                 physDev->xrender->tile_xpm,
1296                                                                 format,
1297                                                                 CPRepeat, &pa);
1298             wine_tsx11_unlock();
1299             TRACE("Created pixmap of depth %d\n", format->depth);
1300             /* init lastTextColor to something different from textPixel */
1301             physDev->xrender->lastTextColor = ~physDev->textPixel;
1302
1303         }
1304
1305         if(physDev->textPixel != physDev->xrender->lastTextColor) {
1306             if(physDev->depth != 1) {
1307                 /* Map 0 -- 0xff onto 0 -- 0xffff */
1308                 int             r_shift, r_len;
1309                 int             g_shift, g_len;
1310                 int             b_shift, b_len;
1311
1312                 ExamineBitfield (visual->red_mask, &r_shift, &r_len );
1313                 ExamineBitfield (visual->green_mask, &g_shift, &g_len);
1314                 ExamineBitfield (visual->blue_mask, &b_shift, &b_len);
1315
1316                 col.red = GetField(physDev->textPixel, r_shift, r_len);
1317                 col.red |= col.red << 8;
1318                 col.green = GetField(physDev->textPixel, g_shift, g_len);
1319                 col.green |= col.green << 8;
1320                 col.blue = GetField(physDev->textPixel, b_shift, b_len);
1321                 col.blue |= col.blue << 8;
1322                 col.alpha = 0x0;
1323             } else { /* for a 1bpp bitmap we always need a 1 in the tile */
1324                 col.red = col.green = col.blue = 0;
1325                 col.alpha = 0xffff;
1326             }
1327             wine_tsx11_lock();
1328             pXRenderFillRectangle(gdi_display, PictOpSrc,
1329                                   physDev->xrender->tile_pict,
1330                                   &col, 0, 0, 1, 1);
1331             wine_tsx11_unlock();
1332             physDev->xrender->lastTextColor = physDev->textPixel;
1333         }
1334
1335         /* FIXME the mapping of Text/BkColor onto 1 or 0 needs investigation.
1336          */
1337         if((physDev->depth == 1) && (textPixel == 0))
1338             render_op = PictOpOutReverse; /* This gives us 'black' text */
1339     }
1340
1341     EnterCriticalSection(&xrender_cs);
1342     entry = glyphsetCache + physDev->xrender->cache_index;
1343     if( disable_antialias == FALSE )
1344         antialias = entry->aa_default;
1345     formatEntry = entry->format[antialias];
1346
1347     for(idx = 0; idx < count; idx++) {
1348         if( !formatEntry ) {
1349             UploadGlyph(physDev, glyphs[idx], antialias);
1350             formatEntry = entry->format[antialias];
1351         } else if( glyphs[idx] >= formatEntry->nrealized || formatEntry->realized[glyphs[idx]] == FALSE) {
1352             UploadGlyph(physDev, glyphs[idx], antialias);
1353         }
1354     }
1355     assert(formatEntry);
1356
1357     TRACE("Writing %s at %ld,%ld\n", debugstr_wn(wstr,count),
1358           physDev->org.x + x, physDev->org.y + y);
1359
1360     if(X11DRV_XRender_Installed) {
1361         wine_tsx11_lock();
1362         if(!deltas)
1363             pXRenderCompositeString16(gdi_display, render_op,
1364                                       physDev->xrender->tile_pict,
1365                                       physDev->xrender->pict,
1366                                       formatEntry->font_format, formatEntry->glyphset,
1367                                       0, 0, physDev->org.x + x, physDev->org.y + y,
1368                                       glyphs, count);
1369
1370         else {
1371             INT offset = 0, xoff = 0, yoff = 0;
1372             for(idx = 0; idx < count; idx++) {
1373                 pXRenderCompositeString16(gdi_display, render_op,
1374                                           physDev->xrender->tile_pict,
1375                                           physDev->xrender->pict,
1376                                           formatEntry->font_format, formatEntry->glyphset,
1377                                           0, 0, physDev->org.x + x + xoff,
1378                                           physDev->org.y + y + yoff,
1379                                           glyphs + idx, 1);
1380                 offset += X11DRV_XWStoDS(physDev, deltas[idx]);
1381                 xoff = offset * cosEsc;
1382                 yoff = offset * -sinEsc;
1383             }
1384         }
1385         wine_tsx11_unlock();
1386
1387     } else {
1388         INT offset = 0, xoff = 0, yoff = 0;
1389         wine_tsx11_lock();
1390         XSetForeground( gdi_display, physDev->gc, textPixel );
1391
1392         if(antialias == AA_None) {
1393             for(idx = 0; idx < count; idx++) {
1394                 SharpGlyphMono(physDev, physDev->org.x + x + xoff,
1395                                physDev->org.y + y + yoff,
1396                                formatEntry->bitmaps[glyphs[idx]],
1397                                &formatEntry->gis[glyphs[idx]]);
1398                 if(deltas) {
1399                     offset += X11DRV_XWStoDS(physDev, deltas[idx]);
1400                     xoff = offset * cosEsc;
1401                     yoff = offset * -sinEsc;
1402
1403                 } else {
1404                     xoff += formatEntry->gis[glyphs[idx]].xOff;
1405                     yoff += formatEntry->gis[glyphs[idx]].yOff;
1406                 }
1407             }
1408         } else if(physDev->depth == 1) {
1409             for(idx = 0; idx < count; idx++) {
1410                 SharpGlyphGray(physDev, physDev->org.x + x + xoff,
1411                                physDev->org.y + y + yoff,
1412                                formatEntry->bitmaps[glyphs[idx]],
1413                                &formatEntry->gis[glyphs[idx]]);
1414                 if(deltas) {
1415                     offset += X11DRV_XWStoDS(physDev, deltas[idx]);
1416                     xoff = offset * cosEsc;
1417                     yoff = offset * -sinEsc;
1418
1419                 } else {
1420                     xoff += formatEntry->gis[glyphs[idx]].xOff;
1421                     yoff += formatEntry->gis[glyphs[idx]].yOff;
1422                 }
1423                     
1424             }
1425         } else {
1426             XImage *image;
1427             unsigned int w, h, dummy_uint;
1428             Window dummy_window;
1429             int dummy_int;
1430             int image_x, image_y, image_off_x, image_off_y, image_w, image_h;
1431             RECT extents = {0, 0, 0, 0};
1432             POINT cur = {0, 0};
1433             
1434             
1435             XGetGeometry(gdi_display, physDev->drawable, &dummy_window, &dummy_int, &dummy_int,
1436                          &w, &h, &dummy_uint, &dummy_uint);
1437             TRACE("drawable %dx%d\n", w, h);
1438
1439             for(idx = 0; idx < count; idx++) {
1440                 if(extents.left > cur.x - formatEntry->gis[glyphs[idx]].x)
1441                     extents.left = cur.x - formatEntry->gis[glyphs[idx]].x;
1442                 if(extents.top > cur.y - formatEntry->gis[glyphs[idx]].y)
1443                     extents.top = cur.y - formatEntry->gis[glyphs[idx]].y;
1444                 if(extents.right < cur.x - formatEntry->gis[glyphs[idx]].x + formatEntry->gis[glyphs[idx]].width)
1445                     extents.right = cur.x - formatEntry->gis[glyphs[idx]].x + formatEntry->gis[glyphs[idx]].width;
1446                 if(extents.bottom < cur.y - formatEntry->gis[glyphs[idx]].y + formatEntry->gis[glyphs[idx]].height)
1447                     extents.bottom = cur.y - formatEntry->gis[glyphs[idx]].y + formatEntry->gis[glyphs[idx]].height;
1448                 if(deltas) {
1449                     offset += X11DRV_XWStoDS(physDev, deltas[idx]);
1450                     cur.x = offset * cosEsc;
1451                     cur.y = offset * -sinEsc;
1452                 } else {
1453                     cur.x += formatEntry->gis[glyphs[idx]].xOff;
1454                     cur.y += formatEntry->gis[glyphs[idx]].yOff;
1455                 }
1456             }
1457             TRACE("glyph extents %ld,%ld - %ld,%ld drawable x,y %ld,%ld\n", extents.left, extents.top,
1458                   extents.right, extents.bottom, physDev->org.x + x, physDev->org.y + y);
1459
1460             if(physDev->org.x + x + extents.left >= 0) {
1461                 image_x = physDev->org.x + x + extents.left;
1462                 image_off_x = 0;
1463             } else {
1464                 image_x = 0;
1465                 image_off_x = physDev->org.x + x + extents.left;
1466             }
1467             if(physDev->org.y + y + extents.top >= 0) {
1468                 image_y = physDev->org.y + y + extents.top;
1469                 image_off_y = 0;
1470             } else {
1471                 image_y = 0;
1472                 image_off_y = physDev->org.y + y + extents.top;
1473             }
1474             if(physDev->org.x + x + extents.right < w)
1475                 image_w = physDev->org.x + x + extents.right - image_x;
1476             else
1477                 image_w = w - image_x;
1478             if(physDev->org.y + y + extents.bottom < h)
1479                 image_h = physDev->org.y + y + extents.bottom - image_y;
1480             else
1481                 image_h = h - image_y;
1482
1483             if(image_w <= 0 || image_h <= 0) goto no_image;
1484
1485             X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1486             image = XGetImage(gdi_display, physDev->drawable,
1487                               image_x, image_y, image_w, image_h,
1488                               AllPlanes, ZPixmap);
1489             X11DRV_check_error();
1490
1491             TRACE("XGetImage(%p, %x, %d, %d, %d, %d, %lx, %x) depth = %d rets %p\n",
1492                   gdi_display, (int)physDev->drawable, image_x, image_y,
1493                   image_w, image_h, AllPlanes, ZPixmap,
1494                   physDev->depth, image);
1495             if(!image) {
1496                 Pixmap xpm = XCreatePixmap(gdi_display, physDev->drawable, image_w, image_h,
1497                                            physDev->depth);
1498                 GC gc;
1499                 XGCValues gcv;
1500
1501                 gcv.graphics_exposures = False;
1502                 gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
1503                 XCopyArea(gdi_display, physDev->drawable, xpm, gc, image_x, image_y,
1504                           image_w, image_h, 0, 0);
1505                 XFreeGC(gdi_display, gc);
1506                 X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
1507                 image = XGetImage(gdi_display, xpm, 0, 0, image_w, image_h, AllPlanes,
1508                                   ZPixmap);
1509                 X11DRV_check_error();
1510                 XFreePixmap(gdi_display, xpm);
1511             }
1512             if(!image) goto no_image;
1513
1514             image->red_mask = visual->red_mask;
1515             image->green_mask = visual->green_mask;
1516             image->blue_mask = visual->blue_mask;
1517
1518             offset = xoff = yoff = 0;
1519             for(idx = 0; idx < count; idx++) {
1520                 SmoothGlyphGray(image, xoff + image_off_x - extents.left,
1521                                 yoff + image_off_y - extents.top,
1522                                 formatEntry->bitmaps[glyphs[idx]],
1523                                 &formatEntry->gis[glyphs[idx]],
1524                                 physDev->textPixel);
1525                 if(deltas) {
1526                     offset += X11DRV_XWStoDS(physDev, deltas[idx]);
1527                     xoff = offset * cosEsc;
1528                     yoff = offset * -sinEsc;
1529                 } else {
1530                     xoff += formatEntry->gis[glyphs[idx]].xOff;
1531                     yoff += formatEntry->gis[glyphs[idx]].yOff;
1532                 }
1533                     
1534             }
1535             XPutImage(gdi_display, physDev->drawable, physDev->gc, image, 0, 0,
1536                       image_x, image_y, image_w, image_h);
1537             XDestroyImage(image);
1538         }
1539     no_image:
1540         wine_tsx11_unlock();
1541     }
1542     LeaveCriticalSection(&xrender_cs);
1543
1544     if (lf.lfUnderline || lf.lfStrikeOut) {
1545         int underlinePos, strikeoutPos;
1546         int underlineWidth, strikeoutWidth;
1547         UINT nMetricsSize = GetOutlineTextMetricsW(hdc, 0, NULL);
1548         OUTLINETEXTMETRICW* otm = NULL;
1549
1550         if(!nMetricsSize) {
1551             underlinePos = 0;
1552             underlineWidth = tm.tmAscent / 20 + 1;
1553             strikeoutPos = tm.tmAscent / 2;
1554             strikeoutWidth = underlineWidth;
1555         } else {
1556             otm = HeapAlloc(GetProcessHeap(), 0, nMetricsSize);
1557             if (!otm) goto done_unlock;
1558
1559             GetOutlineTextMetricsW(hdc, nMetricsSize, otm);
1560             underlinePos = otm->otmsUnderscorePosition;
1561             underlineWidth = otm->otmsUnderscoreSize;
1562             strikeoutPos = otm->otmsStrikeoutPosition;
1563             strikeoutWidth = otm->otmsStrikeoutSize;
1564         }
1565
1566         wine_tsx11_lock();
1567         XSetForeground( gdi_display, physDev->gc, physDev->textPixel );
1568
1569         if (lf.lfUnderline) {
1570             underlinePos = X11DRV_YWStoDS(physDev, underlinePos);
1571             underlineWidth = X11DRV_YWStoDS(physDev, underlineWidth);
1572
1573             XSetLineAttributes( gdi_display, physDev->gc, underlineWidth,
1574                                 LineSolid, CapProjecting, JoinBevel );
1575             XDrawLine( gdi_display, physDev->drawable, physDev->gc,
1576                        physDev->org.x + x - underlinePos * sinEsc,
1577                        physDev->org.y + y - underlinePos * cosEsc,
1578                        physDev->org.x + x + width * cosEsc - underlinePos * sinEsc,
1579                        physDev->org.y + y - width * sinEsc - underlinePos * cosEsc );
1580         }
1581
1582         if (lf.lfStrikeOut) { 
1583             strikeoutPos = X11DRV_YWStoDS(physDev, strikeoutPos);
1584             strikeoutWidth = X11DRV_YWStoDS(physDev, strikeoutWidth);
1585             
1586             XSetLineAttributes( gdi_display, physDev->gc, strikeoutWidth,
1587                                 LineSolid, CapProjecting, JoinBevel );
1588             XDrawLine( gdi_display, physDev->drawable, physDev->gc,
1589                        physDev->org.x + x - strikeoutPos * sinEsc,
1590                        physDev->org.y + y - strikeoutPos * cosEsc,
1591                        physDev->org.x + x + width * cosEsc - strikeoutPos * sinEsc,
1592                        physDev->org.y + y - width * sinEsc - strikeoutPos * cosEsc);
1593         }
1594         wine_tsx11_unlock();
1595         HeapFree(GetProcessHeap(), 0, otm);
1596     }
1597
1598     if(deltas && deltas != lpDx)
1599         HeapFree(GetProcessHeap(), 0, deltas);
1600
1601     if (flags & ETO_CLIPPED)
1602     {
1603         /* restore the device region */
1604         X11DRV_SetDeviceClipping( physDev, saved_region, 0 );
1605         DeleteObject( saved_region );
1606     }
1607
1608     retv = TRUE;
1609
1610 done_unlock:
1611     X11DRV_UnlockDIBSection( physDev, TRUE );
1612 done:
1613     if(glyphs != wstr) HeapFree(GetProcessHeap(), 0, (WORD*)glyphs);
1614     return retv;
1615 }
1616
1617 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1618                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1619                        BLENDFUNCTION blendfn)
1620 {
1621     XRenderPictureAttributes pa;
1622     XRenderPictFormat *src_format;
1623     Picture dst_pict, src_pict;
1624     Pixmap xpm;
1625     HBITMAP hBitmap;
1626     DIBSECTION dib;
1627     XImage *image;
1628     GC gc;
1629     XGCValues gcv;
1630     char *dstbits, *data;
1631     int y;
1632     POINT pts[2];
1633     BOOL top_down = FALSE;
1634
1635     if(!X11DRV_XRender_Installed) {
1636         FIXME("Unable to AlphaBlend without Xrender\n");
1637         return FALSE;
1638     }
1639     pts[0].x = xDst;
1640     pts[0].y = yDst;
1641     pts[1].x = xDst + widthDst;
1642     pts[1].y = yDst + heightDst;
1643     LPtoDP(devDst->hdc, pts, 2);
1644     xDst      = pts[0].x;
1645     yDst      = pts[0].y;
1646     widthDst  = pts[1].x - pts[0].x;
1647     heightDst = pts[1].y - pts[0].y;
1648
1649     pts[0].x = xSrc;
1650     pts[0].y = ySrc;
1651     pts[1].x = xSrc + widthSrc;
1652     pts[1].y = ySrc + heightSrc;
1653     LPtoDP(devSrc->hdc, pts, 2);
1654     xSrc      = pts[0].x;
1655     ySrc      = pts[0].y;
1656     widthSrc  = pts[1].x - pts[0].x;
1657     heightSrc = pts[1].y - pts[0].y;
1658
1659 #ifndef HAVE_XRENDERSETPICTURETRANSFORM
1660     if(widthDst != widthSrc || heightDst != heightSrc)
1661 #else
1662     if(!pXRenderSetPictureTransform)
1663 #endif
1664     {
1665         FIXME("Unable to Stretch, XRenderSetPictureTransform is currently required\n");
1666         return FALSE;
1667     }
1668
1669     hBitmap = GetCurrentObject( devSrc->hdc, OBJ_BITMAP );
1670     if (GetObjectW( 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 BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
1792                        X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1793                        BLENDFUNCTION blendfn)
1794 {
1795   FIXME("not supported - XRENDER headers were missing at compile time\n");
1796   return FALSE;
1797 }
1798
1799 #endif /* HAVE_X11_EXTENSIONS_XRENDER_H */