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