xrender.c 49.2 KB
Newer Older
1 2 3
/*
 * Functions to use the XRender extension
 *
4 5 6 7
 * Copyright 2001, 2002 Huw D M Davies for CodeWeavers
 *
 * Some parts also:
 * Copyright 2000 Keith Packard, member of The XFree86 Project, Inc.
8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22 23
 */
#include "config.h"
24 25 26
#include "wine/port.h"

#include <assert.h>
27
#include <stdarg.h>
28 29
#include <string.h>
#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 "winternl.h"
37
#include "wine/library.h"
38
#include "wine/unicode.h"
39
#include "wine/debug.h"
40

41 42 43
static BOOL X11DRV_XRender_Installed = FALSE;
int using_client_side_fonts = FALSE;

44
WINE_DEFAULT_DEBUG_CHANNEL(xrender);
45

46
#ifdef HAVE_X11_EXTENSIONS_XRENDER_H
47

48
#include <X11/Xlib.h>
49
#include <X11/extensions/Xrender.h>
50 51 52 53 54 55

static XRenderPictFormat *screen_format; /* format of screen */
static XRenderPictFormat *mono_format; /* format of mono bitmap */

typedef struct
{
56
    LOGFONTW lf;
57 58
    SIZE     devsize;  /* size in device coords */
    DWORD    hash;
59 60 61 62
} LFANDSIZE;

#define INITIAL_REALIZED_BUF_SIZE 128

63
typedef enum { AA_None = 0, AA_Grey, AA_RGB, AA_BGR, AA_VRGB, AA_VBGR, AA_MAXVALUE } AA_Type;
64 65 66

typedef struct
{
67 68 69 70 71 72
    GlyphSet glyphset;
    XRenderPictFormat *font_format;
    int nrealized;
    BOOL *realized;
    void **bitmaps;
    XGlyphInfo *gis;
73 74 75 76 77 78 79
} gsCacheEntryFormat;

typedef struct
{
    LFANDSIZE lfsz;
    AA_Type aa_default;
    gsCacheEntryFormat * format[AA_MAXVALUE];
80
    INT count;
81
    INT next;
82 83 84 85
} gsCacheEntry;

struct tagXRENDERINFO
{
86
    int                cache_index;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    Picture            pict;
    Picture            tile_pict;
    Pixmap             tile_xpm;
    COLORREF           lastTextColor;
};


static gsCacheEntry *glyphsetCache = NULL;
static DWORD glyphsetCacheSize = 0;
static INT lastfree = -1;
static INT mru = -1;

#define INIT_CACHE_SIZE 10

static int antialias = 1;

103 104 105 106 107 108 109 110 111 112 113
/* some default values just in case */
#ifndef SONAME_LIBX11
#define SONAME_LIBX11 "libX11.so"
#endif
#ifndef SONAME_LIBXEXT
#define SONAME_LIBXEXT "libXext.so"
#endif
#ifndef SONAME_LIBXRENDER
#define SONAME_LIBXRENDER "libXrender.so"
#endif

114 115 116 117
static void *xrender_handle;

#define MAKE_FUNCPTR(f) static typeof(f) * p##f;
MAKE_FUNCPTR(XRenderAddGlyphs)
118
MAKE_FUNCPTR(XRenderComposite)
119 120 121 122 123 124 125 126 127 128 129
MAKE_FUNCPTR(XRenderCompositeString8)
MAKE_FUNCPTR(XRenderCompositeString16)
MAKE_FUNCPTR(XRenderCompositeString32)
MAKE_FUNCPTR(XRenderCreateGlyphSet)
MAKE_FUNCPTR(XRenderCreatePicture)
MAKE_FUNCPTR(XRenderFillRectangle)
MAKE_FUNCPTR(XRenderFindFormat)
MAKE_FUNCPTR(XRenderFindVisualFormat)
MAKE_FUNCPTR(XRenderFreeGlyphSet)
MAKE_FUNCPTR(XRenderFreePicture)
MAKE_FUNCPTR(XRenderSetPictureClipRectangles)
130 131 132
#ifdef HAVE_XRENDERSETPICTURETRANSFORM
MAKE_FUNCPTR(XRenderSetPictureTransform)
#endif
133 134 135
MAKE_FUNCPTR(XRenderQueryExtension)
#undef MAKE_FUNCPTR

136 137 138 139 140
static CRITICAL_SECTION xrender_cs;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &xrender_cs,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
141
      0, 0, { (DWORD_PTR)(__FILE__ ": xrender_cs") }
142 143
};
static CRITICAL_SECTION xrender_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
#define MS_MAKE_TAG( _x1, _x2, _x3, _x4 ) \
          ( ( (ULONG)_x4 << 24 ) |     \
            ( (ULONG)_x3 << 16 ) |     \
            ( (ULONG)_x2 <<  8 ) |     \
              (ULONG)_x1         )

#define MS_GASP_TAG MS_MAKE_TAG('g', 'a', 's', 'p')

#define GASP_GRIDFIT 0x01
#define GASP_DOGRAY  0x02

#ifdef WORDS_BIGENDIAN
#define get_be_word(x) (x)
#else
#define get_be_word(x) RtlUshortByteSwap(x)
#endif
161

162 163 164 165 166 167 168 169 170 171 172
/***********************************************************************
 *   X11DRV_XRender_Init
 *
 * Let's see if our XServer has the extension available
 *
 */
void X11DRV_XRender_Init(void)
{
    int error_base, event_base, i;
    XRenderPictFormat pf;

173 174 175 176 177
    if (client_side_with_render &&
	wine_dlopen(SONAME_LIBX11, RTLD_NOW|RTLD_GLOBAL, NULL, 0) &&
	wine_dlopen(SONAME_LIBXEXT, RTLD_NOW|RTLD_GLOBAL, NULL, 0) && 
	(xrender_handle = wine_dlopen(SONAME_LIBXRENDER, RTLD_NOW, NULL, 0)))
    {
178 179 180

#define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(xrender_handle, #f, NULL, 0)) == NULL) goto sym_not_found;
LOAD_FUNCPTR(XRenderAddGlyphs)
181
LOAD_FUNCPTR(XRenderComposite)
182 183 184 185 186 187 188 189 190 191 192 193 194
LOAD_FUNCPTR(XRenderCompositeString8)
LOAD_FUNCPTR(XRenderCompositeString16)
LOAD_FUNCPTR(XRenderCompositeString32)
LOAD_FUNCPTR(XRenderCreateGlyphSet)
LOAD_FUNCPTR(XRenderCreatePicture)
LOAD_FUNCPTR(XRenderFillRectangle)
LOAD_FUNCPTR(XRenderFindFormat)
LOAD_FUNCPTR(XRenderFindVisualFormat)
LOAD_FUNCPTR(XRenderFreeGlyphSet)
LOAD_FUNCPTR(XRenderFreePicture)
LOAD_FUNCPTR(XRenderSetPictureClipRectangles)
LOAD_FUNCPTR(XRenderQueryExtension)
#undef LOAD_FUNCPTR
195 196 197 198 199 200
#ifdef HAVE_XRENDERSETPICTURETRANSFORM
#define LOAD_OPTIONAL_FUNCPTR(f) p##f = wine_dlsym(xrender_handle, #f, NULL, 0);
LOAD_OPTIONAL_FUNCPTR(XRenderSetPictureTransform)
#undef LOAD_OPTIONAL_FUNCPTR
#endif

201

202 203 204 205 206
        wine_tsx11_lock();
        if(pXRenderQueryExtension(gdi_display, &event_base, &error_base)) {
            X11DRV_XRender_Installed = TRUE;
            TRACE("Xrender is up and running error_base = %d\n", error_base);
            screen_format = pXRenderFindVisualFormat(gdi_display, visual);
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            if(!screen_format)
            {
                /* Xrender doesn't like DirectColor visuals, try to find a TrueColor one instead */
                if (visual->class == DirectColor)
                {
                    XVisualInfo info;
                    if (XMatchVisualInfo( gdi_display, DefaultScreen(gdi_display),
                                          screen_depth, TrueColor, &info ))
                    {
                        screen_format = pXRenderFindVisualFormat(gdi_display, info.visual);
                        if (screen_format) visual = info.visual;
                    }
                }
            }
            if(!screen_format) /* This fails in buggy versions of libXrender.so */
            {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
                wine_tsx11_unlock();
                WINE_MESSAGE(
                    "Wine has detected that you probably have a buggy version\n"
                    "of libXrender.so .  Because of this client side font rendering\n"
                    "will be disabled.  Please upgrade this library.\n");
                X11DRV_XRender_Installed = FALSE;
                return;
            }
            pf.type = PictTypeDirect;
            pf.depth = 1;
            pf.direct.alpha = 0;
            pf.direct.alphaMask = 1;
            mono_format = pXRenderFindFormat(gdi_display, PictFormatType |
                                             PictFormatDepth | PictFormatAlpha |
                                             PictFormatAlphaMask, &pf, 0);
            if(!mono_format) {
                ERR("mono_format == NULL?\n");
                X11DRV_XRender_Installed = FALSE;
            }
242 243 244 245
            if (!visual->red_mask || !visual->green_mask || !visual->blue_mask) {
                WARN("one or more of the colour masks are 0, disabling XRENDER. Try running in 16-bit mode or higher.\n");
                X11DRV_XRender_Installed = FALSE;
            }
246 247 248 249 250 251 252
        }
        wine_tsx11_unlock();
    }

sym_not_found:
    if(X11DRV_XRender_Installed || client_side_with_core)
    {
253 254 255 256 257 258 259 260 261 262
	glyphsetCache = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
				  sizeof(*glyphsetCache) * INIT_CACHE_SIZE);

	glyphsetCacheSize = INIT_CACHE_SIZE;
	lastfree = 0;
	for(i = 0; i < INIT_CACHE_SIZE; i++) {
	  glyphsetCache[i].next = i + 1;
	  glyphsetCache[i].count = -1;
	}
	glyphsetCache[i-1].next = -1;
263
	using_client_side_fonts = 1;
264

265 266 267 268 269 270 271 272 273 274
	if(!X11DRV_XRender_Installed) {
	    TRACE("Xrender is not available on your XServer, client side rendering with the core protocol instead.\n");
	    if(screen_depth <= 8 || !client_side_antialias_with_core)
	        antialias = 0;
	} else {
	    if(screen_depth <= 8 || !client_side_antialias_with_render)
	        antialias = 0;
	}
    }
    else TRACE("Using X11 core fonts\n");
