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