/*		DIBSection DirectDrawSurface driver
 *
 * Copyright 1997-2000 Marcus Meissner
 * Copyright 1998-2000 Lionel Ulmer
 * Copyright 2000-2003 TransGaming Technologies Inc.
 * Copyright 2003 Jarmo Nikkanen (Surface_Blt support for clippers and colorkeys)
 */

#include "config.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "winerror.h"
#include "bitmap.h"
#include "wine/debug.h"
#include "ddraw_private.h"
#include "dsurface/main.h"
#include "dsurface/dib.h"

WINE_DEFAULT_DEBUG_CHANNEL(ddraw);

static ICOM_VTABLE(IDirectDrawSurface7) DIB_IDirectDrawSurface7_VTable;

/* this routine is only used if the HAL didn't allocate a DIB section itself,
 * and if we really need a DIB section for stuff like GetDC */
static HRESULT create_dib(IDirectDrawSurfaceImpl* This)
{
    BITMAPINFO* b_info;
    UINT usage;
    HDC ddc;
    DIB_DirectDrawSurfaceImpl* priv = This->private;
    DIBSECTION dib_info;
    LPVOID bitmap_data, old_data;

    assert(This->surface_desc.u1.lPitch != 0);

    switch (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount)
    {
    case 16:
    case 32:
	/* Allocate extra space to store the RGB bit masks. */
	b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
					sizeof(BITMAPINFOHEADER)
					+ 3 * sizeof(DWORD));
	break;

    case 24:
	b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
					sizeof(BITMAPINFOHEADER));
	break;

    default:
	/* Allocate extra space for a palette. */
	b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
					sizeof(BITMAPINFOHEADER)
					+ sizeof(RGBQUAD)
					* (1 << This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount));
	break;
    }

    b_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    b_info->bmiHeader.biWidth = This->surface_desc.dwWidth;
    b_info->bmiHeader.biHeight = -This->surface_desc.dwHeight;
    b_info->bmiHeader.biPlanes = 1;
    b_info->bmiHeader.biBitCount = This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount;

    if ((This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount != 16)
	&& (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount != 32))
        b_info->bmiHeader.biCompression = BI_RGB;
    else
        b_info->bmiHeader.biCompression = BI_BITFIELDS;

    b_info->bmiHeader.biSizeImage
	= This->surface_desc.u1.lPitch * This->surface_desc.dwHeight;

    b_info->bmiHeader.biXPelsPerMeter = 0;
    b_info->bmiHeader.biYPelsPerMeter = 0;
    b_info->bmiHeader.biClrUsed = 0;
    b_info->bmiHeader.biClrImportant = 0;

    switch (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount)
    {
    case 16:
    case 32:
    {
	DWORD *masks = (DWORD *) &(b_info->bmiColors);

	usage = 0;
	masks[0] = This->surface_desc.u4.ddpfPixelFormat.u2.dwRBitMask;
	masks[1] = This->surface_desc.u4.ddpfPixelFormat.u3.dwGBitMask;
	masks[2] = This->surface_desc.u4.ddpfPixelFormat.u4.dwBBitMask;
    }
    break;

    case 24:
	/* Nothing to do */
	usage = DIB_RGB_COLORS;
	break;

    default:
	/* Don't know palette */
	usage = 0;
	break;
    }

    ddc = CreateDCA("DISPLAY", NULL, NULL, NULL);
    if (ddc == 0)
    {
	HeapFree(GetProcessHeap(), 0, b_info);
	return HRESULT_FROM_WIN32(GetLastError());
    }

    /* since the HAL didn't allocate a DIB section itself, it probably
     * won't mind that we relocate the buffer to one */
    priv->dib.DIBsection
	= CreateDIBSection(ddc, b_info, usage, &bitmap_data, 0, 0);
    GetObjectA(priv->dib.DIBsection, sizeof(dib_info), &dib_info);
    old_data = This->lock_update(This, NULL, DDLOCK_WAIT | DDLOCK_READONLY);
    if (old_data) {
	if (dib_info.dsBm.bmWidthBytes != This->t.gbl.u4.lPitch) {
	    unsigned u;
	    /* transfer line by line since the pitch differs */
	    for (u=0; u<This->t.gbl.wHeight; u++) {
		SetDIBits(ddc, priv->dib.DIBsection, u, 1,
			  old_data + u*This->t.gbl.u4.lPitch,
			  b_info, usage);
	    }
	} else {
	    SetDIBits(ddc, priv->dib.DIBsection, 0, This->t.gbl.wHeight,
		      old_data, b_info, usage);
	}
	if (!priv->dib.client_memory) {
	    if (This->t.gbl.fpVidMem)
		HeapFree(surface_heap, 0, (LPVOID)This->t.gbl.fpVidMem);
	} else {
	    /* we can't support this properly without messing with GDI internals */
	    /* so for now, the app must live with its client memory being unused */
	    ERR("app supplied client memory but needs DIB section without HAL support\n");
	}
    }
    This->unlock_update(This, NULL);
    if (dib_info.dsBm.bmWidthBytes != This->surface_desc.u1.lPitch) {
	WARN("DIB section and surface pitches differ\n");
	This->surface_desc.u1.lPitch = dib_info.dsBm.bmWidthBytes;
	This->t.gbl.u4.lPitch = dib_info.dsBm.bmWidthBytes;
    }
    DeleteDC(ddc);
    if (!priv->dib.DIBsection) {
	ERR("CreateDIBSection failed!\n");
	HeapFree(GetProcessHeap(), 0, b_info);
	return HRESULT_FROM_WIN32(GetLastError());
    }

    TRACE("DIBSection at : %p\n", bitmap_data);

    This->surface_desc.lpSurface = bitmap_data;

    This->t.gbl.fpVidMem = (FLATPTR)This->surface_desc.lpSurface;

    HeapFree(GetProcessHeap(), 0, b_info);

    HAL_DIB(This) = priv->dib.DIBsection;

    return S_OK;
}

void DIB_DirectDrawSurface_final_release(IDirectDrawSurfaceImpl* This)
{
    DIB_DirectDrawSurfaceImpl* priv = This->private;

    if (priv->dib.DIBsection) {
	DeleteObject(priv->dib.DIBsection);
	HAL_DIB(This) = 0;
	This->t.gbl.fpVidMem = 0;
    }

    if (!priv->dib.client_memory)
    {
	DirectDraw_Deallocate_Memory(This->ddraw_owner, This->surface_desc.u1.lPitch * This->surface_desc.dwHeight);
	if (This->t.gbl.fpVidMem)
	    HeapFree(surface_heap, 0, (LPVOID)This->t.gbl.fpVidMem);
    }

    Main_DirectDrawSurface_final_release(This);
}

HRESULT DIB_DirectDrawSurface_duplicate_surface(IDirectDrawSurfaceImpl* This,
						LPDIRECTDRAWSURFACE7* ppDup)
{
    return DIB_DirectDrawSurface_Create(This->ddraw_owner,
					&This->surface_desc, ppDup, NULL);
}