275 276 277 278 279
}

static BOOL fontcmp(LFANDSIZE *p1, LFANDSIZE *p2)
{
  if(p1->hash != p2->hash) return TRUE;
280
  if(memcmp(&p1->devsize, &p2->devsize, sizeof(p1->devsize))) return TRUE;
281 282 283 284
  if(memcmp(&p1->lf, &p2->lf, offsetof(LOGFONTW, lfFaceName))) return TRUE;
  return strcmpW(p1->lf.lfFaceName, p2->lf.lfFaceName);
}

285
#if 0
286 287 288 289
static void walk_cache(void)
{
  int i;

290
  EnterCriticalSection(&xrender_cs);
291 292
  for(i=mru; i >= 0; i = glyphsetCache[i].next)
    TRACE("item %d\n", i);
293
  LeaveCriticalSection(&xrender_cs);
294
}
295
#endif
296

297
static int LookupEntry(LFANDSIZE *plfsz)
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
{
  int i, prev_i = -1;

  for(i = mru; i >= 0; i = glyphsetCache[i].next) {
    TRACE("%d\n", i);
    if(glyphsetCache[i].count == -1) { /* reached free list so stop */
      i = -1;
      break;
    }

    if(!fontcmp(&glyphsetCache[i].lfsz, plfsz)) {
      glyphsetCache[i].count++;
      if(prev_i >= 0) {
	glyphsetCache[prev_i].next = glyphsetCache[i].next;
	glyphsetCache[i].next = mru;
	mru = i;
      }
      TRACE("found font in cache %d\n", i);
316
      return i;
317 318 319 320
    }
    prev_i = i;
  }
  TRACE("font not in cache\n");
321
  return -1;
322 323
}

324 325
static void FreeEntry(int entry)
{
326 327 328 329
    int i, format;
  
    for(format = 0; format < AA_MAXVALUE; format++) {
        gsCacheEntryFormat * formatEntry;
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        if( !glyphsetCache[entry].format[format] )
            continue;

        formatEntry = glyphsetCache[entry].format[format];

        if(formatEntry->glyphset) {
            wine_tsx11_lock();
            pXRenderFreeGlyphSet(gdi_display, formatEntry->glyphset);
            wine_tsx11_unlock();
            formatEntry->glyphset = 0;
        }
        if(formatEntry->nrealized) {
            HeapFree(GetProcessHeap(), 0, formatEntry->realized);
            formatEntry->realized = NULL;
            if(formatEntry->bitmaps) {
                for(i = 0; i < formatEntry->nrealized; i++)
                    if(formatEntry->bitmaps[i])
                        HeapFree(GetProcessHeap(), 0, formatEntry->bitmaps[i]);
                HeapFree(GetProcessHeap(), 0, formatEntry->bitmaps);
                formatEntry->bitmaps = NULL;
                HeapFree(GetProcessHeap(), 0, formatEntry->gis);
                formatEntry->gis = NULL;
            }
            formatEntry->nrealized = 0;
        }

        HeapFree(GetProcessHeap(), 0, formatEntry);
        glyphsetCache[entry].format[format] = NULL;
359 360 361
    }
}

362
static int AllocEntry(void)
363 364 365 366 367 368 369
{
  int best = -1, prev_best = -1, i, prev_i = -1;

  if(lastfree >= 0) {
    assert(glyphsetCache[lastfree].count == -1);
    glyphsetCache[lastfree].count = 1;
    best = lastfree;
370
    lastfree = glyphsetCache[lastfree].next;
371 372 373 374 375
    assert(best != mru);
    glyphsetCache[best].next = mru;
    mru = best;

    TRACE("empty space at %d, next lastfree = %d\n", mru, lastfree);
376
    return mru;
377 378 379 380 381 382 383 384 385 386 387 388
  }

  for(i = mru; i >= 0; i = glyphsetCache[i].next) {
    if(glyphsetCache[i].count == 0) {
      best = i;
      prev_best = prev_i;
    }
    prev_i = i;
  }

  if(best >= 0) {
    TRACE("freeing unused glyphset at cache %d\n", best);
389
    FreeEntry(best);
390 391 392 393 394 395 396 397
    glyphsetCache[best].count = 1;
    if(prev_best >= 0) {
      glyphsetCache[prev_best].next = glyphsetCache[best].next;
      glyphsetCache[best].next = mru;
      mru = best;
    } else {
      assert(mru == best);
    }
398
    return mru;
399 400 401
  }

  TRACE("Growing cache\n");
402 403 404
  
  if (glyphsetCache)
    glyphsetCache = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
405 406 407
			      glyphsetCache,
			      (glyphsetCacheSize + INIT_CACHE_SIZE)
			      * sizeof(*glyphsetCache));
408 409 410 411 412
  else
    glyphsetCache = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			      (glyphsetCacheSize + INIT_CACHE_SIZE)
			      * sizeof(*glyphsetCache));

413 414 415 416 417 418 419 420 421 422 423 424 425
  for(best = i = glyphsetCacheSize; i < glyphsetCacheSize + INIT_CACHE_SIZE;
      i++) {
    glyphsetCache[i].next = i + 1;
    glyphsetCache[i].count = -1;
  }
  glyphsetCache[i-1].next = -1;
  glyphsetCacheSize += INIT_CACHE_SIZE;

  lastfree = glyphsetCache[best].next;
  glyphsetCache[best].count = 1;
  glyphsetCache[best].next = mru;
  mru = best;
  TRACE("new free cache slot at %d\n", mru);
426
  return mru;
427
}
428

