dib.c 49 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1
/*
Alexandre Julliard's avatar
Alexandre Julliard committed
2
 * GDI device-independent bitmaps
Alexandre Julliard's avatar
Alexandre Julliard committed
3
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
4
 * Copyright 1993,1994  Alexandre Julliard
5
 *
6 7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
19 20
 */

21 22 23 24 25 26 27 28 29 30
/*
  Important information:
  
  * Current Windows versions support two different DIB structures:

    - BITMAPCOREINFO / BITMAPCOREHEADER (legacy structures; used in OS/2)
    - BITMAPINFO / BITMAPINFOHEADER
  
    Most Windows API functions taking a BITMAPINFO* / BITMAPINFOHEADER* also
    accept the old "core" structures, and so must WINE.
31
    You can distinguish them by looking at the first member (bcSize/biSize).
32 33 34 35 36 37 38 39 40 41 42 43

    
  * The palettes are stored in different formats:

    - BITMAPCOREINFO: Array of RGBTRIPLE
    - BITMAPINFO:     Array of RGBQUAD

    
  * There are even more DIB headers, but they all extend BITMAPINFOHEADER:
    
    - BITMAPV4HEADER: Introduced in Windows 95 / NT 4.0
    - BITMAPV5HEADER: Introduced in Windows 98 / 2000
44 45 46 47
    
    If biCompression is BI_BITFIELDS, the color masks are at the same position
    in all the headers (they start at bmiColors of BITMAPINFOHEADER), because
    the new headers have structure members for the masks.
48 49 50 51 52 53 54 55 56 57 58 59 60 61


  * You should never access the color table using the bmiColors member,
    because the passed structure may have one of the extended headers
    mentioned above. Use this to calculate the location:
    
    BITMAPINFO* info;
    void* colorPtr = (LPBYTE) info + (WORD) info->bmiHeader.biSize;

    
  * More information:
    Search for "Bitmap Structures" in MSDN
*/

62
#include <stdarg.h>
63
#include <stdlib.h>
64
#include <string.h>
65
#include <assert.h>
66

67
#include "windef.h"
68
#include "winbase.h"
69
#include "gdi_private.h"
70
#include "wine/debug.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
71

72
WINE_DEFAULT_DEBUG_CHANNEL(bitmap);
73

Alexandre Julliard's avatar
Alexandre Julliard committed
74

Alexandre Julliard's avatar
Alexandre Julliard committed
75
/***********************************************************************
76
 *           bitmap_info_size
Alexandre Julliard's avatar
Alexandre Julliard committed
77
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
78
 * Return the size of the bitmap info structure including color table.
Alexandre Julliard's avatar
Alexandre Julliard committed
79
 */
