wbemprox: Store the class name in the class object.
[wine] / dlls / gdiplus / image.c
1 /*
2  * Copyright (C) 2007 Google (Evan Stade)
3  * Copyright (C) 2012 Dmitry Timoshkov
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 #include <stdarg.h>
21 #include <assert.h>
22
23 #define NONAMELESSUNION
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winuser.h"
28 #include "wingdi.h"
29
30 #define COBJMACROS
31 #include "objbase.h"
32 #include "olectl.h"
33 #include "ole2.h"
34
35 #include "initguid.h"
36 #include "wincodec.h"
37 #include "gdiplus.h"
38 #include "gdiplus_private.h"
39 #include "wine/debug.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(gdiplus);
42
43 #define PIXELFORMATBPP(x) ((x) ? ((x) >> 8) & 255 : 24)
44
45 static const struct
46 {
47     const WICPixelFormatGUID *wic_format;
48     PixelFormat gdip_format;
49     /* predefined palette type to use for pixel format conversions */
50     WICBitmapPaletteType palette_type;
51 } pixel_formats[] =
52 {
53     { &GUID_WICPixelFormatBlackWhite, PixelFormat1bppIndexed, WICBitmapPaletteTypeFixedBW },
54     { &GUID_WICPixelFormat1bppIndexed, PixelFormat1bppIndexed, WICBitmapPaletteTypeFixedBW },
55     { &GUID_WICPixelFormat8bppGray, PixelFormat8bppIndexed, WICBitmapPaletteTypeFixedGray256 },
56     { &GUID_WICPixelFormat8bppIndexed, PixelFormat8bppIndexed, WICBitmapPaletteTypeFixedHalftone256 },
57     { &GUID_WICPixelFormat16bppBGR555, PixelFormat16bppRGB555, WICBitmapPaletteTypeFixedHalftone256 },
58     { &GUID_WICPixelFormat24bppBGR, PixelFormat24bppRGB, WICBitmapPaletteTypeFixedHalftone256 },
59     { &GUID_WICPixelFormat32bppBGR, PixelFormat32bppRGB, WICBitmapPaletteTypeFixedHalftone256 },
60     { &GUID_WICPixelFormat32bppBGRA, PixelFormat32bppARGB, WICBitmapPaletteTypeFixedHalftone256 },
61     { &GUID_WICPixelFormat32bppPBGRA, PixelFormat32bppPARGB, WICBitmapPaletteTypeFixedHalftone256 },
62     { NULL }
63 };
64
65 static ColorPalette *get_palette(IWICBitmapFrameDecode *frame, WICBitmapPaletteType palette_type)
66 {
67     HRESULT hr;
68     IWICImagingFactory *factory;
69     IWICPalette *wic_palette;
70     ColorPalette *palette = NULL;
71
72     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
73                           &IID_IWICImagingFactory, (void **)&factory);
74     if (hr != S_OK) return NULL;
75
76     hr = IWICImagingFactory_CreatePalette(factory, &wic_palette);
77     if (hr == S_OK)
78     {
79         hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
80         if (frame)
81             hr = IWICBitmapFrameDecode_CopyPalette(frame, wic_palette);
82         if (hr != S_OK)
83         {
84             TRACE("using predefined palette %#x\n", palette_type);
85             hr = IWICPalette_InitializePredefined(wic_palette, palette_type, FALSE);
86         }
87         if (hr == S_OK)
88         {
89             UINT count;
90             BOOL mono, gray;
91
92             IWICPalette_IsBlackWhite(wic_palette, &mono);
93             IWICPalette_IsGrayscale(wic_palette, &gray);
94
95             IWICPalette_GetColorCount(wic_palette, &count);
96             palette = HeapAlloc(GetProcessHeap(), 0, 2 * sizeof(UINT) + count * sizeof(ARGB));
97             IWICPalette_GetColors(wic_palette, count, palette->Entries, &palette->Count);
98
99             if (mono)
100                 palette->Flags = 0;
101             else if (gray)
102                 palette->Flags = PaletteFlagsGrayScale;
103             else
104                 palette->Flags = PaletteFlagsHalftone;
105         }
106         IWICPalette_Release(wic_palette);
107     }
108     IWICImagingFactory_Release(factory);
109     return palette;
110 }
111
112 static INT ipicture_pixel_height(IPicture *pic)
113 {
114     HDC hdcref;
115     OLE_YSIZE_HIMETRIC y;
116
117     IPicture_get_Height(pic, &y);
118
119     hdcref = GetDC(0);
120
121     y = MulDiv(y, GetDeviceCaps(hdcref, LOGPIXELSY), INCH_HIMETRIC);
122     ReleaseDC(0, hdcref);
123
124     return y;
125 }
126
127 static INT ipicture_pixel_width(IPicture *pic)
128 {
129     HDC hdcref;
130     OLE_XSIZE_HIMETRIC x;
131
132     IPicture_get_Width(pic, &x);
133
134     hdcref = GetDC(0);
135
136     x = MulDiv(x, GetDeviceCaps(hdcref, LOGPIXELSX), INCH_HIMETRIC);
137
138     ReleaseDC(0, hdcref);
139
140     return x;
141 }
142
143 GpStatus WINGDIPAPI GdipBitmapApplyEffect(GpBitmap* bitmap, CGpEffect* effect,
144     RECT* roi, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
145 {
146     FIXME("(%p %p %p %d %p %p): stub\n", bitmap, effect, roi, useAuxData, auxData, auxDataSize);
147     /*
148      * Note: According to Jose Roca's GDI+ docs, this function is not
149      * implemented in Windows's GDI+.
150      */
151     return NotImplemented;
152 }
153
154 GpStatus WINGDIPAPI GdipBitmapCreateApplyEffect(GpBitmap** inputBitmaps,
155     INT numInputs, CGpEffect* effect, RECT* roi, RECT* outputRect,
156     GpBitmap** outputBitmap, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
157 {
158     FIXME("(%p %d %p %p %p %p %d %p %p): stub\n", inputBitmaps, numInputs, effect, roi, outputRect, outputBitmap, useAuxData, auxData, auxDataSize);
159     /*
160      * Note: According to Jose Roca's GDI+ docs, this function is not
161      * implemented in Windows's GDI+.
162      */
163     return NotImplemented;
164 }
165
166 static inline void getpixel_1bppIndexed(BYTE *index, const BYTE *row, UINT x)
167 {
168     *index = (row[x/8]>>(7-x%8)) & 1;
169 }
170
171 static inline void getpixel_4bppIndexed(BYTE *index, const BYTE *row, UINT x)
172 {
173     if (x & 1)
174         *index = row[x/2]&0xf;
175     else
176         *index = row[x/2]>>4;
177 }
178
179 static inline void getpixel_8bppIndexed(BYTE *index, const BYTE *row, UINT x)
180 {
181     *index = row[x];
182 }
183
184 static inline void getpixel_16bppGrayScale(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
185     const BYTE *row, UINT x)
186 {
187     *r = *g = *b = row[x*2+1];
188     *a = 255;
189 }
190
191 static inline void getpixel_16bppRGB555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
192     const BYTE *row, UINT x)
193 {
194     WORD pixel = *((const WORD*)(row)+x);
195     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
196     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
197     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
198     *a = 255;
199 }
200
201 static inline void getpixel_16bppRGB565(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
202     const BYTE *row, UINT x)
203 {
204     WORD pixel = *((const WORD*)(row)+x);
205     *r = (pixel>>8&0xf8)|(pixel>>13&0x7);
206     *g = (pixel>>3&0xfc)|(pixel>>9&0x3);
207     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
208     *a = 255;
209 }
210
211 static inline void getpixel_16bppARGB1555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
212     const BYTE *row, UINT x)
213 {
214     WORD pixel = *((const WORD*)(row)+x);
215     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
216     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
217     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
218     if ((pixel&0x8000) == 0x8000)
219         *a = 255;
220     else
221         *a = 0;
222 }
223
224 static inline void getpixel_24bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
225     const BYTE *row, UINT x)
226 {
227     *r = row[x*3+2];
228     *g = row[x*3+1];
229     *b = row[x*3];
230     *a = 255;
231 }
232
233 static inline void getpixel_32bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
234     const BYTE *row, UINT x)
235 {
236     *r = row[x*4+2];
237     *g = row[x*4+1];
238     *b = row[x*4];
239     *a = 255;
240 }
241
242 static inline void getpixel_32bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
243     const BYTE *row, UINT x)
244 {
245     *r = row[x*4+2];
246     *g = row[x*4+1];
247     *b = row[x*4];
248     *a = row[x*4+3];
249 }
250
251 static inline void getpixel_32bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
252     const BYTE *row, UINT x)
253 {
254     *a = row[x*4+3];
255     if (*a == 0)
256         *r = *g = *b = 0;
257     else
258     {
259         *r = row[x*4+2] * 255 / *a;
260         *g = row[x*4+1] * 255 / *a;
261         *b = row[x*4] * 255 / *a;
262     }
263 }
264
265 static inline void getpixel_48bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
266     const BYTE *row, UINT x)
267 {
268     *r = row[x*6+5];
269     *g = row[x*6+3];
270     *b = row[x*6+1];
271     *a = 255;
272 }
273
274 static inline void getpixel_64bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
275     const BYTE *row, UINT x)
276 {
277     *r = row[x*8+5];
278     *g = row[x*8+3];
279     *b = row[x*8+1];
280     *a = row[x*8+7];
281 }
282
283 static inline void getpixel_64bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
284     const BYTE *row, UINT x)
285 {
286     *a = row[x*8+7];
287     if (*a == 0)
288         *r = *g = *b = 0;
289     else
290     {
291         *r = row[x*8+5] * 255 / *a;
292         *g = row[x*8+3] * 255 / *a;
293         *b = row[x*8+1] * 255 / *a;
294     }
295 }
296
297 GpStatus WINGDIPAPI GdipBitmapGetPixel(GpBitmap* bitmap, INT x, INT y,
298     ARGB *color)
299 {
300     BYTE r, g, b, a;
301     BYTE index;
302     BYTE *row;
303     TRACE("%p %d %d %p\n", bitmap, x, y, color);
304
305     if(!bitmap || !color ||
306        x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
307         return InvalidParameter;
308
309     row = bitmap->bits+bitmap->stride*y;
310
311     switch (bitmap->format)
312     {
313         case PixelFormat1bppIndexed:
314             getpixel_1bppIndexed(&index,row,x);
315             break;
316         case PixelFormat4bppIndexed:
317             getpixel_4bppIndexed(&index,row,x);
318             break;
319         case PixelFormat8bppIndexed:
320             getpixel_8bppIndexed(&index,row,x);
321             break;
322         case PixelFormat16bppGrayScale:
323             getpixel_16bppGrayScale(&r,&g,&b,&a,row,x);
324             break;
325         case PixelFormat16bppRGB555:
326             getpixel_16bppRGB555(&r,&g,&b,&a,row,x);
327             break;
328         case PixelFormat16bppRGB565:
329             getpixel_16bppRGB565(&r,&g,&b,&a,row,x);
330             break;
331         case PixelFormat16bppARGB1555:
332             getpixel_16bppARGB1555(&r,&g,&b,&a,row,x);
333             break;
334         case PixelFormat24bppRGB:
335             getpixel_24bppRGB(&r,&g,&b,&a,row,x);
336             break;
337         case PixelFormat32bppRGB:
338             getpixel_32bppRGB(&r,&g,&b,&a,row,x);
339             break;
340         case PixelFormat32bppARGB:
341             getpixel_32bppARGB(&r,&g,&b,&a,row,x);
342             break;
343         case PixelFormat32bppPARGB:
344             getpixel_32bppPARGB(&r,&g,&b,&a,row,x);
345             break;
346         case PixelFormat48bppRGB:
347             getpixel_48bppRGB(&r,&g,&b,&a,row,x);
348             break;
349         case PixelFormat64bppARGB:
350             getpixel_64bppARGB(&r,&g,&b,&a,row,x);
351             break;
352         case PixelFormat64bppPARGB:
353             getpixel_64bppPARGB(&r,&g,&b,&a,row,x);
354             break;
355         default:
356             FIXME("not implemented for format 0x%x\n", bitmap->format);
357             return NotImplemented;
358     }
359
360     if (bitmap->format & PixelFormatIndexed)
361         *color = bitmap->image.palette->Entries[index];
362     else
363         *color = a<<24|r<<16|g<<8|b;
364
365     return Ok;
366 }
367
368 static inline UINT get_palette_index(BYTE r, BYTE g, BYTE b, BYTE a, ColorPalette *palette)
369 {
370     BYTE index = 0;
371     int best_distance = 0x7fff;
372     int distance;
373     int i;
374
375     if (!palette) return 0;
376     /* This algorithm scans entire palette,
377        computes difference from desired color (all color components have equal weight)
378        and returns the index of color with least difference.
379
380        Note: Maybe it could be replaced with a better algorithm for better image quality
381        and performance, though better algorithm would probably need some pre-built lookup
382        tables and thus may actually be slower if this method is called only few times per
383        every image.
384     */
385     for(i=0;i<palette->Count;i++) {
386         ARGB color=palette->Entries[i];
387         distance=abs(b-(color & 0xff)) + abs(g-(color>>8 & 0xff)) + abs(r-(color>>16 & 0xff)) + abs(a-(color>>24 & 0xff));
388         if (distance<best_distance) {
389             best_distance=distance;
390             index=i;
391         }
392     }
393     return index;
394 }
395
396 static inline void setpixel_8bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
397     BYTE *row, UINT x, ColorPalette *palette)
398 {
399      BYTE index = get_palette_index(r,g,b,a,palette);
400      row[x]=index;
401 }
402
403 static inline void setpixel_1bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
404     BYTE *row, UINT x, ColorPalette *palette)
405 {
406     row[x/8]  = (row[x/8] & ~(1<<(7-x%8))) | (get_palette_index(r,g,b,a,palette)<<(7-x%8));
407 }
408
409 static inline void setpixel_4bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
410     BYTE *row, UINT x, ColorPalette *palette)
411 {
412     if (x & 1)
413         row[x/2] = (row[x/2] & 0xf0) | get_palette_index(r,g,b,a,palette);
414     else
415         row[x/2] = (row[x/2] & 0x0f) | get_palette_index(r,g,b,a,palette)<<4;
416 }
417
418 static inline void setpixel_16bppGrayScale(BYTE r, BYTE g, BYTE b, BYTE a,
419     BYTE *row, UINT x)
420 {
421     *((WORD*)(row)+x) = (r+g+b)*85;
422 }
423
424 static inline void setpixel_16bppRGB555(BYTE r, BYTE g, BYTE b, BYTE a,
425     BYTE *row, UINT x)
426 {
427     *((WORD*)(row)+x) = (r<<7&0x7c00)|
428                         (g<<2&0x03e0)|
429                         (b>>3&0x001f);
430 }
431
432 static inline void setpixel_16bppRGB565(BYTE r, BYTE g, BYTE b, BYTE a,
433     BYTE *row, UINT x)
434 {
435     *((WORD*)(row)+x) = (r<<8&0xf800)|
436                          (g<<3&0x07e0)|
437                          (b>>3&0x001f);
438 }
439
440 static inline void setpixel_16bppARGB1555(BYTE r, BYTE g, BYTE b, BYTE a,
441     BYTE *row, UINT x)
442 {
443     *((WORD*)(row)+x) = (a<<8&0x8000)|
444                         (r<<7&0x7c00)|
445                         (g<<2&0x03e0)|
446                         (b>>3&0x001f);
447 }
448
449 static inline void setpixel_24bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
450     BYTE *row, UINT x)
451 {
452     row[x*3+2] = r;
453     row[x*3+1] = g;
454     row[x*3] = b;
455 }
456
457 static inline void setpixel_32bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
458     BYTE *row, UINT x)
459 {
460     *((DWORD*)(row)+x) = (r<<16)|(g<<8)|b;
461 }
462
463 static inline void setpixel_32bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
464     BYTE *row, UINT x)
465 {
466     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
467 }
468
469 static inline void setpixel_32bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
470     BYTE *row, UINT x)
471 {
472     r = r * a / 255;
473     g = g * a / 255;
474     b = b * a / 255;
475     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
476 }
477
478 static inline void setpixel_48bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
479     BYTE *row, UINT x)
480 {
481     row[x*6+5] = row[x*6+4] = r;
482     row[x*6+3] = row[x*6+2] = g;
483     row[x*6+1] = row[x*6] = b;
484 }
485
486 static inline void setpixel_64bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
487     BYTE *row, UINT x)
488 {
489     UINT64 a64=a, r64=r, g64=g, b64=b;
490     *((UINT64*)(row)+x) = (a64<<56)|(a64<<48)|(r64<<40)|(r64<<32)|(g64<<24)|(g64<<16)|(b64<<8)|b64;
491 }
492
493 static inline void setpixel_64bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
494     BYTE *row, UINT x)
495 {
496     UINT64 a64, r64, g64, b64;
497     a64 = a * 257;
498     r64 = r * a / 255;
499     g64 = g * a / 255;
500     b64 = b * a / 255;
501     *((UINT64*)(row)+x) = (a64<<48)|(r64<<32)|(g64<<16)|b64;
502 }
503
504 GpStatus WINGDIPAPI GdipBitmapSetPixel(GpBitmap* bitmap, INT x, INT y,
505     ARGB color)
506 {
507     BYTE a, r, g, b;
508     BYTE *row;
509     TRACE("bitmap:%p, x:%d, y:%d, color:%08x\n", bitmap, x, y, color);
510
511     if(!bitmap || x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
512         return InvalidParameter;
513
514     a = color>>24;
515     r = color>>16;
516     g = color>>8;
517     b = color;
518
519     row = bitmap->bits + bitmap->stride * y;
520
521     switch (bitmap->format)
522     {
523         case PixelFormat16bppGrayScale:
524             setpixel_16bppGrayScale(r,g,b,a,row,x);
525             break;
526         case PixelFormat16bppRGB555:
527             setpixel_16bppRGB555(r,g,b,a,row,x);
528             break;
529         case PixelFormat16bppRGB565:
530             setpixel_16bppRGB565(r,g,b,a,row,x);
531             break;
532         case PixelFormat16bppARGB1555:
533             setpixel_16bppARGB1555(r,g,b,a,row,x);
534             break;
535         case PixelFormat24bppRGB:
536             setpixel_24bppRGB(r,g,b,a,row,x);
537             break;
538         case PixelFormat32bppRGB:
539             setpixel_32bppRGB(r,g,b,a,row,x);
540             break;
541         case PixelFormat32bppARGB:
542             setpixel_32bppARGB(r,g,b,a,row,x);
543             break;
544         case PixelFormat32bppPARGB:
545             setpixel_32bppPARGB(r,g,b,a,row,x);
546             break;
547         case PixelFormat48bppRGB:
548             setpixel_48bppRGB(r,g,b,a,row,x);
549             break;
550         case PixelFormat64bppARGB:
551             setpixel_64bppARGB(r,g,b,a,row,x);
552             break;
553         case PixelFormat64bppPARGB:
554             setpixel_64bppPARGB(r,g,b,a,row,x);
555             break;
556         case PixelFormat8bppIndexed:
557             setpixel_8bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
558             break;
559         case PixelFormat4bppIndexed:
560             setpixel_4bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
561             break;
562         case PixelFormat1bppIndexed:
563             setpixel_1bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
564             break;
565         default:
566             FIXME("not implemented for format 0x%x\n", bitmap->format);
567             return NotImplemented;
568     }
569
570     return Ok;
571 }
572
573 GpStatus convert_pixels(INT width, INT height,
574     INT dst_stride, BYTE *dst_bits, PixelFormat dst_format,
575     INT src_stride, const BYTE *src_bits, PixelFormat src_format,
576     ColorPalette *palette)
577 {
578     INT x, y;
579
580     if (src_format == dst_format ||
581         (dst_format == PixelFormat32bppRGB && PIXELFORMATBPP(src_format) == 32))
582     {
583         UINT widthbytes = PIXELFORMATBPP(src_format) * width / 8;
584         for (y=0; y<height; y++)
585             memcpy(dst_bits+dst_stride*y, src_bits+src_stride*y, widthbytes);
586         return Ok;
587     }
588
589 #define convert_indexed_to_rgb(getpixel_function, setpixel_function) do { \
590     for (x=0; x<width; x++) \
591         for (y=0; y<height; y++) { \
592             BYTE index; \
593             ARGB argb; \
594             BYTE *color = (BYTE *)&argb; \
595             getpixel_function(&index, src_bits+src_stride*y, x); \
596             argb = (palette && index < palette->Count) ? palette->Entries[index] : 0; \
597             setpixel_function(color[2], color[1], color[0], color[3], dst_bits+dst_stride*y, x); \
598         } \
599     return Ok; \
600 } while (0);
601
602 #define convert_rgb_to_rgb(getpixel_function, setpixel_function) do { \
603     for (x=0; x<width; x++) \
604         for (y=0; y<height; y++) { \
605             BYTE r, g, b, a; \
606             getpixel_function(&r, &g, &b, &a, src_bits+src_stride*y, x); \
607             setpixel_function(r, g, b, a, dst_bits+dst_stride*y, x); \
608         } \
609     return Ok; \
610 } while (0);
611
612 #define convert_rgb_to_indexed(getpixel_function, setpixel_function) do { \
613     for (x=0; x<width; x++) \
614         for (y=0; y<height; y++) { \
615             BYTE r, g, b, a; \
616             getpixel_function(&r, &g, &b, &a, src_bits+src_stride*y, x); \
617             setpixel_function(r, g, b, a, dst_bits+dst_stride*y, x, palette); \
618         } \
619     return Ok; \
620 } while (0);
621
622     switch (src_format)
623     {
624     case PixelFormat1bppIndexed:
625         switch (dst_format)
626         {
627         case PixelFormat16bppGrayScale:
628             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppGrayScale);
629         case PixelFormat16bppRGB555:
630             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppRGB555);
631         case PixelFormat16bppRGB565:
632             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppRGB565);
633         case PixelFormat16bppARGB1555:
634             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppARGB1555);
635         case PixelFormat24bppRGB:
636             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_24bppRGB);
637         case PixelFormat32bppRGB:
638             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppRGB);
639         case PixelFormat32bppARGB:
640             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppARGB);
641         case PixelFormat32bppPARGB:
642             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppPARGB);
643         case PixelFormat48bppRGB:
644             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_48bppRGB);
645         case PixelFormat64bppARGB:
646             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_64bppARGB);
647         default:
648             break;
649         }
650         break;
651     case PixelFormat4bppIndexed:
652         switch (dst_format)
653         {
654         case PixelFormat16bppGrayScale:
655             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppGrayScale);
656         case PixelFormat16bppRGB555:
657             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppRGB555);
658         case PixelFormat16bppRGB565:
659             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppRGB565);
660         case PixelFormat16bppARGB1555:
661             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppARGB1555);
662         case PixelFormat24bppRGB:
663             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_24bppRGB);
664         case PixelFormat32bppRGB:
665             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppRGB);
666         case PixelFormat32bppARGB:
667             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppARGB);
668         case PixelFormat32bppPARGB:
669             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppPARGB);
670         case PixelFormat48bppRGB:
671             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_48bppRGB);
672         case PixelFormat64bppARGB:
673             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_64bppARGB);
674         default:
675             break;
676         }
677         break;
678     case PixelFormat8bppIndexed:
679         switch (dst_format)
680         {
681         case PixelFormat16bppGrayScale:
682             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppGrayScale);
683         case PixelFormat16bppRGB555:
684             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppRGB555);
685         case PixelFormat16bppRGB565:
686             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppRGB565);
687         case PixelFormat16bppARGB1555:
688             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppARGB1555);
689         case PixelFormat24bppRGB:
690             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_24bppRGB);
691         case PixelFormat32bppRGB:
692             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppRGB);
693         case PixelFormat32bppARGB:
694             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppARGB);
695         case PixelFormat32bppPARGB:
696             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppPARGB);
697         case PixelFormat48bppRGB:
698             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_48bppRGB);
699         case PixelFormat64bppARGB:
700             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_64bppARGB);
701         default:
702             break;
703         }
704         break;
705     case PixelFormat16bppGrayScale:
706         switch (dst_format)
707         {
708         case PixelFormat1bppIndexed:
709             convert_rgb_to_indexed(getpixel_16bppGrayScale, setpixel_1bppIndexed);
710         case PixelFormat8bppIndexed:
711             convert_rgb_to_indexed(getpixel_16bppGrayScale, setpixel_8bppIndexed);
712         case PixelFormat16bppRGB555:
713             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppRGB555);
714         case PixelFormat16bppRGB565:
715             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppRGB565);
716         case PixelFormat16bppARGB1555:
717             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppARGB1555);
718         case PixelFormat24bppRGB:
719             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_24bppRGB);
720         case PixelFormat32bppRGB:
721             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppRGB);
722         case PixelFormat32bppARGB:
723             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppARGB);
724         case PixelFormat32bppPARGB:
725             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppPARGB);
726         case PixelFormat48bppRGB:
727             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_48bppRGB);
728         case PixelFormat64bppARGB:
729             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_64bppARGB);
730         default:
731             break;
732         }
733         break;
734     case PixelFormat16bppRGB555:
735         switch (dst_format)
736         {
737         case PixelFormat1bppIndexed:
738             convert_rgb_to_indexed(getpixel_16bppRGB555, setpixel_1bppIndexed);
739         case PixelFormat8bppIndexed:
740             convert_rgb_to_indexed(getpixel_16bppRGB555, setpixel_8bppIndexed);
741         case PixelFormat16bppGrayScale:
742             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppGrayScale);
743         case PixelFormat16bppRGB565:
744             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppRGB565);
745         case PixelFormat16bppARGB1555:
746             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppARGB1555);
747         case PixelFormat24bppRGB:
748             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_24bppRGB);
749         case PixelFormat32bppRGB:
750             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppRGB);
751         case PixelFormat32bppARGB:
752             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppARGB);
753         case PixelFormat32bppPARGB:
754             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppPARGB);
755         case PixelFormat48bppRGB:
756             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_48bppRGB);
757         case PixelFormat64bppARGB:
758             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_64bppARGB);
759         default:
760             break;
761         }
762         break;
763     case PixelFormat16bppRGB565:
764         switch (dst_format)
765         {
766         case PixelFormat1bppIndexed:
767             convert_rgb_to_indexed(getpixel_16bppRGB565, setpixel_1bppIndexed);
768         case PixelFormat8bppIndexed:
769             convert_rgb_to_indexed(getpixel_16bppRGB565, setpixel_8bppIndexed);
770         case PixelFormat16bppGrayScale:
771             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppGrayScale);
772         case PixelFormat16bppRGB555:
773             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppRGB555);
774         case PixelFormat16bppARGB1555:
775             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppARGB1555);
776         case PixelFormat24bppRGB:
777             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_24bppRGB);
778         case PixelFormat32bppRGB:
779             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppRGB);
780         case PixelFormat32bppARGB:
781             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppARGB);
782         case PixelFormat32bppPARGB:
783             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppPARGB);
784         case PixelFormat48bppRGB:
785             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_48bppRGB);
786         case PixelFormat64bppARGB:
787             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_64bppARGB);
788         default:
789             break;
790         }
791         break;
792     case PixelFormat16bppARGB1555:
793         switch (dst_format)
794         {
795         case PixelFormat1bppIndexed:
796             convert_rgb_to_indexed(getpixel_16bppARGB1555, setpixel_1bppIndexed);
797         case PixelFormat8bppIndexed:
798             convert_rgb_to_indexed(getpixel_16bppARGB1555, setpixel_8bppIndexed);
799         case PixelFormat16bppGrayScale:
800             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppGrayScale);
801         case PixelFormat16bppRGB555:
802             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppRGB555);
803         case PixelFormat16bppRGB565:
804             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppRGB565);
805         case PixelFormat24bppRGB:
806             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_24bppRGB);
807         case PixelFormat32bppRGB:
808             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppRGB);
809         case PixelFormat32bppARGB:
810             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppARGB);
811         case PixelFormat32bppPARGB:
812             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppPARGB);
813         case PixelFormat48bppRGB:
814             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_48bppRGB);
815         case PixelFormat64bppARGB:
816             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_64bppARGB);
817         default:
818             break;
819         }
820         break;
821     case PixelFormat24bppRGB:
822         switch (dst_format)
823         {
824         case PixelFormat1bppIndexed:
825             convert_rgb_to_indexed(getpixel_24bppRGB, setpixel_1bppIndexed);
826         case PixelFormat8bppIndexed:
827             convert_rgb_to_indexed(getpixel_24bppRGB, setpixel_8bppIndexed);
828         case PixelFormat16bppGrayScale:
829             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppGrayScale);
830         case PixelFormat16bppRGB555:
831             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppRGB555);
832         case PixelFormat16bppRGB565:
833             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppRGB565);
834         case PixelFormat16bppARGB1555:
835             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppARGB1555);
836         case PixelFormat32bppRGB:
837             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppRGB);
838         case PixelFormat32bppARGB:
839             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppARGB);
840         case PixelFormat32bppPARGB:
841             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppPARGB);
842         case PixelFormat48bppRGB:
843             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_48bppRGB);
844         case PixelFormat64bppARGB:
845             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_64bppARGB);
846         default:
847             break;
848         }
849         break;
850     case PixelFormat32bppRGB:
851         switch (dst_format)
852         {
853         case PixelFormat1bppIndexed:
854             convert_rgb_to_indexed(getpixel_32bppRGB, setpixel_1bppIndexed);
855         case PixelFormat8bppIndexed:
856             convert_rgb_to_indexed(getpixel_32bppRGB, setpixel_8bppIndexed);
857         case PixelFormat16bppGrayScale:
858             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppGrayScale);
859         case PixelFormat16bppRGB555:
860             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppRGB555);
861         case PixelFormat16bppRGB565:
862             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppRGB565);
863         case PixelFormat16bppARGB1555:
864             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppARGB1555);
865         case PixelFormat24bppRGB:
866             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_24bppRGB);
867         case PixelFormat32bppARGB:
868             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_32bppARGB);
869         case PixelFormat32bppPARGB:
870             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_32bppPARGB);
871         case PixelFormat48bppRGB:
872             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_48bppRGB);
873         case PixelFormat64bppARGB:
874             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_64bppARGB);
875         default:
876             break;
877         }
878         break;
879     case PixelFormat32bppARGB:
880         switch (dst_format)
881         {
882         case PixelFormat1bppIndexed:
883             convert_rgb_to_indexed(getpixel_32bppARGB, setpixel_1bppIndexed);
884         case PixelFormat8bppIndexed:
885             convert_rgb_to_indexed(getpixel_32bppARGB, setpixel_8bppIndexed);
886         case PixelFormat16bppGrayScale:
887             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppGrayScale);
888         case PixelFormat16bppRGB555:
889             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppRGB555);
890         case PixelFormat16bppRGB565:
891             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppRGB565);
892         case PixelFormat16bppARGB1555:
893             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppARGB1555);
894         case PixelFormat24bppRGB:
895             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_24bppRGB);
896         case PixelFormat32bppPARGB:
897             convert_32bppARGB_to_32bppPARGB(width, height, dst_bits, dst_stride, src_bits, src_stride);
898             return Ok;
899         case PixelFormat48bppRGB:
900             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_48bppRGB);
901         case PixelFormat64bppARGB:
902             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_64bppARGB);
903         default:
904             break;
905         }
906         break;
907     case PixelFormat32bppPARGB:
908         switch (dst_format)
909         {
910         case PixelFormat1bppIndexed:
911             convert_rgb_to_indexed(getpixel_32bppPARGB, setpixel_1bppIndexed);
912         case PixelFormat8bppIndexed:
913             convert_rgb_to_indexed(getpixel_32bppPARGB, setpixel_8bppIndexed);
914         case PixelFormat16bppGrayScale:
915             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppGrayScale);
916         case PixelFormat16bppRGB555:
917             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppRGB555);
918         case PixelFormat16bppRGB565:
919             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppRGB565);
920         case PixelFormat16bppARGB1555:
921             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppARGB1555);
922         case PixelFormat24bppRGB:
923             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_24bppRGB);
924         case PixelFormat32bppRGB:
925             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_32bppRGB);
926         case PixelFormat32bppARGB:
927             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_32bppARGB);
928         case PixelFormat48bppRGB:
929             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_48bppRGB);
930         case PixelFormat64bppARGB:
931             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_64bppARGB);
932         default:
933             break;
934         }
935         break;
936     case PixelFormat48bppRGB:
937         switch (dst_format)
938         {
939         case PixelFormat1bppIndexed:
940             convert_rgb_to_indexed(getpixel_48bppRGB, setpixel_1bppIndexed);
941         case PixelFormat8bppIndexed:
942             convert_rgb_to_indexed(getpixel_48bppRGB, setpixel_8bppIndexed);
943         case PixelFormat16bppGrayScale:
944             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppGrayScale);
945         case PixelFormat16bppRGB555:
946             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppRGB555);
947         case PixelFormat16bppRGB565:
948             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppRGB565);
949         case PixelFormat16bppARGB1555:
950             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppARGB1555);
951         case PixelFormat24bppRGB:
952             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_24bppRGB);
953         case PixelFormat32bppRGB:
954             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppRGB);
955         case PixelFormat32bppARGB:
956             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppARGB);
957         case PixelFormat32bppPARGB:
958             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppPARGB);
959         case PixelFormat64bppARGB:
960             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_64bppARGB);
961         default:
962             break;
963         }
964         break;
965     case PixelFormat64bppARGB:
966         switch (dst_format)
967         {
968         case PixelFormat1bppIndexed:
969             convert_rgb_to_indexed(getpixel_64bppARGB, setpixel_1bppIndexed);
970         case PixelFormat8bppIndexed:
971             convert_rgb_to_indexed(getpixel_64bppARGB, setpixel_8bppIndexed);
972         case PixelFormat16bppGrayScale:
973             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppGrayScale);
974         case PixelFormat16bppRGB555:
975             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppRGB555);
976         case PixelFormat16bppRGB565:
977             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppRGB565);
978         case PixelFormat16bppARGB1555:
979             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppARGB1555);
980         case PixelFormat24bppRGB:
981             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_24bppRGB);
982         case PixelFormat32bppRGB:
983             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppRGB);
984         case PixelFormat32bppARGB:
985             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppARGB);
986         case PixelFormat32bppPARGB:
987             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppPARGB);
988         case PixelFormat48bppRGB:
989             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_48bppRGB);
990         default:
991             break;
992         }
993         break;
994     case PixelFormat64bppPARGB:
995         switch (dst_format)
996         {
997         case PixelFormat1bppIndexed:
998             convert_rgb_to_indexed(getpixel_64bppPARGB, setpixel_1bppIndexed);
999         case PixelFormat8bppIndexed:
1000             convert_rgb_to_indexed(getpixel_64bppPARGB, setpixel_8bppIndexed);
1001         case PixelFormat16bppGrayScale:
1002             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppGrayScale);
1003         case PixelFormat16bppRGB555:
1004             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppRGB555);
1005         case PixelFormat16bppRGB565:
1006             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppRGB565);
1007         case PixelFormat16bppARGB1555:
1008             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppARGB1555);
1009         case PixelFormat24bppRGB:
1010             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_24bppRGB);
1011         case PixelFormat32bppRGB:
1012             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppRGB);
1013         case PixelFormat32bppARGB:
1014             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppARGB);
1015         case PixelFormat32bppPARGB:
1016             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppPARGB);
1017         case PixelFormat48bppRGB:
1018             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_48bppRGB);
1019         case PixelFormat64bppARGB:
1020             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_64bppARGB);
1021         default:
1022             break;
1023         }
1024         break;
1025     default:
1026         break;
1027     }
1028
1029 #undef convert_indexed_to_rgb
1030 #undef convert_rgb_to_rgb
1031
1032     return NotImplemented;
1033 }
1034
1035 /* This function returns a pointer to an array of pixels that represents the
1036  * bitmap. The *entire* bitmap is locked according to the lock mode specified by
1037  * flags.  It is correct behavior that a user who calls this function with write
1038  * privileges can write to the whole bitmap (not just the area in rect).
1039  *
1040  * FIXME: only used portion of format is bits per pixel. */
1041 GpStatus WINGDIPAPI GdipBitmapLockBits(GpBitmap* bitmap, GDIPCONST GpRect* rect,
1042     UINT flags, PixelFormat format, BitmapData* lockeddata)
1043 {
1044     INT bitspp = PIXELFORMATBPP(format);
1045     GpRect act_rect; /* actual rect to be used */
1046     GpStatus stat;
1047
1048     TRACE("%p %p %d 0x%x %p\n", bitmap, rect, flags, format, lockeddata);
1049
1050     if(!lockeddata || !bitmap)
1051         return InvalidParameter;
1052
1053     if(rect){
1054         if(rect->X < 0 || rect->Y < 0 || (rect->X + rect->Width > bitmap->width) ||
1055           (rect->Y + rect->Height > bitmap->height) || !flags)
1056             return InvalidParameter;
1057
1058         act_rect = *rect;
1059     }
1060     else{
1061         act_rect.X = act_rect.Y = 0;
1062         act_rect.Width  = bitmap->width;
1063         act_rect.Height = bitmap->height;
1064     }
1065
1066     if(bitmap->lockmode)
1067     {
1068         WARN("bitmap is already locked and cannot be locked again\n");
1069         return WrongState;
1070     }
1071
1072     if (bitmap->bits && bitmap->format == format && !(flags & ImageLockModeUserInputBuf))
1073     {
1074         /* no conversion is necessary; just use the bits directly */
1075         lockeddata->Width = act_rect.Width;
1076         lockeddata->Height = act_rect.Height;
1077         lockeddata->PixelFormat = format;
1078         lockeddata->Reserved = flags;
1079         lockeddata->Stride = bitmap->stride;
1080         lockeddata->Scan0 = bitmap->bits + (bitspp / 8) * act_rect.X +
1081                             bitmap->stride * act_rect.Y;
1082
1083         bitmap->lockmode = flags | ImageLockModeRead;
1084         bitmap->numlocks++;
1085
1086         return Ok;
1087     }
1088
1089     /* Make sure we can convert to the requested format. */
1090     if (flags & ImageLockModeRead)
1091     {
1092         stat = convert_pixels(0, 0, 0, NULL, format, 0, NULL, bitmap->format, NULL);
1093         if (stat == NotImplemented)
1094         {
1095             FIXME("cannot read bitmap from %x to %x\n", bitmap->format, format);
1096             return NotImplemented;
1097         }
1098     }
1099
1100     /* If we're opening for writing, make sure we'll be able to write back in
1101      * the original format. */
1102     if (flags & ImageLockModeWrite)
1103     {
1104         stat = convert_pixels(0, 0, 0, NULL, bitmap->format, 0, NULL, format, NULL);
1105         if (stat == NotImplemented)
1106         {
1107             FIXME("cannot write bitmap from %x to %x\n", format, bitmap->format);
1108             return NotImplemented;
1109         }
1110     }
1111
1112     lockeddata->Width  = act_rect.Width;
1113     lockeddata->Height = act_rect.Height;
1114     lockeddata->PixelFormat = format;
1115     lockeddata->Reserved = flags;
1116
1117     if(!(flags & ImageLockModeUserInputBuf))
1118     {
1119         lockeddata->Stride = (((act_rect.Width * bitspp + 7) / 8) + 3) & ~3;
1120
1121         bitmap->bitmapbits = GdipAlloc(lockeddata->Stride * act_rect.Height);
1122
1123         if (!bitmap->bitmapbits) return OutOfMemory;
1124
1125         lockeddata->Scan0  = bitmap->bitmapbits;
1126     }
1127
1128     if (flags & ImageLockModeRead)
1129     {
1130         static int fixme=0;
1131
1132         if (!fixme && (PIXELFORMATBPP(bitmap->format) * act_rect.X) % 8 != 0)
1133         {
1134             FIXME("Cannot copy rows that don't start at a whole byte.\n");
1135             fixme = 1;
1136         }
1137
1138         stat = convert_pixels(act_rect.Width, act_rect.Height,
1139             lockeddata->Stride, lockeddata->Scan0, format,
1140             bitmap->stride,
1141             bitmap->bits + bitmap->stride * act_rect.Y + PIXELFORMATBPP(bitmap->format) * act_rect.X / 8,
1142             bitmap->format, bitmap->image.palette);
1143
1144         if (stat != Ok)
1145         {
1146             GdipFree(bitmap->bitmapbits);
1147             bitmap->bitmapbits = NULL;
1148             return stat;
1149         }
1150     }
1151
1152     bitmap->lockmode = flags | ImageLockModeRead;
1153     bitmap->numlocks++;
1154     bitmap->lockx = act_rect.X;
1155     bitmap->locky = act_rect.Y;
1156
1157     return Ok;
1158 }
1159
1160 GpStatus WINGDIPAPI GdipBitmapSetResolution(GpBitmap* bitmap, REAL xdpi, REAL ydpi)
1161 {
1162     TRACE("(%p, %.2f, %.2f)\n", bitmap, xdpi, ydpi);
1163
1164     if (!bitmap || xdpi == 0.0 || ydpi == 0.0)
1165         return InvalidParameter;
1166
1167     bitmap->image.xres = xdpi;
1168     bitmap->image.yres = ydpi;
1169
1170     return Ok;
1171 }
1172
1173 GpStatus WINGDIPAPI GdipBitmapUnlockBits(GpBitmap* bitmap,
1174     BitmapData* lockeddata)
1175 {
1176     GpStatus stat;
1177     static int fixme=0;
1178
1179     TRACE("(%p,%p)\n", bitmap, lockeddata);
1180
1181     if(!bitmap || !lockeddata)
1182         return InvalidParameter;
1183
1184     if(!bitmap->lockmode)
1185         return WrongState;
1186
1187     if(!(lockeddata->Reserved & ImageLockModeWrite)){
1188         if(!(--bitmap->numlocks))
1189             bitmap->lockmode = 0;
1190
1191         GdipFree(bitmap->bitmapbits);
1192         bitmap->bitmapbits = NULL;
1193         return Ok;
1194     }
1195
1196     if (!bitmap->bitmapbits && !(lockeddata->Reserved & ImageLockModeUserInputBuf))
1197     {
1198         /* we passed a direct reference; no need to do anything */
1199         bitmap->lockmode = 0;
1200         bitmap->numlocks = 0;
1201         return Ok;
1202     }
1203
1204     if (!fixme && (PIXELFORMATBPP(bitmap->format) * bitmap->lockx) % 8 != 0)
1205     {
1206         FIXME("Cannot copy rows that don't start at a whole byte.\n");
1207         fixme = 1;
1208     }
1209
1210     stat = convert_pixels(lockeddata->Width, lockeddata->Height,
1211         bitmap->stride,
1212         bitmap->bits + bitmap->stride * bitmap->locky + PIXELFORMATBPP(bitmap->format) * bitmap->lockx / 8,
1213         bitmap->format,
1214         lockeddata->Stride, lockeddata->Scan0, lockeddata->PixelFormat, NULL);
1215
1216     if (stat != Ok)
1217     {
1218         ERR("failed to convert pixels; this should never happen\n");
1219     }
1220
1221     GdipFree(bitmap->bitmapbits);
1222     bitmap->bitmapbits = NULL;
1223     bitmap->lockmode = 0;
1224     bitmap->numlocks = 0;
1225
1226     return stat;
1227 }
1228
1229 GpStatus WINGDIPAPI GdipCloneBitmapArea(REAL x, REAL y, REAL width, REAL height,
1230     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
1231 {
1232     BitmapData lockeddata_src, lockeddata_dst;
1233     int i;
1234     UINT row_size;
1235     Rect area;
1236     GpStatus stat;
1237
1238     TRACE("(%f,%f,%f,%f,0x%x,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
1239
1240     if (!srcBitmap || !dstBitmap || srcBitmap->image.type != ImageTypeBitmap ||
1241         x < 0 || y < 0 ||
1242         x + width > srcBitmap->width || y + height > srcBitmap->height)
1243     {
1244         TRACE("<-- InvalidParameter\n");
1245         return InvalidParameter;
1246     }
1247
1248     if (format == PixelFormatDontCare)
1249         format = srcBitmap->format;
1250
1251     area.X = roundr(x);
1252     area.Y = roundr(y);
1253     area.Width = roundr(width);
1254     area.Height = roundr(height);
1255
1256     stat = GdipBitmapLockBits(srcBitmap, &area, ImageLockModeRead, format,
1257         &lockeddata_src);
1258     if (stat != Ok) return stat;
1259
1260     stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
1261         0, lockeddata_src.PixelFormat, NULL, dstBitmap);
1262     if (stat == Ok)
1263     {
1264         stat = GdipBitmapLockBits(*dstBitmap, NULL, ImageLockModeWrite,
1265             lockeddata_src.PixelFormat, &lockeddata_dst);
1266
1267         if (stat == Ok)
1268         {
1269             /* copy the image data */
1270             row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
1271             for (i=0; i<lockeddata_src.Height; i++)
1272                 memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
1273                        (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
1274                        row_size);
1275
1276             GdipBitmapUnlockBits(*dstBitmap, &lockeddata_dst);
1277         }
1278
1279         if (stat != Ok)
1280             GdipDisposeImage((GpImage*)*dstBitmap);
1281     }
1282
1283     GdipBitmapUnlockBits(srcBitmap, &lockeddata_src);
1284
1285     if (stat != Ok)
1286     {
1287         *dstBitmap = NULL;
1288     }
1289
1290     return stat;
1291 }
1292
1293 GpStatus WINGDIPAPI GdipCloneBitmapAreaI(INT x, INT y, INT width, INT height,
1294     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
1295 {
1296     TRACE("(%i,%i,%i,%i,0x%x,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
1297
1298     return GdipCloneBitmapArea(x, y, width, height, format, srcBitmap, dstBitmap);
1299 }
1300
1301 GpStatus WINGDIPAPI GdipCloneImage(GpImage *image, GpImage **cloneImage)
1302 {
1303     GpStatus stat = GenericError;
1304
1305     TRACE("%p, %p\n", image, cloneImage);
1306
1307     if (!image || !cloneImage)
1308         return InvalidParameter;
1309
1310     if (image->picture)
1311     {
1312         IStream* stream;
1313         HRESULT hr;
1314         INT size;
1315         LARGE_INTEGER move;
1316
1317         hr = CreateStreamOnHGlobal(0, TRUE, &stream);
1318         if (FAILED(hr))
1319             return GenericError;
1320
1321         hr = IPicture_SaveAsFile(image->picture, stream, FALSE, &size);
1322         if(FAILED(hr))
1323         {
1324             WARN("Failed to save image on stream\n");
1325             goto out;
1326         }
1327
1328         /* Set seek pointer back to the beginning of the picture */
1329         move.QuadPart = 0;
1330         hr = IStream_Seek(stream, move, STREAM_SEEK_SET, NULL);
1331         if (FAILED(hr))
1332             goto out;
1333
1334         stat = GdipLoadImageFromStream(stream, cloneImage);
1335         if (stat != Ok) WARN("Failed to load image from stream\n");
1336
1337     out:
1338         IStream_Release(stream);
1339         return stat;
1340     }
1341     else if (image->type == ImageTypeBitmap)
1342     {
1343         GpBitmap *bitmap = (GpBitmap*)image;
1344         BitmapData lockeddata_src, lockeddata_dst;
1345         int i;
1346         UINT row_size;
1347
1348         stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format,
1349             &lockeddata_src);
1350         if (stat != Ok) return stat;
1351
1352         stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
1353             0, lockeddata_src.PixelFormat, NULL, (GpBitmap**)cloneImage);
1354         if (stat == Ok)
1355         {
1356             stat = GdipBitmapLockBits((GpBitmap*)*cloneImage, NULL, ImageLockModeWrite,
1357                 lockeddata_src.PixelFormat, &lockeddata_dst);
1358
1359             if (stat == Ok)
1360             {
1361                 /* copy the image data */
1362                 row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
1363                 for (i=0; i<lockeddata_src.Height; i++)
1364                     memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
1365                            (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
1366                            row_size);
1367
1368                 GdipBitmapUnlockBits((GpBitmap*)*cloneImage, &lockeddata_dst);
1369             }
1370
1371             if (stat != Ok)
1372                 GdipDisposeImage(*cloneImage);
1373         }
1374
1375         GdipBitmapUnlockBits(bitmap, &lockeddata_src);
1376
1377         if (stat != Ok)
1378         {
1379             *cloneImage = NULL;
1380         }
1381         else memcpy(&(*cloneImage)->format, &image->format, sizeof(GUID));
1382
1383         return stat;
1384     }
1385     else
1386     {
1387         ERR("GpImage with no IPicture or bitmap?!\n");
1388         return NotImplemented;
1389     }
1390 }
1391
1392 GpStatus WINGDIPAPI GdipCreateBitmapFromFile(GDIPCONST WCHAR* filename,
1393     GpBitmap **bitmap)
1394 {
1395     GpStatus stat;
1396     IStream *stream;
1397
1398     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
1399
1400     if(!filename || !bitmap)
1401         return InvalidParameter;
1402
1403     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
1404
1405     if(stat != Ok)
1406         return stat;
1407
1408     stat = GdipCreateBitmapFromStream(stream, bitmap);
1409
1410     IStream_Release(stream);
1411
1412     return stat;
1413 }
1414
1415 GpStatus WINGDIPAPI GdipCreateBitmapFromGdiDib(GDIPCONST BITMAPINFO* info,
1416                                                VOID *bits, GpBitmap **bitmap)
1417 {
1418     DWORD height, stride;
1419     PixelFormat format;
1420
1421     FIXME("(%p, %p, %p) - partially implemented\n", info, bits, bitmap);
1422
1423     if (!info || !bits || !bitmap)
1424         return InvalidParameter;
1425
1426     height = abs(info->bmiHeader.biHeight);
1427     stride = ((info->bmiHeader.biWidth * info->bmiHeader.biBitCount + 31) >> 3) & ~3;
1428
1429     if(info->bmiHeader.biHeight > 0) /* bottom-up */
1430     {
1431         bits = (BYTE*)bits + (height - 1) * stride;
1432         stride = -stride;
1433     }
1434
1435     switch(info->bmiHeader.biBitCount) {
1436     case 1:
1437         format = PixelFormat1bppIndexed;
1438         break;
1439     case 4:
1440         format = PixelFormat4bppIndexed;
1441         break;
1442     case 8:
1443         format = PixelFormat8bppIndexed;
1444         break;
1445     case 16:
1446         format = PixelFormat16bppRGB555;
1447         break;
1448     case 24:
1449         format = PixelFormat24bppRGB;
1450         break;
1451     case 32:
1452         format = PixelFormat32bppRGB;
1453         break;
1454     default:
1455         FIXME("don't know how to handle %d bpp\n", info->bmiHeader.biBitCount);
1456         *bitmap = NULL;
1457         return InvalidParameter;
1458     }
1459
1460     return GdipCreateBitmapFromScan0(info->bmiHeader.biWidth, height, stride, format,
1461                                      bits, bitmap);
1462
1463 }
1464
1465 /* FIXME: no icm */
1466 GpStatus WINGDIPAPI GdipCreateBitmapFromFileICM(GDIPCONST WCHAR* filename,
1467     GpBitmap **bitmap)
1468 {
1469     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
1470
1471     return GdipCreateBitmapFromFile(filename, bitmap);
1472 }
1473
1474 GpStatus WINGDIPAPI GdipCreateBitmapFromResource(HINSTANCE hInstance,
1475     GDIPCONST WCHAR* lpBitmapName, GpBitmap** bitmap)
1476 {
1477     HBITMAP hbm;
1478     GpStatus stat = InvalidParameter;
1479
1480     TRACE("%p (%s) %p\n", hInstance, debugstr_w(lpBitmapName), bitmap);
1481
1482     if(!lpBitmapName || !bitmap)
1483         return InvalidParameter;
1484
1485     /* load DIB */
1486     hbm = LoadImageW(hInstance, lpBitmapName, IMAGE_BITMAP, 0, 0,
1487                      LR_CREATEDIBSECTION);
1488
1489     if(hbm){
1490         stat = GdipCreateBitmapFromHBITMAP(hbm, NULL, bitmap);
1491         DeleteObject(hbm);
1492     }
1493
1494     return stat;
1495 }
1496
1497 GpStatus WINGDIPAPI GdipCreateHBITMAPFromBitmap(GpBitmap* bitmap,
1498     HBITMAP* hbmReturn, ARGB background)
1499 {
1500     GpStatus stat;
1501     HBITMAP result;
1502     UINT width, height;
1503     BITMAPINFOHEADER bih;
1504     LPBYTE bits;
1505     BitmapData lockeddata;
1506     TRACE("(%p,%p,%x)\n", bitmap, hbmReturn, background);
1507
1508     if (!bitmap || !hbmReturn) return InvalidParameter;
1509
1510     GdipGetImageWidth((GpImage*)bitmap, &width);
1511     GdipGetImageHeight((GpImage*)bitmap, &height);
1512
1513     bih.biSize = sizeof(bih);
1514     bih.biWidth = width;
1515     bih.biHeight = height;
1516     bih.biPlanes = 1;
1517     bih.biBitCount = 32;
1518     bih.biCompression = BI_RGB;
1519     bih.biSizeImage = 0;
1520     bih.biXPelsPerMeter = 0;
1521     bih.biYPelsPerMeter = 0;
1522     bih.biClrUsed = 0;
1523     bih.biClrImportant = 0;
1524
1525     result = CreateDIBSection(0, (BITMAPINFO*)&bih, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
1526
1527     if (result)
1528     {
1529         lockeddata.Stride = -width * 4;
1530         lockeddata.Scan0 = bits + (width * 4 * (height - 1));
1531
1532         stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead|ImageLockModeUserInputBuf,
1533             PixelFormat32bppPARGB, &lockeddata);
1534
1535         if (stat == Ok)
1536             stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
1537     }
1538     else
1539         stat = GenericError;
1540
1541     if (stat != Ok && result)
1542     {
1543         DeleteObject(result);
1544         result = NULL;
1545     }
1546
1547     *hbmReturn = result;
1548
1549     return stat;
1550 }
1551
1552 GpStatus WINGDIPAPI GdipConvertToEmfPlus(const GpGraphics* ref,
1553     GpMetafile* metafile, BOOL* succ, EmfType emfType,
1554     const WCHAR* description, GpMetafile** out_metafile)
1555 {
1556     static int calls;
1557
1558     TRACE("(%p,%p,%p,%u,%s,%p)\n", ref, metafile, succ, emfType,
1559         debugstr_w(description), out_metafile);
1560
1561     if(!ref || !metafile || !out_metafile)
1562         return InvalidParameter;
1563
1564     *succ = FALSE;
1565     *out_metafile = NULL;
1566
1567     if(!(calls++))
1568         FIXME("not implemented\n");
1569
1570     return NotImplemented;
1571 }
1572
1573 /* FIXME: this should create a bitmap in the given size with the attributes
1574  * (resolution etc.) of the graphics object */
1575 GpStatus WINGDIPAPI GdipCreateBitmapFromGraphics(INT width, INT height,
1576     GpGraphics* target, GpBitmap** bitmap)
1577 {
1578     static int calls;
1579     GpStatus ret;
1580
1581     TRACE("(%d, %d, %p, %p)\n", width, height, target, bitmap);
1582
1583     if(!target || !bitmap)
1584         return InvalidParameter;
1585
1586     if(!(calls++))
1587         FIXME("hacked stub\n");
1588
1589     ret = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat24bppRGB,
1590                                     NULL, bitmap);
1591
1592     return ret;
1593 }
1594
1595 GpStatus WINGDIPAPI GdipCreateBitmapFromHICON(HICON hicon, GpBitmap** bitmap)
1596 {
1597     GpStatus stat;
1598     ICONINFO iinfo;
1599     BITMAP bm;
1600     int ret;
1601     UINT width, height;
1602     GpRect rect;
1603     BitmapData lockeddata;
1604     HDC screendc;
1605     BOOL has_alpha;
1606     int x, y;
1607     BYTE *bits;
1608     BITMAPINFOHEADER bih;
1609     DWORD *src;
1610     BYTE *dst_row;
1611     DWORD *dst;
1612
1613     TRACE("%p, %p\n", hicon, bitmap);
1614
1615     if(!bitmap || !GetIconInfo(hicon, &iinfo))
1616         return InvalidParameter;
1617
1618     /* get the size of the icon */
1619     ret = GetObjectA(iinfo.hbmColor ? iinfo.hbmColor : iinfo.hbmMask, sizeof(bm), &bm);
1620     if (ret == 0) {
1621         DeleteObject(iinfo.hbmColor);
1622         DeleteObject(iinfo.hbmMask);
1623         return GenericError;
1624     }
1625
1626     width = bm.bmWidth;
1627
1628     if (iinfo.hbmColor)
1629         height = abs(bm.bmHeight);
1630     else /* combined bitmap + mask */
1631         height = abs(bm.bmHeight) / 2;
1632
1633     bits = HeapAlloc(GetProcessHeap(), 0, 4*width*height);
1634     if (!bits) {
1635         DeleteObject(iinfo.hbmColor);
1636         DeleteObject(iinfo.hbmMask);
1637         return OutOfMemory;
1638     }
1639
1640     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppARGB, NULL, bitmap);
1641     if (stat != Ok) {
1642         DeleteObject(iinfo.hbmColor);
1643         DeleteObject(iinfo.hbmMask);
1644         HeapFree(GetProcessHeap(), 0, bits);
1645         return stat;
1646     }
1647
1648     rect.X = 0;
1649     rect.Y = 0;
1650     rect.Width = width;
1651     rect.Height = height;
1652
1653     stat = GdipBitmapLockBits(*bitmap, &rect, ImageLockModeWrite, PixelFormat32bppARGB, &lockeddata);
1654     if (stat != Ok) {
1655         DeleteObject(iinfo.hbmColor);
1656         DeleteObject(iinfo.hbmMask);
1657         HeapFree(GetProcessHeap(), 0, bits);
1658         GdipDisposeImage((GpImage*)*bitmap);
1659         return stat;
1660     }
1661
1662     bih.biSize = sizeof(bih);
1663     bih.biWidth = width;
1664     bih.biHeight = -height;
1665     bih.biPlanes = 1;
1666     bih.biBitCount = 32;
1667     bih.biCompression = BI_RGB;
1668     bih.biSizeImage = 0;
1669     bih.biXPelsPerMeter = 0;
1670     bih.biYPelsPerMeter = 0;
1671     bih.biClrUsed = 0;
1672     bih.biClrImportant = 0;
1673
1674     screendc = GetDC(0);
1675     if (iinfo.hbmColor)
1676     {
1677         GetDIBits(screendc, iinfo.hbmColor, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1678
1679         if (bm.bmBitsPixel == 32)
1680         {
1681             has_alpha = FALSE;
1682
1683             /* If any pixel has a non-zero alpha, ignore hbmMask */
1684             src = (DWORD*)bits;
1685             for (x=0; x<width && !has_alpha; x++)
1686                 for (y=0; y<height && !has_alpha; y++)
1687                     if ((*src++ & 0xff000000) != 0)
1688                         has_alpha = TRUE;
1689         }
1690         else has_alpha = FALSE;
1691     }
1692     else
1693     {
1694         GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1695         has_alpha = FALSE;
1696     }
1697
1698     /* copy the image data to the Bitmap */
1699     src = (DWORD*)bits;
1700     dst_row = lockeddata.Scan0;
1701     for (y=0; y<height; y++)
1702     {
1703         memcpy(dst_row, src, width*4);
1704         src += width;
1705         dst_row += lockeddata.Stride;
1706     }
1707
1708     if (!has_alpha)
1709     {
1710         if (iinfo.hbmMask)
1711         {
1712             /* read alpha data from the mask */
1713             if (iinfo.hbmColor)
1714                 GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1715             else
1716                 GetDIBits(screendc, iinfo.hbmMask, height, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1717
1718             src = (DWORD*)bits;
1719             dst_row = lockeddata.Scan0;
1720             for (y=0; y<height; y++)
1721             {
1722                 dst = (DWORD*)dst_row;
1723                 for (x=0; x<height; x++)
1724                 {
1725                     DWORD src_value = *src++;
1726                     if (src_value)
1727                         *dst++ = 0;
1728                     else
1729                         *dst++ |= 0xff000000;
1730                 }
1731                 dst_row += lockeddata.Stride;
1732             }
1733         }
1734         else
1735         {
1736             /* set constant alpha of 255 */
1737             dst_row = bits;
1738             for (y=0; y<height; y++)
1739             {
1740                 dst = (DWORD*)dst_row;
1741                 for (x=0; x<height; x++)
1742                     *dst++ |= 0xff000000;
1743                 dst_row += lockeddata.Stride;
1744             }
1745         }
1746     }
1747
1748     ReleaseDC(0, screendc);
1749
1750     DeleteObject(iinfo.hbmColor);
1751     DeleteObject(iinfo.hbmMask);
1752
1753     GdipBitmapUnlockBits(*bitmap, &lockeddata);
1754
1755     HeapFree(GetProcessHeap(), 0, bits);
1756
1757     return Ok;
1758 }
1759
1760 static void generate_halftone_palette(ARGB *entries, UINT count)
1761 {
1762     static const BYTE halftone_values[6]={0x00,0x33,0x66,0x99,0xcc,0xff};
1763     UINT i;
1764
1765     for (i=0; i<8 && i<count; i++)
1766     {
1767         entries[i] = 0xff000000;
1768         if (i&1) entries[i] |= 0x800000;
1769         if (i&2) entries[i] |= 0x8000;
1770         if (i&4) entries[i] |= 0x80;
1771     }
1772
1773     if (8 < count)
1774         entries[i] = 0xffc0c0c0;
1775
1776     for (i=9; i<16 && i<count; i++)
1777     {
1778         entries[i] = 0xff000000;
1779         if (i&1) entries[i] |= 0xff0000;
1780         if (i&2) entries[i] |= 0xff00;
1781         if (i&4) entries[i] |= 0xff;
1782     }
1783
1784     for (i=16; i<40 && i<count; i++)
1785     {
1786         entries[i] = 0;
1787     }
1788
1789     for (i=40; i<256 && i<count; i++)
1790     {
1791         entries[i] = 0xff000000;
1792         entries[i] |= halftone_values[(i-40)%6];
1793         entries[i] |= halftone_values[((i-40)/6)%6] << 8;
1794         entries[i] |= halftone_values[((i-40)/36)%6] << 16;
1795     }
1796 }
1797
1798 static GpStatus get_screen_resolution(REAL *xres, REAL *yres)
1799 {
1800     HDC screendc = GetDC(0);
1801
1802     if (!screendc) return GenericError;
1803
1804     *xres = (REAL)GetDeviceCaps(screendc, LOGPIXELSX);
1805     *yres = (REAL)GetDeviceCaps(screendc, LOGPIXELSY);
1806
1807     ReleaseDC(0, screendc);
1808
1809     return Ok;
1810 }
1811
1812 GpStatus WINGDIPAPI GdipCreateBitmapFromScan0(INT width, INT height, INT stride,
1813     PixelFormat format, BYTE* scan0, GpBitmap** bitmap)
1814 {
1815     BITMAPINFO* pbmi;
1816     HBITMAP hbitmap=NULL;
1817     INT row_size, dib_stride;
1818     BYTE *bits=NULL, *own_bits=NULL;
1819     REAL xres, yres;
1820     GpStatus stat;
1821
1822     TRACE("%d %d %d 0x%x %p %p\n", width, height, stride, format, scan0, bitmap);
1823
1824     if (!bitmap) return InvalidParameter;
1825
1826     if(width <= 0 || height <= 0 || (scan0 && (stride % 4))){
1827         *bitmap = NULL;
1828         return InvalidParameter;
1829     }
1830
1831     if(scan0 && !stride)
1832         return InvalidParameter;
1833
1834     stat = get_screen_resolution(&xres, &yres);
1835     if (stat != Ok) return stat;
1836
1837     row_size = (width * PIXELFORMATBPP(format)+7) / 8;
1838     dib_stride = (row_size + 3) & ~3;
1839
1840     if(stride == 0)
1841         stride = dib_stride;
1842
1843     if (format & PixelFormatGDI && !(format & (PixelFormatAlpha|PixelFormatIndexed)) && !scan0)
1844     {
1845         pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
1846         if (!pbmi)
1847             return OutOfMemory;
1848
1849         pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1850         pbmi->bmiHeader.biWidth = width;
1851         pbmi->bmiHeader.biHeight = -height;
1852         pbmi->bmiHeader.biPlanes = 1;
1853         /* FIXME: use the rest of the data from format */
1854         pbmi->bmiHeader.biBitCount = PIXELFORMATBPP(format);
1855         pbmi->bmiHeader.biCompression = BI_RGB;
1856         pbmi->bmiHeader.biSizeImage = 0;
1857         pbmi->bmiHeader.biXPelsPerMeter = 0;
1858         pbmi->bmiHeader.biYPelsPerMeter = 0;
1859         pbmi->bmiHeader.biClrUsed = 0;
1860         pbmi->bmiHeader.biClrImportant = 0;
1861
1862         hbitmap = CreateDIBSection(0, pbmi, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
1863
1864         GdipFree(pbmi);
1865
1866         if (!hbitmap) return GenericError;
1867
1868         stride = dib_stride;
1869     }
1870     else
1871     {
1872         /* Not a GDI format; don't try to make an HBITMAP. */
1873         if (scan0)
1874             bits = scan0;
1875         else
1876         {
1877             INT size = abs(stride) * height;
1878
1879             own_bits = bits = GdipAlloc(size);
1880             if (!own_bits) return OutOfMemory;
1881
1882             if (stride < 0)
1883                 bits += stride * (1 - height);
1884         }
1885     }
1886
1887     *bitmap = GdipAlloc(sizeof(GpBitmap));
1888     if(!*bitmap)
1889     {
1890         DeleteObject(hbitmap);
1891         GdipFree(own_bits);
1892         return OutOfMemory;
1893     }
1894
1895     (*bitmap)->image.type = ImageTypeBitmap;
1896     memcpy(&(*bitmap)->image.format, &ImageFormatMemoryBMP, sizeof(GUID));
1897     (*bitmap)->image.flags = ImageFlagsNone;
1898     (*bitmap)->image.frame_count = 1;
1899     (*bitmap)->image.current_frame = 0;
1900     (*bitmap)->image.palette = NULL;
1901     (*bitmap)->image.xres = xres;
1902     (*bitmap)->image.yres = yres;
1903     (*bitmap)->width = width;
1904     (*bitmap)->height = height;
1905     (*bitmap)->format = format;
1906     (*bitmap)->image.picture = NULL;
1907     (*bitmap)->image.stream = NULL;
1908     (*bitmap)->hbitmap = hbitmap;
1909     (*bitmap)->hdc = NULL;
1910     (*bitmap)->bits = bits;
1911     (*bitmap)->stride = stride;
1912     (*bitmap)->own_bits = own_bits;
1913     (*bitmap)->metadata_reader = NULL;
1914
1915     /* set format-related flags */
1916     if (format & (PixelFormatAlpha|PixelFormatPAlpha|PixelFormatIndexed))
1917         (*bitmap)->image.flags |= ImageFlagsHasAlpha;
1918
1919     if (format == PixelFormat1bppIndexed ||
1920         format == PixelFormat4bppIndexed ||
1921         format == PixelFormat8bppIndexed)
1922     {
1923         (*bitmap)->image.palette = GdipAlloc(sizeof(UINT) * 2 + sizeof(ARGB) * (1 << PIXELFORMATBPP(format)));
1924
1925         if (!(*bitmap)->image.palette)
1926         {
1927             GdipDisposeImage(&(*bitmap)->image);
1928             *bitmap = NULL;
1929             return OutOfMemory;
1930         }
1931
1932         (*bitmap)->image.palette->Count = 1 << PIXELFORMATBPP(format);
1933
1934         if (format == PixelFormat1bppIndexed)
1935         {
1936             (*bitmap)->image.palette->Flags = PaletteFlagsGrayScale;
1937             (*bitmap)->image.palette->Entries[0] = 0xff000000;
1938             (*bitmap)->image.palette->Entries[1] = 0xffffffff;
1939         }
1940         else
1941         {
1942             if (format == PixelFormat8bppIndexed)
1943                 (*bitmap)->image.palette->Flags = PaletteFlagsHalftone;
1944
1945             generate_halftone_palette((*bitmap)->image.palette->Entries,
1946                 (*bitmap)->image.palette->Count);
1947         }
1948     }
1949
1950     TRACE("<-- %p\n", *bitmap);
1951
1952     return Ok;
1953 }
1954
1955 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
1956     GpBitmap **bitmap)
1957 {
1958     GpStatus stat;
1959
1960     TRACE("%p %p\n", stream, bitmap);
1961
1962     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
1963
1964     if(stat != Ok)
1965         return stat;
1966
1967     if((*bitmap)->image.type != ImageTypeBitmap){
1968         GdipDisposeImage(&(*bitmap)->image);
1969         *bitmap = NULL;
1970         return GenericError; /* FIXME: what error to return? */
1971     }
1972
1973     return Ok;
1974 }
1975
1976 /* FIXME: no icm */
1977 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
1978     GpBitmap **bitmap)
1979 {
1980     TRACE("%p %p\n", stream, bitmap);
1981
1982     return GdipCreateBitmapFromStream(stream, bitmap);
1983 }
1984
1985 GpStatus WINGDIPAPI GdipCreateCachedBitmap(GpBitmap *bitmap, GpGraphics *graphics,
1986     GpCachedBitmap **cachedbmp)
1987 {
1988     GpStatus stat;
1989
1990     TRACE("%p %p %p\n", bitmap, graphics, cachedbmp);
1991
1992     if(!bitmap || !graphics || !cachedbmp)
1993         return InvalidParameter;
1994
1995     *cachedbmp = GdipAlloc(sizeof(GpCachedBitmap));
1996     if(!*cachedbmp)
1997         return OutOfMemory;
1998
1999     stat = GdipCloneImage(&(bitmap->image), &(*cachedbmp)->image);
2000     if(stat != Ok){
2001         GdipFree(*cachedbmp);
2002         return stat;
2003     }
2004
2005     return Ok;
2006 }
2007
2008 GpStatus WINGDIPAPI GdipCreateHICONFromBitmap(GpBitmap *bitmap, HICON *hicon)
2009 {
2010     GpStatus stat;
2011     BitmapData lockeddata;
2012     ULONG andstride, xorstride, bitssize;
2013     LPBYTE andbits, xorbits, androw, xorrow, srcrow;
2014     UINT x, y;
2015
2016     TRACE("(%p, %p)\n", bitmap, hicon);
2017
2018     if (!bitmap || !hicon)
2019         return InvalidParameter;
2020
2021     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead,
2022         PixelFormat32bppPARGB, &lockeddata);
2023     if (stat == Ok)
2024     {
2025         andstride = ((lockeddata.Width+31)/32)*4;
2026         xorstride = lockeddata.Width*4;
2027         bitssize = (andstride + xorstride) * lockeddata.Height;
2028
2029         andbits = GdipAlloc(bitssize);
2030
2031         if (andbits)
2032         {
2033             xorbits = andbits + andstride * lockeddata.Height;
2034
2035             for (y=0; y<lockeddata.Height; y++)
2036             {
2037                 srcrow = ((LPBYTE)lockeddata.Scan0) + lockeddata.Stride * y;
2038
2039                 androw = andbits + andstride * y;
2040                 for (x=0; x<lockeddata.Width; x++)
2041                     if (srcrow[3+4*x] >= 128)
2042                         androw[x/8] |= 1 << (7-x%8);
2043
2044                 xorrow = xorbits + xorstride * y;
2045                 memcpy(xorrow, srcrow, xorstride);
2046             }
2047
2048             *hicon = CreateIcon(NULL, lockeddata.Width, lockeddata.Height, 1, 32,
2049                 andbits, xorbits);
2050
2051             GdipFree(andbits);
2052         }
2053         else
2054             stat = OutOfMemory;
2055
2056         GdipBitmapUnlockBits(bitmap, &lockeddata);
2057     }
2058
2059     return stat;
2060 }
2061
2062 GpStatus WINGDIPAPI GdipDeleteCachedBitmap(GpCachedBitmap *cachedbmp)
2063 {
2064     TRACE("%p\n", cachedbmp);
2065
2066     if(!cachedbmp)
2067         return InvalidParameter;
2068
2069     GdipDisposeImage(cachedbmp->image);
2070     GdipFree(cachedbmp);
2071
2072     return Ok;
2073 }
2074
2075 GpStatus WINGDIPAPI GdipDrawCachedBitmap(GpGraphics *graphics,
2076     GpCachedBitmap *cachedbmp, INT x, INT y)
2077 {
2078     TRACE("%p %p %d %d\n", graphics, cachedbmp, x, y);
2079
2080     if(!graphics || !cachedbmp)
2081         return InvalidParameter;
2082
2083     return GdipDrawImage(graphics, cachedbmp->image, (REAL)x, (REAL)y);
2084 }
2085
2086 GpStatus WINGDIPAPI GdipEmfToWmfBits(HENHMETAFILE hemf, UINT cbData16,
2087     LPBYTE pData16, INT iMapMode, INT eFlags)
2088 {
2089     FIXME("(%p, %d, %p, %d, %d): stub\n", hemf, cbData16, pData16, iMapMode, eFlags);
2090     return NotImplemented;
2091 }
2092
2093 /* Internal utility function: Replace the image data of dst with that of src,
2094  * and free src. */
2095 static void move_bitmap(GpBitmap *dst, GpBitmap *src, BOOL clobber_palette)
2096 {
2097     assert(src->image.type == ImageTypeBitmap);
2098     assert(dst->image.type == ImageTypeBitmap);
2099
2100     GdipFree(dst->bitmapbits);
2101     GdipFree(dst->own_bits);
2102     DeleteDC(dst->hdc);
2103     DeleteObject(dst->hbitmap);
2104
2105     if (clobber_palette)
2106     {
2107         GdipFree(dst->image.palette);
2108         dst->image.palette = src->image.palette;
2109     }
2110     else
2111         GdipFree(src->image.palette);
2112
2113     dst->image.xres = src->image.xres;
2114     dst->image.yres = src->image.yres;
2115     dst->width = src->width;
2116     dst->height = src->height;
2117     dst->format = src->format;
2118     dst->hbitmap = src->hbitmap;
2119     dst->hdc = src->hdc;
2120     dst->bits = src->bits;
2121     dst->stride = src->stride;
2122     dst->own_bits = src->own_bits;
2123     if (dst->metadata_reader)
2124         IWICMetadataReader_Release(dst->metadata_reader);
2125     dst->metadata_reader = src->metadata_reader;
2126     if (dst->image.stream)
2127         IStream_Release(dst->image.stream);
2128     dst->image.stream = src->image.stream;
2129     dst->image.frame_count = src->image.frame_count;
2130     dst->image.current_frame = src->image.current_frame;
2131     dst->image.format = src->image.format;
2132
2133     src->image.type = ~0;
2134     GdipFree(src);
2135 }
2136
2137 static GpStatus free_image_data(GpImage *image)
2138 {
2139     if(!image)
2140         return InvalidParameter;
2141
2142     if (image->type == ImageTypeBitmap)
2143     {
2144         GdipFree(((GpBitmap*)image)->bitmapbits);
2145         GdipFree(((GpBitmap*)image)->own_bits);
2146         DeleteDC(((GpBitmap*)image)->hdc);
2147         DeleteObject(((GpBitmap*)image)->hbitmap);
2148         if (((GpBitmap*)image)->metadata_reader)
2149             IWICMetadataReader_Release(((GpBitmap*)image)->metadata_reader);
2150     }
2151     else if (image->type == ImageTypeMetafile)
2152     {
2153         GpMetafile *metafile = (GpMetafile*)image;
2154         GdipFree(metafile->comment_data);
2155         DeleteEnhMetaFile(CloseEnhMetaFile(metafile->record_dc));
2156         DeleteEnhMetaFile(metafile->hemf);
2157         if (metafile->record_graphics)
2158         {
2159             WARN("metafile closed while recording\n");
2160             /* not sure what to do here; for now just prevent the graphics from functioning or using this object */
2161             metafile->record_graphics->image = NULL;
2162             metafile->record_graphics->busy = TRUE;
2163         }
2164     }
2165     else
2166     {
2167         WARN("invalid image: %p\n", image);
2168         return ObjectBusy;
2169     }
2170     if (image->picture)
2171         IPicture_Release(image->picture);
2172     if (image->stream)
2173         IStream_Release(image->stream);
2174     GdipFree(image->palette);
2175
2176     return Ok;
2177 }
2178
2179 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
2180 {
2181     GpStatus status;
2182
2183     TRACE("%p\n", image);
2184
2185     status = free_image_data(image);
2186     if (status != Ok) return status;
2187     image->type = ~0;
2188     GdipFree(image);
2189
2190     return Ok;
2191 }
2192
2193 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
2194 {
2195     static int calls;
2196
2197     TRACE("(%p,%p)\n", image, item);
2198
2199     if(!image || !item)
2200         return InvalidParameter;
2201
2202     if (!(calls++))
2203         FIXME("not implemented\n");
2204
2205     return NotImplemented;
2206 }
2207
2208 GpStatus WINGDIPAPI GdipGetImageItemData(GpImage *image, ImageItemData *item)
2209 {
2210     static int calls;
2211
2212     TRACE("(%p,%p)\n", image, item);
2213
2214     if (!(calls++))
2215         FIXME("not implemented\n");
2216
2217     return NotImplemented;
2218 }
2219
2220 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
2221     GpUnit *srcUnit)
2222 {
2223     TRACE("%p %p %p\n", image, srcRect, srcUnit);
2224
2225     if(!image || !srcRect || !srcUnit)
2226         return InvalidParameter;
2227     if(image->type == ImageTypeMetafile){
2228         *srcRect = ((GpMetafile*)image)->bounds;
2229         *srcUnit = ((GpMetafile*)image)->unit;
2230     }
2231     else if(image->type == ImageTypeBitmap){
2232         srcRect->X = srcRect->Y = 0.0;
2233         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
2234         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
2235         *srcUnit = UnitPixel;
2236     }
2237     else{
2238         srcRect->X = srcRect->Y = 0.0;
2239         srcRect->Width = ipicture_pixel_width(image->picture);
2240         srcRect->Height = ipicture_pixel_height(image->picture);
2241         *srcUnit = UnitPixel;
2242     }
2243
2244     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
2245           srcRect->Width, srcRect->Height, *srcUnit);
2246
2247     return Ok;
2248 }
2249
2250 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
2251     REAL *height)
2252 {
2253     TRACE("%p %p %p\n", image, width, height);
2254
2255     if(!image || !height || !width)
2256         return InvalidParameter;
2257
2258     if(image->type == ImageTypeMetafile){
2259         HDC hdc = GetDC(0);
2260         REAL res = (REAL)GetDeviceCaps(hdc, LOGPIXELSX);
2261
2262         ReleaseDC(0, hdc);
2263
2264         *height = convert_unit(res, ((GpMetafile*)image)->unit) *
2265                         ((GpMetafile*)image)->bounds.Height;
2266
2267         *width = convert_unit(res, ((GpMetafile*)image)->unit) *
2268                         ((GpMetafile*)image)->bounds.Width;
2269     }
2270
2271     else if(image->type == ImageTypeBitmap){
2272         *height = ((GpBitmap*)image)->height;
2273         *width = ((GpBitmap*)image)->width;
2274     }
2275     else{
2276         *height = ipicture_pixel_height(image->picture);
2277         *width = ipicture_pixel_width(image->picture);
2278     }
2279
2280     TRACE("returning (%f, %f)\n", *height, *width);
2281     return Ok;
2282 }
2283
2284 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
2285     GpGraphics **graphics)
2286 {
2287     HDC hdc;
2288     GpStatus stat;
2289
2290     TRACE("%p %p\n", image, graphics);
2291
2292     if(!image || !graphics)
2293         return InvalidParameter;
2294
2295     if (image->type == ImageTypeBitmap && ((GpBitmap*)image)->hbitmap)
2296     {
2297         hdc = ((GpBitmap*)image)->hdc;
2298
2299         if(!hdc){
2300             hdc = CreateCompatibleDC(0);
2301             SelectObject(hdc, ((GpBitmap*)image)->hbitmap);
2302             ((GpBitmap*)image)->hdc = hdc;
2303         }
2304
2305         stat = GdipCreateFromHDC(hdc, graphics);
2306
2307         if (stat == Ok)
2308         {
2309             (*graphics)->image = image;
2310             (*graphics)->xres = image->xres;
2311             (*graphics)->yres = image->yres;
2312         }
2313     }
2314     else if (image->type == ImageTypeMetafile)
2315         stat = METAFILE_GetGraphicsContext((GpMetafile*)image, graphics);
2316     else
2317         stat = graphics_from_image(image, graphics);
2318
2319     return stat;
2320 }
2321
2322 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
2323 {
2324     TRACE("%p %p\n", image, height);
2325
2326     if(!image || !height)
2327         return InvalidParameter;
2328
2329     if(image->type == ImageTypeMetafile){
2330         HDC hdc = GetDC(0);
2331         REAL res = (REAL)GetDeviceCaps(hdc, LOGPIXELSX);
2332
2333         ReleaseDC(0, hdc);
2334
2335         *height = roundr(convert_unit(res, ((GpMetafile*)image)->unit) *
2336                         ((GpMetafile*)image)->bounds.Height);
2337     }
2338     else if(image->type == ImageTypeBitmap)
2339         *height = ((GpBitmap*)image)->height;
2340     else
2341         *height = ipicture_pixel_height(image->picture);
2342
2343     TRACE("returning %d\n", *height);
2344
2345     return Ok;
2346 }
2347
2348 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
2349 {
2350     if(!image || !res)
2351         return InvalidParameter;
2352
2353     *res = image->xres;
2354
2355     TRACE("(%p) <-- %0.2f\n", image, *res);
2356
2357     return Ok;
2358 }
2359
2360 GpStatus WINGDIPAPI GdipGetImagePaletteSize(GpImage *image, INT *size)
2361 {
2362     TRACE("%p %p\n", image, size);
2363
2364     if(!image || !size)
2365         return InvalidParameter;
2366
2367     if (!image->palette || image->palette->Count == 0)
2368         *size = sizeof(ColorPalette);
2369     else
2370         *size = sizeof(UINT)*2 + sizeof(ARGB)*image->palette->Count;
2371
2372     TRACE("<-- %u\n", *size);
2373
2374     return Ok;
2375 }
2376
2377 /* FIXME: test this function for non-bitmap types */
2378 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
2379 {
2380     TRACE("%p %p\n", image, format);
2381
2382     if(!image || !format)
2383         return InvalidParameter;
2384
2385     if(image->type != ImageTypeBitmap)
2386         *format = PixelFormat24bppRGB;
2387     else
2388         *format = ((GpBitmap*) image)->format;
2389
2390     return Ok;
2391 }
2392
2393 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
2394 {
2395     TRACE("(%p, %p)\n", image, format);
2396
2397     if(!image || !format)
2398         return InvalidParameter;
2399
2400     memcpy(format, &image->format, sizeof(GUID));
2401
2402     return Ok;
2403 }
2404
2405 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
2406 {
2407     TRACE("%p %p\n", image, type);
2408
2409     if(!image || !type)
2410         return InvalidParameter;
2411
2412     *type = image->type;
2413
2414     return Ok;
2415 }
2416
2417 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
2418 {
2419     if(!image || !res)
2420         return InvalidParameter;
2421
2422     *res = image->yres;
2423
2424     TRACE("(%p) <-- %0.2f\n", image, *res);
2425
2426     return Ok;
2427 }
2428
2429 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
2430 {
2431     TRACE("%p %p\n", image, width);
2432
2433     if(!image || !width)
2434         return InvalidParameter;
2435
2436     if(image->type == ImageTypeMetafile){
2437         HDC hdc = GetDC(0);
2438         REAL res = (REAL)GetDeviceCaps(hdc, LOGPIXELSX);
2439
2440         ReleaseDC(0, hdc);
2441
2442         *width = roundr(convert_unit(res, ((GpMetafile*)image)->unit) *
2443                         ((GpMetafile*)image)->bounds.Width);
2444     }
2445     else if(image->type == ImageTypeBitmap)
2446         *width = ((GpBitmap*)image)->width;
2447     else
2448         *width = ipicture_pixel_width(image->picture);
2449
2450     TRACE("returning %d\n", *width);
2451
2452     return Ok;
2453 }
2454
2455 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
2456     MetafileHeader * header)
2457 {
2458     static int calls;
2459
2460     TRACE("(%p, %p)\n", metafile, header);
2461
2462     if(!metafile || !header)
2463         return InvalidParameter;
2464
2465     if(!(calls++))
2466         FIXME("not implemented\n");
2467
2468     memset(header, 0, sizeof(MetafileHeader));
2469
2470     return Ok;
2471 }
2472
2473 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromEmf(HENHMETAFILE hEmf,
2474     MetafileHeader *header)
2475 {
2476     static int calls;
2477
2478     if(!hEmf || !header)
2479         return InvalidParameter;
2480
2481     if(!(calls++))
2482         FIXME("not implemented\n");
2483
2484     memset(header, 0, sizeof(MetafileHeader));
2485
2486     return Ok;
2487 }
2488
2489 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromFile(GDIPCONST WCHAR *filename,
2490     MetafileHeader *header)
2491 {
2492     static int calls;
2493
2494     TRACE("(%s,%p)\n", debugstr_w(filename), header);
2495
2496     if(!filename || !header)
2497         return InvalidParameter;
2498
2499     if(!(calls++))
2500         FIXME("not implemented\n");
2501
2502     memset(header, 0, sizeof(MetafileHeader));
2503
2504     return Ok;
2505 }
2506
2507 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromStream(IStream *stream,
2508     MetafileHeader *header)
2509 {
2510     static int calls;
2511
2512     TRACE("(%p,%p)\n", stream, header);
2513
2514     if(!stream || !header)
2515         return InvalidParameter;
2516
2517     if(!(calls++))
2518         FIXME("not implemented\n");
2519
2520     memset(header, 0, sizeof(MetafileHeader));
2521
2522     return Ok;
2523 }
2524
2525 GpStatus WINGDIPAPI GdipGetPropertyCount(GpImage *image, UINT *num)
2526 {
2527     TRACE("(%p, %p)\n", image, num);
2528
2529     if (!image || !num) return InvalidParameter;
2530
2531     *num = 0;
2532
2533     if (image->type == ImageTypeBitmap)
2534     {
2535         if (((GpBitmap *)image)->metadata_reader)
2536             IWICMetadataReader_GetCount(((GpBitmap *)image)->metadata_reader, num);
2537     }
2538
2539     return Ok;
2540 }
2541
2542 GpStatus WINGDIPAPI GdipGetPropertyIdList(GpImage *image, UINT num, PROPID *list)
2543 {
2544     HRESULT hr;
2545     IWICMetadataReader *reader;
2546     IWICEnumMetadataItem *enumerator;
2547     UINT prop_count, i, items_returned;
2548
2549     TRACE("(%p, %u, %p)\n", image, num, list);
2550
2551     if (!image || !list) return InvalidParameter;
2552
2553     if (image->type != ImageTypeBitmap)
2554     {
2555         FIXME("Not implemented for type %d\n", image->type);
2556         return NotImplemented;
2557     }
2558
2559     reader = ((GpBitmap *)image)->metadata_reader;
2560     if (!reader)
2561     {
2562         if (num != 0) return InvalidParameter;
2563         return Ok;
2564     }
2565
2566     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2567     if (FAILED(hr)) return hresult_to_status(hr);
2568
2569     if (num != prop_count) return InvalidParameter;
2570
2571     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2572     if (FAILED(hr)) return hresult_to_status(hr);
2573
2574     IWICEnumMetadataItem_Reset(enumerator);
2575
2576     for (i = 0; i < num; i++)
2577     {
2578         PROPVARIANT id;
2579
2580         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, NULL, &items_returned);
2581         if (hr != S_OK) break;
2582
2583         if (id.vt != VT_UI2)
2584         {
2585             FIXME("not supported propvariant type for id: %u\n", id.vt);
2586             list[i] = 0;
2587             continue;
2588         }
2589         list[i] = id.u.uiVal;
2590     }
2591
2592     IWICEnumMetadataItem_Release(enumerator);
2593
2594     return hr == S_OK ? Ok : hresult_to_status(hr);
2595 }
2596
2597 static UINT propvariant_size(PROPVARIANT *value)
2598 {
2599     switch (value->vt & ~VT_VECTOR)
2600     {
2601     case VT_EMPTY:
2602         return 0;
2603     case VT_I1:
2604     case VT_UI1:
2605         if (!(value->vt & VT_VECTOR)) return 1;
2606         return value->u.caub.cElems;
2607     case VT_I2:
2608     case VT_UI2:
2609         if (!(value->vt & VT_VECTOR)) return 2;
2610         return value->u.caui.cElems * 2;
2611     case VT_I4:
2612     case VT_UI4:
2613     case VT_R4:
2614         if (!(value->vt & VT_VECTOR)) return 4;
2615         return value->u.caul.cElems * 4;
2616     case VT_I8:
2617     case VT_UI8:
2618     case VT_R8:
2619         if (!(value->vt & VT_VECTOR)) return 8;
2620         return value->u.cauh.cElems * 8;
2621     case VT_LPSTR:
2622         return value->u.pszVal ? strlen(value->u.pszVal) + 1 : 0;
2623     case VT_BLOB:
2624         return value->u.blob.cbSize;
2625     default:
2626         FIXME("not supported variant type %d\n", value->vt);
2627         return 0;
2628     }
2629 }
2630
2631 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID propid, UINT *size)
2632 {
2633     HRESULT hr;
2634     IWICMetadataReader *reader;
2635     PROPVARIANT id, value;
2636
2637     TRACE("(%p,%#x,%p)\n", image, propid, size);
2638
2639     if (!size || !image) return InvalidParameter;
2640
2641     if (image->type != ImageTypeBitmap)
2642     {
2643         FIXME("Not implemented for type %d\n", image->type);
2644         return NotImplemented;
2645     }
2646
2647     reader = ((GpBitmap *)image)->metadata_reader;
2648     if (!reader) return PropertyNotFound;
2649
2650     id.vt = VT_UI2;
2651     id.u.uiVal = propid;
2652     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2653     if (FAILED(hr)) return PropertyNotFound;
2654
2655     *size = propvariant_size(&value);
2656     if (*size) *size += sizeof(PropertyItem);
2657     PropVariantClear(&value);
2658
2659     return Ok;
2660 }
2661
2662 #ifndef PropertyTagTypeSByte
2663 #define PropertyTagTypeSByte  6
2664 #define PropertyTagTypeSShort 8
2665 #define PropertyTagTypeFloat  11
2666 #define PropertyTagTypeDouble 12
2667 #endif
2668
2669 static UINT vt_to_itemtype(UINT vt)
2670 {
2671     static const struct
2672     {
2673         UINT vt, type;
2674     } vt2type[] =
2675     {
2676         { VT_I1, PropertyTagTypeSByte },
2677         { VT_UI1, PropertyTagTypeByte },
2678         { VT_I2, PropertyTagTypeSShort },
2679         { VT_UI2, PropertyTagTypeShort },
2680         { VT_I4, PropertyTagTypeSLONG },
2681         { VT_UI4, PropertyTagTypeLong },
2682         { VT_I8, PropertyTagTypeSRational },
2683         { VT_UI8, PropertyTagTypeRational },
2684         { VT_R4, PropertyTagTypeFloat },
2685         { VT_R8, PropertyTagTypeDouble },
2686         { VT_LPSTR, PropertyTagTypeASCII },
2687         { VT_BLOB, PropertyTagTypeUndefined }
2688     };
2689     UINT i;
2690     for (i = 0; i < sizeof(vt2type)/sizeof(vt2type[0]); i++)
2691     {
2692         if (vt2type[i].vt == vt) return vt2type[i].type;
2693     }
2694     FIXME("not supported variant type %u\n", vt);
2695     return 0;
2696 }
2697
2698 static GpStatus propvariant_to_item(PROPVARIANT *value, PropertyItem *item,
2699                                     UINT size, PROPID id)
2700 {
2701     UINT item_size, item_type;
2702
2703     item_size = propvariant_size(value);
2704     if (size != item_size + sizeof(PropertyItem)) return InvalidParameter;
2705
2706     item_type = vt_to_itemtype(value->vt & ~VT_VECTOR);
2707     if (!item_type) return InvalidParameter;
2708
2709     item->value = item + 1;
2710
2711     switch (value->vt & ~VT_VECTOR)
2712     {
2713     case VT_I1:
2714     case VT_UI1:
2715         if (!(value->vt & VT_VECTOR))
2716             *(BYTE *)item->value = value->u.bVal;
2717         else
2718             memcpy(item->value, value->u.caub.pElems, item_size);
2719         break;
2720     case VT_I2:
2721     case VT_UI2:
2722         if (!(value->vt & VT_VECTOR))
2723             *(USHORT *)item->value = value->u.uiVal;
2724         else
2725             memcpy(item->value, value->u.caui.pElems, item_size);
2726         break;
2727     case VT_I4:
2728     case VT_UI4:
2729     case VT_R4:
2730         if (!(value->vt & VT_VECTOR))
2731             *(ULONG *)item->value = value->u.ulVal;
2732         else
2733             memcpy(item->value, value->u.caul.pElems, item_size);
2734         break;
2735     case VT_I8:
2736     case VT_UI8:
2737     case VT_R8:
2738         if (!(value->vt & VT_VECTOR))
2739             *(ULONGLONG *)item->value = value->u.uhVal.QuadPart;
2740         else
2741             memcpy(item->value, value->u.cauh.pElems, item_size);
2742         break;
2743     case VT_LPSTR:
2744         memcpy(item->value, value->u.pszVal, item_size);
2745         break;
2746     case VT_BLOB:
2747         memcpy(item->value, value->u.blob.pBlobData, item_size);
2748         break;
2749     default:
2750         FIXME("not supported variant type %d\n", value->vt);
2751         return InvalidParameter;
2752     }
2753
2754     item->length = item_size;
2755     item->type = item_type;
2756     item->id = id;
2757
2758     return Ok;
2759 }
2760
2761 GpStatus WINGDIPAPI GdipGetPropertyItem(GpImage *image, PROPID propid, UINT size,
2762                                         PropertyItem *buffer)
2763 {
2764     GpStatus stat;
2765     HRESULT hr;
2766     IWICMetadataReader *reader;
2767     PROPVARIANT id, value;
2768
2769     TRACE("(%p,%#x,%u,%p)\n", image, propid, size, buffer);
2770
2771     if (!image || !buffer) return InvalidParameter;
2772
2773     if (image->type != ImageTypeBitmap)
2774     {
2775         FIXME("Not implemented for type %d\n", image->type);
2776         return NotImplemented;
2777     }
2778
2779     reader = ((GpBitmap *)image)->metadata_reader;
2780     if (!reader) return PropertyNotFound;
2781
2782     id.vt = VT_UI2;
2783     id.u.uiVal = propid;
2784     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2785     if (FAILED(hr)) return PropertyNotFound;
2786
2787     stat = propvariant_to_item(&value, buffer, size, propid);
2788     PropVariantClear(&value);
2789
2790     return stat;
2791 }
2792
2793 GpStatus WINGDIPAPI GdipGetPropertySize(GpImage *image, UINT *size, UINT *count)
2794 {
2795     HRESULT hr;
2796     IWICMetadataReader *reader;
2797     IWICEnumMetadataItem *enumerator;
2798     UINT prop_count, prop_size, i;
2799     PROPVARIANT id, value;
2800
2801     TRACE("(%p,%p,%p)\n", image, size, count);
2802
2803     if (!image || !size || !count) return InvalidParameter;
2804
2805     if (image->type != ImageTypeBitmap)
2806     {
2807         FIXME("Not implemented for type %d\n", image->type);
2808         return NotImplemented;
2809     }
2810
2811     reader = ((GpBitmap *)image)->metadata_reader;
2812     if (!reader) return PropertyNotFound;
2813
2814     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2815     if (FAILED(hr)) return hresult_to_status(hr);
2816
2817     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2818     if (FAILED(hr)) return hresult_to_status(hr);
2819
2820     IWICEnumMetadataItem_Reset(enumerator);
2821
2822     prop_size = 0;
2823
2824     PropVariantInit(&id);
2825     PropVariantInit(&value);
2826
2827     for (i = 0; i < prop_count; i++)
2828     {
2829         UINT items_returned, item_size;
2830
2831         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2832         if (hr != S_OK) break;
2833
2834         item_size = propvariant_size(&value);
2835         if (item_size) prop_size += sizeof(PropertyItem) + item_size;
2836
2837         PropVariantClear(&id);
2838         PropVariantClear(&value);
2839     }
2840
2841     IWICEnumMetadataItem_Release(enumerator);
2842
2843     if (hr != S_OK) return PropertyNotFound;
2844
2845     *count = prop_count;
2846     *size = prop_size;
2847     return Ok;
2848 }
2849
2850 GpStatus WINGDIPAPI GdipGetAllPropertyItems(GpImage *image, UINT size,
2851                                             UINT count, PropertyItem *buf)
2852 {
2853     GpStatus status;
2854     HRESULT hr;
2855     IWICMetadataReader *reader;
2856     IWICEnumMetadataItem *enumerator;
2857     UINT prop_count, prop_size, i;
2858     PROPVARIANT id, value;
2859     char *item_value;
2860
2861     TRACE("(%p,%u,%u,%p)\n", image, size, count, buf);
2862
2863     if (!image || !buf) return InvalidParameter;
2864
2865     if (image->type != ImageTypeBitmap)
2866     {
2867         FIXME("Not implemented for type %d\n", image->type);
2868         return NotImplemented;
2869     }
2870
2871     status = GdipGetPropertySize(image, &prop_size, &prop_count);
2872     if (status != Ok) return status;
2873
2874     if (prop_count != count || prop_size != size) return InvalidParameter;
2875
2876     reader = ((GpBitmap *)image)->metadata_reader;
2877     if (!reader) return PropertyNotFound;
2878
2879     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2880     if (FAILED(hr)) return hresult_to_status(hr);
2881
2882     IWICEnumMetadataItem_Reset(enumerator);
2883
2884     item_value = (char *)(buf + prop_count);
2885
2886     PropVariantInit(&id);
2887     PropVariantInit(&value);
2888
2889     for (i = 0; i < prop_count; i++)
2890     {
2891         PropertyItem *item;
2892         UINT items_returned, item_size;
2893
2894         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2895         if (hr != S_OK) break;
2896
2897         if (id.vt != VT_UI2)
2898         {
2899             FIXME("not supported propvariant type for id: %u\n", id.vt);
2900             continue;
2901         }
2902
2903         item_size = propvariant_size(&value);
2904         if (item_size)
2905         {
2906             item = HeapAlloc(GetProcessHeap(), 0, item_size + sizeof(*item));
2907
2908             propvariant_to_item(&value, item, item_size + sizeof(*item), id.u.uiVal);
2909             buf[i].id = item->id;
2910             buf[i].type = item->type;
2911             buf[i].length = item_size;
2912             buf[i].value = item_value;
2913             memcpy(item_value, item->value, item_size);
2914             item_value += item_size;
2915
2916             HeapFree(GetProcessHeap(), 0, item);
2917         }
2918
2919         PropVariantClear(&id);
2920         PropVariantClear(&value);
2921     }
2922
2923     IWICEnumMetadataItem_Release(enumerator);
2924
2925     if (hr != S_OK) return PropertyNotFound;
2926
2927     return Ok;
2928 }
2929
2930 struct image_format_dimension
2931 {
2932     const GUID *format;
2933     const GUID *dimension;
2934 };
2935
2936 static const struct image_format_dimension image_format_dimensions[] =
2937 {
2938     {&ImageFormatGIF, &FrameDimensionTime},
2939     {&ImageFormatIcon, &FrameDimensionResolution},
2940     {NULL}
2941 };
2942
2943 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
2944     GDIPCONST GUID* dimensionID, UINT* count)
2945 {
2946     TRACE("(%p,%s,%p)\n", image, debugstr_guid(dimensionID), count);
2947
2948     if(!image || !count)
2949         return InvalidParameter;
2950
2951     if (!dimensionID ||
2952         IsEqualGUID(dimensionID, &image->format) ||
2953         IsEqualGUID(dimensionID, &FrameDimensionPage) ||
2954         IsEqualGUID(dimensionID, &FrameDimensionTime))
2955     {
2956         *count = image->frame_count;
2957         return Ok;
2958     }
2959
2960     return InvalidParameter;
2961 }
2962
2963 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsCount(GpImage *image,
2964     UINT* count)
2965 {
2966     TRACE("(%p, %p)\n", image, count);
2967
2968     /* Native gdiplus 1.1 does not yet support multiple frame dimensions. */
2969
2970     if(!image || !count)
2971         return InvalidParameter;
2972
2973     *count = 1;
2974
2975     return Ok;
2976 }
2977
2978 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
2979     GUID* dimensionIDs, UINT count)
2980 {
2981     int i;
2982     const GUID *result=NULL;
2983
2984     TRACE("(%p,%p,%u)\n", image, dimensionIDs, count);
2985
2986     if(!image || !dimensionIDs || count != 1)
2987         return InvalidParameter;
2988
2989     for (i=0; image_format_dimensions[i].format; i++)
2990     {
2991         if (IsEqualGUID(&image->format, image_format_dimensions[i].format))
2992         {
2993             result = image_format_dimensions[i].dimension;
2994             break;
2995         }
2996     }
2997
2998     if (!result)
2999         result = &FrameDimensionPage;
3000
3001     memcpy(dimensionIDs, result, sizeof(GUID));
3002
3003     return Ok;
3004 }
3005
3006 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
3007                                           GpImage **image)
3008 {
3009     GpStatus stat;
3010     IStream *stream;
3011
3012     TRACE("(%s) %p\n", debugstr_w(filename), image);
3013
3014     if (!filename || !image)
3015         return InvalidParameter;
3016
3017     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
3018
3019     if (stat != Ok)
3020         return stat;
3021
3022     stat = GdipLoadImageFromStream(stream, image);
3023
3024     IStream_Release(stream);
3025
3026     return stat;
3027 }
3028
3029 /* FIXME: no icm handling */
3030 GpStatus WINGDIPAPI GdipLoadImageFromFileICM(GDIPCONST WCHAR* filename,GpImage **image)
3031 {
3032     TRACE("(%s) %p\n", debugstr_w(filename), image);
3033
3034     return GdipLoadImageFromFile(filename, image);
3035 }
3036
3037 static GpStatus decode_image_wic(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3038 {
3039     GpStatus status=Ok;
3040     GpBitmap *bitmap;
3041     HRESULT hr;
3042     IWICBitmapDecoder *decoder;
3043     IWICBitmapFrameDecode *frame;
3044     IWICBitmapSource *source=NULL;
3045     IWICMetadataBlockReader *block_reader;
3046     WICPixelFormatGUID wic_format;
3047     PixelFormat gdip_format=0;
3048     ColorPalette *palette = NULL;
3049     WICBitmapPaletteType palette_type = WICBitmapPaletteTypeFixedHalftone256;
3050     int i;
3051     UINT width, height, frame_count;
3052     BitmapData lockeddata;
3053     WICRect wrc;
3054     HRESULT initresult;
3055
3056     initresult = CoInitialize(NULL);
3057
3058     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
3059         &IID_IWICBitmapDecoder, (void**)&decoder);
3060     if (FAILED(hr)) goto end;
3061
3062     hr = IWICBitmapDecoder_Initialize(decoder, stream, WICDecodeMetadataCacheOnLoad);
3063     if (SUCCEEDED(hr))
3064     {
3065         IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3066         hr = IWICBitmapDecoder_GetFrame(decoder, active_frame, &frame);
3067     }
3068
3069     if (SUCCEEDED(hr)) /* got frame */
3070     {
3071         hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &wic_format);
3072
3073         if (SUCCEEDED(hr))
3074         {
3075             IWICBitmapSource *bmp_source;
3076             IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICBitmapSource, (void **)&bmp_source);
3077
3078             for (i=0; pixel_formats[i].wic_format; i++)
3079             {
3080                 if (IsEqualGUID(&wic_format, pixel_formats[i].wic_format))
3081                 {
3082                     source = bmp_source;
3083                     gdip_format = pixel_formats[i].gdip_format;
3084                     palette_type = pixel_formats[i].palette_type;
3085                     break;
3086                 }
3087             }
3088             if (!source)
3089             {
3090                 /* unknown format; fall back on 32bppARGB */
3091                 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, bmp_source, &source);
3092                 gdip_format = PixelFormat32bppARGB;
3093                 IWICBitmapSource_Release(bmp_source);
3094             }
3095             TRACE("%s => %#x\n", wine_dbgstr_guid(&wic_format), gdip_format);
3096         }
3097
3098         if (SUCCEEDED(hr)) /* got source */
3099         {
3100             hr = IWICBitmapSource_GetSize(source, &width, &height);
3101
3102             if (SUCCEEDED(hr))
3103                 status = GdipCreateBitmapFromScan0(width, height, 0, gdip_format,
3104                     NULL, &bitmap);
3105
3106             if (SUCCEEDED(hr) && status == Ok) /* created bitmap */
3107             {
3108                 status = GdipBitmapLockBits(bitmap, NULL, ImageLockModeWrite,
3109                     gdip_format, &lockeddata);
3110                 if (status == Ok) /* locked bitmap */
3111                 {
3112                     wrc.X = 0;
3113                     wrc.Width = width;
3114                     wrc.Height = 1;
3115                     for (i=0; i<height; i++)
3116                     {
3117                         wrc.Y = i;
3118                         hr = IWICBitmapSource_CopyPixels(source, &wrc, abs(lockeddata.Stride),
3119                             abs(lockeddata.Stride), (BYTE*)lockeddata.Scan0+lockeddata.Stride*i);
3120                         if (FAILED(hr)) break;
3121                     }
3122
3123                     GdipBitmapUnlockBits(bitmap, &lockeddata);
3124                 }
3125
3126                 if (SUCCEEDED(hr) && status == Ok)
3127                     *image = (GpImage*)bitmap;
3128                 else
3129                 {
3130                     *image = NULL;
3131                     GdipDisposeImage((GpImage*)bitmap);
3132                 }
3133
3134                 if (SUCCEEDED(hr) && status == Ok)
3135                 {
3136                     double dpix, dpiy;
3137                     hr = IWICBitmapSource_GetResolution(source, &dpix, &dpiy);
3138                     if (SUCCEEDED(hr))
3139                     {
3140                         bitmap->image.xres = dpix;
3141                         bitmap->image.yres = dpiy;
3142                     }
3143                     hr = S_OK;
3144                 }
3145             }
3146
3147             IWICBitmapSource_Release(source);
3148         }
3149
3150         bitmap->metadata_reader = NULL;
3151         if (IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader) == S_OK)
3152         {
3153             UINT block_count = 0;
3154             if (IWICMetadataBlockReader_GetCount(block_reader, &block_count) == S_OK && block_count)
3155                 IWICMetadataBlockReader_GetReaderByIndex(block_reader, 0, &bitmap->metadata_reader);
3156             IWICMetadataBlockReader_Release(block_reader);
3157         }
3158
3159         palette = get_palette(frame, palette_type);
3160         IWICBitmapFrameDecode_Release(frame);
3161     }
3162
3163     IWICBitmapDecoder_Release(decoder);
3164
3165 end:
3166     if (SUCCEEDED(initresult)) CoUninitialize();
3167
3168     if (FAILED(hr) && status == Ok) status = hresult_to_status(hr);
3169
3170     if (status == Ok)
3171     {
3172         /* Native GDI+ used to be smarter, but since Win7 it just sets these flags. */
3173         bitmap->image.flags |= ImageFlagsReadOnly|ImageFlagsHasRealPixelSize|ImageFlagsHasRealDPI|ImageFlagsColorSpaceRGB;
3174         bitmap->image.frame_count = frame_count;
3175         bitmap->image.current_frame = active_frame;
3176         bitmap->image.stream = stream;
3177         if (palette)
3178         {
3179             GdipFree(bitmap->image.palette);
3180             bitmap->image.palette = palette;
3181         }
3182         else
3183         {
3184             if (IsEqualGUID(&wic_format, &GUID_WICPixelFormatBlackWhite))
3185                 bitmap->image.palette->Flags = 0;
3186         }
3187         /* Pin the source stream */
3188         IStream_AddRef(stream);
3189     }
3190
3191     return status;
3192 }
3193
3194 static GpStatus decode_image_icon(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3195 {
3196     return decode_image_wic(stream, &CLSID_WICIcoDecoder, active_frame, image);
3197 }
3198
3199 static GpStatus decode_image_bmp(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3200 {
3201     GpStatus status;
3202     GpBitmap* bitmap;
3203
3204     status = decode_image_wic(stream, &CLSID_WICBmpDecoder, active_frame, image);
3205
3206     bitmap = (GpBitmap*)*image;
3207
3208     if (status == Ok && bitmap->format == PixelFormat32bppARGB)
3209     {
3210         /* WIC supports bmp files with alpha, but gdiplus does not */
3211         bitmap->format = PixelFormat32bppRGB;
3212     }
3213
3214     return status;
3215 }
3216
3217 static GpStatus decode_image_jpeg(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3218 {
3219     return decode_image_wic(stream, &CLSID_WICJpegDecoder, active_frame, image);
3220 }
3221
3222 static GpStatus decode_image_png(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3223 {
3224     return decode_image_wic(stream, &CLSID_WICPngDecoder, active_frame, image);
3225 }
3226
3227 static GpStatus decode_image_gif(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3228 {
3229     return decode_image_wic(stream, &CLSID_WICGifDecoder, active_frame, image);
3230 }
3231
3232 static GpStatus decode_image_tiff(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3233 {
3234     return decode_image_wic(stream, &CLSID_WICTiffDecoder, active_frame, image);
3235 }
3236
3237 static GpStatus decode_image_olepicture_metafile(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3238 {
3239     IPicture *pic;
3240
3241     TRACE("%p %p\n", stream, image);
3242
3243     if(!stream || !image)
3244         return InvalidParameter;
3245
3246     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
3247         (LPVOID*) &pic) != S_OK){
3248         TRACE("Could not load picture\n");
3249         return GenericError;
3250     }
3251
3252     /* FIXME: missing initialization code */
3253     *image = GdipAlloc(sizeof(GpMetafile));
3254     if(!*image) return OutOfMemory;
3255     (*image)->type = ImageTypeMetafile;
3256     (*image)->stream = NULL;
3257     (*image)->picture = pic;
3258     (*image)->flags   = ImageFlagsNone;
3259     (*image)->frame_count = 1;
3260     (*image)->current_frame = 0;
3261     (*image)->palette = NULL;
3262
3263     TRACE("<-- %p\n", *image);
3264
3265     return Ok;
3266 }
3267
3268 typedef GpStatus (*encode_image_func)(GpImage *image, IStream* stream,
3269     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params);
3270
3271 typedef GpStatus (*decode_image_func)(IStream *stream, REFCLSID clsid, UINT active_frame, GpImage **image);
3272
3273 typedef struct image_codec {
3274     ImageCodecInfo info;
3275     encode_image_func encode_func;
3276     decode_image_func decode_func;
3277 } image_codec;
3278
3279 typedef enum {
3280     BMP,
3281     JPEG,
3282     GIF,
3283     TIFF,
3284     EMF,
3285     WMF,
3286     PNG,
3287     ICO,
3288     NUM_CODECS
3289 } ImageFormat;
3290
3291 static const struct image_codec codecs[NUM_CODECS];
3292
3293 static GpStatus get_decoder_info(IStream* stream, const struct image_codec **result)
3294 {
3295     BYTE signature[8];
3296     const BYTE *pattern, *mask;
3297     LARGE_INTEGER seek;
3298     HRESULT hr;
3299     UINT bytesread;
3300     int i, j, sig;
3301
3302     /* seek to the start of the stream */
3303     seek.QuadPart = 0;
3304     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3305     if (FAILED(hr)) return hresult_to_status(hr);
3306
3307     /* read the first 8 bytes */
3308     /* FIXME: This assumes all codecs have signatures <= 8 bytes in length */
3309     hr = IStream_Read(stream, signature, 8, &bytesread);
3310     if (FAILED(hr)) return hresult_to_status(hr);
3311     if (hr == S_FALSE || bytesread == 0) return GenericError;
3312
3313     for (i = 0; i < NUM_CODECS; i++) {
3314         if ((codecs[i].info.Flags & ImageCodecFlagsDecoder) &&
3315             bytesread >= codecs[i].info.SigSize)
3316         {
3317             for (sig=0; sig<codecs[i].info.SigCount; sig++)
3318             {
3319                 pattern = &codecs[i].info.SigPattern[codecs[i].info.SigSize*sig];
3320                 mask = &codecs[i].info.SigMask[codecs[i].info.SigSize*sig];
3321                 for (j=0; j<codecs[i].info.SigSize; j++)
3322                     if ((signature[j] & mask[j]) != pattern[j])
3323                         break;
3324                 if (j == codecs[i].info.SigSize)
3325                 {
3326                     *result = &codecs[i];
3327                     return Ok;
3328                 }
3329             }
3330         }
3331     }
3332
3333     TRACE("no match for %i byte signature %x %x %x %x %x %x %x %x\n", bytesread,
3334         signature[0],signature[1],signature[2],signature[3],
3335         signature[4],signature[5],signature[6],signature[7]);
3336
3337     return GenericError;
3338 }
3339
3340 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image, GDIPCONST GUID *dimensionID,
3341                                                UINT frame)
3342 {
3343     GpStatus stat;
3344     LARGE_INTEGER seek;
3345     HRESULT hr;
3346     const struct image_codec *codec = NULL;
3347     IStream *stream;
3348     GpImage *new_image;
3349
3350     TRACE("(%p,%s,%u)\n", image, debugstr_guid(dimensionID), frame);
3351
3352     if (!image || !dimensionID)
3353         return InvalidParameter;
3354
3355     if (frame >= image->frame_count)
3356         return InvalidParameter;
3357
3358     if (image->type != ImageTypeBitmap && image->type != ImageTypeMetafile)
3359     {
3360         WARN("invalid image type %d\n", image->type);
3361         return InvalidParameter;
3362     }
3363
3364     if (image->current_frame == frame)
3365         return Ok;
3366
3367     if (!image->stream)
3368     {
3369         TRACE("image doesn't have an associated stream\n");
3370         return Ok;
3371     }
3372
3373     hr = IStream_Clone(image->stream, &stream);
3374     if (FAILED(hr))
3375     {
3376         STATSTG statstg;
3377
3378         hr = IStream_Stat(image->stream, &statstg, STATFLAG_NOOPEN);
3379         if (FAILED(hr)) return hresult_to_status(hr);
3380
3381         stat = GdipCreateStreamOnFile(statstg.pwcsName, GENERIC_READ, &stream);
3382         if (stat != Ok) return stat;
3383     }
3384
3385     /* choose an appropriate image decoder */
3386     stat = get_decoder_info(stream, &codec);
3387     if (stat != Ok)
3388     {
3389         IStream_Release(stream);
3390         return stat;
3391     }
3392
3393     /* seek to the start of the stream */
3394     seek.QuadPart = 0;
3395     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3396     if (FAILED(hr))
3397     {
3398         IStream_Release(stream);
3399         return hresult_to_status(hr);
3400     }
3401
3402     /* call on the image decoder to do the real work */
3403     stat = codec->decode_func(stream, &codec->info.Clsid, frame, &new_image);
3404
3405     if (stat == Ok)
3406     {
3407         memcpy(&new_image->format, &codec->info.FormatID, sizeof(GUID));
3408         free_image_data(image);
3409         if (image->type == ImageTypeBitmap)
3410             *(GpBitmap *)image = *(GpBitmap *)new_image;
3411         else if (image->type == ImageTypeMetafile)
3412             *(GpMetafile *)image = *(GpMetafile *)new_image;
3413         new_image->type = ~0;
3414         GdipFree(new_image);
3415         return Ok;
3416     }
3417
3418     IStream_Release(stream);
3419     return stat;
3420 }
3421
3422 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream *stream, GpImage **image)
3423 {
3424     GpStatus stat;
3425     LARGE_INTEGER seek;
3426     HRESULT hr;
3427     const struct image_codec *codec=NULL;
3428
3429     /* choose an appropriate image decoder */
3430     stat = get_decoder_info(stream, &codec);
3431     if (stat != Ok) return stat;
3432
3433     /* seek to the start of the stream */
3434     seek.QuadPart = 0;
3435     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3436     if (FAILED(hr)) return hresult_to_status(hr);
3437
3438     /* call on the image decoder to do the real work */
3439     stat = codec->decode_func(stream, &codec->info.Clsid, 0, image);
3440
3441     /* take note of the original data format */
3442     if (stat == Ok)
3443     {
3444         memcpy(&(*image)->format, &codec->info.FormatID, sizeof(GUID));
3445         return Ok;
3446     }
3447
3448     return stat;
3449 }
3450
3451 /* FIXME: no ICM */
3452 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
3453 {
3454     TRACE("%p %p\n", stream, image);
3455
3456     return GdipLoadImageFromStream(stream, image);
3457 }
3458
3459 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
3460 {
3461     static int calls;
3462
3463     TRACE("(%p,%u)\n", image, propId);
3464
3465     if(!image)
3466         return InvalidParameter;
3467
3468     if(!(calls++))
3469         FIXME("not implemented\n");
3470
3471     return NotImplemented;
3472 }
3473
3474 GpStatus WINGDIPAPI GdipSetPropertyItem(GpImage *image, GDIPCONST PropertyItem* item)
3475 {
3476     static int calls;
3477
3478     if (!image || !item) return InvalidParameter;
3479
3480     TRACE("(%p,%p:%#x,%u,%u,%p)\n", image, item, item->id, item->type, item->length, item->value);
3481
3482     if(!(calls++))
3483         FIXME("not implemented\n");
3484
3485     return NotImplemented;
3486 }
3487
3488 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
3489                                         GDIPCONST CLSID *clsidEncoder,
3490                                         GDIPCONST EncoderParameters *encoderParams)
3491 {
3492     GpStatus stat;
3493     IStream *stream;
3494
3495     TRACE("%p (%s) %p %p\n", image, debugstr_w(filename), clsidEncoder, encoderParams);
3496
3497     if (!image || !filename|| !clsidEncoder)
3498         return InvalidParameter;
3499
3500     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
3501     if (stat != Ok)
3502         return GenericError;
3503
3504     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
3505
3506     IStream_Release(stream);
3507     return stat;
3508 }
3509
3510 /*************************************************************************
3511  * Encoding functions -
3512  *   These functions encode an image in different image file formats.
3513  */
3514 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
3515 #define BITMAP_FORMAT_JPEG  0xd8ff
3516 #define BITMAP_FORMAT_GIF   0x4947
3517 #define BITMAP_FORMAT_PNG   0x5089
3518 #define BITMAP_FORMAT_APM   0xcdd7
3519
3520 static GpStatus encode_image_WIC(GpImage *image, IStream* stream,
3521     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3522 {
3523     GpStatus stat;
3524     GpBitmap *bitmap;
3525     IWICBitmapEncoder *encoder;
3526     IWICBitmapFrameEncode *frameencode;
3527     IPropertyBag2 *encoderoptions;
3528     HRESULT hr;
3529     UINT width, height;
3530     PixelFormat gdipformat=0;
3531     WICPixelFormatGUID wicformat;
3532     GpRect rc;
3533     BitmapData lockeddata;
3534     HRESULT initresult;
3535     UINT i;
3536
3537     if (image->type != ImageTypeBitmap)
3538         return GenericError;
3539
3540     bitmap = (GpBitmap*)image;
3541
3542     GdipGetImageWidth(image, &width);
3543     GdipGetImageHeight(image, &height);
3544
3545     rc.X = 0;
3546     rc.Y = 0;
3547     rc.Width = width;
3548     rc.Height = height;
3549
3550     initresult = CoInitialize(NULL);
3551
3552     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
3553         &IID_IWICBitmapEncoder, (void**)&encoder);
3554     if (FAILED(hr))
3555     {
3556         if (SUCCEEDED(initresult)) CoUninitialize();
3557         return hresult_to_status(hr);
3558     }
3559
3560     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
3561
3562     if (SUCCEEDED(hr))
3563     {
3564         hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frameencode, &encoderoptions);
3565     }
3566
3567     if (SUCCEEDED(hr)) /* created frame */
3568     {
3569         hr = IWICBitmapFrameEncode_Initialize(frameencode, encoderoptions);
3570
3571         if (SUCCEEDED(hr))
3572             hr = IWICBitmapFrameEncode_SetSize(frameencode, width, height);
3573
3574         if (SUCCEEDED(hr))
3575             hr = IWICBitmapFrameEncode_SetResolution(frameencode, image->xres, image->yres);
3576
3577         if (SUCCEEDED(hr))
3578         {
3579             for (i=0; pixel_formats[i].wic_format; i++)
3580             {
3581                 if (pixel_formats[i].gdip_format == bitmap->format)
3582                 {
3583                     memcpy(&wicformat, pixel_formats[i].wic_format, sizeof(GUID));
3584                     gdipformat = bitmap->format;
3585                     break;
3586                 }
3587             }
3588             if (!gdipformat)
3589             {
3590                 memcpy(&wicformat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
3591                 gdipformat = PixelFormat32bppARGB;
3592             }
3593
3594             hr = IWICBitmapFrameEncode_SetPixelFormat(frameencode, &wicformat);
3595         }
3596
3597         if (SUCCEEDED(hr))
3598         {
3599             stat = GdipBitmapLockBits(bitmap, &rc, ImageLockModeRead, gdipformat,
3600                 &lockeddata);
3601
3602             if (stat == Ok)
3603             {
3604                 UINT row_size = (lockeddata.Width * PIXELFORMATBPP(gdipformat) + 7)/8;
3605                 BYTE *row;
3606
3607                 /* write one row at a time in case stride is negative */
3608                 row = lockeddata.Scan0;
3609                 for (i=0; i<lockeddata.Height; i++)
3610                 {
3611                     hr = IWICBitmapFrameEncode_WritePixels(frameencode, 1, row_size, row_size, row);
3612                     if (FAILED(hr)) break;
3613                     row += lockeddata.Stride;
3614                 }
3615
3616                 GdipBitmapUnlockBits(bitmap, &lockeddata);
3617             }
3618             else
3619                 hr = E_FAIL;
3620         }
3621
3622         if (SUCCEEDED(hr))
3623             hr = IWICBitmapFrameEncode_Commit(frameencode);
3624
3625         IWICBitmapFrameEncode_Release(frameencode);
3626         IPropertyBag2_Release(encoderoptions);
3627     }
3628
3629     if (SUCCEEDED(hr))
3630         hr = IWICBitmapEncoder_Commit(encoder);
3631
3632     IWICBitmapEncoder_Release(encoder);
3633
3634     if (SUCCEEDED(initresult)) CoUninitialize();
3635
3636     return hresult_to_status(hr);
3637 }
3638
3639 static GpStatus encode_image_BMP(GpImage *image, IStream* stream,
3640     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3641 {
3642     return encode_image_WIC(image, stream, &CLSID_WICBmpEncoder, params);
3643 }
3644
3645 static GpStatus encode_image_tiff(GpImage *image, IStream* stream,
3646     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3647 {
3648     return encode_image_WIC(image, stream, &CLSID_WICTiffEncoder, params);
3649 }
3650
3651 static GpStatus encode_image_png(GpImage *image, IStream* stream,
3652     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3653 {
3654     return encode_image_WIC(image, stream, &CLSID_WICPngEncoder, params);
3655 }
3656
3657 static GpStatus encode_image_jpeg(GpImage *image, IStream* stream,
3658     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3659 {
3660     return encode_image_WIC(image, stream, &CLSID_WICJpegEncoder, params);
3661 }
3662
3663 /*****************************************************************************
3664  * GdipSaveImageToStream [GDIPLUS.@]
3665  */
3666 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
3667     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3668 {
3669     GpStatus stat;
3670     encode_image_func encode_image;
3671     int i;
3672
3673     TRACE("%p %p %p %p\n", image, stream, clsid, params);
3674
3675     if(!image || !stream)
3676         return InvalidParameter;
3677
3678     /* select correct encoder */
3679     encode_image = NULL;
3680     for (i = 0; i < NUM_CODECS; i++) {
3681         if ((codecs[i].info.Flags & ImageCodecFlagsEncoder) &&
3682             IsEqualCLSID(clsid, &codecs[i].info.Clsid))
3683             encode_image = codecs[i].encode_func;
3684     }
3685     if (encode_image == NULL)
3686         return UnknownImageFormat;
3687
3688     stat = encode_image(image, stream, clsid, params);
3689
3690     return stat;
3691 }
3692
3693 /*****************************************************************************
3694  * GdipSaveAdd [GDIPLUS.@]
3695  */
3696 GpStatus WINGDIPAPI GdipSaveAdd(GpImage *image, GDIPCONST EncoderParameters *params)
3697 {
3698     FIXME("(%p,%p): stub\n", image, params);
3699     return Ok;
3700 }
3701
3702 /*****************************************************************************
3703  * GdipGetImagePalette [GDIPLUS.@]
3704  */
3705 GpStatus WINGDIPAPI GdipGetImagePalette(GpImage *image, ColorPalette *palette, INT size)
3706 {
3707     INT count;
3708
3709     TRACE("(%p,%p,%i)\n", image, palette, size);
3710
3711     if (!image || !palette)
3712         return InvalidParameter;
3713
3714     count = image->palette ? image->palette->Count : 0;
3715
3716     if (size < (sizeof(UINT)*2+sizeof(ARGB)*count))
3717     {
3718         TRACE("<-- InsufficientBuffer\n");
3719         return InsufficientBuffer;
3720     }
3721
3722     if (image->palette)
3723     {
3724         palette->Flags = image->palette->Flags;
3725         palette->Count = image->palette->Count;
3726         memcpy(palette->Entries, image->palette->Entries, sizeof(ARGB)*image->palette->Count);
3727     }
3728     else
3729     {
3730         palette->Flags = 0;
3731         palette->Count = 0;
3732     }
3733     return Ok;
3734 }
3735
3736 /*****************************************************************************
3737  * GdipSetImagePalette [GDIPLUS.@]
3738  */
3739 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
3740     GDIPCONST ColorPalette *palette)
3741 {
3742     ColorPalette *new_palette;
3743
3744     TRACE("(%p,%p)\n", image, palette);
3745
3746     if(!image || !palette || palette->Count > 256)
3747         return InvalidParameter;
3748
3749     new_palette = GdipAlloc(2 * sizeof(UINT) + palette->Count * sizeof(ARGB));
3750     if (!new_palette) return OutOfMemory;
3751
3752     GdipFree(image->palette);
3753     image->palette = new_palette;
3754     image->palette->Flags = palette->Flags;
3755     image->palette->Count = palette->Count;
3756     memcpy(image->palette->Entries, palette->Entries, sizeof(ARGB)*palette->Count);
3757
3758     return Ok;
3759 }
3760
3761 /*************************************************************************
3762  * Encoders -
3763  *   Structures that represent which formats we support for encoding.
3764  */
3765
3766 /* ImageCodecInfo creation routines taken from libgdiplus */
3767 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
3768 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
3769 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
3770 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
3771 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
3772 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
3773
3774 static const WCHAR jpeg_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'J','P','E','G', 0};
3775 static const WCHAR jpeg_extension[] = {'*','.','J','P','G',';', '*','.','J','P','E','G',';', '*','.','J','P','E',';', '*','.','J','F','I','F',0};
3776 static const WCHAR jpeg_mimetype[] = {'i','m','a','g','e','/','j','p','e','g', 0};
3777 static const WCHAR jpeg_format[] = {'J','P','E','G',0};
3778 static const BYTE jpeg_sig_pattern[] = { 0xFF, 0xD8 };
3779 static const BYTE jpeg_sig_mask[] = { 0xFF, 0xFF };
3780
3781 static const WCHAR gif_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'G','I','F', 0};
3782 static const WCHAR gif_extension[] = {'*','.','G','I','F',0};
3783 static const WCHAR gif_mimetype[] = {'i','m','a','g','e','/','g','i','f', 0};
3784 static const WCHAR gif_format[] = {'G','I','F',0};
3785 static const BYTE gif_sig_pattern[4] = "GIF8";
3786 static const BYTE gif_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
3787
3788 static const WCHAR tiff_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'T','I','F','F', 0};
3789 static const WCHAR tiff_extension[] = {'*','.','T','I','F','F',';','*','.','T','I','F',0};
3790 static const WCHAR tiff_mimetype[] = {'i','m','a','g','e','/','t','i','f','f', 0};
3791 static const WCHAR tiff_format[] = {'T','I','F','F',0};
3792 static const BYTE tiff_sig_pattern[] = {0x49,0x49,42,0,0x4d,0x4d,0,42};
3793 static const BYTE tiff_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
3794
3795 static const WCHAR emf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'E','M','F', 0};
3796 static const WCHAR emf_extension[] = {'*','.','E','M','F',0};
3797 static const WCHAR emf_mimetype[] = {'i','m','a','g','e','/','x','-','e','m','f', 0};
3798 static const WCHAR emf_format[] = {'E','M','F',0};
3799 static const BYTE emf_sig_pattern[] = { 0x01, 0x00, 0x00, 0x00 };
3800 static const BYTE emf_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
3801
3802 static const WCHAR wmf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'W','M','F', 0};
3803 static const WCHAR wmf_extension[] = {'*','.','W','M','F',0};
3804 static const WCHAR wmf_mimetype[] = {'i','m','a','g','e','/','x','-','w','m','f', 0};
3805 static const WCHAR wmf_format[] = {'W','M','F',0};
3806 static const BYTE wmf_sig_pattern[] = { 0xd7, 0xcd };
3807 static const BYTE wmf_sig_mask[] = { 0xFF, 0xFF };
3808
3809 static const WCHAR png_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'P','N','G', 0};
3810 static const WCHAR png_extension[] = {'*','.','P','N','G',0};
3811 static const WCHAR png_mimetype[] = {'i','m','a','g','e','/','p','n','g', 0};
3812 static const WCHAR png_format[] = {'P','N','G',0};
3813 static const BYTE png_sig_pattern[] = { 137, 80, 78, 71, 13, 10, 26, 10, };
3814 static const BYTE png_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
3815
3816 static const WCHAR ico_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'I','C','O', 0};
3817 static const WCHAR ico_extension[] = {'*','.','I','C','O',0};
3818 static const WCHAR ico_mimetype[] = {'i','m','a','g','e','/','x','-','i','c','o','n', 0};
3819 static const WCHAR ico_format[] = {'I','C','O',0};
3820 static const BYTE ico_sig_pattern[] = { 0x00, 0x00, 0x01, 0x00 };
3821 static const BYTE ico_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
3822
3823 static const struct image_codec codecs[NUM_CODECS] = {
3824     {
3825         { /* BMP */
3826             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3827             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3828             /* CodecName */          bmp_codecname,
3829             /* DllName */            NULL,
3830             /* FormatDescription */  bmp_format,
3831             /* FilenameExtension */  bmp_extension,
3832             /* MimeType */           bmp_mimetype,
3833             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3834             /* Version */            1,
3835             /* SigCount */           1,
3836             /* SigSize */            2,
3837             /* SigPattern */         bmp_sig_pattern,
3838             /* SigMask */            bmp_sig_mask,
3839         },
3840         encode_image_BMP,
3841         decode_image_bmp
3842     },
3843     {
3844         { /* JPEG */
3845             /* Clsid */              { 0x557cf401, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3846             /* FormatID */           { 0xb96b3caeU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3847             /* CodecName */          jpeg_codecname,
3848             /* DllName */            NULL,
3849             /* FormatDescription */  jpeg_format,
3850             /* FilenameExtension */  jpeg_extension,
3851             /* MimeType */           jpeg_mimetype,
3852             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3853             /* Version */            1,
3854             /* SigCount */           1,
3855             /* SigSize */            2,
3856             /* SigPattern */         jpeg_sig_pattern,
3857             /* SigMask */            jpeg_sig_mask,
3858         },
3859         encode_image_jpeg,
3860         decode_image_jpeg
3861     },
3862     {
3863         { /* GIF */
3864             /* Clsid */              { 0x557cf402, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3865             /* FormatID */           { 0xb96b3cb0U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3866             /* CodecName */          gif_codecname,
3867             /* DllName */            NULL,
3868             /* FormatDescription */  gif_format,
3869             /* FilenameExtension */  gif_extension,
3870             /* MimeType */           gif_mimetype,
3871             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3872             /* Version */            1,
3873             /* SigCount */           1,
3874             /* SigSize */            4,
3875             /* SigPattern */         gif_sig_pattern,
3876             /* SigMask */            gif_sig_mask,
3877         },
3878         NULL,
3879         decode_image_gif
3880     },
3881     {
3882         { /* TIFF */
3883             /* Clsid */              { 0x557cf405, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3884             /* FormatID */           { 0xb96b3cb1U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3885             /* CodecName */          tiff_codecname,
3886             /* DllName */            NULL,
3887             /* FormatDescription */  tiff_format,
3888             /* FilenameExtension */  tiff_extension,
3889             /* MimeType */           tiff_mimetype,
3890             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsEncoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3891             /* Version */            1,
3892             /* SigCount */           2,
3893             /* SigSize */            4,
3894             /* SigPattern */         tiff_sig_pattern,
3895             /* SigMask */            tiff_sig_mask,
3896         },
3897         encode_image_tiff,
3898         decode_image_tiff
3899     },
3900     {
3901         { /* EMF */
3902             /* Clsid */              { 0x557cf403, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3903             /* FormatID */           { 0xb96b3cacU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3904             /* CodecName */          emf_codecname,
3905             /* DllName */            NULL,
3906             /* FormatDescription */  emf_format,
3907             /* FilenameExtension */  emf_extension,
3908             /* MimeType */           emf_mimetype,
3909             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
3910             /* Version */            1,
3911             /* SigCount */           1,
3912             /* SigSize */            4,
3913             /* SigPattern */         emf_sig_pattern,
3914             /* SigMask */            emf_sig_mask,
3915         },
3916         NULL,
3917         decode_image_olepicture_metafile
3918     },
3919     {
3920         { /* WMF */
3921             /* Clsid */              { 0x557cf404, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3922             /* FormatID */           { 0xb96b3cadU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3923             /* CodecName */          wmf_codecname,
3924             /* DllName */            NULL,
3925             /* FormatDescription */  wmf_format,
3926             /* FilenameExtension */  wmf_extension,
3927             /* MimeType */           wmf_mimetype,
3928             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
3929             /* Version */            1,
3930             /* SigCount */           1,
3931             /* SigSize */            2,
3932             /* SigPattern */         wmf_sig_pattern,
3933             /* SigMask */            wmf_sig_mask,
3934         },
3935         NULL,
3936         decode_image_olepicture_metafile
3937     },
3938     {
3939         { /* PNG */
3940             /* Clsid */              { 0x557cf406, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3941             /* FormatID */           { 0xb96b3cafU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3942             /* CodecName */          png_codecname,
3943             /* DllName */            NULL,
3944             /* FormatDescription */  png_format,
3945             /* FilenameExtension */  png_extension,
3946             /* MimeType */           png_mimetype,
3947             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3948             /* Version */            1,
3949             /* SigCount */           1,
3950             /* SigSize */            8,
3951             /* SigPattern */         png_sig_pattern,
3952             /* SigMask */            png_sig_mask,
3953         },
3954         encode_image_png,
3955         decode_image_png
3956     },
3957     {
3958         { /* ICO */
3959             /* Clsid */              { 0x557cf407, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
3960             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
3961             /* CodecName */          ico_codecname,
3962             /* DllName */            NULL,
3963             /* FormatDescription */  ico_format,
3964             /* FilenameExtension */  ico_extension,
3965             /* MimeType */           ico_mimetype,
3966             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
3967             /* Version */            1,
3968             /* SigCount */           1,
3969             /* SigSize */            4,
3970             /* SigPattern */         ico_sig_pattern,
3971             /* SigMask */            ico_sig_mask,
3972         },
3973         NULL,
3974         decode_image_icon
3975     },
3976 };
3977
3978 /*****************************************************************************
3979  * GdipGetImageDecodersSize [GDIPLUS.@]
3980  */
3981 GpStatus WINGDIPAPI GdipGetImageDecodersSize(UINT *numDecoders, UINT *size)
3982 {
3983     int decoder_count=0;
3984     int i;
3985     TRACE("%p %p\n", numDecoders, size);
3986
3987     if (!numDecoders || !size)
3988         return InvalidParameter;
3989
3990     for (i=0; i<NUM_CODECS; i++)
3991     {
3992         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
3993             decoder_count++;
3994     }
3995
3996     *numDecoders = decoder_count;
3997     *size = decoder_count * sizeof(ImageCodecInfo);
3998
3999     return Ok;
4000 }
4001
4002 /*****************************************************************************
4003  * GdipGetImageDecoders [GDIPLUS.@]
4004  */
4005 GpStatus WINGDIPAPI GdipGetImageDecoders(UINT numDecoders, UINT size, ImageCodecInfo *decoders)
4006 {
4007     int i, decoder_count=0;
4008     TRACE("%u %u %p\n", numDecoders, size, decoders);
4009
4010     if (!decoders ||
4011         size != numDecoders * sizeof(ImageCodecInfo))
4012         return GenericError;
4013
4014     for (i=0; i<NUM_CODECS; i++)
4015     {
4016         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4017         {
4018             if (decoder_count == numDecoders) return GenericError;
4019             memcpy(&decoders[decoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4020             decoder_count++;
4021         }
4022     }
4023
4024     if (decoder_count < numDecoders) return GenericError;
4025
4026     return Ok;
4027 }
4028
4029 /*****************************************************************************
4030  * GdipGetImageEncodersSize [GDIPLUS.@]
4031  */
4032 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
4033 {
4034     int encoder_count=0;
4035     int i;
4036     TRACE("%p %p\n", numEncoders, size);
4037
4038     if (!numEncoders || !size)
4039         return InvalidParameter;
4040
4041     for (i=0; i<NUM_CODECS; i++)
4042     {
4043         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4044             encoder_count++;
4045     }
4046
4047     *numEncoders = encoder_count;
4048     *size = encoder_count * sizeof(ImageCodecInfo);
4049
4050     return Ok;
4051 }
4052
4053 /*****************************************************************************
4054  * GdipGetImageEncoders [GDIPLUS.@]
4055  */
4056 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
4057 {
4058     int i, encoder_count=0;
4059     TRACE("%u %u %p\n", numEncoders, size, encoders);
4060
4061     if (!encoders ||
4062         size != numEncoders * sizeof(ImageCodecInfo))
4063         return GenericError;
4064
4065     for (i=0; i<NUM_CODECS; i++)
4066     {
4067         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4068         {
4069             if (encoder_count == numEncoders) return GenericError;
4070             memcpy(&encoders[encoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4071             encoder_count++;
4072         }
4073     }
4074
4075     if (encoder_count < numEncoders) return GenericError;
4076
4077     return Ok;
4078 }
4079
4080 GpStatus WINGDIPAPI GdipGetEncoderParameterListSize(GpImage *image,
4081     GDIPCONST CLSID* clsidEncoder, UINT *size)
4082 {
4083     static int calls;
4084
4085     TRACE("(%p,%s,%p)\n", image, debugstr_guid(clsidEncoder), size);
4086
4087     if(!(calls++))
4088         FIXME("not implemented\n");
4089
4090     *size = 0;
4091
4092     return NotImplemented;
4093 }
4094
4095 static PixelFormat get_16bpp_format(HBITMAP hbm)
4096 {
4097     BITMAPV4HEADER bmh;
4098     HDC hdc;
4099     PixelFormat result;
4100
4101     hdc = CreateCompatibleDC(NULL);
4102
4103     memset(&bmh, 0, sizeof(bmh));
4104     bmh.bV4Size = sizeof(bmh);
4105     bmh.bV4Width = 1;
4106     bmh.bV4Height = 1;
4107     bmh.bV4V4Compression = BI_BITFIELDS;
4108     bmh.bV4BitCount = 16;
4109
4110     GetDIBits(hdc, hbm, 0, 0, NULL, (BITMAPINFO*)&bmh, DIB_RGB_COLORS);
4111
4112     if (bmh.bV4RedMask == 0x7c00 &&
4113         bmh.bV4GreenMask == 0x3e0 &&
4114         bmh.bV4BlueMask == 0x1f)
4115     {
4116         result = PixelFormat16bppRGB555;
4117     }
4118     else if (bmh.bV4RedMask == 0xf800 &&
4119         bmh.bV4GreenMask == 0x7e0 &&
4120         bmh.bV4BlueMask == 0x1f)
4121     {
4122         result = PixelFormat16bppRGB565;
4123     }
4124     else
4125     {
4126         FIXME("unrecognized bitfields %x,%x,%x\n", bmh.bV4RedMask,
4127             bmh.bV4GreenMask, bmh.bV4BlueMask);
4128         result = PixelFormatUndefined;
4129     }
4130
4131     DeleteDC(hdc);
4132
4133     return result;
4134 }
4135
4136 /*****************************************************************************
4137  * GdipCreateBitmapFromHBITMAP [GDIPLUS.@]
4138  */
4139 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
4140 {
4141     BITMAP bm;
4142     GpStatus retval;
4143     PixelFormat format;
4144     BitmapData lockeddata;
4145     INT y;
4146
4147     TRACE("%p %p %p\n", hbm, hpal, bitmap);
4148
4149     if(!hbm || !bitmap)
4150         return InvalidParameter;
4151
4152     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
4153             return InvalidParameter;
4154
4155     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
4156     switch(bm.bmBitsPixel) {
4157         case 1:
4158             format = PixelFormat1bppIndexed;
4159             break;
4160         case 4:
4161             format = PixelFormat4bppIndexed;
4162             break;
4163         case 8:
4164             format = PixelFormat8bppIndexed;
4165             break;
4166         case 16:
4167             format = get_16bpp_format(hbm);
4168             if (format == PixelFormatUndefined)
4169                 return InvalidParameter;
4170             break;
4171         case 24:
4172             format = PixelFormat24bppRGB;
4173             break;
4174         case 32:
4175             format = PixelFormat32bppRGB;
4176             break;
4177         case 48:
4178             format = PixelFormat48bppRGB;
4179             break;
4180         default:
4181             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
4182             return InvalidParameter;
4183     }
4184
4185     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, 0,
4186         format, NULL, bitmap);
4187
4188     if (retval == Ok)
4189     {
4190         retval = GdipBitmapLockBits(*bitmap, NULL, ImageLockModeWrite,
4191             format, &lockeddata);
4192         if (retval == Ok)
4193         {
4194             if (bm.bmBits)
4195             {
4196                 for (y=0; y<bm.bmHeight; y++)
4197                 {
4198                     memcpy((BYTE*)lockeddata.Scan0+lockeddata.Stride*y,
4199                            (BYTE*)bm.bmBits+bm.bmWidthBytes*(bm.bmHeight-1-y),
4200                            bm.bmWidthBytes);
4201                 }
4202             }
4203             else
4204             {
4205                 HDC hdc;
4206                 HBITMAP oldhbm;
4207                 BITMAPINFO *pbmi;
4208                 INT src_height, dst_stride;
4209                 BYTE *dst_bits;
4210
4211                 hdc = CreateCompatibleDC(NULL);
4212                 oldhbm = SelectObject(hdc, hbm);
4213
4214                 pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
4215
4216                 if (pbmi)
4217                 {
4218                     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
4219                     pbmi->bmiHeader.biBitCount = 0;
4220
4221                     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
4222
4223                     src_height = abs(pbmi->bmiHeader.biHeight);
4224
4225                     if (pbmi->bmiHeader.biHeight > 0)
4226                     {
4227                         dst_bits = (BYTE*)lockeddata.Scan0+lockeddata.Stride*(src_height-1);
4228                         dst_stride = -lockeddata.Stride;
4229                     }
4230                     else
4231                     {
4232                         dst_bits = lockeddata.Scan0;
4233                         dst_stride = lockeddata.Stride;
4234                     }
4235
4236                     for (y=0; y<src_height; y++)
4237                     {
4238                         GetDIBits(hdc, hbm, y, 1, dst_bits+dst_stride*y,
4239                             pbmi, DIB_RGB_COLORS);
4240                     }
4241
4242                     GdipFree(pbmi);
4243                 }
4244                 else
4245                     retval = OutOfMemory;
4246
4247                 SelectObject(hdc, oldhbm);
4248                 DeleteDC(hdc);
4249             }
4250
4251             GdipBitmapUnlockBits(*bitmap, &lockeddata);
4252         }
4253
4254         if (retval == Ok && hpal)
4255         {
4256             WORD num_palette_entries;
4257             PALETTEENTRY *palette_entries=NULL;
4258             ColorPalette *palette=NULL;
4259             int i;
4260
4261             if (!GetObjectW(hpal, sizeof(num_palette_entries), &num_palette_entries))
4262                 retval = GenericError;
4263
4264             if (retval == Ok)
4265             {
4266                 palette_entries = GdipAlloc(sizeof(PALETTEENTRY) * num_palette_entries);
4267                 palette = GdipAlloc(sizeof(ColorPalette) + sizeof(ARGB) * (num_palette_entries-1));
4268
4269                 if (!palette_entries || !palette)
4270                     retval = OutOfMemory;
4271             }
4272
4273             if (retval == Ok)
4274             {
4275                 if (!GetPaletteEntries(hpal, 0, num_palette_entries, palette_entries))
4276                     retval = GenericError;
4277             }
4278
4279             if (retval == Ok)
4280             {
4281                 palette->Flags = 0;
4282                 palette->Count = num_palette_entries;
4283
4284                 for (i=0; i<num_palette_entries; i++)
4285                 {
4286                     PALETTEENTRY * entry = &palette_entries[i];
4287                     palette->Entries[i] = 0xff000000 | entry->peRed << 16 |
4288                         entry->peGreen << 8 | entry->peBlue;
4289                 }
4290
4291                 retval = GdipSetImagePalette((GpImage*)*bitmap, palette);
4292             }
4293
4294             GdipFree(palette_entries);
4295             GdipFree(palette);
4296         }
4297
4298         if (retval != Ok)
4299         {
4300             GdipDisposeImage((GpImage*)*bitmap);
4301             *bitmap = NULL;
4302         }
4303     }
4304
4305     return retval;
4306 }
4307
4308 GpStatus WINGDIPAPI GdipDeleteEffect(CGpEffect *effect)
4309 {
4310     FIXME("(%p): stub\n", effect);
4311     /* note: According to Jose Roca's GDI+ Docs, this is not implemented
4312      * in Windows's gdiplus */
4313     return NotImplemented;
4314 }
4315
4316 /*****************************************************************************
4317  * GdipSetEffectParameters [GDIPLUS.@]
4318  */
4319 GpStatus WINGDIPAPI GdipSetEffectParameters(CGpEffect *effect,
4320     const VOID *params, const UINT size)
4321 {
4322     static int calls;
4323
4324     TRACE("(%p,%p,%u)\n", effect, params, size);
4325
4326     if(!(calls++))
4327         FIXME("not implemented\n");
4328
4329     return NotImplemented;
4330 }
4331
4332 /*****************************************************************************
4333  * GdipGetImageFlags [GDIPLUS.@]
4334  */
4335 GpStatus WINGDIPAPI GdipGetImageFlags(GpImage *image, UINT *flags)
4336 {
4337     TRACE("%p %p\n", image, flags);
4338
4339     if(!image || !flags)
4340         return InvalidParameter;
4341
4342     *flags = image->flags;
4343
4344     return Ok;
4345 }
4346
4347 GpStatus WINGDIPAPI GdipTestControl(GpTestControlEnum control, void *param)
4348 {
4349     TRACE("(%d, %p)\n", control, param);
4350
4351     switch(control){
4352         case TestControlForceBilinear:
4353             if(param)
4354                 FIXME("TestControlForceBilinear not handled\n");
4355             break;
4356         case TestControlNoICM:
4357             if(param)
4358                 FIXME("TestControlNoICM not handled\n");
4359             break;
4360         case TestControlGetBuildNumber:
4361             *((DWORD*)param) = 3102;
4362             break;
4363     }
4364
4365     return Ok;
4366 }
4367
4368 GpStatus WINGDIPAPI GdipRecordMetafileFileName(GDIPCONST WCHAR* fileName,
4369                             HDC hdc, EmfType type, GDIPCONST GpRectF *pFrameRect,
4370                             MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc,
4371                             GpMetafile **metafile)
4372 {
4373     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4374                                  frameUnit, debugstr_w(desc), metafile);
4375
4376     return NotImplemented;
4377 }
4378
4379 GpStatus WINGDIPAPI GdipRecordMetafileFileNameI(GDIPCONST WCHAR* fileName, HDC hdc, EmfType type,
4380                             GDIPCONST GpRect *pFrameRect, MetafileFrameUnit frameUnit,
4381                             GDIPCONST WCHAR *desc, GpMetafile **metafile)
4382 {
4383     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4384                                  frameUnit, debugstr_w(desc), metafile);
4385
4386     return NotImplemented;
4387 }
4388
4389 GpStatus WINGDIPAPI GdipImageForceValidation(GpImage *image)
4390 {
4391     TRACE("%p\n", image);
4392
4393     return Ok;
4394 }
4395
4396 /*****************************************************************************
4397  * GdipGetImageThumbnail [GDIPLUS.@]
4398  */
4399 GpStatus WINGDIPAPI GdipGetImageThumbnail(GpImage *image, UINT width, UINT height,
4400                             GpImage **ret_image, GetThumbnailImageAbort cb,
4401                             VOID * cb_data)
4402 {
4403     GpStatus stat;
4404     GpGraphics *graphics;
4405     UINT srcwidth, srcheight;
4406
4407     TRACE("(%p %u %u %p %p %p)\n",
4408         image, width, height, ret_image, cb, cb_data);
4409
4410     if (!image || !ret_image)
4411         return InvalidParameter;
4412
4413     if (!width) width = 120;
4414     if (!height) height = 120;
4415
4416     GdipGetImageWidth(image, &srcwidth);
4417     GdipGetImageHeight(image, &srcheight);
4418
4419     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppARGB,
4420         NULL, (GpBitmap**)ret_image);
4421
4422     if (stat == Ok)
4423     {
4424         stat = GdipGetImageGraphicsContext(*ret_image, &graphics);
4425
4426         if (stat == Ok)
4427         {
4428             stat = GdipDrawImageRectRectI(graphics, image,
4429                 0, 0, width, height, 0, 0, srcwidth, srcheight, UnitPixel,
4430                 NULL, NULL, NULL);
4431
4432             GdipDeleteGraphics(graphics);
4433         }
4434
4435         if (stat != Ok)
4436         {
4437             GdipDisposeImage(*ret_image);
4438             *ret_image = NULL;
4439         }
4440     }
4441
4442     return stat;
4443 }
4444
4445 /*****************************************************************************
4446  * GdipImageRotateFlip [GDIPLUS.@]
4447  */
4448 GpStatus WINGDIPAPI GdipImageRotateFlip(GpImage *image, RotateFlipType type)
4449 {
4450     GpBitmap *new_bitmap;
4451     GpBitmap *bitmap;
4452     int bpp, bytesperpixel;
4453     int rotate_90, flip_x, flip_y;
4454     int src_x_offset, src_y_offset;
4455     LPBYTE src_origin;
4456     UINT x, y, width, height;
4457     BitmapData src_lock, dst_lock;
4458     GpStatus stat;
4459
4460     TRACE("(%p, %u)\n", image, type);
4461
4462     if (!image)
4463         return InvalidParameter;
4464
4465     rotate_90 = type&1;
4466     flip_x = (type&6) == 2 || (type&6) == 4;
4467     flip_y = (type&3) == 1 || (type&3) == 2;
4468
4469     if (image->type != ImageTypeBitmap)
4470     {
4471         FIXME("Not implemented for type %i\n", image->type);
4472         return NotImplemented;
4473     }
4474
4475     bitmap = (GpBitmap*)image;
4476     bpp = PIXELFORMATBPP(bitmap->format);
4477
4478     if (bpp < 8)
4479     {
4480         FIXME("Not implemented for %i bit images\n", bpp);
4481         return NotImplemented;
4482     }
4483
4484     if (rotate_90)
4485     {
4486         width = bitmap->height;
4487         height = bitmap->width;
4488     }
4489     else
4490     {
4491         width = bitmap->width;
4492         height = bitmap->height;
4493     }
4494
4495     bytesperpixel = bpp/8;
4496
4497     stat = GdipCreateBitmapFromScan0(width, height, 0, bitmap->format, NULL, &new_bitmap);
4498
4499     if (stat != Ok)
4500         return stat;
4501
4502     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format, &src_lock);
4503
4504     if (stat == Ok)
4505     {
4506         stat = GdipBitmapLockBits(new_bitmap, NULL, ImageLockModeWrite, bitmap->format, &dst_lock);
4507
4508         if (stat == Ok)
4509         {
4510             LPBYTE src_row, src_pixel;
4511             LPBYTE dst_row, dst_pixel;
4512
4513             src_origin = src_lock.Scan0;
4514             if (flip_x) src_origin += bytesperpixel * (bitmap->width - 1);
4515             if (flip_y) src_origin += src_lock.Stride * (bitmap->height - 1);
4516
4517             if (rotate_90)
4518             {
4519                 if (flip_y) src_x_offset = -src_lock.Stride;
4520                 else src_x_offset = src_lock.Stride;
4521                 if (flip_x) src_y_offset = -bytesperpixel;
4522                 else src_y_offset = bytesperpixel;
4523             }
4524             else
4525             {
4526                 if (flip_x) src_x_offset = -bytesperpixel;
4527                 else src_x_offset = bytesperpixel;
4528                 if (flip_y) src_y_offset = -src_lock.Stride;
4529                 else src_y_offset = src_lock.Stride;
4530             }
4531
4532             src_row = src_origin;
4533             dst_row = dst_lock.Scan0;
4534             for (y=0; y<height; y++)
4535             {
4536                 src_pixel = src_row;
4537                 dst_pixel = dst_row;
4538                 for (x=0; x<width; x++)
4539                 {
4540                     /* FIXME: This could probably be faster without memcpy. */
4541                     memcpy(dst_pixel, src_pixel, bytesperpixel);
4542                     dst_pixel += bytesperpixel;
4543                     src_pixel += src_x_offset;
4544                 }
4545                 src_row += src_y_offset;
4546                 dst_row += dst_lock.Stride;
4547             }
4548
4549             GdipBitmapUnlockBits(new_bitmap, &dst_lock);
4550         }
4551
4552         GdipBitmapUnlockBits(bitmap, &src_lock);
4553     }
4554
4555     if (stat == Ok)
4556         move_bitmap(bitmap, new_bitmap, FALSE);
4557     else
4558         GdipDisposeImage((GpImage*)new_bitmap);
4559
4560     return stat;
4561 }
4562
4563 /*****************************************************************************
4564  * GdipConvertToEmfPlusToFile [GDIPLUS.@]
4565  */
4566
4567 GpStatus WINGDIPAPI GdipConvertToEmfPlusToFile(const GpGraphics* refGraphics,
4568                                                GpMetafile* metafile, BOOL* conversionSuccess,
4569                                                const WCHAR* filename, EmfType emfType,
4570                                                const WCHAR* description, GpMetafile** out_metafile)
4571 {
4572     FIXME("stub: %p, %p, %p, %p, %u, %p, %p\n", refGraphics, metafile, conversionSuccess, filename, emfType, description, out_metafile);
4573     return NotImplemented;
4574 }