429 430 431
static BOOL get_gasp_flags(X11DRV_PDEVICE *physDev, WORD *flags)
{
    DWORD size;
432
    WORD *gasp, *buffer;
433 434 435 436 437 438 439 440 441 442
    WORD num_recs;
    DWORD ppem;
    TEXTMETRICW tm;

    *flags = 0;

    size = GetFontData(physDev->hdc, MS_GASP_TAG,  0, NULL, 0);
    if(size == GDI_ERROR)
        return FALSE;

443
    gasp = buffer = HeapAlloc(GetProcessHeap(), 0, size);
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    GetFontData(physDev->hdc, MS_GASP_TAG,  0, gasp, size);

    GetTextMetricsW(physDev->hdc, &tm);
    ppem = abs(X11DRV_YWStoDS(physDev, tm.tmAscent + tm.tmDescent - tm.tmInternalLeading));

    gasp++;
    num_recs = get_be_word(*gasp);
    gasp++;
    while(num_recs--)
    {
        *flags = get_be_word(*(gasp + 1));
        if(ppem <= get_be_word(*gasp))
            break;
        gasp += 2;
    }
    TRACE("got flags %04x for ppem %ld\n", *flags, ppem);

461
    HeapFree(GetProcessHeap(), 0, buffer);
462 463 464 465
    return TRUE;
}

static int GetCacheEntry(X11DRV_PDEVICE *physDev, LFANDSIZE *plfsz)
466
{
467
    int ret;
468
    int format;
469
    gsCacheEntry *entry;
470
    WORD flags;
471
    static int hinter = -1;
472

473 474 475 476 477
    if((ret = LookupEntry(plfsz)) != -1) return ret;

    ret = AllocEntry();
    entry = glyphsetCache + ret;
    entry->lfsz = *plfsz;
478 479 480
    for( format = 0; format < AA_MAXVALUE; format++ ) {
        assert( !entry->format[format] );
    }
481

482
    if(antialias && plfsz->lf.lfQuality != NONANTIALIASED_QUALITY)
483
    {
484 485 486 487 488 489 490
        if(hinter == -1)
        {
            RASTERIZER_STATUS status;
            GetRasterizerCaps(&status, sizeof(status));
            hinter = status.wFlags & WINE_TT_HINTER_ENABLED;
        }
        if(!hinter || !get_gasp_flags(physDev, &flags) || flags & GASP_DOGRAY)
491 492 493 494
            entry->aa_default = AA_Grey;
        else
            entry->aa_default = AA_None;
    }
495
    else
496
        entry->aa_default = AA_None;
497 498

    return ret;
499 500
}

501
static void dec_ref_cache(int index)
502
{
503 504 505 506
    assert(index >= 0);
    TRACE("dec'ing entry %d to %d\n", index, glyphsetCache[index].count - 1);
    assert(glyphsetCache[index].count > 0);
    glyphsetCache[index].count--;
507 508 509 510 511 512 513
}

static void lfsz_calc_hash(LFANDSIZE *plfsz)
{
  DWORD hash = 0, *ptr;
  int i;

514 515
  hash ^= plfsz->devsize.cx;
  hash ^= plfsz->devsize.cy;
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  for(i = 0, ptr = (DWORD*)&plfsz->lf; i < 7; i++, ptr++)
    hash ^= *ptr;
  for(i = 0, ptr = (DWORD*)&plfsz->lf.lfFaceName; i < LF_FACESIZE/2; i++, ptr++) {
    WCHAR *pwc = (WCHAR *)ptr;
    if(!*pwc) break;
    hash ^= *ptr;
    pwc++;
    if(!*pwc) break;
  }
  plfsz->hash = hash;
  return;
}

/***********************************************************************
 *   X11DRV_XRender_Finalize
 */
void X11DRV_XRender_Finalize(void)
{
534 535 536 537 538 539
    int i;

    EnterCriticalSection(&xrender_cs);
    for(i = mru; i >= 0; i = glyphsetCache[i].next)
	FreeEntry(i);
    LeaveCriticalSection(&xrender_cs);
540 541 542 543 544 545
}


/***********************************************************************
 *   X11DRV_XRender_SelectFont
 */
546
BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
547 548 549 550 551 552 553
{
    LFANDSIZE lfsz;

    GetObjectW(hfont, sizeof(lfsz.lf), &lfsz.lf);
    TRACE("h=%ld w=%ld weight=%ld it=%d charset=%d name=%s\n",
	  lfsz.lf.lfHeight, lfsz.lf.lfWidth, lfsz.lf.lfWeight,
	  lfsz.lf.lfItalic, lfsz.lf.lfCharSet, debugstr_w(lfsz.lf.lfFaceName));
554 555
    lfsz.devsize.cx = X11DRV_XWStoDS( physDev, lfsz.lf.lfWidth );
    lfsz.devsize.cy = X11DRV_YWStoDS( physDev, lfsz.lf.lfHeight );
556 557
    lfsz_calc_hash(&lfsz);

558 559
    EnterCriticalSection(&xrender_cs);
    if(!physDev->xrender) {
560 561
        physDev->xrender = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
				     sizeof(*physDev->xrender));
562 563 564 565
	physDev->xrender->cache_index = -1;
    }
    else if(physDev->xrender->cache_index != -1)
        dec_ref_cache(physDev->xrender->cache_index);
566
    physDev->xrender->cache_index = GetCacheEntry(physDev, &lfsz);
567
    LeaveCriticalSection(&xrender_cs);
568 569 570 571 572 573
    return 0;
}

/***********************************************************************
 *   X11DRV_XRender_DeleteDC
 */
574
void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
575
{
576
    wine_tsx11_lock();
577
    if(physDev->xrender->tile_pict)
578
        pXRenderFreePicture(gdi_display, physDev->xrender->tile_pict);
579 580

    if(physDev->xrender->tile_xpm)
581
        XFreePixmap(gdi_display, physDev->xrender->tile_xpm);
582 583

    if(physDev->xrender->pict) {
584
	TRACE("freeing pict = %lx dc = %p\n", physDev->xrender->pict, physDev->hdc);
585
        pXRenderFreePicture(gdi_display, physDev->xrender->pict);
586
    }
587
    wine_tsx11_unlock();
588

589 590 591 592
    EnterCriticalSection(&xrender_cs);
    if(physDev->xrender->cache_index != -1)
        dec_ref_cache(physDev->xrender->cache_index);
    LeaveCriticalSection(&xrender_cs);
593

594 595 596 597 598 599 600 601
    HeapFree(GetProcessHeap(), 0, physDev->xrender);
    physDev->xrender = NULL;
    return;
}

/***********************************************************************
 *   X11DRV_XRender_UpdateDrawable
 *
602 603
 * This gets called from X11DRV_SetDrawable and X11DRV_SelectBitmap.
 * It deletes the pict when the drawable changes.
604
 */
605
void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
606 607
{
    if(physDev->xrender->pict) {
608
        TRACE("freeing pict %08lx from dc %p drawable %08lx\n", physDev->xrender->pict,
609
              physDev->hdc, physDev->drawable);
610
        wine_tsx11_lock();
611
        XFlush(gdi_display);
612 613
        pXRenderFreePicture(gdi_display, physDev->xrender->pict);
        wine_tsx11_unlock();
614 615 616 617 618
    }
    physDev->xrender->pict = 0;
    return;
}

619 620 621 622 623
/************************************************************************
 *   UploadGlyph
 *
 * Helper to ExtTextOut.  Must be called inside xrender_cs
 */