HRESULT DIB_DirectDrawSurface_Construct(IDirectDrawSurfaceImpl *This,
					IDirectDrawImpl *pDD,
					const DDSURFACEDESC2 *pDDSD)
{
    HRESULT hr;
    DIB_DirectDrawSurfaceImpl* priv = This->private;

    TRACE("(%p)->(%p,%p)\n",This,pDD,pDDSD);
    hr = Main_DirectDrawSurface_Construct(This, pDD, pDDSD);
    if (FAILED(hr)) return hr;

    ICOM_INIT_INTERFACE(This, IDirectDrawSurface7,
			DIB_IDirectDrawSurface7_VTable);

    This->final_release = DIB_DirectDrawSurface_final_release;
    This->duplicate_surface = DIB_DirectDrawSurface_duplicate_surface;
    This->flip_data = DIB_DirectDrawSurface_flip_data;

    This->get_dc     = DIB_DirectDrawSurface_get_dc;
    This->release_dc = DIB_DirectDrawSurface_release_dc;
    This->hDC = (HDC)NULL;

    This->set_palette    = DIB_DirectDrawSurface_set_palette;
    This->update_palette = DIB_DirectDrawSurface_update_palette;

    /* Ensure that the handle to the DibSection is initialized to
     * NULL - it's only needed if we're rendering to a surface */
    priv->dib.DIBsection = (HBITMAP)NULL;

    /* This function will force the DIBSection to be initialized, if we
     * need it for 3D rendering into an XPixmap, for example */
    This->lazy_alloc_dibsection = DIB_DirectDrawSurface_lazy_alloc_dibsection;

    TRACE("(%ldx%ld, pitch=%ld)\n",
	  This->surface_desc.dwWidth, This->surface_desc.dwHeight,
	  This->surface_desc.u1.lPitch);
    /* XXX load dwWidth and dwHeight from pDD if they are not specified? */
#if 0
    /* When compressed formats are properly supported, we should handle
     * them here.  In the meantime, we let them continue on so that
     * memory is allocated for them to prevent crashes in apps that use
     * them */
    if (This->surface_desc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) {
	Main_DirectDrawSurface_final_release(This);
	return DDERR_INVALIDPIXELFORMAT;
    }
#endif

    if (This->surface_desc.dwFlags & DDSD_LPSURFACE)
    {
	/* "Client memory": it is managed by the application. */
	/* XXX What if lPitch is not set? Use dwWidth or fail? */

	priv->dib.client_memory = TRUE;
	This->t.gbl.dwGlobalFlags |= DDRAWISURFGBL_ISCLIENTMEM;
	This->t.gbl.fpVidMem = (FLATPTR)This->surface_desc.lpSurface;
	This->t.gbl.u4.lPitch = This->surface_desc.u1.lPitch;
    }
    else
    {
	int pitch;

	if (This->surface_desc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) {
	    FIXME("Trying to fake compressed format surface by pretending bpp=16\n");
	    This->surface_desc.u1.lPitch = 16;
	} else
	if (!(This->surface_desc.dwFlags & DDSD_PITCH)
	    || This->surface_desc.u1.lPitch == 0)
	{
	    This->surface_desc.u1.lPitch
		= DDRAW_width_bpp_to_pitch(This->surface_desc.dwWidth,
					   This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount);
	}

	pitch = This->surface_desc.u1.lPitch;
	if (pitch % 8 != 0)
	    pitch += 8 - (pitch % 8);
	pitch = max(pitch, 8);
	This->surface_desc.u1.lPitch = pitch;
	This->t.gbl.u4.lPitch = pitch;

	if (!HAL_DIB(This)) {
	    LPVOID data = HeapAlloc(surface_heap, 0, This->surface_desc.u1.lPitch
				    * This->surface_desc.dwHeight);

	    /* it is no longer necessary for us to keep the surface pointer in lpSurface,
	     * so we'll set it to null as long as it's still relocatable (i.e. no DIB
	     * section is currently allocated yet for this surface) */
	    This->surface_desc.lpSurface = NULL;
	    This->t.gbl.fpVidMem = (FLATPTR)data;
	}

	if (This->t.gbl.fpVidMem == 0)
	{
	    Main_DirectDrawSurface_final_release(This);
	    return HRESULT_FROM_WIN32(GetLastError());
	}

	DirectDraw_Allocate_Memory(This->ddraw_owner, This->surface_desc.u1.lPitch * This->surface_desc.dwHeight);
	priv->dib.client_memory = FALSE;
    }

    return DD_OK;
}

/* Not an API */
HRESULT DIB_DirectDrawSurface_Create(IDirectDrawImpl *pDD,
				     const DDSURFACEDESC2 *pDDSD,
				     LPDIRECTDRAWSURFACE7 *ppSurf,
				     IUnknown *pUnkOuter)
{
    IDirectDrawSurfaceImpl* This;
    HRESULT hr;
    assert(pUnkOuter == NULL);

    This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
		     sizeof(*This) + sizeof(DIB_DirectDrawSurfaceImpl));
    if (This == NULL) return E_OUTOFMEMORY;

    This->private = (DIB_DirectDrawSurfaceImpl*)(This+1);

    hr = DIB_DirectDrawSurface_Construct(This, pDD, pDDSD);
    if (FAILED(hr))
	HeapFree(GetProcessHeap(), 0, This);
    else
	*ppSurf = ICOM_INTERFACE(This, IDirectDrawSurface7);

    return hr;

}

/* AddAttachedSurface: generic */
/* AddOverlayDirtyRect: generic, unimplemented */

static HRESULT _Blt_ColorFill(
    LPBYTE buf, int width, int height, int bpp, LONG lPitch, DWORD color
) {
    int x, y;
    LPBYTE first;

    /* Do first row */

#define COLORFILL_ROW(type) { \
    type *d = (type *) buf; \
    for (x = 0; x < width; x++) \
	d[x] = (type) color; \
    break; \
}

    switch(bpp) {
    case 1: COLORFILL_ROW(BYTE)
    case 2: COLORFILL_ROW(WORD)
    case 4: COLORFILL_ROW(DWORD)
    default:
	FIXME("Color fill not implemented for bpp %d!\n", bpp*8);
	return DDERR_UNSUPPORTED;
    }

#undef COLORFILL_ROW

    /* Now copy first row */
    first = buf;
    for (y = 1; y < height; y++) {
	buf += lPitch;
	memcpy(buf, first, width * bpp);
    }
    return DD_OK;
}





/*
 * These functions and macros are a part of DIB_DirectDrawSurface_Blt
 */

#define COPYBOX_COLORKEY(type) { \
  type *d = (type *)dbuf, *s = (type *)sbuf, tmp; \
  for (y = 0; y < h; y++) { \
    for (x = 0; x < w; x++) { \
      tmp = s[x]; \
      if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
    } \
    (LPBYTE)s += spitch; \
    (LPBYTE)d += dpitch; \
  } \
}

