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