624
static BOOL UploadGlyph(X11DRV_PDEVICE *physDev, int glyph, AA_Type format)
625
{
626
    unsigned int buflen;
627 628 629 630
    char *buf;
    Glyph gid;
    GLYPHMETRICS gm;
    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 637 638 639 640 641 642
    /* If there is nothing for the current type, we create the entry. */
    if( !entry->format[format] ) {
        entry->format[format] = HeapAlloc(GetProcessHeap(),
                                          HEAP_ZERO_MEMORY,
                                          sizeof(gsCacheEntryFormat));
    }
    formatEntry = entry->format[format];
643

644 645 646 647 648
    if(formatEntry->nrealized <= glyph) {
        formatEntry->nrealized = (glyph / 128 + 1) * 128;

	if (formatEntry->realized)
	    formatEntry->realized = HeapReAlloc(GetProcessHeap(),
649
				      HEAP_ZERO_MEMORY,
650 651
				      formatEntry->realized,
				      formatEntry->nrealized * sizeof(BOOL));
652
	else
653
	    formatEntry->realized = HeapAlloc(GetProcessHeap(),
654
				      HEAP_ZERO_MEMORY,
655
				      formatEntry->nrealized * sizeof(BOOL));
656

657
	if(!X11DRV_XRender_Installed) {
658 659
	  if (formatEntry->bitmaps)
	    formatEntry->bitmaps = HeapReAlloc(GetProcessHeap(),
660
				      HEAP_ZERO_MEMORY,
661 662
				      formatEntry->bitmaps,
				      formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
663
	  else
664
	    formatEntry->bitmaps = HeapAlloc(GetProcessHeap(),
665
				      HEAP_ZERO_MEMORY,
666
				      formatEntry->nrealized * sizeof(formatEntry->bitmaps[0]));
667

668 669
	  if (formatEntry->gis)
	    formatEntry->gis = HeapReAlloc(GetProcessHeap(),
670
				   HEAP_ZERO_MEMORY,
671 672
				   formatEntry->gis,
				   formatEntry->nrealized * sizeof(formatEntry->gis[0]));
673
	  else
674
	    formatEntry->gis = HeapAlloc(GetProcessHeap(),
675
				   HEAP_ZERO_MEMORY,
676
				   formatEntry->nrealized * sizeof(formatEntry->gis[0]));
677
	}
678 679
    }

680
    switch(format) {
681
    case AA_Grey:
682
	ggo_format |= WINE_GGO_GRAY16_BITMAP;
683 684 685
	break;

    default:
686
        ERR("aa = %d - not implemented\n", format);
687 688 689
    case AA_None:
        ggo_format |= GGO_BITMAP;
	break;
690 691
    }

692
    buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
693
			      NULL);
694
    if(buflen == GDI_ERROR) {
695 696 697
        if(format != AA_None) {
            format = AA_None;
            entry->aa_default = AA_None;
698 699 700 701 702 703
            ggo_format &= ~WINE_GGO_GRAY16_BITMAP;
            ggo_format |= GGO_BITMAP;
            buflen = GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, 0, NULL,
                                      NULL);
        }
        if(buflen == GDI_ERROR) {
704
            ERR("GetGlyphOutlineW failed\n");
705 706 707 708 709
            return FALSE;
        }
        TRACE("Turning off antialiasing for this monochrome font\n");
    }

710 711
    if(formatEntry->glyphset == 0 && X11DRV_XRender_Installed) {
        switch(format) {
712 713 714 715 716 717
	case AA_Grey:
	    pf.depth = 8;
	    pf.direct.alphaMask = 0xff;
	    break;

	default:
718
	    ERR("aa = %d - not implemented\n", format);
719 720 721 722 723 724 725 726 727 728
	case AA_None:
	    pf.depth = 1;
	    pf.direct.alphaMask = 1;
	    break;
	}

	pf.type = PictTypeDirect;
	pf.direct.alpha = 0;

	wine_tsx11_lock();
729
	formatEntry->font_format = pXRenderFindFormat(gdi_display,
730 731 732 733 734 735
						PictFormatType |
						PictFormatDepth |
						PictFormatAlpha |
						PictFormatAlphaMask,
						&pf, 0);

736
	formatEntry->glyphset = pXRenderCreateGlyphSet(gdi_display, formatEntry->font_format);
737
	wine_tsx11_unlock();
738 739
    }

740 741

    buf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buflen);
742
    GetGlyphOutlineW(physDev->hdc, glyph, ggo_format, &gm, buflen, buf, NULL);
743
    formatEntry->realized[glyph] = TRUE;
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

    TRACE("buflen = %d. Got metrics: %dx%d adv=%d,%d origin=%ld,%ld\n",
	  buflen,
	  gm.gmBlackBoxX, gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY,
	  gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);

    gi.width = gm.gmBlackBoxX;
    gi.height = gm.gmBlackBoxY;
    gi.x = -gm.gmptGlyphOrigin.x;
    gi.y = gm.gmptGlyphOrigin.y;
    gi.xOff = gm.gmCellIncX;
    gi.yOff = gm.gmCellIncY;

    if(TRACE_ON(xrender)) {
        int pitch, i, j;
	char output[300];
	unsigned char *line;

762
	if(format == AA_None) {
763 764
	    pitch = ((gi.width + 31) / 32) * 4;
	    for(i = 0; i < gi.height; i++) {
765
	        line = (unsigned char*) buf + i * pitch;
766 767 768 769 770 771 772 773
		output[0] = '\0';
		for(j = 0; j < pitch * 8; j++) {
	            strcat(output, (line[j / 8] & (1 << (7 - (j % 8)))) ? "#" : " ");
		}
		strcat(output, "\n");
		TRACE(output);
	    }
	} else {
774
	    static const char blks[] = " .:;!o*#";
775 776 777 778 779
	    char str[2];

	    str[1] = '\0';
	    pitch = ((gi.width + 3) / 4) * 4;
	    for(i = 0; i < gi.height; i++) {
780
	        line = (unsigned char*) buf + i * pitch;
781 782 783 784 785 786 787 788 789 790 791
		output[0] = '\0';
		for(j = 0; j < pitch; j++) {
		    str[0] = blks[line[j] >> 5];
		    strcat(output, str);
		}
		strcat(output, "\n");
		TRACE(output);
	    }
	}
    }

792 793
    if(formatEntry->glyphset) {
        if(format == AA_None && BitmapBitOrder(gdi_display) != MSBFirst) {
794
	    unsigned char *byte = (unsigned char*) buf, c;
795
	    int i = buflen;
796

797 798
	    while(i--) {
	        c = *byte;
799

800 801 802 803
		/* magic to flip bit order */
		c = ((c << 1) & 0xaa) | ((c >> 1) & 0x55);
		c = ((c << 2) & 0xcc) | ((c >> 2) & 0x33);
		c = ((c << 4) & 0xf0) | ((c >> 4) & 0x0f);
804

805 806
		*byte++ = c;
	    }
807
	}
808 809
	gid = glyph;
        wine_tsx11_lock();
810
	pXRenderAddGlyphs(gdi_display, formatEntry->glyphset, &gid, &gi, 1,
811 812 813 814
			  buf, buflen);
	wine_tsx11_unlock();
	HeapFree(GetProcessHeap(), 0, buf);
    } else {
815 816
        formatEntry->bitmaps[glyph] = buf;
	memcpy(&formatEntry->gis[glyph], &gi, sizeof(gi));
817 818 819 820
    }
    return TRUE;
}

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
static void SharpGlyphMono(X11DRV_PDEVICE *physDev, INT x, INT y,
			    void *bitmap, XGlyphInfo *gi)
{
    unsigned char   *srcLine = bitmap, *src;
    unsigned char   bits, bitsMask;
    int             width = gi->width;
    int             stride = ((width + 31) & ~31) >> 3;
    int             height = gi->height;
    int             w;
    int             xspan, lenspan;

    TRACE("%d, %d\n", x, y);
    x -= gi->x;
    y -= gi->y;
    while (height--)
    {
        src = srcLine;
        srcLine += stride;
        w = width;
        
        bitsMask = 0x80;    /* FreeType is always MSB first */
        bits = *src++;
        
        xspan = x;
        while (w)
        {
            if (bits & bitsMask)
            {
                lenspan = 0;
                do
                {
                    lenspan++;
                    if (lenspan == w)
                        break;
                    bitsMask = bitsMask >> 1;
                    if (!bitsMask)
                    {
                        bits = *src++;
                        bitsMask = 0x80;
                    }
                } while (bits & bitsMask);
                XFillRectangle (gdi_display, physDev->drawable, 
                                physDev->gc, xspan, y, lenspan, 1);
                xspan += lenspan;
                w -= lenspan;
            }
            else
            {
                do
                {
                    w--;
                    xspan++;
                    if (!w)
                        break;
                    bitsMask = bitsMask >> 1;
                    if (!bitsMask)
                    {
                        bits = *src++;
                        bitsMask = 0x80;
                    }
                } while (!(bits & bitsMask));
            }
        }
        y++;
    }
}