80
int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
Alexandre Julliard's avatar
Alexandre Julliard committed
81
{
82
    unsigned int colors, size, masks = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
83 84 85

    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
86
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
Alexandre Julliard's avatar
Alexandre Julliard committed
87
        colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
88 89 90 91 92
        return sizeof(BITMAPCOREHEADER) + colors *
             ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
    }
    else  /* assume BITMAPINFOHEADER */
    {
93
        colors = get_dib_num_of_colors( info );
94
        if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
95 96
        size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
        return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
Alexandre Julliard's avatar
Alexandre Julliard committed
97
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
/*******************************************************************************************
 * Verify that the DIB parameters are valid.
 */
static BOOL is_valid_dib_format( const BITMAPINFOHEADER *info, BOOL allow_compression )
{
    if (info->biWidth <= 0) return FALSE;
    if (info->biHeight == 0) return FALSE;

    if (allow_compression && (info->biCompression == BI_RLE4 || info->biCompression == BI_RLE8))
    {
        if (info->biHeight < 0) return FALSE;
        if (!info->biSizeImage) return FALSE;
        return info->biBitCount == (info->biCompression == BI_RLE4 ? 4 : 8);
    }

    if (!info->biPlanes) return FALSE;

    switch (info->biBitCount)
    {
    case 1:
    case 4:
    case 8:
    case 24:
        return (info->biCompression == BI_RGB);
    case 16:
    case 32:
        return (info->biCompression == BI_BITFIELDS || info->biCompression == BI_RGB);
    default:
        return FALSE;
    }
}

132
/*******************************************************************************************
133
 *  Fill out a true BITMAPINFOHEADER from a variable sized BITMAPINFOHEADER / BITMAPCOREHEADER.
134
 */
135
static BOOL bitmapinfoheader_from_user_bitmapinfo( BITMAPINFOHEADER *dst, const BITMAPINFOHEADER *info )
136
{
137
    if (!info) return FALSE;
138

139
    if (info->biSize == sizeof(BITMAPCOREHEADER))
140
    {
141 142 143 144 145 146
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
        dst->biWidth         = core->bcWidth;
        dst->biHeight        = core->bcHeight;
        dst->biPlanes        = core->bcPlanes;
        dst->biBitCount      = core->bcBitCount;
        dst->biCompression   = BI_RGB;
147 148 149 150 151
        dst->biXPelsPerMeter = 0;
        dst->biYPelsPerMeter = 0;
        dst->biClrUsed       = 0;
        dst->biClrImportant  = 0;
    }
152 153 154 155 156 157 158 159 160
    else if (info->biSize >= sizeof(BITMAPINFOHEADER)) /* assume BITMAPINFOHEADER */
    {
        *dst = *info;
    }
    else
    {
        WARN( "(%u): unknown/wrong size for header\n", info->biSize );
        return FALSE;
    }
161

162 163 164 165 166
    dst->biSize = sizeof(*dst);
    if (dst->biCompression == BI_RGB || dst->biCompression == BI_BITFIELDS)
        dst->biSizeImage = get_dib_image_size( (BITMAPINFO *)dst );
    return TRUE;
}
167

168 169 170
/*******************************************************************************************
 *  Fill out a true BITMAPINFO from a variable sized BITMAPINFO / BITMAPCOREINFO.
 */
171 172
static BOOL bitmapinfo_from_user_bitmapinfo( BITMAPINFO *dst, const BITMAPINFO *info,
                                             UINT coloruse, BOOL allow_compression )
173 174 175
{
    void *src_colors;
    unsigned int colors;
176

177
    if (!bitmapinfoheader_from_user_bitmapinfo( &dst->bmiHeader, &info->bmiHeader )) return FALSE;
178
    if (!is_valid_dib_format( &dst->bmiHeader, allow_compression )) return FALSE;
179 180 181 182

    src_colors = (char *)info + info->bmiHeader.biSize;
    colors = get_dib_num_of_colors( dst );

183
    if (dst->bmiHeader.biCompression == BI_BITFIELDS)
184 185 186
    {
        /* bitfields are always at bmiColors even in larger structures */
        memcpy( dst->bmiColors, info->bmiColors, 3 * sizeof(DWORD) );
187
    }
188
    else if (colors)
189
    {
190 191 192 193 194
        if (coloruse == DIB_PAL_COLORS)
            memcpy( dst->bmiColors, src_colors, colors * sizeof(WORD) );
        else if (info->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
            memcpy( dst->bmiColors, src_colors, colors * sizeof(RGBQUAD) );
        else
195
        {
196 197 198
            unsigned int i;
            RGBTRIPLE *triple = (RGBTRIPLE *)src_colors;
            for (i = 0; i < colors; i++)
199
            {
200 201 202 203
                dst->bmiColors[i].rgbRed      = triple[i].rgbtRed;
                dst->bmiColors[i].rgbGreen    = triple[i].rgbtGreen;
                dst->bmiColors[i].rgbBlue     = triple[i].rgbtBlue;
                dst->bmiColors[i].rgbReserved = 0;
204 205
            }
        }
206
        dst->bmiHeader.biClrUsed = colors;
207 208 209 210
    }
    return TRUE;
}

211
static int fill_color_table_from_palette( BITMAPINFO *info, HDC hdc )
212 213
{
    PALETTEENTRY palEntry[256];
214
    HPALETTE palette = GetCurrentObject( hdc, OBJ_PAL );
215
    int i, colors = get_dib_num_of_colors( info );
216

217
    if (!palette) return 0;
218 219 220
    if (!colors) return 0;

    memset( palEntry, 0, sizeof(palEntry) );
221
    if (!GetPaletteEntries( palette, 0, colors, palEntry ))
222 223 224 225 226 227 228 229 230 231 232 233 234
        return 0;

    for (i = 0; i < colors; i++)
    {
        info->bmiColors[i].rgbRed      = palEntry[i].peRed;
        info->bmiColors[i].rgbGreen    = palEntry[i].peGreen;
        info->bmiColors[i].rgbBlue     = palEntry[i].peBlue;
        info->bmiColors[i].rgbReserved = 0;
    }

    return colors;
}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
static void *get_pixel_ptr( const BITMAPINFO *info, void *bits, int x, int y )
{
    const int width = info->bmiHeader.biWidth, height = info->bmiHeader.biHeight;
    const int bpp = info->bmiHeader.biBitCount;

    if (height > 0)
        return (char *)bits + (height - y - 1) * get_dib_stride( width, bpp ) + x * bpp / 8;
    else
        return (char *)bits + y * get_dib_stride( width, bpp ) + x * bpp / 8;
}

static BOOL build_rle_bitmap( const BITMAPINFO *info, struct gdi_image_bits *bits, HRGN *clip )
{
    int i = 0;
    int left, right;
    int x, y, width = info->bmiHeader.biWidth, height = info->bmiHeader.biHeight;
    HRGN run = NULL;
    BYTE skip, num, data;
    BYTE *out_bits, *in_bits = bits->ptr;

    *clip = NULL;

    assert( info->bmiHeader.biBitCount == 4 || info->bmiHeader.biBitCount == 8 );

    out_bits = HeapAlloc( GetProcessHeap(), 0, get_dib_image_size( info ) );
    *clip = CreateRectRgn( 0, 0, 0, 0 );
    run   = CreateRectRgn( 0, 0, 0, 0 );
    if (!out_bits || !*clip || !run) goto fail;

    x = left = right = 0;
    y = height - 1;

    while (i < info->bmiHeader.biSizeImage - 1)
    {
        num = in_bits[i];
        data = in_bits[i + 1];
        i += 2;

        if (num)
        {
            if (x + num > width) num = width - x;
            if (num)
            {
                BYTE s = data, *out_ptr = get_pixel_ptr( info, out_bits, x, y );
                if (info->bmiHeader.biBitCount == 8)
                    memset( out_ptr, s, num );
                else
                {
                    if(x & 1)
                    {
                        s = ((s >> 4) & 0x0f) | ((s << 4) & 0xf0);
                        *out_ptr = (*out_ptr & 0xf0) | (s & 0x0f);
                        out_ptr++;
                        x++;
                        num--;
                    }
                    /* this will write one too many if num is odd, but that doesn't matter */
                    if (num) memset( out_ptr, s, (num + 1) / 2 );
                }
            }
            x += num;
            right = x;
        }
        else
        {
            if (data < 3)
            {
                if(left != right)
                {
                    SetRectRgn( run, left, y, right, y + 1 );
                    CombineRgn( *clip, run, *clip, RGN_OR );
                }
                switch (data)
                {
                case 0: /* eol */
                    left = right = x = 0;
                    y--;
                    if(y < 0) goto done;
                    break;

                case 1: /* eod */
                    goto done;

                case 2: /* delta */
                    if (i >= info->bmiHeader.biSizeImage - 1) goto done;
                    x += in_bits[i];
                    if (x > width) x = width;
                    left = right = x;
                    y -= in_bits[i + 1];
                    if(y < 0) goto done;
                    i += 2;
                }
            }
            else /* data bytes of data */
            {
                num = data;
                skip = (num * info->bmiHeader.biBitCount + 7) / 8;
                if (skip > info->bmiHeader.biSizeImage - i) goto done;
                skip = (skip + 1) & ~1;
                if (x + num > width) num = width - x;
                if (num)
                {
                    BYTE *out_ptr = get_pixel_ptr( info, out_bits, x, y );
                    if (info->bmiHeader.biBitCount == 8)
                        memcpy( out_ptr, in_bits + i, num );
                    else
                    {
                        if(x & 1)
                        {
                            const BYTE *in_ptr = in_bits + i;
                            for ( ; num; num--, x++)
                            {
                                if (x & 1)
                                {
                                    *out_ptr = (*out_ptr & 0xf0) | ((*in_ptr >> 4) & 0x0f);
                                    out_ptr++;
                                }
                                else
                                    *out_ptr = (*in_ptr++ << 4) & 0xf0;
                            }
                        }
                        else
                            memcpy( out_ptr, in_bits + i, (num + 1) / 2);
                    }
                }
                x += num;
                right = x;
                i += skip;
            }
        }
    }

done:
    DeleteObject( run );
    if (bits->free) bits->free( bits );

    bits->ptr     = out_bits;
    bits->is_copy = TRUE;
    bits->free    = free_heap_bits;

    return TRUE;

fail:
    if (run) DeleteObject( run );
    if (*clip) DeleteObject( *clip );
    HeapFree( GetProcessHeap(), 0, out_bits );
    return FALSE;
}



386
/* nulldrv fallback implementation using SetDIBits/StretchBlt */
387 388
INT nulldrv_StretchDIBits( PHYSDEV dev, INT xDst, INT yDst, INT widthDst, INT heightDst,
                           INT xSrc, INT ySrc, INT widthSrc, INT heightSrc, const void *bits,
389
                           BITMAPINFO *info, UINT coloruse, DWORD rop )
Alexandre Julliard's avatar
Alexandre Julliard committed
390
{
391
    DC *dc = get_nulldrv_dc( dev );
392
    INT ret;
393
    LONG height;
394 395 396
    HBITMAP hBitmap;
    HDC hdcMem;

397 398
    /* make sure we have a real implementation for StretchBlt and PutImage */
    if (GET_DC_PHYSDEV( dc, pStretchBlt ) == dev || GET_DC_PHYSDEV( dc, pPutImage ) == dev)
399
        return 0;
400

401
    height = info->bmiHeader.biHeight;
402

403 404
    if (xSrc == 0 && ySrc == 0 && widthDst == widthSrc && heightDst == heightSrc &&
        info->bmiHeader.biCompression == BI_RGB)
405
    {
406 407 408
        /* Windows appears to have a fast case optimization
         * that uses the wrong origin for top-down DIBs */
        if (height < 0 && heightSrc < abs(height)) ySrc = abs(height) - heightSrc;
409

410
        if (xDst == 0 && yDst == 0 && info->bmiHeader.biCompression == BI_RGB && rop == SRCCOPY)
411
        {
412 413 414 415
            BITMAP bm;
            hBitmap = GetCurrentObject( dev->hdc, OBJ_BITMAP );
            if (GetObjectW( hBitmap, sizeof(bm), &bm ) &&
                bm.bmWidth == widthSrc && bm.bmHeight == heightSrc &&
416
                bm.bmBitsPixel == info->bmiHeader.biBitCount && bm.bmPlanes == 1)
417
            {
418
                /* fast path */
419
                return SetDIBits( dev->hdc, hBitmap, 0, abs( height ), bits, info, coloruse );
420
            }
421
        }
422
    }
423

424
    hdcMem = CreateCompatibleDC( dev->hdc );
425
    hBitmap = CreateCompatibleBitmap( dev->hdc, info->bmiHeader.biWidth, height );
426 427 428
    SelectObject( hdcMem, hBitmap );
    if (coloruse == DIB_PAL_COLORS)
        SelectPalette( hdcMem, GetCurrentObject( dev->hdc, OBJ_PAL ), FALSE );
429

430 431 432 433 434 435 436 437 438 439 440 441 442
    if (info->bmiHeader.biCompression == BI_RLE4 || info->bmiHeader.biCompression == BI_RLE8)
    {
        /* when RLE compression is used, there may be some gaps (ie the DIB doesn't
         * contain all the rectangle described in bmiHeader, but only part of it.
         * This mean that those undescribed pixels must be left untouched.
         * So, we first copy on a memory bitmap the current content of the
         * destination rectangle, blit the DIB bits on top of it - hence leaving
         * the gaps untouched -, and blitting the rectangle back.
         * This insure that gaps are untouched on the destination rectangle
         */
        StretchBlt( hdcMem, xSrc, abs(height) - heightSrc - ySrc, widthSrc, heightSrc,
                    dev->hdc, xDst, yDst, widthDst, heightDst, rop );
    }
443
    ret = SetDIBits( hdcMem, hBitmap, 0, abs( height ), bits, info, coloruse );
444 445 446 447 448 449
    if (ret) StretchBlt( dev->hdc, xDst, yDst, widthDst, heightDst,
                         hdcMem, xSrc, abs(height) - heightSrc - ySrc, widthSrc, heightSrc, rop );
    DeleteDC( hdcMem );
    DeleteObject( hBitmap );
    return ret;
}
450

451 452 453 454 455
/***********************************************************************
 *           StretchDIBits   (GDI32.@)
 */
INT WINAPI StretchDIBits(HDC hdc, INT xDst, INT yDst, INT widthDst, INT heightDst,
                         INT xSrc, INT ySrc, INT widthSrc, INT heightSrc, const void *bits,
456
                         const BITMAPINFO *bmi, UINT coloruse, DWORD rop )
457
{
458 459
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
460 461 462
    DC *dc;
    INT ret = 0;

463
    if (!bits) return 0;
464 465 466 467 468
    if (!bitmapinfo_from_user_bitmapinfo( info, bmi, coloruse, TRUE ))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }
469 470 471 472 473 474 475 476

    if ((dc = get_dc_ptr( hdc )))
    {
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pStretchDIBits );
        update_dc( dc );
        ret = physdev->funcs->pStretchDIBits( physdev, xDst, yDst, widthDst, heightDst,
                                              xSrc, ySrc, widthSrc, heightSrc, bits, info, coloruse, rop );
        release_dc_ptr( dc );
477
    }
478
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
479 480
}

