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