static void SharpGlyphGray(X11DRV_PDEVICE *physDev, INT x, INT y,
			    void *bitmap, XGlyphInfo *gi)
{
    unsigned char   *srcLine = bitmap, *src, bits;
    int             width = gi->width;
    int             stride = ((width + 3) & ~3);
    int             height = gi->height;
    int             w;
    int             xspan, lenspan;

    x -= gi->x;
    y -= gi->y;
    while (height--)
    {
        src = srcLine;
        srcLine += stride;
        w = width;
        
        bits = *src++;
        xspan = x;
        while (w)
        {
            if (bits >= 0x80)
            {
                lenspan = 0;
                do
                {
                    lenspan++;
                    if (lenspan == w)
                        break;
                    bits = *src++;
                } while (bits >= 0x80);
                XFillRectangle (gdi_display, physDev->drawable, 
                                physDev->gc, xspan, y, lenspan, 1);
                xspan += lenspan;
                w -= lenspan;
            }
            else
            {
                do
                {
                    w--;
                    xspan++;
                    if (!w)
                        break;
                    bits = *src++;
                } while (bits < 0x80);
            }
        }
        y++;
    }
}


static void ExamineBitfield (DWORD mask, int *shift, int *len)
{
    int s, l;

    s = 0;
    while ((mask & 1) == 0)
    {
        mask >>= 1;
        s++;
    }
    l = 0;
    while ((mask & 1) == 1)
    {
        mask >>= 1;
        l++;
    }
    *shift = s;
    *len = l;
}

static DWORD GetField (DWORD pixel, int shift, int len)
{
    pixel = pixel & (((1 << (len)) - 1) << shift);
    pixel = pixel << (32 - (shift + len)) >> 24;
    while (len < 8)
    {
        pixel |= (pixel >> len);
        len <<= 1;
    }
    return pixel;
}


static DWORD PutField (DWORD pixel, int shift, int len)
{
    shift = shift - (8 - len);
    if (len <= 8)
        pixel &= (((1 << len) - 1) << (8 - len));
    if (shift < 0)
        pixel >>= -shift;
    else
        pixel <<= shift;
    return pixel;
}

static void SmoothGlyphGray(XImage *image, int x, int y, void *bitmap, XGlyphInfo *gi,
988
			    int color)
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
{
    int             r_shift, r_len;
    int             g_shift, g_len;
    int             b_shift, b_len;
    BYTE            *maskLine, *mask, m;
    int             maskStride;
    DWORD           pixel;
    int             width, height;
    int             w, tx;
    BYTE            src_r, src_g, src_b;

    x -= gi->x;
    y -= gi->y;
    width = gi->width;
    height = gi->height;

    maskLine = (unsigned char *) bitmap;
    maskStride = (width + 3) & ~3;

    ExamineBitfield (image->red_mask, &r_shift, &r_len);
    ExamineBitfield (image->green_mask, &g_shift, &g_len);
    ExamineBitfield (image->blue_mask, &b_shift, &b_len);
1011 1012 1013 1014 1015

    src_r = GetField(color, r_shift, r_len);
    src_g = GetField(color, g_shift, g_len);
    src_b = GetField(color, b_shift, b_len);
    
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    for(; height--; y++)
    {
        mask = maskLine;
        maskLine += maskStride;
        w = width;
        tx = x;

	if(y < 0) continue;
	if(y >= image->height) break;

        for(; w--; tx++)
        {
	    if(tx >= image->width) break;

            m = *mask++;
	    if(tx < 0) continue;

	    if (m == 0xff)
1034
		XPutPixel (image, tx, y, color);
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
	    else if (m)
	    {
	        BYTE r, g, b;

		pixel = XGetPixel (image, tx, y);

		r = GetField(pixel, r_shift, r_len);
		r = ((BYTE)~m * (WORD)r + (BYTE)m * (WORD)src_r) >> 8;
		g = GetField(pixel, g_shift, g_len);
		g = ((BYTE)~m * (WORD)g + (BYTE)m * (WORD)src_g) >> 8;
		b = GetField(pixel, b_shift, b_len);
		b = ((BYTE)~m * (WORD)b + (BYTE)m * (WORD)src_b) >> 8;

		pixel = (PutField (r, r_shift, r_len) |
			 PutField (g, g_shift, g_len) |
			 PutField (b, b_shift, b_len));
		XPutPixel (image, tx, y, pixel);
	    }
        }
    }
}

static int XRenderErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
{
    return 1;
}

1062 1063 1064
/***********************************************************************
 *   X11DRV_XRender_ExtTextOut
 */
1065
BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
1066
				const RECT *lprect, LPCWSTR wstr, UINT count,
1067
				const INT *lpDx )