481

Alexandre Julliard's avatar
Alexandre Julliard committed
482
/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
483 484 485
 * SetDIBits [GDI32.@]
 *
 * Sets pixels in a bitmap using colors from DIB.
Alexandre Julliard's avatar
Alexandre Julliard committed
486 487 488 489 490 491 492 493 494 495 496 497 498
 *
 * PARAMS
 *    hdc       [I] Handle to device context
 *    hbitmap   [I] Handle to bitmap
 *    startscan [I] Starting scan line
 *    lines     [I] Number of scan lines
 *    bits      [I] Array of bitmap bits
 *    info      [I] Address of structure with data
 *    coloruse  [I] Type of color indexes to use
 *
 * RETURNS
 *    Success: Number of scan lines copied
 *    Failure: 0
Alexandre Julliard's avatar
Alexandre Julliard committed
499
 */
500
INT WINAPI SetDIBits( HDC hdc, HBITMAP hbitmap, UINT startscan,
501 502
		      UINT lines, LPCVOID bits, const BITMAPINFO *info,
		      UINT coloruse )
Alexandre Julliard's avatar
Alexandre Julliard committed
503
{
504
    BITMAPOBJ *bitmap;
505 506
    char src_bmibuf[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *src_info = (BITMAPINFO *)src_bmibuf;
507 508
    char dst_bmibuf[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *dst_info = (BITMAPINFO *)dst_bmibuf;
509
    INT result = 0;
510 511 512 513 514
    DWORD err;
    struct gdi_image_bits src_bits;
    struct bitblt_coords src, dst;
    INT src_to_dst_offset;
    HRGN clip = 0;
515
    const struct gdi_dc_funcs *funcs;
516

517 518 519 520 521 522
    if (!bitmapinfo_from_user_bitmapinfo( src_info, info, coloruse, TRUE ))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

523 524 525 526
    src_bits.ptr = (void *)bits;
    src_bits.is_copy = FALSE;
    src_bits.free = NULL;
    src_bits.param = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
527

528
    if (coloruse == DIB_PAL_COLORS && !fill_color_table_from_palette( src_info, hdc )) return 0;
529

530
    if (!(bitmap = GDI_GetObjPtr( hbitmap, OBJ_BITMAP ))) return 0;
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

    if (src_info->bmiHeader.biCompression == BI_RLE4 || src_info->bmiHeader.biCompression == BI_RLE8)
    {
        if (lines == 0) goto done;
        else lines = src_info->bmiHeader.biHeight;
        startscan = 0;

        if (!build_rle_bitmap( src_info, &src_bits, &clip )) goto done;
    }

    dst.visrect.left   = 0;
    dst.visrect.top    = 0;
    dst.visrect.right  = bitmap->bitmap.bmWidth;
    dst.visrect.bottom = bitmap->bitmap.bmHeight;

    src.visrect.left   = 0;
    src.visrect.top    = 0;
    src.visrect.right  = src_info->bmiHeader.biWidth;
    src.visrect.bottom = abs( src_info->bmiHeader.biHeight );

    if (src_info->bmiHeader.biHeight > 0)
    {
        src_to_dst_offset = -startscan;
        lines = min( lines, src.visrect.bottom - startscan );
        if (lines < src.visrect.bottom) src.visrect.top = src.visrect.bottom - lines;
    }
    else
    {
        src_to_dst_offset = src.visrect.bottom - lines - startscan;
        /* Unlike the bottom-up case, Windows doesn't limit lines. */
        if (lines < src.visrect.bottom) src.visrect.bottom = lines;
    }

564
    funcs = get_bitmap_funcs( bitmap );
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    result = lines;

    offset_rect( &src.visrect, 0, src_to_dst_offset );
    if (!intersect_rect( &dst.visrect, &src.visrect, &dst.visrect )) goto done;
    src.visrect = dst.visrect;
    offset_rect( &src.visrect, 0, -src_to_dst_offset );

    src.x      = src.visrect.left;
    src.y      = src.visrect.top;
    src.width  = src.visrect.right - src.visrect.left;
    src.height = src.visrect.bottom - src.visrect.top;

    dst.x      = dst.visrect.left;
    dst.y      = dst.visrect.top;
    dst.width  = dst.visrect.right - dst.visrect.left;
    dst.height = dst.visrect.bottom - dst.visrect.top;

    memcpy( dst_info, src_info, FIELD_OFFSET( BITMAPINFO, bmiColors[256] ));

585
    err = funcs->pPutImage( NULL, hbitmap, clip, dst_info, &src_bits, &src, &dst, 0 );
586 587 588 589 590 591 592 593
    if (err == ERROR_BAD_FORMAT)
    {
        void *ptr;

        dst_info->bmiHeader.biWidth = dst.width;
        ptr = HeapAlloc( GetProcessHeap(), 0, get_dib_image_size( dst_info ));
        if (ptr)
        {
594
            err = convert_bitmapinfo( src_info, src_bits.ptr, &src, dst_info, ptr );
595 596 597 598 599 600
            if (src_bits.free) src_bits.free( &src_bits );
            src_bits.ptr = ptr;
            src_bits.is_copy = TRUE;
            src_bits.free = free_heap_bits;
            if (!err)
                err = funcs->pPutImage( NULL, hbitmap, clip, dst_info, &src_bits, &src, &dst, 0 );
601 602 603 604
        }
        else err = ERROR_OUTOFMEMORY;
    }
    if(err) result = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
605

606
done:
607 608
    if (src_bits.free) src_bits.free( &src_bits );
    if (clip) DeleteObject( clip );
609
    GDI_ReleaseObj( hbitmap );
Alexandre Julliard's avatar
Alexandre Julliard committed
610
    return result;
Alexandre Julliard's avatar
Alexandre Julliard committed
611 612 613
}


614 615 616 617 618 619 620 621 622
INT nulldrv_SetDIBitsToDevice( PHYSDEV dev, INT x_dst, INT y_dst, DWORD cx, DWORD cy,
                               INT x_src, INT y_src, UINT startscan, UINT lines,
                               const void *bits, BITMAPINFO *src_info, UINT coloruse )
{
    DC *dc = get_nulldrv_dc( dev );
    char dst_buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *dst_info = (BITMAPINFO *)dst_buffer;
    struct bitblt_coords src, dst;
    struct gdi_image_bits src_bits;
623
    HRGN clip = 0;
624 625 626 627 628 629 630 631 632 633 634 635 636
    DWORD err;
    UINT height;
    BOOL top_down;
    POINT pt;
    RECT rect;

    top_down = (src_info->bmiHeader.biHeight < 0);
    height = abs( src_info->bmiHeader.biHeight );

    src_bits.ptr = (void *)bits;
    src_bits.is_copy = FALSE;
    src_bits.free = NULL;

637
    if (!lines) return 0;
638 639
    if (coloruse == DIB_PAL_COLORS && !fill_color_table_from_palette( src_info, dev->hdc )) return 0;

640 641 642 643 644 645 646 647 648 649 650 651 652 653
    if (src_info->bmiHeader.biCompression == BI_RLE4 || src_info->bmiHeader.biCompression == BI_RLE8)
    {
        startscan = 0;
        lines = height;
        src_info->bmiHeader.biWidth = x_src + cx;
        src_info->bmiHeader.biHeight = y_src + cy;
        if (src_info->bmiHeader.biWidth <= 0 || src_info->bmiHeader.biHeight <= 0) return 0;
        src.x = x_src;
        src.y = 0;
        src.width = cx;
        src.height = cy;
        if (!build_rle_bitmap( src_info, &src_bits, &clip )) return 0;
    }
    else
654
    {
655 656 657 658 659 660 661 662 663
        if (startscan >= height) return 0;
        if (!top_down && lines > height - startscan) lines = height - startscan;

        /* map src to top-down coordinates with startscan as origin */
        src.x = x_src;
        src.y = startscan + lines - (y_src + cy);
        src.width = cx;
        src.height = cy;
        if (src.y > 0)
664
        {
665 666 667 668 669 670 671 672
            if (!top_down)
            {
                /* get rid of unnecessary lines */
                if (src.y >= lines) return 0;
                lines -= src.y;
                src.y = 0;
            }
            else if (src.y >= lines) return lines;
673
        }
674
        src_info->bmiHeader.biHeight = top_down ? -lines : lines;
675 676 677 678 679 680 681 682 683 684
    }

    src.visrect.left = src.x;
    src.visrect.top = src.y;
    src.visrect.right = src.x + cx;
    src.visrect.bottom = src.y + cy;
    rect.left = 0;
    rect.top = 0;
    rect.right = src_info->bmiHeader.biWidth;
    rect.bottom = abs( src_info->bmiHeader.biHeight );
685 686 687 688 689
    if (!intersect_rect( &src.visrect, &src.visrect, &rect ))
    {
        lines = 0;
        goto done;
    }
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

    pt.x = x_dst;
    pt.y = y_dst;
    LPtoDP( dev->hdc, &pt, 1 );
    dst.x = pt.x;
    dst.y = pt.y;
    dst.width = cx;
    dst.height = cy;
    if (GetLayout( dev->hdc ) & LAYOUT_RTL) dst.x -= cx - 1;

    dst.visrect.left = dst.x;
    dst.visrect.top = dst.y;
    dst.visrect.right = dst.x + cx;
    dst.visrect.bottom = dst.y + cy;
    if (get_clip_box( dc, &rect )) intersect_rect( &dst.visrect, &dst.visrect, &rect );

    offset_rect( &src.visrect, dst.x - src.x, dst.y - src.y );
    intersect_rect( &rect, &src.visrect, &dst.visrect );
    src.visrect = dst.visrect = rect;
    offset_rect( &src.visrect, src.x - dst.x, src.y - dst.y );
710 711
    if (is_rect_empty( &dst.visrect )) goto done;
    if (clip) OffsetRgn( clip, dst.x - src.x, dst.y - src.y );
712 713 714

    dev = GET_DC_PHYSDEV( dc, pPutImage );
    memcpy( dst_info, src_info, FIELD_OFFSET( BITMAPINFO, bmiColors[256] ));
715
    err = dev->funcs->pPutImage( dev, 0, clip, dst_info, &src_bits, &src, &dst, SRCCOPY );
716 717 718 719 720 721 722 723 724 725 726 727 728
    if (err == ERROR_BAD_FORMAT)
    {
        void *ptr;

        dst_info->bmiHeader.biWidth = src.visrect.right - src.visrect.left;
        ptr = HeapAlloc( GetProcessHeap(), 0, get_dib_image_size( dst_info ));
        if (ptr)
        {
            err = convert_bitmapinfo( src_info, src_bits.ptr, &src, dst_info, ptr );
            if (src_bits.free) src_bits.free( &src_bits );
            src_bits.ptr = ptr;
            src_bits.is_copy = TRUE;
            src_bits.free = free_heap_bits;
729
            if (!err) err = dev->funcs->pPutImage( dev, 0, clip, dst_info, &src_bits, &src, &dst, SRCCOPY );
730 731 732 733
        }
        else err = ERROR_OUTOFMEMORY;
    }
    if (err) lines = 0;
734 735

done:
736
    if (src_bits.free) src_bits.free( &src_bits );
737
    if (clip) DeleteObject( clip );
738 739 740
    return lines;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
741
/***********************************************************************
742
 *           SetDIBitsToDevice   (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
743
 */
744 745
INT WINAPI SetDIBitsToDevice(HDC hdc, INT xDest, INT yDest, DWORD cx,
                           DWORD cy, INT xSrc, INT ySrc, UINT startscan,
746
                           UINT lines, LPCVOID bits, const BITMAPINFO *bmi,
747
                           UINT coloruse )
Alexandre Julliard's avatar
Alexandre Julliard committed
748
{
749 750
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
751
    INT ret = 0;
752
    DC *dc;
Alexandre Julliard's avatar
Alexandre Julliard committed
753

754
    if (!bits) return 0;
755 756 757 758 759
    if (!bitmapinfo_from_user_bitmapinfo( info, bmi, coloruse, TRUE ))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }
760

761
    if ((dc = get_dc_ptr( hdc )))
762
    {
763
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pSetDIBitsToDevice );
764
        update_dc( dc );
765 766 767
        ret = physdev->funcs->pSetDIBitsToDevice( physdev, xDest, yDest, cx, cy, xSrc,
                                                  ySrc, startscan, lines, bits, info, coloruse );
        release_dc_ptr( dc );
Alexandre Julliard's avatar
Alexandre Julliard committed
768
    }
769
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
770 771
}

Alexandre Julliard's avatar
Alexandre Julliard committed
772
/***********************************************************************
773
 *           SetDIBColorTable    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
774
 */
775
UINT WINAPI SetDIBColorTable( HDC hdc, UINT startpos, UINT entries, CONST RGBQUAD *colors )
Alexandre Julliard's avatar
Alexandre Julliard committed
776 777
{
    DC * dc;
778
    UINT result = 0;
779
    BITMAPOBJ * bitmap;
Alexandre Julliard's avatar
Alexandre Julliard committed
780

781
    if (!(dc = get_dc_ptr( hdc ))) return 0;
782

783
    if ((bitmap = GDI_GetObjPtr( dc->hBitmap, OBJ_BITMAP )))
784
    {
785 786
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pSetDIBColorTable );

787 788 789 790 791 792 793 794 795 796 797
        /* Check if currently selected bitmap is a DIB */
        if (bitmap->color_table)
        {
            if (startpos < bitmap->nb_colors)
            {
                if (startpos + entries > bitmap->nb_colors) entries = bitmap->nb_colors - startpos;
                memcpy(bitmap->color_table + startpos, colors, entries * sizeof(RGBQUAD));
                result = entries;
            }
        }
        GDI_ReleaseObj( dc->hBitmap );
798
        physdev->funcs->pSetDIBColorTable( physdev, startpos, entries, colors );
799
    }
800
    release_dc_ptr( dc );
801
    return result;
Alexandre Julliard's avatar
Alexandre Julliard committed
802 803
}