#define STRETCH_ROW(type) { \
		    type *s = (type *) sbuf, *d = (type *) dbuf; \
		    for (x = sx = 0; x < w; x++, sx += xinc) \
		      d[x] = s[sx >> 16]; \
}

#define STRETCH_ROW_24 { \
        LPBYTE s, d = dbuf; \
        for (x = sx = 0; x < w; x++, sx+= xinc) { \
          DWORD pixel;\
          s = sbuf+3*(sx>>16); \
          pixel = (s[0]<<16)|(s[1]<<8)|s[2]; \
          d[0] = (pixel>>16)&0xff; \
          d[1] = (pixel>> 8)&0xff; \
          d[2] = (pixel    )&0xff; \
          d+=3; \
        } \
}


#define COPYROW_COLORKEY(type) { \
		type *s = (type *) sbuf, *d = (type *) dbuf, tmp; \
		for (x = sx = 0; x < w; x++, sx += xinc) { \
		    tmp=s[sx >> 16]; \
		    if (tmp < keylow || tmp > keyhigh ) d[x] = tmp; \
		} \
}

BOOL __is_invalid(RECT *r)
{
  if (r->top>=r->bottom) return TRUE;
  if (r->left>=r->right) return TRUE;
  return FALSE;
}

RECT __intersect(RECT *a, RECT *b)
{
  RECT r;
  r.top    = max(a->top, b->top);
  r.left   = max(a->left, b->left);
  r.right  = min(a->right, b->right);
  r.bottom = min(a->bottom, b->bottom);
  return r;
}

void __scale_rect(RECT *a,DWORD xm,DWORD xd,DWORD ym,DWORD yd)
{
  int w=(a->right-a->left)*xm/xd;
  int h=(a->bottom-a->top)*ym/yd;
  a->right=a->left+w;
  a->bottom=a->top+h;
}