1068 1069
{
    XRenderColor col;
1070
    RGNDATA *data;
1071 1072
    XGCValues xgcval;
    int render_op = PictOpOver;
1073
    gsCacheEntry *entry;
1074
    gsCacheEntryFormat *formatEntry;
1075
    BOOL retv = FALSE;
1076
    HDC hdc = physDev->hdc;
1077
    int textPixel, backgroundPixel;
1078
    HRGN saved_region = 0;
1079 1080 1081
    BOOL disable_antialias = FALSE;
    AA_Type antialias = AA_None;
    DIBSECTION bmp;
1082 1083 1084
    unsigned int idx;
    double cosEsc, sinEsc;
    LOGFONTW lf;
1085 1086

    /* Do we need to disable antialiasing because of palette mode? */
1087
    if( !physDev->bitmap || GetObjectW( physDev->bitmap->hbitmap, sizeof(bmp), &bmp ) != sizeof(bmp) ) {
1088 1089 1090 1091 1092 1093
        TRACE("bitmap is not a DIB\n");
    }
    else if (bmp.dsBmih.biBitCount <= 8) {
        TRACE("Disabling antialiasing\n");
        disable_antialias = TRUE;
    }
1094 1095 1096 1097

    xgcval.function = GXcopy;
    xgcval.background = physDev->backgroundPixel;
    xgcval.fill_style = FillSolid;
1098 1099 1100
    wine_tsx11_lock();
    XChangeGC( gdi_display, physDev->gc, GCFunction | GCBackground | GCFillStyle, &xgcval );
    wine_tsx11_unlock();
1101

1102
    X11DRV_LockDIBSection( physDev, DIB_Status_GdiMod, FALSE );
1103

1104
    if(physDev->depth == 1) {
1105
        if((physDev->textPixel & 0xffffff) == 0) {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
	    textPixel = 0;
	    backgroundPixel = 1;
	} else {
	    textPixel = 1;
	    backgroundPixel = 0;
	}
    } else {
        textPixel = physDev->textPixel;
	backgroundPixel = physDev->backgroundPixel;
    }

1117 1118
    if(flags & ETO_OPAQUE)
    {
1119 1120 1121
        wine_tsx11_lock();
        XSetForeground( gdi_display, physDev->gc, backgroundPixel );
        XFillRectangle( gdi_display, physDev->drawable, physDev->gc,
1122 1123
                        physDev->org.x + lprect->left, physDev->org.y + lprect->top,
                        lprect->right - lprect->left, lprect->bottom - lprect->top );
1124
        wine_tsx11_unlock();
1125 1126
    }

1127 1128 1129
    if(count == 0)
    {
	retv = TRUE;
1130
        goto done_unlock;
1131 1132
    }

1133 1134 1135 1136 1137
    
    GetObjectW(GetCurrentObject(physDev->hdc, OBJ_FONT), sizeof(lf), &lf);
    if(lf.lfEscapement != 0) {
        cosEsc = cos(lf.lfEscapement * M_PI / 1800);
        sinEsc = sin(lf.lfEscapement * M_PI / 1800);
1138
    } else {
1139 1140
        cosEsc = 1;
        sinEsc = 0;
1141 1142 1143 1144
    }

    if (flags & ETO_CLIPPED)
    {
1145 1146
        HRGN clip_region;

1147
        clip_region = CreateRectRgnIndirect( lprect );
1148 1149 1150 1151 1152
        /* make a copy of the current device region */
        saved_region = CreateRectRgn( 0, 0, 0, 0 );
        CombineRgn( saved_region, physDev->region, 0, RGN_COPY );
        X11DRV_SetDeviceClipping( physDev, saved_region, clip_region );
        DeleteObject( clip_region );
1153 1154
    }

1155 1156 1157 1158
    if(X11DRV_XRender_Installed) {
        if(!physDev->xrender->pict) {
	    XRenderPictureAttributes pa;
	    pa.subwindow_mode = IncludeInferiors;
1159

1160 1161 1162
	    wine_tsx11_lock();
	    physDev->xrender->pict = pXRenderCreatePicture(gdi_display,
							   physDev->drawable,
1163
							   (physDev->depth == 1) ?
1164 1165 1166
							   mono_format : screen_format,
							   CPSubwindowMode, &pa);
	    wine_tsx11_unlock();
1167

1168 1169
	    TRACE("allocing pict = %lx dc = %p drawable = %08lx\n",
                  physDev->xrender->pict, hdc, physDev->drawable);
1170
	} else {
1171 1172
	    TRACE("using existing pict = %lx dc = %p drawable = %08lx\n",
                  physDev->xrender->pict, hdc, physDev->drawable);
1173
	}
1174

1175
	if ((data = X11DRV_GetRegionData( physDev->region, 0 )))
1176 1177 1178 1179 1180 1181 1182 1183
	{
	    wine_tsx11_lock();
	    pXRenderSetPictureClipRectangles( gdi_display, physDev->xrender->pict,
					      physDev->org.x, physDev->org.y,
					      (XRectangle *)data->Buffer, data->rdh.nCount );
	    wine_tsx11_unlock();
	    HeapFree( GetProcessHeap(), 0, data );
	}
1184 1185
    }

1186 1187 1188 1189 1190
    if(X11DRV_XRender_Installed) {
        /* Create a 1x1 pixmap to tile over the font mask */
        if(!physDev->xrender->tile_xpm) {
	    XRenderPictureAttributes pa;

1191
	    XRenderPictFormat *format = (physDev->depth == 1) ? mono_format : screen_format;
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
	    wine_tsx11_lock();
	    physDev->xrender->tile_xpm = XCreatePixmap(gdi_display,
						       physDev->drawable,
						       1, 1,
						       format->depth);
	    pa.repeat = True;
	    physDev->xrender->tile_pict = pXRenderCreatePicture(gdi_display,
								physDev->xrender->tile_xpm,
								format,
								CPRepeat, &pa);
	    wine_tsx11_unlock();
	    TRACE("Created pixmap of depth %d\n", format->depth);
1204 1205
	    /* init lastTextColor to something different from textPixel */
	    physDev->xrender->lastTextColor = ~physDev->textPixel;
1206 1207 1208

	}

1209
	if(physDev->textPixel != physDev->xrender->lastTextColor) {
1210
	    if(physDev->depth != 1) {
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
                /* Map 0 -- 0xff onto 0 -- 0xffff */
                int             r_shift, r_len;
                int             g_shift, g_len;
                int             b_shift, b_len;

                ExamineBitfield (visual->red_mask, &r_shift, &r_len );
                ExamineBitfield (visual->green_mask, &g_shift, &g_len);
                ExamineBitfield (visual->blue_mask, &b_shift, &b_len);

	        col.red = GetField(physDev->textPixel, r_shift, r_len);
1221
		col.red |= col.red << 8;
1222
		col.green = GetField(physDev->textPixel, g_shift, g_len);
1223
		col.green |= col.green << 8;
1224
		col.blue = GetField(physDev->textPixel, b_shift, b_len);
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
		col.blue |= col.blue << 8;
		col.alpha = 0x0;
	    } else { /* for a 1bpp bitmap we always need a 1 in the tile */
	        col.red = col.green = col.blue = 0;
		col.alpha = 0xffff;
	    }
	    wine_tsx11_lock();
	    pXRenderFillRectangle(gdi_display, PictOpSrc,
				  physDev->xrender->tile_pict,
				  &col, 0, 0, 1, 1);
	    wine_tsx11_unlock();
1236
	    physDev->xrender->lastTextColor = physDev->textPixel;
1237 1238 1239 1240
	}

	/* FIXME the mapping of Text/BkColor onto 1 or 0 needs investigation.
	 */
1241
	if((physDev->depth == 1) && (textPixel == 0))
1242 1243
	    render_op = PictOpOutReverse; /* This gives us 'black' text */
    }
1244

1245 1246
    EnterCriticalSection(&xrender_cs);
    entry = glyphsetCache + physDev->xrender->cache_index;
1247 1248 1249
    if( disable_antialias == FALSE )
        antialias = entry->aa_default;
    formatEntry = entry->format[antialias];
1250

1251
    for(idx = 0; idx < count; idx++) {
1252
        if( !formatEntry ) {
1253
	    UploadGlyph(physDev, wstr[idx], antialias);
1254
            formatEntry = entry->format[antialias];
1255 1256
        } else if( wstr[idx] >= formatEntry->nrealized || formatEntry->realized[wstr[idx]] == FALSE) {
	    UploadGlyph(physDev, wstr[idx], antialias);
1257 1258
	}
    }
1259
    assert(formatEntry);
1260

1261 1262
    TRACE("Writing %s at %ld,%ld\n", debugstr_wn(wstr,count),
          physDev->org.x + x, physDev->org.y + y);
1263

1264 1265
    if(X11DRV_XRender_Installed) {
        wine_tsx11_lock();
1266
	if(!lpDx)
1267 1268 1269
	    pXRenderCompositeString16(gdi_display, render_op,
				      physDev->xrender->tile_pict,
				      physDev->xrender->pict,
1270
				      formatEntry->font_format, formatEntry->glyphset,
1271
				      0, 0, physDev->org.x + x, physDev->org.y + y,
1272
				      wstr, count);
1273 1274 1275 1276 1277 1278
	else {
	    INT offset = 0, xoff = 0, yoff = 0;
	    for(idx = 0; idx < count; idx++) {
	        pXRenderCompositeString16(gdi_display, render_op,
					  physDev->xrender->tile_pict,
					  physDev->xrender->pict,
1279
					  formatEntry->font_format, formatEntry->glyphset,
1280 1281
					  0, 0, physDev->org.x + x + xoff,
					  physDev->org.y + y + yoff,
1282 1283
					  wstr + idx, 1);
                offset += lpDx[idx];
1284 1285 1286 1287 1288
		xoff = offset * cosEsc;
		yoff = offset * -sinEsc;
	    }
	}
	wine_tsx11_unlock();
1289

1290
    } else {
1291
        INT offset = 0, xoff = 0, yoff = 0;
1292 1293 1294
        wine_tsx11_lock();
	XSetForeground( gdi_display, physDev->gc, textPixel );

1295
	if(antialias == AA_None) {
1296 1297 1298
	    for(idx = 0; idx < count; idx++) {
	        SharpGlyphMono(physDev, physDev->org.x + x + xoff,
			       physDev->org.y + y + yoff,
1299 1300 1301 1302
			       formatEntry->bitmaps[wstr[idx]],
			       &formatEntry->gis[wstr[idx]]);
		if(lpDx) {
		    offset += lpDx[idx];
1303 1304 1305
		    xoff = offset * cosEsc;
		    yoff = offset * -sinEsc;
		} else {
1306 1307
		    xoff += formatEntry->gis[wstr[idx]].xOff;
		    yoff += formatEntry->gis[wstr[idx]].yOff;
1308 1309
		}
	    }
1310
	} else if(physDev->depth == 1) {
1311 1312 1313
	    for(idx = 0; idx < count; idx++) {
	        SharpGlyphGray(physDev, physDev->org.x + x + xoff,
			       physDev->org.y + y + yoff,
1314 1315 1316 1317
			       formatEntry->bitmaps[wstr[idx]],
			       &formatEntry->gis[wstr[idx]]);
		if(lpDx) {
		    offset += lpDx[idx];
1318 1319 1320
		    xoff = offset * cosEsc;
		    yoff = offset * -sinEsc;
		} else {
1321 1322
		    xoff += formatEntry->gis[wstr[idx]].xOff;
		    yoff += formatEntry->gis[wstr[idx]].yOff;
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
		}
		    
	    }
	} else {
	    XImage *image;
	    unsigned int w, h, dummy_uint;
	    Window dummy_window;
	    int dummy_int;
	    int image_x, image_y, image_off_x, image_off_y, image_w, image_h;
	    RECT extents = {0, 0, 0, 0};
	    POINT cur = {0, 0};
	    
	    
	    XGetGeometry(gdi_display, physDev->drawable, &dummy_window, &dummy_int, &dummy_int,
			 &w, &h, &dummy_uint, &dummy_uint);
	    TRACE("drawable %dx%d\n", w, h);

	    for(idx = 0; idx < count; idx++) {
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
	        if(extents.left > cur.x - formatEntry->gis[wstr[idx]].x)
		    extents.left = cur.x - formatEntry->gis[wstr[idx]].x;
		if(extents.top > cur.y - formatEntry->gis[wstr[idx]].y)
		    extents.top = cur.y - formatEntry->gis[wstr[idx]].y;
		if(extents.right < cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width)
		    extents.right = cur.x - formatEntry->gis[wstr[idx]].x + formatEntry->gis[wstr[idx]].width;
		if(extents.bottom < cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height)
		    extents.bottom = cur.y - formatEntry->gis[wstr[idx]].y + formatEntry->gis[wstr[idx]].height;
		if(lpDx) {
		    offset += lpDx[idx];
1351 1352 1353
		    cur.x = offset * cosEsc;
		    cur.y = offset * -sinEsc;
		} else {
1354 1355
		    cur.x += formatEntry->gis[wstr[idx]].xOff;
		    cur.y += formatEntry->gis[wstr[idx]].yOff;
1356 1357
		}
	    }
1358
	    TRACE("glyph extents %ld,%ld - %ld,%ld drawable x,y %ld,%ld\n", extents.left, extents.top,
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
		  extents.right, extents.bottom, physDev->org.x + x, physDev->org.y + y);

	    if(physDev->org.x + x + extents.left >= 0) {
	        image_x = physDev->org.x + x + extents.left;
		image_off_x = 0;
	    } else {
	        image_x = 0;
		image_off_x = physDev->org.x + x + extents.left;
	    }
	    if(physDev->org.y + y + extents.top >= 0) {
	        image_y = physDev->org.y + y + extents.top;
		image_off_y = 0;
	    } else {
	        image_y = 0;
		image_off_y = physDev->org.y + y + extents.top;
	    }
	    if(physDev->org.x + x + extents.right < w)
	        image_w = physDev->org.x + x + extents.right - image_x;
	    else
	        image_w = w - image_x;
	    if(physDev->org.y + y + extents.bottom < h)
	        image_h = physDev->org.y + y + extents.bottom - image_y;
	    else
	        image_h = h - image_y;

	    if(image_w <= 0 || image_h <= 0) goto no_image;

	    X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
	    image = XGetImage(gdi_display, physDev->drawable,
			      image_x, image_y, image_w, image_h,
			      AllPlanes, ZPixmap);
	    X11DRV_check_error();

	    TRACE("XGetImage(%p, %x, %d, %d, %d, %d, %lx, %x) depth = %d rets %p\n",
		  gdi_display, (int)physDev->drawable, image_x, image_y,
		  image_w, image_h, AllPlanes, ZPixmap,
1395
		  physDev->depth, image);
1396 1397
	    if(!image) {
	        Pixmap xpm = XCreatePixmap(gdi_display, physDev->drawable, image_w, image_h,
1398
					   physDev->depth);
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
		GC gc;
		XGCValues gcv;

		gcv.graphics_exposures = False;
		gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
		XCopyArea(gdi_display, physDev->drawable, xpm, gc, image_x, image_y,
			  image_w, image_h, 0, 0);
		XFreeGC(gdi_display, gc);
		X11DRV_expect_error(gdi_display, XRenderErrorHandler, NULL);
		image = XGetImage(gdi_display, xpm, 0, 0, image_w, image_h, AllPlanes,
				  ZPixmap);
		X11DRV_check_error();
		XFreePixmap(gdi_display, xpm);
	    }
	    if(!image) goto no_image;

	    image->red_mask = visual->red_mask;
	    image->green_mask = visual->green_mask;
	    image->blue_mask = visual->blue_mask;

	    offset = xoff = yoff = 0;
	    for(idx = 0; idx < count; idx++) {
	        SmoothGlyphGray(image, xoff + image_off_x - extents.left,
				yoff + image_off_y - extents.top,
1423 1424
				formatEntry->bitmaps[wstr[idx]],
				&formatEntry->gis[wstr[idx]],
1425
				physDev->textPixel);
1426 1427
		if(lpDx) {
		    offset += lpDx[idx];
1428 1429 1430
		    xoff = offset * cosEsc;
		    yoff = offset * -sinEsc;
		} else {
1431 1432
		    xoff += formatEntry->gis[wstr[idx]].xOff;
		    yoff += formatEntry->gis[wstr[idx]].yOff;
1433 1434 1435 1436 1437
		}
	    }
	    XPutImage(gdi_display, physDev->drawable, physDev->gc, image, 0, 0,
		      image_x, image_y, image_w, image_h);
	    XDestroyImage(image);
1438
	}
1439
    no_image:
1440
	wine_tsx11_unlock();
1441
    }
1442 1443
    LeaveCriticalSection(&xrender_cs);

1444
    if (flags & ETO_CLIPPED)
1445 1446 1447 1448 1449
    {
        /* restore the device region */
        X11DRV_SetDeviceClipping( physDev, saved_region, 0 );
        DeleteObject( saved_region );
    }
1450

1451 1452
    retv = TRUE;

1453
done_unlock:
1454
    X11DRV_UnlockDIBSection( physDev, TRUE );
1455
    return retv;
1456 1457
}