Alexandre Julliard's avatar
Alexandre Julliard committed
804

Alexandre Julliard's avatar
Alexandre Julliard committed
805
/***********************************************************************
806
 *           GetDIBColorTable    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
807
 */
808
UINT WINAPI GetDIBColorTable( HDC hdc, UINT startpos, UINT entries, RGBQUAD *colors )
Alexandre Julliard's avatar
Alexandre Julliard committed
809 810
{
    DC * dc;
811
    BITMAPOBJ *bitmap;
812
    UINT result = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
813

814
    if (!(dc = get_dc_ptr( hdc ))) return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
815

816
    if ((bitmap = GDI_GetObjPtr( dc->hBitmap, OBJ_BITMAP )))
817
    {
818 819
        /* Check if currently selected bitmap is a DIB */
        if (bitmap->color_table)
820
        {
821
            if (startpos < bitmap->nb_colors)
822
            {
823 824 825
                if (startpos + entries > bitmap->nb_colors) entries = bitmap->nb_colors - startpos;
                memcpy(colors, bitmap->color_table + startpos, entries * sizeof(RGBQUAD));
                result = entries;
826 827
            }
        }
828
        GDI_ReleaseObj( dc->hBitmap );
829
    }
830
    release_dc_ptr( dc );
831
    return result;
Alexandre Julliard's avatar
Alexandre Julliard committed
832
}
Alexandre Julliard's avatar
Alexandre Julliard committed
833