HRESULT WINAPI
DIB_DirectDrawSurface_Blt(LPDIRECTDRAWSURFACE7 iface, LPRECT rdst,
			  LPDIRECTDRAWSURFACE7 src, LPRECT rsrc,
			  DWORD dwFlags, LPDDBLTFX lpbltfx)
{

    ICOM_THIS(IDirectDrawSurfaceImpl,iface);
    DDSURFACEDESC2	ddesc,sdesc;
    HRESULT		ret = DD_OK;
    int bpp, srcheight, srcwidth, dstheight, dstwidth;
    int x, y;
    LPBYTE dbuf, sbuf;
    DWORD keylow=0, keyhigh=0, xinc=0, yinc=0, fillcolor=0;

    /* Clipper Data */
    LPDIRECTDRAWCLIPPER dClipper;
    LPRGNDATA lpDstClipList=NULL;
    LPRECT    lpDstRects=NULL;
    DWORD     drcount=0;
    DWORD     dwSize=0;
    RECT      DefaultDstClipRect;
    RECT      DefaultSrcClipRect;
    RECT      srect, drect;

    /* Reset mode flags */
    BYTE has_dclipper=0;
    BYTE has_scaling=0;
    BYTE has_scolorkey=0;
    BYTE has_dcolorkey=0;

    TRACE("(%p)->(%p,%p,%p,%08lx,%p)\n", This,rdst,src,rsrc,dwFlags,lpbltfx);

    CHECK_LOST(This);

    DD_STRUCT_INIT(&ddesc);
    DD_STRUCT_INIT(&sdesc);

     /* Make Some Checks */
    if (dwFlags & (DDBLT_WAIT|DDBLT_ASYNC)){
      static BOOL displayed = FALSE;
      if (!displayed) {
        FIXME("dwFlags DDBLT_WAIT and/or DDBLT_ASYNC: can't handle right now.\n");
        displayed = TRUE;
      }
      dwFlags &= ~(DDBLT_WAIT|DDBLT_ASYNC);
    }

    sdesc.dwSize = sizeof(sdesc);
    if (src) IDirectDrawSurface7_Lock(src, NULL, &sdesc, DDLOCK_READONLY, 0);
    ddesc.dwSize = sizeof(ddesc);
    IDirectDrawSurface7_Lock(iface,NULL,&ddesc,DDLOCK_WRITEONLY,0);

    /* Default Clipping Rectangles */
    DefaultDstClipRect.top = DefaultDstClipRect.left = 0;
    DefaultDstClipRect.right = ddesc.dwWidth;
    DefaultDstClipRect.bottom = ddesc.dwHeight;

    if (src) {
      DefaultSrcClipRect.right = sdesc.dwWidth;
      DefaultSrcClipRect.bottom = sdesc.dwHeight;
    } else {
      DefaultSrcClipRect.right = DefaultSrcClipRect.bottom = 0;
    }
    DefaultSrcClipRect.top = DefaultSrcClipRect.left = 0;

    /* Process Compressed Formats */
    if (sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC)
    {
       if (ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) {
           if (sdesc.u4.ddpfPixelFormat.dwFourCC == ddesc.u4.ddpfPixelFormat.dwFourCC &&
               sdesc.u1.dwLinearSize == ddesc.u1.dwLinearSize) {
               memcpy(ddesc.lpSurface, sdesc.lpSurface, ddesc.u1.dwLinearSize);
           } else {
               FIXME("trying to decompress %4.4s surface to %4.4s surface\n", (char*)&sdesc.u4.ddpfPixelFormat.dwFourCC,
                                                                              (char*)&ddesc.u4.ddpfPixelFormat.dwFourCC);
           }
       } else {
           FIXME("software-decompression of %4.4s surface not supported\n", (char*)&sdesc.u4.ddpfPixelFormat.dwFourCC);
           /* most compression algorithms are patented, which limits source distribution...
            * patented software decompressors will only be available in the WineX binaries */
           /* here, we'll just clear the destination surface */
           memset(ddesc.lpSurface, 0, ddesc.u1.lPitch * ddesc.dwHeight);
       }
       goto release;
    }


    /* Access Clippers and find clipping rectangles */
    if (IDirectDrawSurface7_GetClipper(iface, &dClipper)==DD_OK) { /* Clipper Found */
      /* Query clipper size */
      if (IDirectDrawClipper_GetClipList(dClipper, &DefaultDstClipRect, NULL, &dwSize)==DD_OK) {
        /* Allocate space for ClipList */
        lpDstClipList = (LPRGNDATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
        if (lpDstClipList && IDirectDrawClipper_GetClipList(dClipper, &DefaultDstClipRect, lpDstClipList, &dwSize)==DD_OK) {
          has_dclipper = 1;
          lpDstRects   = (LPRECT)lpDstClipList->Buffer; /* Pointer to rectangles */
          drcount      = lpDstClipList->rdh.nCount; /* How many rectangles we have */
          TRACE("Has ClipList %lu entries\n",drcount);
	  if (TRACE_ON(ddraw)) {
	    DWORD i;
	    for (i=0; i<drcount; i++) {
	      TRACE("%lu: (%d, %d, %d, %d)\n",i+1,lpDstRects[i].left,lpDstRects[i].top,
		lpDstRects[i].right,lpDstRects[i].bottom);
	    }
	  }

        }
      }
      IDirectDrawClipper_Release(dClipper);
    }

    /* Set Default clip-rectangle for destination if no cliplist defined */
    if (!has_dclipper) {
      drcount=1;
      lpDstRects=&DefaultDstClipRect;
    }

    /* Check that input rectangles are valid, Use defaults if NULL */
    if (rdst) {
      if (__is_invalid(rdst)) { ret=DDERR_INVALIDRECT; goto error; }
    } else { 
      rdst = &DefaultDstClipRect; 
    }

    if (rsrc) {
      if (__is_invalid(rsrc)) { ret=DDERR_INVALIDRECT; goto error; }
    } else {
      rsrc = &DefaultSrcClipRect;
    }

    /* Width & Height values for original src,dst-rectangles */
    bpp = GET_BPP(ddesc);
    srcheight = rsrc->bottom - rsrc->top;
    srcwidth = rsrc->right - rsrc->left;
    dstheight = rdst->bottom - rdst->top;
    dstwidth = rdst->right - rdst->left;

    /* Scaling configuration */
    if (src && (srcwidth!=dstwidth || srcheight!=dstheight)) {
       if (iface==src && (srcwidth>dstwidth || srcheight>dstheight)) {
          FIXME("Can not selfcopy while enlarging.\n");
          ret=DDERR_UNSUPPORTED; goto error;
       }
       if (iface==src && (rdst->left > 0 || rdst->top > 0)) {
          FIXME("Can not perform this operation.\n");
          ret=DDERR_UNSUPPORTED; goto error;
       }
       xinc = (srcwidth << 16) / dstwidth;
       yinc = (srcheight << 16) / dstheight;
       has_scaling=1;
    }

    /* Configure Special Operations */
    if (dwFlags & DDBLT_ZBUFFER) { FIXME("Z-Buffer not supported\n"); ret=DDERR_UNSUPPORTED; goto error; }
    if (dwFlags & DDBLT_COLORFILL) fillcolor=lpbltfx->u5.dwFillColor;
    if (dwFlags & DDBLT_ROP) { /* Blt Raster Ops */
      switch(lpbltfx->dwROP) {
        case BLACKNESS: fillcolor=0;  dwFlags|=DDBLT_COLORFILL; break;
        case WHITENESS: fillcolor=~0; dwFlags|=DDBLT_COLORFILL; break;
        case SRCCOPY:   break;
        case 0xAA0029: /* No-op */ break;
        default:
          FIXME("Unsupported raster op: %08lx  Pattern: %p\n", lpbltfx->dwROP, lpbltfx->u5.lpDDSPattern);
          goto error;
      }
      dwFlags &= ~DDBLT_ROP;
    }
    if (dwFlags & DDBLT_DDFX) {  /* Blt FX */
       ret = DDERR_UNSUPPORTED;
       DDRAW_dump_DDBLTFX(lpbltfx->dwDDFX);
       dwFlags &= ~DDBLT_DDFX;
       goto error;
    }

    /* ColorKey Configuration */
    if (dwFlags & (DDBLT_KEYSRC | DDBLT_KEYSRCOVERRIDE | DDBLT_KEYDESTOVERRIDE | DDBLT_KEYDEST)) {
      if (dwFlags & DDBLT_KEYSRCOVERRIDE) {
        keylow  = lpbltfx->ddckSrcColorkey.dwColorSpaceLowValue;
        keyhigh = lpbltfx->ddckSrcColorkey.dwColorSpaceHighValue;
        dwFlags &= ~DDBLT_KEYSRCOVERRIDE;
        has_scolorkey=1;
      }
      else if (dwFlags & DDBLT_KEYDESTOVERRIDE) {
        keylow  = lpbltfx->ddckDestColorkey.dwColorSpaceLowValue;
        keyhigh = lpbltfx->ddckDestColorkey.dwColorSpaceHighValue;
        dwFlags &= ~DDBLT_KEYDESTOVERRIDE;
        has_dcolorkey=1;
      }
      else if (dwFlags&DDBLT_KEYSRC) {
        if (sdesc.dwFlags&DDSD_CKSRCBLT) {
          keylow  = sdesc.ddckCKSrcBlt.dwColorSpaceLowValue;
          keyhigh = sdesc.ddckCKSrcBlt.dwColorSpaceHighValue;
          has_scolorkey=1;
        }
        dwFlags &= ~DDBLT_KEYSRC;
      }
      else if (dwFlags&DDBLT_KEYDEST) {
        if (ddesc.dwFlags&DDSD_CKDESTBLT) {
          keylow  = ddesc.ddckCKDestBlt.dwColorSpaceLowValue;
          keyhigh = ddesc.ddckCKDestBlt.dwColorSpaceHighValue;
          has_dcolorkey=1;
        }
        dwFlags &= ~DDBLT_KEYDEST;
      }
      if (has_scolorkey==0 && has_dcolorkey==0) goto release;
    }

    if (has_dcolorkey) {
      FIXME("Destination colorkeying not implemented... disabled\n");
      has_dcolorkey = has_scolorkey = 0;
    }

    /* Primary loop for clipping operations */
    /* Rectangles in clip list shouldn't overlap */

    TRACE("Start blitting %ld rectangles\n",drcount);

    while (drcount) {
      int w, h;
      DWORD width;

      drcount--;

      if (has_dclipper) { /* We have a clipper */
	RECT rect = lpDstRects[drcount];
	if (__is_invalid(&rect)) { continue; }     /*** ABORT this iteration ***/

	/* Compute operative rectangles srect and drect */
	if (!src) {
	  drect = __intersect(&rect, rdst); /* Sourceless Blits */
	} else {
	  int disx = rsrc->left - rdst->left;
	  int disy = rsrc->top - rdst->top;

	  drect = __intersect(&rect, rdst);               /* Destination clipping */
	  if (__is_invalid(&drect)) { continue; }  /*** ABORT this iteration ***/
	  srect = __intersect(&DefaultSrcClipRect, rsrc); /* Source clipping */
	      
	  OffsetRect(&drect, disx, disy);  /* Overlap and unscale for final combination */
	  if (has_scaling) {
	    __scale_rect(&drect, srcwidth, dstwidth, srcheight, dstheight);
	  }
	  drect = srect = __intersect(&srect, &drect); /* Combine source and distination */
	  if (has_scaling) {
	    __scale_rect(&drect, dstwidth, srcwidth, dstheight, srcheight); /* UnScale */
	  }
	  OffsetRect(&drect, -disx, -disy); /* UnTranslate */
	  if (__is_invalid(&srect)) { continue; }  /*** ABORT this iteration ***/
	}
      } else { /* No clipper */
	if (rdst->left < DefaultDstClipRect.left ||
	    rdst->top < DefaultDstClipRect.top ||
	    rdst->right > DefaultDstClipRect.right ||
	    rdst->bottom > DefaultDstClipRect.bottom) { continue; } /* ABORT this iteration */
	drect = *rdst;
	if (src) {
	  if (rsrc->left < DefaultSrcClipRect.left ||
	      rsrc->top < DefaultSrcClipRect.top ||
	      rsrc->right > DefaultSrcClipRect.right ||
	      rsrc->bottom > DefaultSrcClipRect.bottom) { continue; } /* ABORT this iteration */
	  srect = *rsrc;
	}
      } /* clipper */

      h = drect.bottom - drect.top;
      w = drect.right - drect.left;
      if (w<=0 || h<=0) { continue; }  /*** ABORT this iteration ***/
      width = w*bpp;

      if (!src) { /* Source-less operations */

	dbuf = (BYTE*)ddesc.lpSurface+(drect.top*ddesc.u1.lPitch)+(drect.left*bpp);

	if (dwFlags & DDBLT_COLORFILL) {
	  ret = _Blt_ColorFill(dbuf, w, h, bpp, ddesc.u1.lPitch, fillcolor);
	  if (ret != DD_OK) { goto error; }  /*** ERROR - ABORT ***/
	}
	/* This relies on the underlying hal driver to copy the z dib bits into the GL z-buffer */
	if (dwFlags & DDBLT_DEPTHFILL) {
	  ret = _Blt_ColorFill(dbuf, w, h, bpp, ddesc.u1.lPitch, lpbltfx->u5.dwFillDepth);
	  if (ret != DD_OK) { goto error; }  /*** ERROR - ABORT ***/
	}
	if (dwFlags & DDBLT_DDROPS) {
	  FIXME("\tDdraw Raster Ops: %08lx  Pattern: %p\n", lpbltfx->dwDDROP, lpbltfx->u5.lpDDSPattern);
	  ret = DDERR_UNSUPPORTED;
	  goto error;   /** UNSUPPORTED - ABORT ***/
	}

      } else { /* Operations With Source */

	LONG spitch = sdesc.u1.lPitch;
	LONG dpitch = ddesc.u1.lPitch;
	dbuf = (BYTE*)ddesc.lpSurface+(drect.top*ddesc.u1.lPitch)+(drect.left*bpp);
	sbuf = (BYTE*)sdesc.lpSurface+(srect.top*sdesc.u1.lPitch)+(srect.left*bpp);

	/* Copy Source to Destination */
	if (!has_scaling) {  /* copy without scaling */

	  if (!(has_scolorkey || has_dcolorkey)) { /* Copy without colorkey */

	    /* Detect self-copies and ensure that we copy rows in the
             * right order to avoid overwriting a row that is still needed.
	     * (memmove is used to ensure that the pixels in a row are
	     * copied in the right order.) */
	    if (src == iface && srect.top < drect.top) {
	      LPBYTE surf = (BYTE*)sdesc.lpSurface;
	      sbuf = surf + (srect.bottom-1)*spitch + srect.left*bpp;
	      dbuf = surf + (drect.top+h-1)*dpitch + drect.left*bpp;
	      spitch = -spitch;
	      dpitch = -dpitch;
	    }
	    for (y = 0; y < h; y++) {
	      memmove(dbuf, sbuf, width);
	      sbuf += spitch;
	      dbuf += dpitch;
	    }

	  } else {  /* Copy with colorkey */

	    switch (bpp) {
	    case 1: COPYBOX_COLORKEY(BYTE)  break;
	    case 2: COPYBOX_COLORKEY(WORD)  break;
	    case 4: COPYBOX_COLORKEY(DWORD) break;
	    default:
	      FIXME("Color key blitting not supported for bpp %d\n",bpp*8);
	      ret = DDERR_UNSUPPORTED; goto error;
	    }
	  } /* copy with colorkey */

	} else { /* Copy with scaling */

	  LPBYTE sbase;
	  int sx, sy;
	  sbase = (BYTE*)sdesc.lpSurface+(srect.top*sdesc.u1.lPitch)+srect.left*bpp;

	  if (!has_scolorkey) {  /* copy without source color key */

	    if (dstwidth == srcwidth) { /* Stretching in Y direction only */
	      for (y = sy = 0; y < h; y++, sy += yinc) {
		  sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;
		  memmove(dbuf, sbuf, width);
		  dbuf += ddesc.u1.lPitch;
	      }
	      
	    } else { /* Stretch all directions */

	      int last_sy = -1;
	      for (y = sy = 0; y < h; y++, sy += yinc) {
		sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;
		if ((sy >> 16) == (last_sy >> 16)) {
		  /* this sourcerow is the same as last sourcerow copy already stretched row */
		  memmove(dbuf, dbuf - ddesc.u1.lPitch, width);
		}
		else {
		  switch(bpp) {
		  case 1: STRETCH_ROW(BYTE) break;
		  case 2: STRETCH_ROW(WORD) break;
		  case 4: STRETCH_ROW(DWORD) break;
		  case 3: STRETCH_ROW_24 break;
		  default:
		    FIXME("Stretched blit not implemented for bpp %d!\n", bpp*8);
		    ret = DDERR_UNSUPPORTED; goto error;
		  }
		}
		dbuf += ddesc.u1.lPitch;
		last_sy = sy;
	      }
	    } /* stretch all directions */

	  } else { /* copy with source color key (has_scolorkey) */
	    
	    for (y = sy = 0; y < h; y++, sy += yinc) {
	      sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;

	      switch (bpp) {
		case 1: COPYROW_COLORKEY(BYTE) break;
		case 2: COPYROW_COLORKEY(WORD) break;
		case 4: COPYROW_COLORKEY(DWORD) break;
		default:
		  FIXME("Color-keyed blit not implemented for bpp %d!\n",bpp*8);
		  ret = DDERR_UNSUPPORTED;
		  goto error;
	      }
	      dbuf += ddesc.u1.lPitch;
	    }

	  } /* has_scolorkey */

	} /* has_scaling */

      } /* has_srccopy */
    } /* main loop ends */

error:
release:

    /* clear checked flags */
    if (dwFlags & DDBLT_COLORFILL) dwFlags &= ~DDBLT_COLORFILL;
    if (dwFlags & DDBLT_DEPTHFILL) dwFlags &= ~DDBLT_DEPTHFILL;
    if (dwFlags & DDBLT_DDROPS) dwFlags &= ~DDBLT_DDROPS;

    if (dwFlags && FIXME_ON(ddraw)) {
      FIXME("\tUnsupported flags: ");
      DDRAW_dump_DDBLT(dwFlags);
    }

    if (lpDstClipList) HeapFree(GetProcessHeap(), 0, lpDstClipList);

    IDirectDrawSurface7_Unlock(iface,NULL);
    if (src) IDirectDrawSurface7_Unlock(src,NULL);
    return ret;
}

#undef COPYBOX_COLORKEY
#undef STRETCH_ROW
#undef COPYROW_COLORKEY
#undef STRETCH_ROW_24
   

/* BltBatch: generic, unimplemented */

HRESULT WINAPI
DIB_DirectDrawSurface_BltFast(LPDIRECTDRAWSURFACE7 iface, DWORD dstx,
			      DWORD dsty, LPDIRECTDRAWSURFACE7 src,
			      LPRECT rsrc, DWORD trans)
{
    ICOM_THIS(IDirectDrawSurfaceImpl,iface);
    int			bpp, w, h, x, y;
    DDSURFACEDESC2	ddesc,sdesc;
    HRESULT		ret = DD_OK;
    LPBYTE		sbuf, dbuf;
    RECT		rsrc2;


    if (TRACE_ON(ddraw)) {
	FIXME("(%p)->(%ld,%ld,%p,%p,%08lx)\n",
		This,dstx,dsty,src,rsrc,trans
	);
	FIXME("	trans:");
	if (FIXME_ON(ddraw))
	  DDRAW_dump_DDBLTFAST(trans);
	if (rsrc)
	  FIXME("\tsrcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
	else
	  FIXME(" srcrect: NULL\n");
    }

    /* We need to lock the surfaces, or we won't get refreshes when done. */
    sdesc.dwSize = sizeof(sdesc);
    IDirectDrawSurface7_Lock(src, NULL,&sdesc,DDLOCK_READONLY, 0);
    ddesc.dwSize = sizeof(ddesc);
    IDirectDrawSurface7_Lock(iface,NULL,&ddesc,DDLOCK_WRITEONLY,0);

    if (sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC)
    {
       if (ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) {
           if (sdesc.u4.ddpfPixelFormat.dwFourCC == ddesc.u4.ddpfPixelFormat.dwFourCC &&
               sdesc.u1.dwLinearSize == ddesc.u1.dwLinearSize) {
               TRACE("compressed-surface copy (%ld bytes)\n", ddesc.u1.dwLinearSize);
               memcpy(ddesc.lpSurface, sdesc.lpSurface, ddesc.u1.dwLinearSize);
           } else {
               FIXME("trying to decompress %4.4s surface to %4.4s surface\n", (char*)&sdesc.u4.ddpfPixelFormat.dwFourCC,
                                                                              (char*)&ddesc.u4.ddpfPixelFormat.dwFourCC);
           }
       } else {
           FIXME("software-decompression of %4.4s surface not supported\n", (char*)&sdesc.u4.ddpfPixelFormat.dwFourCC);
           /* most compression algorithms are patented, which limits source distribution...
            * patented software decompressors will only be available in the WineX binaries */
           /* here, we'll just clear the destination surface */
           memset(ddesc.lpSurface, 0, ddesc.u1.lPitch * ddesc.dwHeight);
       }
       goto release;
    }

   if (!rsrc) {
	   WARN("rsrc is NULL!\n");
	   rsrc = &rsrc2;
	   rsrc->left = rsrc->top = 0;
	   rsrc->right = sdesc.dwWidth;
	   rsrc->bottom = sdesc.dwHeight;
   }

   h=rsrc->bottom-rsrc->top;
   w=rsrc->right-rsrc->left;

   /* Check that rect is valid */
   if (h<0 || w<0) {  ret=DDERR_INVALIDRECT; goto error; }

   /* This will prevent blitting over left and top borders */
   if (dstx>ddesc.dwWidth || dsty>ddesc.dwHeight || rsrc->left<0 || rsrc->top<0) {
     ret=DDERR_INVALIDPARAMS; goto error;
   } 

    bpp = GET_BPP(This->surface_desc);
    sbuf = (BYTE *)sdesc.lpSurface+(rsrc->top*sdesc.u1.lPitch)+rsrc->left*bpp;
    dbuf = (BYTE *)ddesc.lpSurface+(dsty*ddesc.u1.lPitch)+dstx* bpp;


    if (h>ddesc.dwHeight-dsty) h=ddesc.dwHeight-dsty;
    if (h>sdesc.dwHeight-rsrc->top) h=sdesc.dwHeight-rsrc->top;

    if (w>ddesc.dwWidth-dstx) w=ddesc.dwWidth-dstx;
    if (w>sdesc.dwWidth-rsrc->left) w=sdesc.dwWidth-rsrc->left;
    if (w<=0 || h<=0) goto release;

    if (trans & (DDBLTFAST_SRCCOLORKEY | DDBLTFAST_DESTCOLORKEY)) {
	DWORD keylow, keyhigh;
	if (trans & DDBLTFAST_SRCCOLORKEY) {
	    keylow  = sdesc.ddckCKSrcBlt.dwColorSpaceLowValue;
	    keyhigh = sdesc.ddckCKSrcBlt.dwColorSpaceHighValue;
	} else {
	    /* I'm not sure if this is correct */
	    FIXME("DDBLTFAST_DESTCOLORKEY not fully supported yet.\n");
	    keylow  = ddesc.ddckCKDestBlt.dwColorSpaceLowValue;
	    keyhigh = ddesc.ddckCKDestBlt.dwColorSpaceHighValue;
	}

#define COPYBOX_COLORKEY(type) { \
    type *d = (type *)dbuf, *s = (type *)sbuf, tmp; \
    s = (type *) ((BYTE *) sdesc.lpSurface + (rsrc->top * sdesc.u1.lPitch) + rsrc->left * bpp); \
    d = (type *) ((BYTE *) ddesc.lpSurface + (dsty * ddesc.u1.lPitch) + dstx * bpp); \
    for (y = 0; y < h; y++) { \
	for (x = 0; x < w; x++) { \
	    tmp = s[x]; \
	    if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
	} \
	(LPBYTE)s += sdesc.u1.lPitch; \
	(LPBYTE)d += ddesc.u1.lPitch; \
    } \
    break; \
}

	switch (bpp) {
	case 1: COPYBOX_COLORKEY(BYTE)
	case 2: COPYBOX_COLORKEY(WORD)
	case 4: COPYBOX_COLORKEY(DWORD)
	default:
	    FIXME("Source color key blitting not supported for bpp %d\n",bpp*8);
	    ret = DDERR_UNSUPPORTED;
	    goto error;
	}
#undef COPYBOX_COLORKEY
    } else {
	int width = w * bpp;

	LONG spitch = sdesc.u1.lPitch;
	LONG dpitch = ddesc.u1.lPitch;

	/* Detect self-copies and ensure that we copy rows in the
	 * right order to avoid overwriting a that is still needed.
	 * (memmove is used to ensure that the pixels in a row are
	 * copied in the right order.) */
	if (src == iface && rsrc->top < dsty)
	{
	    LPBYTE surf = (BYTE*)sdesc.lpSurface;
	    sbuf = surf + (rsrc->bottom-1)*spitch + rsrc->left*bpp;
	    dbuf = surf + (dsty + h - 1)*dpitch + dstx*bpp;

	    spitch = -spitch;
	    dpitch = -dpitch;
	}

	for (y = 0; y < h; y++) {
	    memmove(dbuf, sbuf, width);
	    sbuf += spitch;
	    dbuf += dpitch;
	}
    }
error:
release:
    IDirectDrawSurface7_Unlock(iface, NULL);
    IDirectDrawSurface7_Unlock(src, NULL);
    return ret;
}

/* ChangeUniquenessValue: generic */
/* DeleteAttachedSurface: generic */
/* EnumAttachedSurfaces: generic */
/* EnumOverlayZOrders: generic, unimplemented */

BOOL DIB_DirectDrawSurface_flip_data(IDirectDrawSurfaceImpl* front,
				     IDirectDrawSurfaceImpl* back,
				     DWORD dwFlags)
{
    DIB_DirectDrawSurfaceImpl* front_priv = front->private;
    DIB_DirectDrawSurfaceImpl* back_priv = back->private;

    TRACE("(%p,%p)\n",front,back);

    {
	HBITMAP tmp;
	tmp = front_priv->dib.DIBsection;
	front_priv->dib.DIBsection = back_priv->dib.DIBsection;
	back_priv->dib.DIBsection = tmp;
    }

    {
	void* tmp;
	tmp = front->surface_desc.lpSurface;
	front->surface_desc.lpSurface = back->surface_desc.lpSurface;
	back->surface_desc.lpSurface = tmp;
    }

    /* client_memory should not be different, but just in case */
    {
	BOOL tmp;
	tmp = front_priv->dib.client_memory;
	front_priv->dib.client_memory = back_priv->dib.client_memory;
	back_priv->dib.client_memory = tmp;
    }

    {
	DWORD tmp;
	tmp = front->t.gbl.dwGlobalFlags;
	front->t.gbl.dwGlobalFlags &= ~DDRAWISURFGBL_ISCLIENTMEM;
	front->t.gbl.dwGlobalFlags |= back->t.gbl.dwGlobalFlags & DDRAWISURFGBL_ISCLIENTMEM;
	back->t.gbl.dwGlobalFlags &= ~DDRAWISURFGBL_ISCLIENTMEM;
	back->t.gbl.dwGlobalFlags |= tmp & DDRAWISURFGBL_ISCLIENTMEM;
    }

    return Main_DirectDrawSurface_flip_data(front, back, dwFlags);
}

/* Flip: generic */
/* FreePrivateData: generic */
/* GetAttachedSurface: generic */
/* GetBltStatus: generic */
/* GetCaps: generic (Returns the caps from This->surface_desc.) */
/* GetClipper: generic */
/* GetColorKey: generic */

HRESULT DIB_DirectDrawSurface_alloc_dc(IDirectDrawSurfaceImpl* This, HDC* phDC)
{
    DIB_PRIV_VAR(priv, This);
    HDC hDC;
    HRESULT hr = S_OK;
    IDirectDrawPaletteImpl* tmpPalette = NULL;

    TRACE("Grabbing a DC for surface: %p\n", This);

    /* First, ensure that we have a DIBsection to use... */
    if (!HAL_DIB(This))
    {
        TRACE("Creating DIBsection for surface: %p\n", This);
        hr = create_dib(This);
    }

    if (FAILED(hr))
    {
        TRACE("Failed to create DIBsection for surface: %p\n", This);
        return hr;
    }

    hDC = CreateCompatibleDC(0);
    priv->dib.holdbitmap = SelectObject(hDC, HAL_DIB(This));
    if (This->palette)
	    tmpPalette = This->palette;
    else if (This->ddraw_owner &&
		    This->ddraw_owner->primary_surface &&
		    This->ddraw_owner->primary_surface->palette)
	    tmpPalette = This->ddraw_owner->primary_surface->palette;
    if (tmpPalette)
    {
	    RGBQUAD col[256];
	    int i;
	    for (i = 0; i < 256; i++)
	    {
		    col[i].rgbRed   = tmpPalette->palents[i].peRed;
		    col[i].rgbGreen = tmpPalette->palents[i].peGreen;
		    col[i].rgbBlue  = tmpPalette->palents[i].peBlue;
		    col[i].rgbReserved = 0;
	    }
	    SetDIBColorTable(hDC, 0, 256, col);
	    SelectPalette(hDC, tmpPalette->hpal, FALSE);
    }

    *phDC = hDC;

    return S_OK;
}

HRESULT DIB_DirectDrawSurface_free_dc(IDirectDrawSurfaceImpl* This, HDC hDC)
{
    DIB_PRIV_VAR(priv, This);

    TRACE("Releasing DC for surface: %p\n", This);

    SelectObject(hDC, priv->dib.holdbitmap);
    DeleteDC(hDC);

    return S_OK;
}

HRESULT DIB_DirectDrawSurface_get_dc(IDirectDrawSurfaceImpl* This, HDC* phDC)
{
    return DIB_DirectDrawSurface_alloc_dc(This, phDC);
}

HRESULT DIB_DirectDrawSurface_release_dc(IDirectDrawSurfaceImpl* This, HDC hDC)
{
    return DIB_DirectDrawSurface_free_dc(This, hDC);
}

/* GetDDInterface: generic */
/* GetFlipStatus: generic */
/* GetLOD: generic */
/* GetOverlayPosition: generic */
/* GetPalette: generic */
/* GetPixelFormat: generic */
/* GetPriority: generic */
/* GetPrivateData: generic */
/* GetSurfaceDesc: generic */
/* GetUniquenessValue: generic */
/* Initialize: generic */
/* IsLost: generic */
/* Lock: generic with callback? */
/* PageLock: generic */
/* PageUnlock: generic */

HRESULT WINAPI
DIB_DirectDrawSurface_Restore(LPDIRECTDRAWSURFACE7 iface)
{
    TRACE("(%p)\n",iface);
    return DD_OK;	/* ??? */
}

/* SetClipper: generic */
/* SetColorKey: generic */
/* SetLOD: generic */
/* SetOverlayPosition: generic */

void DIB_DirectDrawSurface_set_palette(IDirectDrawSurfaceImpl* This,
				       IDirectDrawPaletteImpl* pal)
{
    if (!pal) return;
    if (This->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
	This->update_palette(This, pal,
			     0, pal->palNumEntries,
			     pal->palents);
}

void DIB_DirectDrawSurface_update_palette(IDirectDrawSurfaceImpl* This,
					  IDirectDrawPaletteImpl* pal,
					  DWORD dwStart, DWORD dwCount,
					  LPPALETTEENTRY palent)
{
    RGBQUAD col[256];
    int n;
    HDC dc;

    TRACE("updating primary palette\n");
    for (n=0; n<dwCount; n++) {
      col[n].rgbRed   = palent[n].peRed;
      col[n].rgbGreen = palent[n].peGreen;
      col[n].rgbBlue  = palent[n].peBlue;
      col[n].rgbReserved = 0;
    }
    This->get_dc(This, &dc);
    SetDIBColorTable(dc, dwStart, dwCount, col);
    This->release_dc(This, dc);

    /* Propagate change to backbuffers if there are any */
    /* Basically this is a modification of the Flip code to find the backbuffer */
    /* and duplicate the palette update there as well */
    if ((This->surface_desc.ddsCaps.dwCaps&(DDSCAPS_FLIP|DDSCAPS_FRONTBUFFER))
	== (DDSCAPS_FLIP|DDSCAPS_FRONTBUFFER))
    {
	static DDSCAPS2 back_caps = { DDSCAPS_BACKBUFFER };
	LPDIRECTDRAWSURFACE7 tgt;

	HRESULT hr = IDirectDrawSurface7_GetAttachedSurface(ICOM_INTERFACE(This,IDirectDrawSurface7),
							    &back_caps, &tgt);
	if (!FAILED(hr))
	{
	    IDirectDrawSurfaceImpl* target = ICOM_OBJECT(IDirectDrawSurfaceImpl,
							 IDirectDrawSurface7,tgt);
	    IDirectDrawSurface7_Release(tgt);
	    target->get_dc(target, &dc);
	    SetDIBColorTable(dc, dwStart, dwCount, col);
	    target->release_dc(target, dc);
	}
    }
}

HRESULT
DIB_DirectDrawSurface_lazy_alloc_dibsection (IDirectDrawSurfaceImpl* This)
{
    /* Ensure that we have a DIBSection allocated */
    if (!HAL_DIB(This))
    {
        TRACE("Creating DIBsection for surface: %p\n", This);
        return create_dib(This);
    }
    return DD_OK;
}

/* SetPalette: generic */
/* SetPriority: generic */
/* SetPrivateData: generic */

HRESULT WINAPI
DIB_DirectDrawSurface_SetSurfaceDesc(LPDIRECTDRAWSURFACE7 iface,
				     LPDDSURFACEDESC2 pDDSD, DWORD dwFlags)
{
    ICOM_THIS(IDirectDrawSurfaceImpl,iface);
    DIB_PRIV_VAR(priv, This);
    HRESULT hr = DD_OK;

    TRACE("(%p)->(%p,%08lx)\n",iface,pDDSD,dwFlags);
    if (pDDSD->dwFlags == DDSD_LPSURFACE) {
	HBITMAP oldbmp = priv->dib.DIBsection;
	LPVOID oldsurf = (LPVOID)This->t.gbl.fpVidMem;
	BOOL oldc = priv->dib.client_memory;

	if (!oldbmp) oldbmp = HAL_DIB(This);

	TRACE("new lpSurface=%p\n",pDDSD->lpSurface);
	This->surface_desc.lpSurface = pDDSD->lpSurface;
	This->t.gbl.fpVidMem = (FLATPTR)This->surface_desc.lpSurface;
	priv->dib.client_memory = TRUE;
	This->t.gbl.dwGlobalFlags |= DDRAWISURFGBL_ISCLIENTMEM;

	HAL_DIB(This) = 0;
	priv->dib.DIBsection = 0;

        if (oldbmp) {
	    DeleteObject(oldbmp);
	    oldsurf = NULL;
	}

	if (!oldc)
	    if (oldsurf)
		HeapFree(surface_heap, 0, oldsurf);

	return hr;
    }
    else {
	FIXME("flags=%08lx\n",pDDSD->dwFlags);
	hr = E_FAIL;
    }
    return hr;
}

/* Unlock: ???, need callback */
/* UpdateOverlay: generic */
/* UpdateOverlayDisplay: generic */
/* UpdateOverlayZOrder: generic */

static ICOM_VTABLE(IDirectDrawSurface7) DIB_IDirectDrawSurface7_VTable =
{
    Main_DirectDrawSurface_QueryInterface,
    Main_DirectDrawSurface_AddRef,
    Main_DirectDrawSurface_Release,
    Main_DirectDrawSurface_AddAttachedSurface,
    Main_DirectDrawSurface_AddOverlayDirtyRect,
    DIB_DirectDrawSurface_Blt,
    Main_DirectDrawSurface_BltBatch,
    DIB_DirectDrawSurface_BltFast,
    Main_DirectDrawSurface_DeleteAttachedSurface,
    Main_DirectDrawSurface_EnumAttachedSurfaces,
    Main_DirectDrawSurface_EnumOverlayZOrders,
    Main_DirectDrawSurface_Flip,
    Main_DirectDrawSurface_GetAttachedSurface,
    Main_DirectDrawSurface_GetBltStatus,
    Main_DirectDrawSurface_GetCaps,
    Main_DirectDrawSurface_GetClipper,
    Main_DirectDrawSurface_GetColorKey,
    Main_DirectDrawSurface_GetDC,
    Main_DirectDrawSurface_GetFlipStatus,
    Main_DirectDrawSurface_GetOverlayPosition,
    Main_DirectDrawSurface_GetPalette,
    Main_DirectDrawSurface_GetPixelFormat,
    Main_DirectDrawSurface_GetSurfaceDesc,
    Main_DirectDrawSurface_Initialize,
    Main_DirectDrawSurface_IsLost,
    Main_DirectDrawSurface_Lock,
    Main_DirectDrawSurface_ReleaseDC,
    DIB_DirectDrawSurface_Restore,
    Main_DirectDrawSurface_SetClipper,
    Main_DirectDrawSurface_SetColorKey,
    Main_DirectDrawSurface_SetOverlayPosition,
    Main_DirectDrawSurface_SetPalette,
    Main_DirectDrawSurface_Unlock,
    Main_DirectDrawSurface_UpdateOverlay,
    Main_DirectDrawSurface_UpdateOverlayDisplay,
    Main_DirectDrawSurface_UpdateOverlayZOrder,
    Main_DirectDrawSurface_GetDDInterface,
    Main_DirectDrawSurface_PageLock,
    Main_DirectDrawSurface_PageUnlock,
    DIB_DirectDrawSurface_SetSurfaceDesc,
    Main_DirectDrawSurface_SetPrivateData,
    Main_DirectDrawSurface_GetPrivateData,
    Main_DirectDrawSurface_FreePrivateData,
    Main_DirectDrawSurface_GetUniquenessValue,
    Main_DirectDrawSurface_ChangeUniquenessValue,
    Main_DirectDrawSurface_SetPriority,
    Main_DirectDrawSurface_GetPriority,
    Main_DirectDrawSurface_SetLOD,
    Main_DirectDrawSurface_GetLOD
};