1458 1459 1460
/******************************************************************************
 * AlphaBlend         (x11drv.@)
 */
1461 1462
BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
                       X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1463
                       BLENDFUNCTION blendfn)
1464 1465 1466
{
    XRenderPictureAttributes pa;
    XRenderPictFormat *src_format;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    XRenderPictFormat argb32_templ = {
        0,                          /* id */
        PictTypeDirect,             /* type */
        32,                         /* depth */
        {                           /* direct */
            16,                     /* direct.red */
            0xff,                   /* direct.redMask */
            8,                      /* direct.green */
            0xff,                   /* direct.greenMask */
            0,                      /* direct.blue */
            0xff,                   /* direct.blueMask */
            24,                     /* direct.alpha */
            0xff,                   /* direct.alphaMask */
        },
        0,                          /* colormap */
    };
    unsigned long argb32_templ_mask = 
        PictFormatType |
        PictFormatDepth |
        PictFormatRed |
        PictFormatRedMask |
        PictFormatGreen |
        PictFormatGreenMask |
        PictFormatBlue |
        PictFormatBlueMask |
        PictFormatAlpha |
        PictFormatAlphaMask;

1495 1496
    Picture dst_pict, src_pict;
    Pixmap xpm;
1497
    DIBSECTION dib;
1498 1499 1500
    XImage *image;
    GC gc;
    XGCValues gcv;
1501 1502
    BYTE *dstbits, *data;
    int y, y2;
1503
    POINT pts[2];
1504
    BOOL top_down = FALSE;
1505
    RGNDATA *rgndata;
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530

    if(!X11DRV_XRender_Installed) {
        FIXME("Unable to AlphaBlend without Xrender\n");
        return FALSE;
    }
    pts[0].x = xDst;
    pts[0].y = yDst;
    pts[1].x = xDst + widthDst;
    pts[1].y = yDst + heightDst;
    LPtoDP(devDst->hdc, pts, 2);
    xDst      = pts[0].x;
    yDst      = pts[0].y;
    widthDst  = pts[1].x - pts[0].x;
    heightDst = pts[1].y - pts[0].y;

    pts[0].x = xSrc;
    pts[0].y = ySrc;
    pts[1].x = xSrc + widthSrc;
    pts[1].y = ySrc + heightSrc;
    LPtoDP(devSrc->hdc, pts, 2);
    xSrc      = pts[0].x;
    ySrc      = pts[0].y;
    widthSrc  = pts[1].x - pts[0].x;
    heightSrc = pts[1].y - pts[0].y;

1531 1532 1533 1534 1535 1536 1537
#ifndef HAVE_XRENDERSETPICTURETRANSFORM
    if(widthDst != widthSrc || heightDst != heightSrc)
#else
    if(!pXRenderSetPictureTransform)
#endif
    {
        FIXME("Unable to Stretch, XRenderSetPictureTransform is currently required\n");
1538 1539 1540
        return FALSE;
    }

1541
    if (!devSrc->bitmap || GetObjectW( devSrc->bitmap->hbitmap, sizeof(dib), &dib ) != sizeof(dib))
1542
    {
1543 1544 1545 1546
        FIXME("not a dibsection\n");
        return FALSE;
    }

1547
    if(dib.dsBm.bmBitsPixel != 32) {
1548 1549 1550 1551
        FIXME("not a 32 bpp dibsection\n");
        return FALSE;
    }
    dstbits = data = HeapAlloc(GetProcessHeap(), 0, heightSrc * widthSrc * 4);
1552

1553
    if(dib.dsBmih.biHeight < 0) { /* top-down dib */
1554 1555
        top_down = TRUE;
        dstbits += widthSrc * (heightSrc - 1) * 4;
1556
        y2 = ySrc;
1557
        y = y2 + heightSrc - 1;
1558
    }
1559 1560 1561
    else
    {
        y = dib.dsBmih.biHeight - ySrc - 1;
1562
        y2 = y - heightSrc + 1;
1563
    }
1564
    for(; y >= y2; y--) {
1565
        memcpy(dstbits, (char *)dib.dsBm.bmBits + y * dib.dsBm.bmWidthBytes + xSrc * 4,
1566
               widthSrc * 4);
1567
        dstbits += (top_down ? -1 : 1) * widthSrc * 4;
1568 1569 1570 1571
    }

    wine_tsx11_lock();
    image = XCreateImage(gdi_display, visual, 32, ZPixmap, 0,
Mike McCormack's avatar
Mike McCormack committed
1572
                         (char*) data, widthSrc, heightSrc, 32, widthSrc * 4);
1573

1574 1575 1576 1577 1578
    /*
      Avoid using XRenderFindStandardFormat as older libraries don't have it
      src_format = pXRenderFindStandardFormat(gdi_display, PictStandardARGB32);
    */
    src_format = pXRenderFindFormat(gdi_display, argb32_templ_mask, &argb32_templ, 0);
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604

    TRACE("src_format %p\n", src_format);

    pa.subwindow_mode = IncludeInferiors;

    /* FIXME use devDst->xrender->pict ? */
    dst_pict = pXRenderCreatePicture(gdi_display,
                                     devDst->drawable,
                                     (devDst->depth == 1) ?
                                     mono_format : screen_format,
                                     CPSubwindowMode, &pa);
    TRACE("dst_pict %08lx\n", dst_pict);
    TRACE("src_drawable = %08lx\n", devSrc->drawable);
    xpm = XCreatePixmap(gdi_display,
                        devSrc->drawable,
                        widthSrc, heightSrc, 32);
    gcv.graphics_exposures = False;
    gc = XCreateGC(gdi_display, xpm, GCGraphicsExposures, &gcv);
    TRACE("xpm = %08lx\n", xpm);
    XPutImage(gdi_display, xpm, gc, image, 0, 0, 0, 0, widthSrc, heightSrc);

    src_pict = pXRenderCreatePicture(gdi_display,
                                     xpm, src_format,
                                     CPSubwindowMode, &pa);
    TRACE("src_pict %08lx\n", src_pict);

1605 1606 1607 1608 1609 1610 1611 1612 1613
    if ((rgndata = X11DRV_GetRegionData( devDst->region, 0 )))
    {
        pXRenderSetPictureClipRectangles( gdi_display, dst_pict,
                                          devDst->org.x, devDst->org.y,
                                          (XRectangle *)rgndata->Buffer, 
                                          rgndata->rdh.nCount );
        HeapFree( GetProcessHeap(), 0, rgndata );
    }

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
#ifdef HAVE_XRENDERSETPICTURETRANSFORM
    if(widthDst != widthSrc || heightDst != heightSrc) {
        double xscale = widthSrc/(double)widthDst;
        double yscale = heightSrc/(double)heightDst;
        XTransform xform = {{
            { XDoubleToFixed(xscale), XDoubleToFixed(0), XDoubleToFixed(0) },
            { XDoubleToFixed(0), XDoubleToFixed(yscale), XDoubleToFixed(0) },
            { XDoubleToFixed(0), XDoubleToFixed(0), XDoubleToFixed(1) }
        }};
        pXRenderSetPictureTransform(gdi_display, src_pict, &xform);
    }
#endif
1626
    pXRenderComposite(gdi_display, PictOpOver, src_pict, 0, dst_pict,
1627
                      0, 0, 0, 0,
1628
                      xDst + devDst->org.x, yDst + devDst->org.y, widthDst, heightDst);
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642


    pXRenderFreePicture(gdi_display, src_pict);
    XFreePixmap(gdi_display, xpm);
    XFreeGC(gdi_display, gc);
    pXRenderFreePicture(gdi_display, dst_pict);
    image->data = NULL;
    XDestroyImage(image);

    wine_tsx11_unlock();
    HeapFree(GetProcessHeap(), 0, data);
    return TRUE;
}