Andrew Ziem's avatar
Andrew Ziem committed
834
static const RGBQUAD DefLogPaletteQuads[20] = { /* Copy of Default Logical Palette */
835
/* rgbBlue, rgbGreen, rgbRed, rgbReserved */
836 837 838 839 840 841 842 843 844 845 846 847 848
    { 0x00, 0x00, 0x00, 0x00 },
    { 0x00, 0x00, 0x80, 0x00 },
    { 0x00, 0x80, 0x00, 0x00 },
    { 0x00, 0x80, 0x80, 0x00 },
    { 0x80, 0x00, 0x00, 0x00 },
    { 0x80, 0x00, 0x80, 0x00 },
    { 0x80, 0x80, 0x00, 0x00 },
    { 0xc0, 0xc0, 0xc0, 0x00 },
    { 0xc0, 0xdc, 0xc0, 0x00 },
    { 0xf0, 0xca, 0xa6, 0x00 },
    { 0xf0, 0xfb, 0xff, 0x00 },
    { 0xa4, 0xa0, 0xa0, 0x00 },
    { 0x80, 0x80, 0x80, 0x00 },
849
    { 0x00, 0x00, 0xff, 0x00 },
850 851 852 853 854 855 856 857
    { 0x00, 0xff, 0x00, 0x00 },
    { 0x00, 0xff, 0xff, 0x00 },
    { 0xff, 0x00, 0x00, 0x00 },
    { 0xff, 0x00, 0xff, 0x00 },
    { 0xff, 0xff, 0x00, 0x00 },
    { 0xff, 0xff, 0xff, 0x00 }
};

858 859 860 861
static const DWORD bit_fields_888[3] = {0xff0000, 0x00ff00, 0x0000ff};
static const DWORD bit_fields_565[3] = {0xf800, 0x07e0, 0x001f};
static const DWORD bit_fields_555[3] = {0x7c00, 0x03e0, 0x001f};

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
static int fill_query_info( BITMAPINFO *info, BITMAPOBJ *bmp )
{
    BITMAPINFOHEADER header;

    header.biSize   = info->bmiHeader.biSize; /* Ensure we don't overwrite the original size when we copy back */
    header.biWidth  = bmp->bitmap.bmWidth;
    header.biHeight = bmp->bitmap.bmHeight;
    header.biPlanes = 1;

    if (bmp->dib)
    {
        header.biBitCount = bmp->dib->dsBm.bmBitsPixel;
        switch (bmp->dib->dsBm.bmBitsPixel)
        {
        case 16:
        case 32:
            header.biCompression = BI_BITFIELDS;
            break;
        default:
            header.biCompression = BI_RGB;
            break;
        }
    }
    else
    {
        header.biCompression = (bmp->bitmap.bmBitsPixel > 8) ? BI_BITFIELDS : BI_RGB;
        header.biBitCount = bmp->bitmap.bmBitsPixel;
    }

891
    header.biSizeImage = get_dib_image_size( (BITMAPINFO *)&header );
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    header.biXPelsPerMeter = 0;
    header.biYPelsPerMeter = 0;
    header.biClrUsed       = 0;
    header.biClrImportant  = 0;

    if ( info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER) )
    {
        BITMAPCOREHEADER *coreheader = (BITMAPCOREHEADER *)info;

        coreheader->bcWidth    = header.biWidth;
        coreheader->bcHeight   = header.biHeight;
        coreheader->bcPlanes   = header.biPlanes;
        coreheader->bcBitCount = header.biBitCount;
    }
    else
        info->bmiHeader = header;

    return abs(bmp->bitmap.bmHeight);
}
911 912 913 914 915 916 917 918

/************************************************************************
 *      copy_color_info
 *
 * Copy BITMAPINFO color information where dst may be a BITMAPCOREINFO.
 */
