Fix strncpyWtoA to actually act as advertised (and not overflow the
[wine] / objects / dib.c
1 /*
2  * GDI device-independent bitmaps
3  *
4  * Copyright 1993,1994  Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <stdarg.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "bitmap.h"
28 #include "selectors.h"
29 #include "gdi.h"
30 #include "wownt32.h"
31 #include "wine/debug.h"
32 #include "palette.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(bitmap);
35
36 /***********************************************************************
37  *           DIB_GetDIBWidthBytes
38  *
39  * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
40  * http://www.microsoft.com/msdn/sdk/platforms/doc/sdk/win32/struc/src/str01.htm
41  */
42 int DIB_GetDIBWidthBytes( int width, int depth )
43 {
44     int words;
45
46     switch(depth)
47     {
48         case 1:  words = (width + 31) / 32; break;
49         case 4:  words = (width + 7) / 8; break;
50         case 8:  words = (width + 3) / 4; break;
51         case 15:
52         case 16: words = (width + 1) / 2; break;
53         case 24: words = (width * 3 + 3)/4; break;
54
55         default:
56             WARN("(%d): Unsupported depth\n", depth );
57         /* fall through */
58         case 32:
59                 words = width;
60     }
61     return 4 * words;
62 }
63
64 /***********************************************************************
65  *           DIB_GetDIBImageBytes
66  *
67  * Return the number of bytes used to hold the image in a DIB bitmap.
68  */
69 int DIB_GetDIBImageBytes( int width, int height, int depth )
70 {
71     return DIB_GetDIBWidthBytes( width, depth ) * abs( height );
72 }
73
74
75 /***********************************************************************
76  *           DIB_BitmapInfoSize
77  *
78  * Return the size of the bitmap info structure including color table.
79  */
80 int DIB_BitmapInfoSize( const BITMAPINFO * info, WORD coloruse )
81 {
82     int colors;
83
84     if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
85     {
86         BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)info;
87         colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
88         return sizeof(BITMAPCOREHEADER) + colors *
89              ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
90     }
91     else  /* assume BITMAPINFOHEADER */
92     {
93         colors = info->bmiHeader.biClrUsed;
94         if (!colors && (info->bmiHeader.biBitCount <= 8))
95             colors = 1 << info->bmiHeader.biBitCount;
96         return sizeof(BITMAPINFOHEADER) + colors *
97                ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
98     }
99 }
100
101
102 /***********************************************************************
103  *           DIB_GetBitmapInfo
104  *
105  * Get the info from a bitmap header.
106  * Return 1 for INFOHEADER, 0 for COREHEADER,
107  * 4 for V4HEADER, 5 for V5HEADER, -1 for error.
108  */
109 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, DWORD *width,
110                               int *height, WORD *bpp, WORD *compr )
111 {
112     if (header->biSize == sizeof(BITMAPINFOHEADER))
113     {
114         *width  = header->biWidth;
115         *height = header->biHeight;
116         *bpp    = header->biBitCount;
117         *compr  = header->biCompression;
118         return 1;
119     }
120     if (header->biSize == sizeof(BITMAPCOREHEADER))
121     {
122         BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)header;
123         *width  = core->bcWidth;
124         *height = core->bcHeight;
125         *bpp    = core->bcBitCount;
126         *compr  = 0;
127         return 0;
128     }
129     if (header->biSize == sizeof(BITMAPV4HEADER))
130     {
131         BITMAPV4HEADER *v4hdr = (BITMAPV4HEADER *)header;
132         *width  = v4hdr->bV4Width;
133         *height = v4hdr->bV4Height;
134         *bpp    = v4hdr->bV4BitCount;
135         *compr  = v4hdr->bV4V4Compression;
136         return 4;
137     }
138     if (header->biSize == sizeof(BITMAPV5HEADER))
139     {
140         BITMAPV5HEADER *v5hdr = (BITMAPV5HEADER *)header;
141         *width  = v5hdr->bV5Width;
142         *height = v5hdr->bV5Height;
143         *bpp    = v5hdr->bV5BitCount;
144         *compr  = v5hdr->bV5Compression;
145         return 5;
146     }
147     ERR("(%ld): unknown/wrong size for header\n", header->biSize );
148     return -1;
149 }
150
151
152 /***********************************************************************
153  *           StretchDIBits   (GDI32.@)
154  */
155 INT WINAPI StretchDIBits(HDC hdc, INT xDst, INT yDst, INT widthDst,
156                        INT heightDst, INT xSrc, INT ySrc, INT widthSrc,
157                        INT heightSrc, const void *bits,
158                        const BITMAPINFO *info, UINT wUsage, DWORD dwRop )
159 {
160     DC *dc;
161
162     if (!bits || !info)
163         return 0;
164
165     dc = DC_GetDCUpdate( hdc );
166     if(!dc) return FALSE;
167     
168     if(dc->funcs->pStretchDIBits)
169     {
170         heightSrc = dc->funcs->pStretchDIBits(dc->physDev, xDst, yDst, widthDst,
171                                               heightDst, xSrc, ySrc, widthSrc,
172                                               heightSrc, bits, info, wUsage, dwRop);
173         GDI_ReleaseObj( hdc );
174     }
175     else /* use StretchBlt */
176     {
177         HBITMAP hBitmap, hOldBitmap;
178         HDC hdcMem;
179
180         GDI_ReleaseObj( hdc );
181         hdcMem = CreateCompatibleDC( hdc );
182         if (info->bmiHeader.biCompression == BI_RLE4 ||
183             info->bmiHeader.biCompression == BI_RLE8) {
184
185            /* when RLE compression is used, there may be some gaps (ie the DIB doesn't
186             * contain all the rectangle described in bmiHeader, but only part of it.
187             * This mean that those undescribed pixels must be left untouched.
188             * So, we first copy on a memory bitmap the current content of the
189             * destination rectangle, blit the DIB bits on top of it - hence leaving
190             * the gaps untouched -, and blitting the rectangle back.
191             * This insure that gaps are untouched on the destination rectangle
192             * Not doing so leads to trashed images (the gaps contain what was on the
193             * memory bitmap => generally black or garbage)
194             * Unfortunately, RLE DIBs without gaps will be slowed down. But this is
195             * another speed vs correctness issue. Anyway, if speed is needed, then the
196             * pStretchDIBits function shall be implemented.
197             * ericP (2000/09/09)
198             */
199            hBitmap = CreateCompatibleBitmap(hdc, info->bmiHeader.biWidth,
200                                             info->bmiHeader.biHeight);
201            hOldBitmap = SelectObject( hdcMem, hBitmap );
202
203            /* copy existing bitmap from destination dc */
204            StretchBlt( hdcMem, xSrc, abs(info->bmiHeader.biHeight) - heightSrc - ySrc,
205                        widthSrc, heightSrc, hdc, xDst, yDst, widthDst, heightDst,
206                        dwRop );
207            SetDIBits(hdcMem, hBitmap, 0, info->bmiHeader.biHeight, bits,
208                      info, DIB_RGB_COLORS);
209
210         } else {
211            hBitmap = CreateDIBitmap( hdc, &info->bmiHeader, CBM_INIT,
212                                      bits, info, wUsage );
213            hOldBitmap = SelectObject( hdcMem, hBitmap );
214         }
215
216         /* Origin for DIBitmap may be bottom left (positive biHeight) or top
217            left (negative biHeight) */
218         StretchBlt( hdc, xDst, yDst, widthDst, heightDst,
219                     hdcMem, xSrc, abs(info->bmiHeader.biHeight) - heightSrc - ySrc,
220                     widthSrc, heightSrc, dwRop );
221         SelectObject( hdcMem, hOldBitmap );
222         DeleteDC( hdcMem );
223         DeleteObject( hBitmap );
224     }
225     return heightSrc;
226 }
227
228
229 /******************************************************************************
230  * SetDIBits [GDI32.@]  Sets pixels in a bitmap using colors from DIB
231  *
232  * PARAMS
233  *    hdc       [I] Handle to device context
234  *    hbitmap   [I] Handle to bitmap
235  *    startscan [I] Starting scan line
236  *    lines     [I] Number of scan lines
237  *    bits      [I] Array of bitmap bits
238  *    info      [I] Address of structure with data
239  *    coloruse  [I] Type of color indexes to use
240  *
241  * RETURNS
242  *    Success: Number of scan lines copied
243  *    Failure: 0
244  */
245 INT WINAPI SetDIBits( HDC hdc, HBITMAP hbitmap, UINT startscan,
246                       UINT lines, LPCVOID bits, const BITMAPINFO *info,
247                       UINT coloruse )
248 {
249     DC *dc;
250     BITMAPOBJ *bitmap;
251     INT result = 0;
252
253     if (!(bitmap = GDI_GetObjPtr( hbitmap, BITMAP_MAGIC ))) return 0;
254
255     if (!(dc = DC_GetDCUpdate( hdc )))
256     {
257         if (coloruse == DIB_RGB_COLORS) FIXME( "shouldn't require a DC for DIB_RGB_COLORS\n" );
258         GDI_ReleaseObj( hbitmap );
259         return 0;
260     }
261
262     if (!bitmap->funcs && !BITMAP_SetOwnerDC( hbitmap, dc )) goto done;
263
264     if (bitmap->funcs && bitmap->funcs->pSetDIBits)
265         result = bitmap->funcs->pSetDIBits( dc->physDev, hbitmap, startscan, lines,
266                                             bits, info, coloruse );
267     else
268         result = lines;
269
270  done:
271     GDI_ReleaseObj( hdc );
272     GDI_ReleaseObj( hbitmap );
273     return result;
274 }
275
276
277 /***********************************************************************
278  *           SetDIBitsToDevice   (GDI32.@)
279  */
280 INT WINAPI SetDIBitsToDevice(HDC hdc, INT xDest, INT yDest, DWORD cx,
281                            DWORD cy, INT xSrc, INT ySrc, UINT startscan,
282                            UINT lines, LPCVOID bits, const BITMAPINFO *info,
283                            UINT coloruse )
284 {
285     INT ret;
286     DC *dc;
287
288     if (!(dc = DC_GetDCUpdate( hdc ))) return 0;
289
290     if(dc->funcs->pSetDIBitsToDevice)
291         ret = dc->funcs->pSetDIBitsToDevice( dc->physDev, xDest, yDest, cx, cy, xSrc,
292                                              ySrc, startscan, lines, bits,
293                                              info, coloruse );
294     else {
295         FIXME("unimplemented on hdc %p\n", hdc);
296         ret = 0;
297     }
298
299     GDI_ReleaseObj( hdc );
300     return ret;
301 }
302
303 /***********************************************************************
304  *           SetDIBColorTable    (GDI32.@)
305  */
306 UINT WINAPI SetDIBColorTable( HDC hdc, UINT startpos, UINT entries, RGBQUAD *colors )
307 {
308     DC * dc;
309     UINT result = 0;
310
311     if (!(dc = DC_GetDCUpdate( hdc ))) return 0;
312
313     if (dc->funcs->pSetDIBColorTable)
314         result = dc->funcs->pSetDIBColorTable(dc->physDev, startpos, entries, colors);
315
316     GDI_ReleaseObj( hdc );
317     return result;
318 }
319
320
321 /***********************************************************************
322  *           GetDIBColorTable    (GDI32.@)
323  */
324 UINT WINAPI GetDIBColorTable( HDC hdc, UINT startpos, UINT entries, RGBQUAD *colors )
325 {
326     DC * dc;
327     UINT result = 0;
328
329     if (!(dc = DC_GetDCUpdate( hdc ))) return 0;
330
331     if (dc->funcs->pGetDIBColorTable)
332         result = dc->funcs->pGetDIBColorTable(dc->physDev, startpos, entries, colors);
333
334     GDI_ReleaseObj( hdc );
335     return result;
336 }
337
338 /* FIXME the following two structs should be combined with __sysPalTemplate in
339    objects/color.c - this should happen after de-X11-ing both of these
340    files.
341    NB. RGBQUAD and PALETTEENTRY have different orderings of red, green
342    and blue - sigh */
343
344 static RGBQUAD EGAColors[16] = {
345 /* rgbBlue, rgbGreen, rgbRed, rgbReserverd */
346     { 0x00, 0x00, 0x00, 0x00 },
347     { 0x00, 0x00, 0x80, 0x00 },
348     { 0x00, 0x80, 0x00, 0x00 },
349     { 0x00, 0x80, 0x80, 0x00 },
350     { 0x80, 0x00, 0x00, 0x00 },
351     { 0x80, 0x00, 0x80, 0x00 },
352     { 0x80, 0x80, 0x00, 0x00 },
353     { 0x80, 0x80, 0x80, 0x00 },
354     { 0xc0, 0xc0, 0xc0, 0x00 },
355     { 0x00, 0x00, 0xff, 0x00 },
356     { 0x00, 0xff, 0x00, 0x00 },
357     { 0x00, 0xff, 0xff, 0x00 },
358     { 0xff, 0x00, 0x00, 0x00 },
359     { 0xff, 0x00, 0xff, 0x00 },
360     { 0xff, 0xff, 0x00, 0x00 },
361     { 0xff, 0xff, 0xff, 0x00 }
362 };
363
364
365 static RGBQUAD DefLogPalette[20] = { /* Copy of Default Logical Palette */
366 /* rgbBlue, rgbGreen, rgbRed, rgbReserverd */
367     { 0x00, 0x00, 0x00, 0x00 },
368     { 0x00, 0x00, 0x80, 0x00 },
369     { 0x00, 0x80, 0x00, 0x00 },
370     { 0x00, 0x80, 0x80, 0x00 },
371     { 0x80, 0x00, 0x00, 0x00 },
372     { 0x80, 0x00, 0x80, 0x00 },
373     { 0x80, 0x80, 0x00, 0x00 },
374     { 0xc0, 0xc0, 0xc0, 0x00 },
375     { 0xc0, 0xdc, 0xc0, 0x00 },
376     { 0xf0, 0xca, 0xa6, 0x00 },
377     { 0xf0, 0xfb, 0xff, 0x00 },
378     { 0xa4, 0xa0, 0xa0, 0x00 },
379     { 0x80, 0x80, 0x80, 0x00 },
380     { 0x00, 0x00, 0xf0, 0x00 },
381     { 0x00, 0xff, 0x00, 0x00 },
382     { 0x00, 0xff, 0xff, 0x00 },
383     { 0xff, 0x00, 0x00, 0x00 },
384     { 0xff, 0x00, 0xff, 0x00 },
385     { 0xff, 0xff, 0x00, 0x00 },
386     { 0xff, 0xff, 0xff, 0x00 }
387 };
388
389
390 /******************************************************************************
391  * GetDIBits [GDI32.@]  Retrieves bits of bitmap and copies to buffer
392  *
393  * RETURNS
394  *    Success: Number of scan lines copied from bitmap
395  *    Failure: 0
396  *
397  * http://www.microsoft.com/msdn/sdk/platforms/doc/sdk/win32/func/src/f30_14.htm
398  */
399 INT WINAPI GetDIBits(
400     HDC hdc,         /* [in]  Handle to device context */
401     HBITMAP hbitmap, /* [in]  Handle to bitmap */
402     UINT startscan,  /* [in]  First scan line to set in dest bitmap */
403     UINT lines,      /* [in]  Number of scan lines to copy */
404     LPVOID bits,       /* [out] Address of array for bitmap bits */
405     BITMAPINFO * info, /* [out] Address of structure with bitmap data */
406     UINT coloruse)   /* [in]  RGB or palette index */
407 {
408     DC * dc;
409     BITMAPOBJ * bmp;
410     PALETTEENTRY * palEntry;
411     PALETTEOBJ * palette;
412     int i;
413
414     if (!info) return 0;
415     if (!(dc = DC_GetDCUpdate( hdc ))) return 0;
416     if (!(bmp = (BITMAPOBJ *)GDI_GetObjPtr( hbitmap, BITMAP_MAGIC )))
417     {
418         GDI_ReleaseObj( hdc );
419         return 0;
420     }
421     if (!(palette = (PALETTEOBJ*)GDI_GetObjPtr( dc->hPalette, PALETTE_MAGIC )))
422     {
423         GDI_ReleaseObj( hdc );
424         GDI_ReleaseObj( hbitmap );
425         return 0;
426     }
427
428     /* Transfer color info */
429
430     if (info->bmiHeader.biBitCount <= 8 && info->bmiHeader.biBitCount > 0 ) {
431
432         info->bmiHeader.biClrUsed = 0;
433
434         if(info->bmiHeader.biBitCount >= bmp->bitmap.bmBitsPixel) {
435             palEntry = palette->logpalette.palPalEntry;
436             for (i = 0; i < (1 << bmp->bitmap.bmBitsPixel); i++, palEntry++) {
437                 if (coloruse == DIB_RGB_COLORS) {
438                     info->bmiColors[i].rgbRed      = palEntry->peRed;
439                     info->bmiColors[i].rgbGreen    = palEntry->peGreen;
440                     info->bmiColors[i].rgbBlue     = palEntry->peBlue;
441                     info->bmiColors[i].rgbReserved = 0;
442                 }
443                 else ((WORD *)info->bmiColors)[i] = (WORD)i;
444             }
445         } else {
446             switch (info->bmiHeader.biBitCount) {
447             case 1:
448                 info->bmiColors[0].rgbRed = info->bmiColors[0].rgbGreen =
449                   info->bmiColors[0].rgbBlue = 0;
450                 info->bmiColors[0].rgbReserved = 0;
451                 info->bmiColors[1].rgbRed = info->bmiColors[1].rgbGreen =
452                   info->bmiColors[1].rgbBlue = 0xff;
453                 info->bmiColors[1].rgbReserved = 0;
454                 break;
455
456             case 4:
457                 memcpy(info->bmiColors, EGAColors, sizeof(EGAColors));
458                 break;
459
460             case 8:
461                 {
462                 INT r, g, b;
463                 RGBQUAD *color;
464
465                 memcpy(info->bmiColors, DefLogPalette,
466                        10 * sizeof(RGBQUAD));
467                 memcpy(info->bmiColors + 246, DefLogPalette + 10,
468                        10 * sizeof(RGBQUAD));
469                 color = info->bmiColors + 10;
470                 for(r = 0; r <= 5; r++) /* FIXME */
471                     for(g = 0; g <= 5; g++)
472                         for(b = 0; b <= 5; b++) {
473                             color->rgbRed =   (r * 0xff) / 5;
474                             color->rgbGreen = (g * 0xff) / 5;
475                             color->rgbBlue =  (b * 0xff) / 5;
476                             color->rgbReserved = 0;
477                             color++;
478                         }
479                 }
480             }
481         }
482     }
483
484     GDI_ReleaseObj( dc->hPalette );
485
486     if (bits && lines)
487     {
488         /* If the bitmap object already have a dib section that contains image data, get the bits from it */
489         if(bmp->dib && bmp->dib->dsBm.bmBitsPixel >= 15 && info->bmiHeader.biBitCount >= 15)
490         {
491             /*FIXME: Only RGB dibs supported for now */
492             unsigned int srcwidth = bmp->dib->dsBm.bmWidth, srcwidthb = bmp->dib->dsBm.bmWidthBytes;
493             int dstwidthb = DIB_GetDIBWidthBytes( info->bmiHeader.biWidth, info->bmiHeader.biBitCount );
494             LPBYTE dbits = bits, sbits = (LPBYTE) bmp->dib->dsBm.bmBits + (startscan * srcwidthb);
495             unsigned int x, y;
496
497             if ((info->bmiHeader.biHeight < 0) ^ (bmp->dib->dsBmih.biHeight < 0))
498             {
499                 dbits = (LPBYTE)bits + (dstwidthb * (lines-1));
500                 dstwidthb = -dstwidthb;
501             }
502
503             switch( info->bmiHeader.biBitCount ) {
504
505             case 15:
506             case 16: /* 16 bpp dstDIB */
507                 {
508                     LPWORD dstbits = (LPWORD)dbits;
509                     WORD rmask = 0x7c00, gmask= 0x03e0, bmask = 0x001f;
510
511                     /* FIXME: BI_BITFIELDS not supported yet */
512
513                     switch(bmp->dib->dsBm.bmBitsPixel) {
514
515                     case 16: /* 16 bpp srcDIB -> 16 bpp dstDIB */
516                         {
517                             /* FIXME: BI_BITFIELDS not supported yet */
518                             for (y = 0; y < lines; y++, dbits+=dstwidthb, sbits+=srcwidthb)
519                                 memcpy(dbits, sbits, srcwidthb);
520                         }
521                         break;
522
523                     case 24: /* 24 bpp srcDIB -> 16 bpp dstDIB */
524                         {
525                             LPBYTE srcbits = sbits;
526
527                             for( y = 0; y < lines; y++) {
528                                 for( x = 0; x < srcwidth; x++, srcbits += 3)
529                                     *dstbits++ = ((srcbits[0] >> 3) & bmask) |
530                                                  (((WORD)srcbits[1] << 2) & gmask) |
531                                                  (((WORD)srcbits[2] << 7) & rmask);
532
533                                 dstbits = (LPWORD)(dbits+=dstwidthb);
534                                 srcbits = (sbits += srcwidthb);
535                             }
536                         }
537                         break;
538
539                     case 32: /* 32 bpp srcDIB -> 16 bpp dstDIB */
540                         {
541                             LPDWORD srcbits = (LPDWORD)sbits;
542                             DWORD val;
543
544                             for( y = 0; y < lines; y++) {
545                                 for( x = 0; x < srcwidth; x++ ) {
546                                     val = *srcbits++;
547                                     *dstbits++ = (WORD)(((val >> 3) & bmask) | ((val >> 6) & gmask) |
548                                                        ((val >> 9) & rmask));
549                                 }
550                                 dstbits = (LPWORD)(dbits+=dstwidthb);
551                                 srcbits = (LPDWORD)(sbits+=srcwidthb);
552                             }
553                         }
554                         break;
555
556                     default: /* ? bit bmp -> 16 bit DIB */
557                         FIXME("15/16 bit DIB %d bit bitmap\n",
558                         bmp->bitmap.bmBitsPixel);
559                         break;
560                     }
561                 }
562                 break;
563
564             case 24: /* 24 bpp dstDIB */
565                 {
566                     LPBYTE dstbits = dbits;
567
568                     switch(bmp->dib->dsBm.bmBitsPixel) {
569
570                     case 16: /* 16 bpp srcDIB -> 24 bpp dstDIB */
571                         {
572                             LPWORD srcbits = (LPWORD)sbits;
573                             WORD val;
574
575                             /* FIXME: BI_BITFIELDS not supported yet */
576                             for( y = 0; y < lines; y++) {
577                                 for( x = 0; x < srcwidth; x++ ) {
578                                     val = *srcbits++;
579                                     *dstbits++ = (BYTE)(((val << 3) & 0xf8) | ((val >> 2) & 0x07));
580                                     *dstbits++ = (BYTE)(((val >> 2) & 0xf8) | ((val >> 7) & 0x07));
581                                     *dstbits++ = (BYTE)(((val >> 7) & 0xf8) | ((val >> 12) & 0x07));
582                                 }
583                                 dstbits = (LPBYTE)(dbits+=dstwidthb);
584                                 srcbits = (LPWORD)(sbits+=srcwidthb);
585                             }
586                         }
587                         break;
588
589                     case 24: /* 24 bpp srcDIB -> 24 bpp dstDIB */
590                         {
591                             for (y = 0; y < lines; y++, dbits+=dstwidthb, sbits+=srcwidthb)
592                                 memcpy(dbits, sbits, srcwidthb);
593                         }
594                         break;
595
596                     case 32: /* 32 bpp srcDIB -> 24 bpp dstDIB */
597                         {
598                             LPBYTE srcbits = (LPBYTE)sbits;
599
600                             for( y = 0; y < lines; y++) {
601                                 for( x = 0; x < srcwidth; x++, srcbits++ ) {
602                                     *dstbits++ = *srcbits++;
603                                     *dstbits++ = *srcbits++;
604                                     *dstbits++ = *srcbits++;
605                                 }
606                                 dstbits=(LPBYTE)(dbits+=dstwidthb);
607                                 srcbits = (LPBYTE)(sbits+=srcwidthb);
608                             }
609                         }
610                         break;
611
612                     default: /* ? bit bmp -> 24 bit DIB */
613                         FIXME("24 bit DIB %d bit bitmap\n",
614                               bmp->bitmap.bmBitsPixel);
615                         break;
616                     }
617                 }
618                 break;
619
620             case 32: /* 32 bpp dstDIB */
621                 {
622                     LPDWORD dstbits = (LPDWORD)dbits;
623
624                     /* FIXME: BI_BITFIELDS not supported yet */
625
626                     switch(bmp->dib->dsBm.bmBitsPixel) {
627                         case 16: /* 16 bpp srcDIB -> 32 bpp dstDIB */
628                         {
629                             LPWORD srcbits = (LPWORD)sbits;
630                             DWORD val;
631
632                             /* FIXME: BI_BITFIELDS not supported yet */
633                             for( y = 0; y < lines; y++) {
634                                 for( x = 0; x < srcwidth; x++ ) {
635                                     val = (DWORD)*srcbits++;
636                                     *dstbits++ = ((val << 3) & 0xf8) | ((val >> 2) & 0x07) |
637                                                  ((val << 6) & 0xf800) | ((val << 1) & 0x0700) |
638                                                  ((val << 9) & 0xf80000) | ((val << 4) & 0x070000);
639                                 }
640                                 dstbits=(LPDWORD)(dbits+=dstwidthb);
641                                 srcbits=(LPWORD)(sbits+=srcwidthb);
642                             }
643                         }
644                         break;
645
646                     case 24: /* 24 bpp srcDIB -> 32 bpp dstDIB */
647                         {
648                             LPBYTE srcbits = sbits;
649
650                             for( y = 0; y < lines; y++) {
651                                 for( x = 0; x < srcwidth; x++, srcbits+=3 )
652                                     *dstbits++ = ((DWORD)*srcbits) & 0x00ffffff;
653                                 dstbits=(LPDWORD)(dbits+=dstwidthb);
654                                 srcbits=(sbits+=srcwidthb);
655                             }
656                         }
657                         break;
658
659                     case 32: /* 32 bpp srcDIB -> 16 bpp dstDIB */
660                         {
661                             /* FIXME: BI_BITFIELDS not supported yet */
662                             for (y = 0; y < lines; y++, dbits+=dstwidthb, sbits+=srcwidthb)
663                                 memcpy(dbits, sbits, srcwidthb);
664                         }
665                         break;
666
667                     default: /* ? bit bmp -> 16 bit DIB */
668                         FIXME("15/16 bit DIB %d bit bitmap\n",
669                         bmp->bitmap.bmBitsPixel);
670                         break;
671                     }
672                 }
673                 break;
674
675             default: /* ? bit DIB */
676                 FIXME("Unsupported DIB depth %d\n", info->bmiHeader.biBitCount);
677                 break;
678             }
679         }
680         /* Otherwise, get bits from the XImage */
681         else
682         {
683             if (!bmp->funcs && !BITMAP_SetOwnerDC( hbitmap, dc )) lines = 0;
684             else
685             {
686                 if (bmp->funcs && bmp->funcs->pGetDIBits)
687                     lines = bmp->funcs->pGetDIBits( dc->physDev, hbitmap, startscan,
688                                                     lines, bits, info, coloruse );
689                 else
690                     lines = 0;  /* FIXME: should copy from bmp->bitmap.bmBits */
691             }
692         }
693     }
694     else if( info->bmiHeader.biSize >= sizeof(BITMAPINFOHEADER) )
695     {
696         /* fill in struct members */
697
698         if( info->bmiHeader.biBitCount == 0)
699         {
700             info->bmiHeader.biWidth = bmp->bitmap.bmWidth;
701             info->bmiHeader.biHeight = bmp->bitmap.bmHeight;
702             info->bmiHeader.biPlanes = 1;
703             info->bmiHeader.biBitCount = bmp->bitmap.bmBitsPixel;
704             info->bmiHeader.biSizeImage =
705                              DIB_GetDIBImageBytes( bmp->bitmap.bmWidth,
706                                                    bmp->bitmap.bmHeight,
707                                                    bmp->bitmap.bmBitsPixel );
708             info->bmiHeader.biCompression = 0;
709         }
710         else
711         {
712             info->bmiHeader.biSizeImage = DIB_GetDIBImageBytes(
713                                                info->bmiHeader.biWidth,
714                                                info->bmiHeader.biHeight,
715                                                info->bmiHeader.biBitCount );
716         }
717     }
718
719     TRACE("biSizeImage = %ld, biWidth = %ld, biHeight = %ld\n",
720           info->bmiHeader.biSizeImage, info->bmiHeader.biWidth,
721           info->bmiHeader.biHeight);
722
723     GDI_ReleaseObj( hdc );
724     GDI_ReleaseObj( hbitmap );
725
726     return lines;
727 }
728
729
730 /***********************************************************************
731  *           CreateDIBitmap    (GDI32.@)
732  */
733 HBITMAP WINAPI CreateDIBitmap( HDC hdc, const BITMAPINFOHEADER *header,
734                             DWORD init, LPCVOID bits, const BITMAPINFO *data,
735                             UINT coloruse )
736 {
737     HBITMAP handle;
738     BOOL fColor;
739     DWORD width;
740     int height;
741     WORD bpp;
742     WORD compr;
743     DC *dc;
744
745     if (DIB_GetBitmapInfo( header, &width, &height, &bpp, &compr ) == -1) return 0;
746     if (height < 0) height = -height;
747
748     /* Check if we should create a monochrome or color bitmap. */
749     /* We create a monochrome bitmap only if it has exactly 2  */
750     /* colors, which are black followed by white, nothing else.  */
751     /* In all other cases, we create a color bitmap.           */
752
753     if (bpp != 1) fColor = TRUE;
754     else if ((coloruse != DIB_RGB_COLORS) ||
755              (init != CBM_INIT) || !data) fColor = FALSE;
756     else
757     {
758         if (data->bmiHeader.biSize == sizeof(BITMAPINFOHEADER))
759         {
760             RGBQUAD *rgb = data->bmiColors;
761             DWORD col = RGB( rgb->rgbRed, rgb->rgbGreen, rgb->rgbBlue );
762
763             /* Check if the first color of the colormap is black */
764             if ((col == RGB(0,0,0)))
765             {
766                 rgb++;
767                 col = RGB( rgb->rgbRed, rgb->rgbGreen, rgb->rgbBlue );
768                 /* If the second color is white, create a monochrome bitmap */
769                 fColor =  (col != RGB(0xff,0xff,0xff));
770             }
771             /* Note : If the first color of the colormap is white
772                followed by black, we have to create a color bitmap.
773                If we don't the white will be displayed in black later on!*/
774             else fColor = TRUE;
775         }
776         else if (data->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
777         {
778             RGBTRIPLE *rgb = ((BITMAPCOREINFO *)data)->bmciColors;
779             DWORD col = RGB( rgb->rgbtRed, rgb->rgbtGreen, rgb->rgbtBlue );
780             if ((col == RGB(0,0,0)))
781             {
782                 rgb++;
783                 col = RGB( rgb->rgbtRed, rgb->rgbtGreen, rgb->rgbtBlue );
784                 fColor = (col != RGB(0xff,0xff,0xff));
785             }
786             else fColor = TRUE;
787         }
788         else if (data->bmiHeader.biSize == sizeof(BITMAPV4HEADER))
789         { /* FIXME: correct ? */
790             RGBQUAD *rgb = data->bmiColors;
791             DWORD col = RGB( rgb->rgbRed, rgb->rgbGreen, rgb->rgbBlue );
792
793             /* Check if the first color of the colormap is black */
794             if ((col == RGB(0,0,0)))
795             {
796                 rgb++;
797                 col = RGB( rgb->rgbRed, rgb->rgbGreen, rgb->rgbBlue );
798                 /* If the second color is white, create a monochrome bitmap */
799                 fColor =  (col != RGB(0xff,0xff,0xff));
800             }
801             /* Note : If the first color of the colormap is white
802                followed by black, we have to create a color bitmap.
803                If we don't the white will be displayed in black later on!*/
804             else fColor = TRUE;
805         }
806         else
807         {
808             ERR("(%ld): wrong/unknown size for data\n",
809                      data->bmiHeader.biSize );
810             return 0;
811         }
812     }
813
814     /* Now create the bitmap */
815
816     if (!(dc = DC_GetDCPtr( hdc ))) return 0;
817
818     if (fColor)
819         handle = CreateBitmap( width, height, GetDeviceCaps( hdc, PLANES ),
820                                GetDeviceCaps( hdc, BITSPIXEL ), NULL );
821     else handle = CreateBitmap( width, height, 1, 1, NULL );
822
823     if (handle)
824     {
825         if (init == CBM_INIT) SetDIBits( hdc, handle, 0, height, bits, data, coloruse );
826         else if (!BITMAP_SetOwnerDC( handle, dc ))
827         {
828             DeleteObject( handle );
829             handle = 0;
830         }
831     }
832
833     GDI_ReleaseObj( hdc );
834     return handle;
835 }
836
837 /***********************************************************************
838  *           CreateDIBSection    (GDI.489)
839  */
840 HBITMAP16 WINAPI CreateDIBSection16 (HDC16 hdc, BITMAPINFO *bmi, UINT16 usage,
841                                      SEGPTR *bits16, HANDLE section, DWORD offset)
842 {
843     LPVOID bits32;
844     HBITMAP hbitmap;
845
846     hbitmap = CreateDIBSection( HDC_32(hdc), bmi, usage, &bits32, section, offset );
847     if (hbitmap)
848     {
849         BITMAPOBJ *bmp = (BITMAPOBJ *) GDI_GetObjPtr(hbitmap, BITMAP_MAGIC);
850         if (bmp && bmp->dib && bits32)
851         {
852             BITMAPINFOHEADER *bi = &bmi->bmiHeader;
853             INT height = bi->biHeight >= 0 ? bi->biHeight : -bi->biHeight;
854             INT width_bytes = DIB_GetDIBWidthBytes(bi->biWidth, bi->biBitCount);
855             INT size  = (bi->biSizeImage && bi->biCompression != BI_RGB) ?
856                          bi->biSizeImage : width_bytes * height;
857
858             /* calculate number of sel's needed for size with 64K steps */
859             WORD count = (size + 0xffff) / 0x10000;
860             WORD sel = AllocSelectorArray16(count);
861             int i;
862
863             for (i = 0; i < count; i++)
864             {
865                 SetSelectorBase(sel + (i << __AHSHIFT), (DWORD)bits32 + i * 0x10000);
866                 SetSelectorLimit16(sel + (i << __AHSHIFT), size - 1); /* yep, limit is correct */
867                 size -= 0x10000;
868             }
869             bmp->segptr_bits = MAKESEGPTR( sel, 0 );
870             if (bits16) *bits16 = bmp->segptr_bits;
871         }
872         if (bmp) GDI_ReleaseObj( hbitmap );
873     }
874     return HBITMAP_16(hbitmap);
875 }
876
877 /***********************************************************************
878  *           DIB_CreateDIBSection
879  */
880 HBITMAP DIB_CreateDIBSection(HDC hdc, BITMAPINFO *bmi, UINT usage,
881                              LPVOID *bits, HANDLE section,
882                              DWORD offset, DWORD ovr_pitch)
883 {
884     HBITMAP hbitmap = 0;
885     DC *dc;
886     BOOL bDesktopDC = FALSE;
887
888     /* If the reference hdc is null, take the desktop dc */
889     if (hdc == 0)
890     {
891         hdc = CreateCompatibleDC(0);
892         bDesktopDC = TRUE;
893     }
894
895     if ((dc = DC_GetDCPtr( hdc )))
896     {
897         hbitmap = dc->funcs->pCreateDIBSection(dc->physDev, bmi, usage, bits, section, offset, ovr_pitch);
898         GDI_ReleaseObj(hdc);
899     }
900
901     if (bDesktopDC)
902       DeleteDC(hdc);
903
904     return hbitmap;
905 }
906
907 /***********************************************************************
908  *           CreateDIBSection    (GDI32.@)
909  */
910 HBITMAP WINAPI CreateDIBSection(HDC hdc, BITMAPINFO *bmi, UINT usage,
911                                 LPVOID *bits, HANDLE section,
912                                 DWORD offset)
913 {
914     return DIB_CreateDIBSection(hdc, bmi, usage, bits, section, offset, 0);
915 }
916
917 /***********************************************************************
918  *           DIB_CreateDIBFromBitmap
919  *  Allocates a packed DIB and copies the bitmap data into it.
920  */
921 HGLOBAL DIB_CreateDIBFromBitmap(HDC hdc, HBITMAP hBmp)
922 {
923     BITMAPOBJ *pBmp = NULL;
924     HGLOBAL hPackedDIB = 0;
925     LPBYTE pPackedDIB = NULL;
926     LPBITMAPINFOHEADER pbmiHeader = NULL;
927     unsigned int width, height, depth, cDataSize = 0, cPackedSize = 0,
928                  OffsetBits = 0, nLinesCopied = 0;
929
930     /* Get a pointer to the BITMAPOBJ structure */
931     pBmp = (BITMAPOBJ *)GDI_GetObjPtr( hBmp, BITMAP_MAGIC );
932     if (!pBmp) return hPackedDIB;
933
934     /* Get the bitmap dimensions */
935     width = pBmp->bitmap.bmWidth;
936     height = pBmp->bitmap.bmHeight;
937     depth = pBmp->bitmap.bmBitsPixel;
938
939     /*
940      * A packed DIB contains a BITMAPINFO structure followed immediately by
941      * an optional color palette and the pixel data.
942      */
943
944     /* Calculate the size of the packed DIB */
945     cDataSize = DIB_GetDIBImageBytes( width, height, depth );
946     cPackedSize = sizeof(BITMAPINFOHEADER)
947                   + ( (depth <= 8) ? (sizeof(RGBQUAD) * (1 << depth)) : 0 )
948                   + cDataSize;
949     /* Get the offset to the bits */
950     OffsetBits = cPackedSize - cDataSize;
951
952     /* Allocate the packed DIB */
953     TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
954     hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
955                              cPackedSize );
956     if ( !hPackedDIB )
957     {
958         WARN("Could not allocate packed DIB!\n");
959         goto END;
960     }
961
962     /* A packed DIB starts with a BITMAPINFOHEADER */
963     pPackedDIB = (LPBYTE)GlobalLock(hPackedDIB);
964     pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
965
966     /* Init the BITMAPINFOHEADER */
967     pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
968     pbmiHeader->biWidth = width;
969     pbmiHeader->biHeight = height;
970     pbmiHeader->biPlanes = 1;
971     pbmiHeader->biBitCount = depth;
972     pbmiHeader->biCompression = BI_RGB;
973     pbmiHeader->biSizeImage = 0;
974     pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
975     pbmiHeader->biClrUsed = 0;
976     pbmiHeader->biClrImportant = 0;
977
978     /* Retrieve the DIB bits from the bitmap and fill in the
979      * DIB color table if present */
980
981     nLinesCopied = GetDIBits(hdc,                       /* Handle to device context */
982                              hBmp,                      /* Handle to bitmap */
983                              0,                         /* First scan line to set in dest bitmap */
984                              height,                    /* Number of scan lines to copy */
985                              pPackedDIB + OffsetBits,   /* [out] Address of array for bitmap bits */
986                              (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
987                              0);                        /* RGB or palette index */
988     GlobalUnlock(hPackedDIB);
989
990     /* Cleanup if GetDIBits failed */
991     if (nLinesCopied != height)
992     {
993         TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, height);
994         GlobalFree(hPackedDIB);
995         hPackedDIB = 0;
996     }
997
998 END:
999     GDI_ReleaseObj( hBmp );
1000     return hPackedDIB;
1001 }