1643
#else /* HAVE_X11_EXTENSIONS_XRENDER_H */
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654

void X11DRV_XRender_Init(void)
{
    TRACE("XRender support not compiled in.\n");
    return;
}

void X11DRV_XRender_Finalize(void)
{
}

1655
BOOL X11DRV_XRender_SelectFont(X11DRV_PDEVICE *physDev, HFONT hfont)
1656 1657 1658 1659 1660
{
  assert(0);
  return FALSE;
}

1661
void X11DRV_XRender_DeleteDC(X11DRV_PDEVICE *physDev)
1662 1663 1664 1665 1666
{
  assert(0);
  return;
}

1667
BOOL X11DRV_XRender_ExtTextOut( X11DRV_PDEVICE *physDev, INT x, INT y, UINT flags,
1668
				const RECT *lprect, LPCWSTR wstr, UINT count,
1669
				const INT *lpDx )
1670 1671 1672 1673 1674
{
  assert(0);
  return FALSE;
}

1675
void X11DRV_XRender_UpdateDrawable(X11DRV_PDEVICE *physDev)
1676 1677 1678 1679 1680
{
  assert(0);
  return;
}

1681 1682 1683
/******************************************************************************
 * AlphaBlend         (x11drv.@)
 */
1684 1685
BOOL X11DRV_AlphaBlend(X11DRV_PDEVICE *devDst, INT xDst, INT yDst, INT widthDst, INT heightDst,
                       X11DRV_PDEVICE *devSrc, INT xSrc, INT ySrc, INT widthSrc, INT heightSrc,
1686
                       BLENDFUNCTION blendfn)
1687 1688 1689 1690 1691
{
  FIXME("not supported - XRENDER headers were missing at compile time\n");
  return FALSE;
}

1692
#endif /* HAVE_X11_EXTENSIONS_XRENDER_H */