static void copy_color_info(BITMAPINFO *dst, const BITMAPINFO *src, UINT coloruse)
{
919
    unsigned int colors = get_dib_num_of_colors( src );
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
    RGBQUAD *src_colors = (RGBQUAD *)((char *)src + src->bmiHeader.biSize);

    assert( src->bmiHeader.biSize >= sizeof(BITMAPINFOHEADER) );

    if (dst->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
        BITMAPCOREINFO *core = (BITMAPCOREINFO *)dst;
        if (coloruse == DIB_PAL_COLORS)
            memcpy( core->bmciColors, src_colors, colors * sizeof(WORD) );
        else
        {
            unsigned int i;
            for (i = 0; i < colors; i++)
            {
                core->bmciColors[i].rgbtRed   = src_colors[i].rgbRed;
                core->bmciColors[i].rgbtGreen = src_colors[i].rgbGreen;
                core->bmciColors[i].rgbtBlue  = src_colors[i].rgbBlue;
            }
        }
    }
    else
    {
        dst->bmiHeader.biClrUsed   = src->bmiHeader.biClrUsed;
        dst->bmiHeader.biSizeImage = src->bmiHeader.biSizeImage;

        if (src->bmiHeader.biCompression == BI_BITFIELDS)
            /* bitfields are always at bmiColors even in larger structures */
            memcpy( dst->bmiColors, src->bmiColors, 3 * sizeof(DWORD) );
        else if (colors)
        {
            void *colorptr = (char *)dst + dst->bmiHeader.biSize;
            unsigned int size;

            if (coloruse == DIB_PAL_COLORS)
                size = colors * sizeof(WORD);
            else
                size = colors * sizeof(RGBQUAD);
            memcpy( colorptr, src_colors, size );
        }
    }
}

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 988 989 990 991 992 993 994 995 996 997 998
static void fill_default_color_table( BITMAPINFO *info )
{
    int i;

    switch (info->bmiHeader.biBitCount)
    {
    case 1:
        info->bmiColors[0].rgbRed = info->bmiColors[0].rgbGreen = info->bmiColors[0].rgbBlue = 0;
        info->bmiColors[0].rgbReserved = 0;
        info->bmiColors[1].rgbRed = info->bmiColors[1].rgbGreen = info->bmiColors[1].rgbBlue = 0xff;
        info->bmiColors[1].rgbReserved = 0;
        break;

    case 4:
        /* The EGA palette is the first and last 8 colours of the default palette
           with the innermost pair swapped */
        memcpy(info->bmiColors,     DefLogPaletteQuads,      7 * sizeof(RGBQUAD));
        memcpy(info->bmiColors + 7, DefLogPaletteQuads + 12, 1 * sizeof(RGBQUAD));
        memcpy(info->bmiColors + 8, DefLogPaletteQuads +  7, 1 * sizeof(RGBQUAD));
        memcpy(info->bmiColors + 9, DefLogPaletteQuads + 13, 7 * sizeof(RGBQUAD));
        break;

    case 8:
        memcpy(info->bmiColors, DefLogPaletteQuads, 10 * sizeof(RGBQUAD));
        memcpy(info->bmiColors + 246, DefLogPaletteQuads + 10, 10 * sizeof(RGBQUAD));
        for (i = 10; i < 246; i++)
        {
            info->bmiColors[i].rgbRed      = (i & 0x07) << 5;
            info->bmiColors[i].rgbGreen    = (i & 0x38) << 2;
            info->bmiColors[i].rgbBlue     =  i & 0xc0;
            info->bmiColors[i].rgbReserved = 0;
        }
        break;

    default:
        ERR("called with bitcount %d\n", info->bmiHeader.biBitCount);
    }
999
    info->bmiHeader.biClrUsed = 1 << info->bmiHeader.biBitCount;
1000 1001
}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
void get_ddb_bitmapinfo( BITMAPOBJ *bmp, BITMAPINFO *info )
{
    info->bmiHeader.biSize          = sizeof(info->bmiHeader);
    info->bmiHeader.biWidth         = bmp->bitmap.bmWidth;
    info->bmiHeader.biHeight        = -bmp->bitmap.bmHeight;
    info->bmiHeader.biPlanes        = 1;
    info->bmiHeader.biBitCount      = bmp->bitmap.bmBitsPixel;
    info->bmiHeader.biCompression   = BI_RGB;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed       = 0;
    info->bmiHeader.biClrImportant  = 0;
    if (info->bmiHeader.biBitCount <= 8) fill_default_color_table( info );
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1018
/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
1019 1020 1021
 * GetDIBits [GDI32.@]
 *
 * Retrieves bits of bitmap and copies to buffer.
Alexandre Julliard's avatar
Alexandre Julliard committed
1022 1023 1024 1025
 *
 * RETURNS
 *    Success: Number of scan lines copied from bitmap
 *    Failure: 0
Alexandre Julliard's avatar
Alexandre Julliard committed
1026
 */
1027 1028 1029 1030 1031
INT WINAPI GetDIBits(
    HDC hdc,         /* [in]  Handle to device context */
    HBITMAP hbitmap, /* [in]  Handle to bitmap */
    UINT startscan,  /* [in]  First scan line to set in dest bitmap */
    UINT lines,      /* [in]  Number of scan lines to copy */
1032
    LPVOID bits,       /* [out] Address of array for bitmap bits */
Alexandre Julliard's avatar
Alexandre Julliard committed
1033
    BITMAPINFO * info, /* [out] Address of structure with bitmap data */
1034
    UINT coloruse)   /* [in]  RGB or palette index */
Alexandre Julliard's avatar
Alexandre Julliard committed
1035 1036
{
    DC * dc;
Alexandre Julliard's avatar
Alexandre Julliard committed
1037
    BITMAPOBJ * bmp;
1038 1039
    int i, dst_to_src_offset, ret = 0;
    DWORD err;
1040 1041
    char dst_bmibuf[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *dst_info = (BITMAPINFO *)dst_bmibuf;
1042 1043
    char src_bmibuf[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *src_info = (BITMAPINFO *)src_bmibuf;
1044
    const struct gdi_dc_funcs *funcs;
1045 1046 1047
    struct gdi_image_bits src_bits;
    struct bitblt_coords src, dst;
    BOOL empty_rect = FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1048

1049 1050
    /* Since info may be a BITMAPCOREINFO or any of the larger BITMAPINFO structures, we'll use our
       own copy and transfer the colour info back at the end */
1051
    if (!bitmapinfoheader_from_user_bitmapinfo( &dst_info->bmiHeader, &info->bmiHeader )) return 0;
1052 1053 1054
    if (bits &&
        (dst_info->bmiHeader.biCompression == BI_JPEG || dst_info->bmiHeader.biCompression == BI_PNG))
        return 0;
1055 1056 1057
    dst_info->bmiHeader.biClrUsed = 0;
    dst_info->bmiHeader.biClrImportant = 0;

1058
    if (!(dc = get_dc_ptr( hdc )))
1059
    {
1060
        SetLastError( ERROR_INVALID_PARAMETER );
1061 1062
        return 0;
    }
1063
    update_dc( dc );
1064
    if (!(bmp = GDI_GetObjPtr( hbitmap, OBJ_BITMAP )))
1065
    {
1066
        release_dc_ptr( dc );
Alexandre Julliard's avatar
Alexandre Julliard committed
1067
	return 0;
1068
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
1069

1070
    funcs = get_bitmap_funcs( bmp );
1071

1072 1073 1074 1075
    src.visrect.left   = 0;
    src.visrect.top    = 0;
    src.visrect.right  = bmp->bitmap.bmWidth;
    src.visrect.bottom = bmp->bitmap.bmHeight;
1076

1077 1078 1079 1080
    dst.visrect.left   = 0;
    dst.visrect.top    = 0;
    dst.visrect.right  = dst_info->bmiHeader.biWidth;
    dst.visrect.bottom = abs( dst_info->bmiHeader.biHeight );
1081

1082 1083
    if (lines == 0 || startscan >= dst.visrect.bottom)
        bits = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
1084

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    if (!bits && dst_info->bmiHeader.biBitCount == 0) /* query bitmap info only */
    {
        ret = fill_query_info( info, bmp );
        goto done;
    }

    /* validate parameters */

    if (dst_info->bmiHeader.biWidth <= 0) goto done;
    if (dst_info->bmiHeader.biHeight == 0) goto done;

    switch (dst_info->bmiHeader.biCompression)
    {
    case BI_RLE4:
        if (dst_info->bmiHeader.biBitCount != 4) goto done;
        if (dst_info->bmiHeader.biHeight < 0) goto done;
        if (bits) goto done;  /* can't retrieve compressed bits */
        break;
    case BI_RLE8:
        if (dst_info->bmiHeader.biBitCount != 8) goto done;
        if (dst_info->bmiHeader.biHeight < 0) goto done;
        if (bits) goto done;  /* can't retrieve compressed bits */
        break;
    case BI_BITFIELDS:
        if (dst_info->bmiHeader.biBitCount != 16 && dst_info->bmiHeader.biBitCount != 32) goto done;
        /* fall through */
    case BI_RGB:
        if (lines && !dst_info->bmiHeader.biPlanes) goto done;
        if (dst_info->bmiHeader.biBitCount == 1) break;
        if (dst_info->bmiHeader.biBitCount == 4) break;
        if (dst_info->bmiHeader.biBitCount == 8) break;
        if (dst_info->bmiHeader.biBitCount == 16) break;
        if (dst_info->bmiHeader.biBitCount == 24) break;
        if (dst_info->bmiHeader.biBitCount == 32) break;
        /* fall through */
    default:
        goto done;
    }

1124
    if (bits)
1125
    {
1126 1127 1128 1129 1130 1131
        if (dst_info->bmiHeader.biHeight > 0)
        {
            dst_to_src_offset = -startscan;
            lines = min( lines, dst.visrect.bottom - startscan );
            if (lines < dst.visrect.bottom) dst.visrect.top = dst.visrect.bottom - lines;
        }
1132
        else
1133 1134 1135 1136 1137 1138 1139 1140 1141
        {
            dst_to_src_offset = dst.visrect.bottom - lines - startscan;
            if (dst_to_src_offset < 0)
            {
                dst_to_src_offset = 0;
                lines = dst.visrect.bottom - startscan;
            }
            if (lines < dst.visrect.bottom) dst.visrect.bottom = lines;
        }
1142

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        offset_rect( &dst.visrect, 0, dst_to_src_offset );
        empty_rect = !intersect_rect( &src.visrect, &src.visrect, &dst.visrect );
        dst.visrect = src.visrect;
        offset_rect( &dst.visrect, 0, -dst_to_src_offset );

        if (dst_info->bmiHeader.biHeight > 0)
        {
            if (dst.visrect.bottom < dst_info->bmiHeader.biHeight)
            {
                int pad_lines = min( dst_info->bmiHeader.biHeight - dst.visrect.bottom, lines );
1153
                int pad_bytes = pad_lines * get_dib_stride( dst_info->bmiHeader.biWidth, dst_info->bmiHeader.biBitCount );
1154 1155 1156 1157 1158 1159 1160 1161
                memset( bits, 0, pad_bytes );
                bits = (char *)bits + pad_bytes;
            }
        }
        else
        {
            if (dst.visrect.bottom < lines)
            {
1162 1163
                int pad_lines = lines - dst.visrect.bottom;
                int stride = get_dib_stride( dst_info->bmiHeader.biWidth, dst_info->bmiHeader.biBitCount );
1164 1165 1166 1167
                int pad_bytes = pad_lines * stride;
                memset( (char *)bits + dst.visrect.bottom * stride, 0, pad_bytes );
            }
        }
1168

1169
        if (empty_rect) bits = NULL;
1170 1171 1172 1173

        src.x      = src.visrect.left;
        src.y      = src.visrect.top;
        src.width  = src.visrect.right - src.visrect.left;
1174
        src.height = src.visrect.bottom - src.visrect.top;
1175

1176 1177 1178 1179
        lines = src.height;
    }

    err = funcs->pGetImage( NULL, hbitmap, src_info, bits ? &src_bits : NULL, bits ? &src : NULL );
1180

1181
    if (err) goto done;
1182

1183 1184 1185
    /* fill out the src colour table, if it needs one */
    if (src_info->bmiHeader.biBitCount <= 8 && src_info->bmiHeader.biClrUsed == 0)
        fill_default_color_table( src_info );
1186

1187 1188 1189 1190
    /* if the src and dst are the same depth, copy the colour info across */
    if (dst_info->bmiHeader.biBitCount == src_info->bmiHeader.biBitCount && coloruse == DIB_RGB_COLORS )
    {
        switch (src_info->bmiHeader.biBitCount)
Alexandre Julliard's avatar
Alexandre Julliard committed
1191
        {
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
        case 16:
            if (src_info->bmiHeader.biCompression == BI_RGB)
            {
                src_info->bmiHeader.biCompression = BI_BITFIELDS;
                memcpy( src_info->bmiColors, bit_fields_555, sizeof(bit_fields_555) );
            }
            break;
        case 32:
            if (src_info->bmiHeader.biCompression == BI_RGB)
            {
                src_info->bmiHeader.biCompression = BI_BITFIELDS;
                memcpy( src_info->bmiColors, bit_fields_888, sizeof(bit_fields_888) );
            }
            break;
1206
        }
1207 1208 1209 1210 1211 1212 1213
        src_info->bmiHeader.biSizeImage = get_dib_image_size( dst_info );
        copy_color_info( dst_info, src_info, coloruse );
    }
    else if (dst_info->bmiHeader.biBitCount <= 8) /* otherwise construct a default colour table for the dst, if needed */
    {
        if( coloruse == DIB_PAL_COLORS )
        {
1214
            if (!fill_color_table_from_palette( dst_info, hdc )) goto done;
1215 1216 1217 1218 1219 1220
        }
        else
        {
            fill_default_color_table( dst_info );
        }
    }
1221

1222 1223
    if (bits)
    {
1224
        if(dst_info->bmiHeader.biHeight > 0)
1225
            dst_info->bmiHeader.biHeight = src.height;
1226
        else
1227
            dst_info->bmiHeader.biHeight = -src.height;
1228

1229
        convert_bitmapinfo( src_info, src_bits.ptr, &src, dst_info, bits );
1230
        if (src_bits.free) src_bits.free( &src_bits );
1231
        ret = lines;
Alexandre Julliard's avatar
Alexandre Julliard committed
1232
    }
1233 1234
    else
        ret = empty_rect ? FALSE : TRUE;
1235

1236 1237 1238
    if (coloruse == DIB_PAL_COLORS)
    {
        WORD *index = (WORD *)dst_info->bmiColors;
1239
        int colors = get_dib_num_of_colors( dst_info );
1240 1241 1242 1243
        for (i = 0; i < colors; i++, index++)
            *index = i;
    }

1244
    copy_color_info( info, dst_info, coloruse );
1245

1246
done:
1247
    release_dc_ptr( dc );
1248
    GDI_ReleaseObj( hbitmap );
1249
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1250 1251 1252
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1253
/***********************************************************************
1254
 *           CreateDIBitmap    (GDI32.@)
1255 1256 1257
 *
 * Creates a DDB (device dependent bitmap) from a DIB.
 * The DDB will have the same color depth as the reference DC.
Alexandre Julliard's avatar
Alexandre Julliard committed
1258
 */
1259
HBITMAP WINAPI CreateDIBitmap( HDC hdc, const BITMAPINFOHEADER *header,
Alexandre Julliard's avatar
Alexandre Julliard committed
1260
                            DWORD init, LPCVOID bits, const BITMAPINFO *data,
1261
                            UINT coloruse )
Alexandre Julliard's avatar
Alexandre Julliard committed
1262
{
1263
    BITMAPINFOHEADER info;
1264
    HBITMAP handle;
1265
    LONG height;
Alexandre Julliard's avatar
Alexandre Julliard committed
1266

1267
    if (!bitmapinfoheader_from_user_bitmapinfo( &info, header )) return 0;
1268
    if (info.biCompression == BI_JPEG || info.biCompression == BI_PNG) return 0;
1269
    if (info.biWidth < 0) return 0;
1270

1271
    /* Top-down DIBs have a negative height */
1272
    height = abs( info.biHeight );
Alexandre Julliard's avatar
Alexandre Julliard committed
1273

1274
    TRACE("hdc=%p, header=%p, init=%u, bits=%p, data=%p, coloruse=%u (bitmap: width=%d, height=%d, bpp=%u, compr=%u)\n",
1275 1276 1277
          hdc, header, init, bits, data, coloruse, info.biWidth, info.biHeight,
          info.biBitCount, info.biCompression);

1278
    if (hdc == NULL)
1279
        handle = CreateBitmap( info.biWidth, height, 1, 1, NULL );
Alexandre Julliard's avatar
Alexandre Julliard committed
1280
    else
1281
        handle = CreateCompatibleBitmap( hdc, info.biWidth, height );
1282

1283 1284
    if (handle)
    {
Huw Davies's avatar
Huw Davies committed
1285
        if (init & CBM_INIT)
1286 1287 1288 1289 1290 1291 1292
        {
            if (SetDIBits( hdc, handle, 0, height, bits, data, coloruse ) == 0)
            {
                DeleteObject( handle );
                handle = 0;
            }
        }
1293
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
1294 1295

    return handle;
Alexandre Julliard's avatar
Alexandre Julliard committed
1296
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1297

1298
/* Copy/synthesize RGB palette from BITMAPINFO */
1299 1300
static void DIB_CopyColorTable( DC *dc, BITMAPOBJ *bmp, WORD coloruse, const BITMAPINFO *info )
{
1301
    unsigned int colors, i;
1302

1303 1304 1305
    colors = get_dib_num_of_colors( info );
    if (!(bmp->color_table = HeapAlloc(GetProcessHeap(), 0, colors * sizeof(RGBQUAD) ))) return;
    bmp->nb_colors = colors;
1306

1307
    if (coloruse == DIB_RGB_COLORS)
1308
    {
1309
        memcpy( bmp->color_table, info->bmiColors, colors * sizeof(RGBQUAD));
1310 1311 1312
    }
    else
    {
1313
        PALETTEENTRY entries[256];
1314
        const WORD *index = (const WORD *)info->bmiColors;
1315
        UINT count = GetPaletteEntries( dc->hPalette, 0, colors, entries );
1316

1317
        for (i = 0; i < colors; i++, index++)
1318
        {
1319
            PALETTEENTRY *entry = &entries[*index % count];
1320 1321 1322 1323
            bmp->color_table[i].rgbRed = entry->peRed;
            bmp->color_table[i].rgbGreen = entry->peGreen;
            bmp->color_table[i].rgbBlue = entry->peBlue;
            bmp->color_table[i].rgbReserved = 0;
1324 1325 1326 1327
        }
    }
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1328
/***********************************************************************
1329
 *           CreateDIBSection    (GDI32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1330
 */
1331 1332
HBITMAP WINAPI CreateDIBSection(HDC hdc, CONST BITMAPINFO *bmi, UINT usage,
                                VOID **bits, HANDLE section, DWORD offset)
Alexandre Julliard's avatar
Alexandre Julliard committed
1333
{
1334 1335
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
1336
    HBITMAP ret = 0;
1337 1338
    DC *dc;
    BOOL bDesktopDC = FALSE;
1339 1340 1341 1342
    DIBSECTION *dib;
    BITMAPOBJ *bmp;
    void *mapBits = NULL;

1343
    if (bits) *bits = NULL;
1344 1345
    if (!bitmapinfo_from_user_bitmapinfo( info, bmi, usage, FALSE )) return 0;
    if (info->bmiHeader.biPlanes != 1)
1346
    {
1347 1348
        if (info->bmiHeader.biPlanes * info->bmiHeader.biBitCount > 16) return 0;
        WARN( "%u planes not properly supported\n", info->bmiHeader.biPlanes );
1349 1350
    }

1351 1352
    if (!(dib = HeapAlloc( GetProcessHeap(), 0, sizeof(*dib) ))) return 0;

1353
    TRACE("format (%d,%d), planes %d, bpp %d, %s, size %d %s\n",
1354 1355 1356 1357
          info->bmiHeader.biWidth, info->bmiHeader.biHeight,
          info->bmiHeader.biPlanes, info->bmiHeader.biBitCount,
          info->bmiHeader.biCompression == BI_BITFIELDS? "BI_BITFIELDS" : "BI_RGB",
          info->bmiHeader.biSizeImage, usage == DIB_PAL_COLORS? "PAL" : "RGB");
1358 1359

    dib->dsBm.bmType       = 0;
1360 1361 1362 1363 1364
    dib->dsBm.bmWidth      = info->bmiHeader.biWidth;
    dib->dsBm.bmHeight     = abs( info->bmiHeader.biHeight );
    dib->dsBm.bmWidthBytes = get_dib_stride( info->bmiHeader.biWidth, info->bmiHeader.biBitCount );
    dib->dsBm.bmPlanes     = info->bmiHeader.biPlanes;
    dib->dsBm.bmBitsPixel  = info->bmiHeader.biBitCount;
1365
    dib->dsBm.bmBits       = NULL;
1366
    dib->dsBmih            = info->bmiHeader;
1367

1368
    /* set number of entries in bmi.bmiColors table */
1369 1370
    if( info->bmiHeader.biBitCount <= 8 )
        dib->dsBmih.biClrUsed = 1 << info->bmiHeader.biBitCount;
1371 1372

    /* set dsBitfields values */
1373
    if (info->bmiHeader.biBitCount == 16 && info->bmiHeader.biCompression == BI_RGB)
1374
    {
1375
        dib->dsBmih.biCompression = BI_BITFIELDS;
1376 1377 1378
        dib->dsBitfields[0] = 0x7c00;
        dib->dsBitfields[1] = 0x03e0;
        dib->dsBitfields[2] = 0x001f;
1379
    }
1380
    else if (info->bmiHeader.biCompression == BI_BITFIELDS)
1381
    {
1382 1383 1384
        dib->dsBitfields[0] =  *(const DWORD *)bmi->bmiColors;
        dib->dsBitfields[1] =  *((const DWORD *)bmi->bmiColors + 1);
        dib->dsBitfields[2] =  *((const DWORD *)bmi->bmiColors + 2);
1385
        if (!dib->dsBitfields[0] || !dib->dsBitfields[1] || !dib->dsBitfields[2]) goto error;
1386
    }
1387
    else dib->dsBitfields[0] = dib->dsBitfields[1] = dib->dsBitfields[2] = 0;
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

    /* get storage location for DIB bits */

    if (section)
    {
        SYSTEM_INFO SystemInfo;
        DWORD mapOffset;
        INT mapSize;

        GetSystemInfo( &SystemInfo );
        mapOffset = offset - (offset % SystemInfo.dwAllocationGranularity);
        mapSize = dib->dsBmih.biSizeImage + (offset - mapOffset);
        mapBits = MapViewOfFile( section, FILE_MAP_ALL_ACCESS, 0, mapOffset, mapSize );
        if (mapBits) dib->dsBm.bmBits = (char *)mapBits + (offset - mapOffset);
    }
    else
    {
        offset = 0;
        dib->dsBm.bmBits = VirtualAlloc( NULL, dib->dsBmih.biSizeImage,
                                         MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
    }
    dib->dshSection = section;
    dib->dsOffset = offset;

    if (!dib->dsBm.bmBits)
    {
        HeapFree( GetProcessHeap(), 0, dib );
        return 0;
    }
1417 1418 1419 1420 1421 1422 1423 1424

    /* If the reference hdc is null, take the desktop dc */
    if (hdc == 0)
    {
        hdc = CreateCompatibleDC(0);
        bDesktopDC = TRUE;
    }

1425
    if (!(dc = get_dc_ptr( hdc ))) goto error;
1426 1427 1428

    /* create Device Dependent Bitmap and add DIB pointer */
    ret = CreateBitmap( dib->dsBm.bmWidth, dib->dsBm.bmHeight, 1,
1429
                        (info->bmiHeader.biBitCount == 1) ? 1 : GetDeviceCaps(hdc, BITSPIXEL), NULL );
1430

1431
    if (ret && ((bmp = GDI_GetObjPtr(ret, OBJ_BITMAP))))
1432
    {
1433
        PHYSDEV physdev = GET_DC_PHYSDEV( dc, pCreateDIBSection );
1434
        bmp->dib = dib;
1435
        bmp->funcs = physdev->funcs;
1436
        /* create local copy of DIB palette */
1437
        if (info->bmiHeader.biBitCount <= 8) DIB_CopyColorTable( dc, bmp, usage, info );
1438 1439
        GDI_ReleaseObj( ret );

1440
        if (!physdev->funcs->pCreateDIBSection( physdev, ret, info, usage ))
1441
        {
1442 1443
            DeleteObject( ret );
            ret = 0;
1444
        }
1445
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
1446

1447
    release_dc_ptr( dc );
1448 1449 1450
    if (bDesktopDC) DeleteDC( hdc );
    if (ret && bits) *bits = dib->dsBm.bmBits;
    return ret;
1451

1452 1453 1454 1455 1456 1457
error:
    if (bDesktopDC) DeleteDC( hdc );
    if (section) UnmapViewOfFile( mapBits );
    else if (!offset) VirtualFree( dib->dsBm.bmBits, 0, MEM_RELEASE );
    HeapFree( GetProcessHeap(), 0, dib );
    return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
1458
}