wbemprox: Add support for uncommitted instances in IWbemClassObject::Get.
[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 = gdip_round(x);
1252     area.Y = gdip_round(y);
1253     area.Width = gdip_round(width);
1254     area.Height = gdip_round(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     (*bitmap)->prop_count = 0;
1915     (*bitmap)->prop_item = NULL;
1916
1917     /* set format-related flags */
1918     if (format & (PixelFormatAlpha|PixelFormatPAlpha|PixelFormatIndexed))
1919         (*bitmap)->image.flags |= ImageFlagsHasAlpha;
1920
1921     if (format == PixelFormat1bppIndexed ||
1922         format == PixelFormat4bppIndexed ||
1923         format == PixelFormat8bppIndexed)
1924     {
1925         (*bitmap)->image.palette = GdipAlloc(sizeof(UINT) * 2 + sizeof(ARGB) * (1 << PIXELFORMATBPP(format)));
1926
1927         if (!(*bitmap)->image.palette)
1928         {
1929             GdipDisposeImage(&(*bitmap)->image);
1930             *bitmap = NULL;
1931             return OutOfMemory;
1932         }
1933
1934         (*bitmap)->image.palette->Count = 1 << PIXELFORMATBPP(format);
1935
1936         if (format == PixelFormat1bppIndexed)
1937         {
1938             (*bitmap)->image.palette->Flags = PaletteFlagsGrayScale;
1939             (*bitmap)->image.palette->Entries[0] = 0xff000000;
1940             (*bitmap)->image.palette->Entries[1] = 0xffffffff;
1941         }
1942         else
1943         {
1944             if (format == PixelFormat8bppIndexed)
1945                 (*bitmap)->image.palette->Flags = PaletteFlagsHalftone;
1946
1947             generate_halftone_palette((*bitmap)->image.palette->Entries,
1948                 (*bitmap)->image.palette->Count);
1949         }
1950     }
1951
1952     TRACE("<-- %p\n", *bitmap);
1953
1954     return Ok;
1955 }
1956
1957 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
1958     GpBitmap **bitmap)
1959 {
1960     GpStatus stat;
1961
1962     TRACE("%p %p\n", stream, bitmap);
1963
1964     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
1965
1966     if(stat != Ok)
1967         return stat;
1968
1969     if((*bitmap)->image.type != ImageTypeBitmap){
1970         GdipDisposeImage(&(*bitmap)->image);
1971         *bitmap = NULL;
1972         return GenericError; /* FIXME: what error to return? */
1973     }
1974
1975     return Ok;
1976 }
1977
1978 /* FIXME: no icm */
1979 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
1980     GpBitmap **bitmap)
1981 {
1982     TRACE("%p %p\n", stream, bitmap);
1983
1984     return GdipCreateBitmapFromStream(stream, bitmap);
1985 }
1986
1987 GpStatus WINGDIPAPI GdipCreateCachedBitmap(GpBitmap *bitmap, GpGraphics *graphics,
1988     GpCachedBitmap **cachedbmp)
1989 {
1990     GpStatus stat;
1991
1992     TRACE("%p %p %p\n", bitmap, graphics, cachedbmp);
1993
1994     if(!bitmap || !graphics || !cachedbmp)
1995         return InvalidParameter;
1996
1997     *cachedbmp = GdipAlloc(sizeof(GpCachedBitmap));
1998     if(!*cachedbmp)
1999         return OutOfMemory;
2000
2001     stat = GdipCloneImage(&(bitmap->image), &(*cachedbmp)->image);
2002     if(stat != Ok){
2003         GdipFree(*cachedbmp);
2004         return stat;
2005     }
2006
2007     return Ok;
2008 }
2009
2010 GpStatus WINGDIPAPI GdipCreateHICONFromBitmap(GpBitmap *bitmap, HICON *hicon)
2011 {
2012     GpStatus stat;
2013     BitmapData lockeddata;
2014     ULONG andstride, xorstride, bitssize;
2015     LPBYTE andbits, xorbits, androw, xorrow, srcrow;
2016     UINT x, y;
2017
2018     TRACE("(%p, %p)\n", bitmap, hicon);
2019
2020     if (!bitmap || !hicon)
2021         return InvalidParameter;
2022
2023     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead,
2024         PixelFormat32bppPARGB, &lockeddata);
2025     if (stat == Ok)
2026     {
2027         andstride = ((lockeddata.Width+31)/32)*4;
2028         xorstride = lockeddata.Width*4;
2029         bitssize = (andstride + xorstride) * lockeddata.Height;
2030
2031         andbits = GdipAlloc(bitssize);
2032
2033         if (andbits)
2034         {
2035             xorbits = andbits + andstride * lockeddata.Height;
2036
2037             for (y=0; y<lockeddata.Height; y++)
2038             {
2039                 srcrow = ((LPBYTE)lockeddata.Scan0) + lockeddata.Stride * y;
2040
2041                 androw = andbits + andstride * y;
2042                 for (x=0; x<lockeddata.Width; x++)
2043                     if (srcrow[3+4*x] >= 128)
2044                         androw[x/8] |= 1 << (7-x%8);
2045
2046                 xorrow = xorbits + xorstride * y;
2047                 memcpy(xorrow, srcrow, xorstride);
2048             }
2049
2050             *hicon = CreateIcon(NULL, lockeddata.Width, lockeddata.Height, 1, 32,
2051                 andbits, xorbits);
2052
2053             GdipFree(andbits);
2054         }
2055         else
2056             stat = OutOfMemory;
2057
2058         GdipBitmapUnlockBits(bitmap, &lockeddata);
2059     }
2060
2061     return stat;
2062 }
2063
2064 GpStatus WINGDIPAPI GdipDeleteCachedBitmap(GpCachedBitmap *cachedbmp)
2065 {
2066     TRACE("%p\n", cachedbmp);
2067
2068     if(!cachedbmp)
2069         return InvalidParameter;
2070
2071     GdipDisposeImage(cachedbmp->image);
2072     GdipFree(cachedbmp);
2073
2074     return Ok;
2075 }
2076
2077 GpStatus WINGDIPAPI GdipDrawCachedBitmap(GpGraphics *graphics,
2078     GpCachedBitmap *cachedbmp, INT x, INT y)
2079 {
2080     TRACE("%p %p %d %d\n", graphics, cachedbmp, x, y);
2081
2082     if(!graphics || !cachedbmp)
2083         return InvalidParameter;
2084
2085     return GdipDrawImage(graphics, cachedbmp->image, (REAL)x, (REAL)y);
2086 }
2087
2088 GpStatus WINGDIPAPI GdipEmfToWmfBits(HENHMETAFILE hemf, UINT cbData16,
2089     LPBYTE pData16, INT iMapMode, INT eFlags)
2090 {
2091     FIXME("(%p, %d, %p, %d, %d): stub\n", hemf, cbData16, pData16, iMapMode, eFlags);
2092     return NotImplemented;
2093 }
2094
2095 /* Internal utility function: Replace the image data of dst with that of src,
2096  * and free src. */
2097 static void move_bitmap(GpBitmap *dst, GpBitmap *src, BOOL clobber_palette)
2098 {
2099     assert(src->image.type == ImageTypeBitmap);
2100     assert(dst->image.type == ImageTypeBitmap);
2101
2102     GdipFree(dst->bitmapbits);
2103     GdipFree(dst->own_bits);
2104     DeleteDC(dst->hdc);
2105     DeleteObject(dst->hbitmap);
2106
2107     if (clobber_palette)
2108     {
2109         GdipFree(dst->image.palette);
2110         dst->image.palette = src->image.palette;
2111     }
2112     else
2113         GdipFree(src->image.palette);
2114
2115     dst->image.xres = src->image.xres;
2116     dst->image.yres = src->image.yres;
2117     dst->width = src->width;
2118     dst->height = src->height;
2119     dst->format = src->format;
2120     dst->hbitmap = src->hbitmap;
2121     dst->hdc = src->hdc;
2122     dst->bits = src->bits;
2123     dst->stride = src->stride;
2124     dst->own_bits = src->own_bits;
2125     if (dst->metadata_reader)
2126         IWICMetadataReader_Release(dst->metadata_reader);
2127     dst->metadata_reader = src->metadata_reader;
2128     GdipFree(dst->prop_item);
2129     dst->prop_item = src->prop_item;
2130     dst->prop_count = src->prop_count;
2131     if (dst->image.stream)
2132         IStream_Release(dst->image.stream);
2133     dst->image.stream = src->image.stream;
2134     dst->image.frame_count = src->image.frame_count;
2135     dst->image.current_frame = src->image.current_frame;
2136     dst->image.format = src->image.format;
2137
2138     src->image.type = ~0;
2139     GdipFree(src);
2140 }
2141
2142 static GpStatus free_image_data(GpImage *image)
2143 {
2144     if(!image)
2145         return InvalidParameter;
2146
2147     if (image->type == ImageTypeBitmap)
2148     {
2149         GdipFree(((GpBitmap*)image)->bitmapbits);
2150         GdipFree(((GpBitmap*)image)->own_bits);
2151         DeleteDC(((GpBitmap*)image)->hdc);
2152         DeleteObject(((GpBitmap*)image)->hbitmap);
2153         if (((GpBitmap*)image)->metadata_reader)
2154             IWICMetadataReader_Release(((GpBitmap*)image)->metadata_reader);
2155         GdipFree(((GpBitmap*)image)->prop_item);
2156     }
2157     else if (image->type == ImageTypeMetafile)
2158     {
2159         GpMetafile *metafile = (GpMetafile*)image;
2160         GdipFree(metafile->comment_data);
2161         DeleteEnhMetaFile(CloseEnhMetaFile(metafile->record_dc));
2162         DeleteEnhMetaFile(metafile->hemf);
2163         if (metafile->record_graphics)
2164         {
2165             WARN("metafile closed while recording\n");
2166             /* not sure what to do here; for now just prevent the graphics from functioning or using this object */
2167             metafile->record_graphics->image = NULL;
2168             metafile->record_graphics->busy = TRUE;
2169         }
2170     }
2171     else
2172     {
2173         WARN("invalid image: %p\n", image);
2174         return ObjectBusy;
2175     }
2176     if (image->picture)
2177         IPicture_Release(image->picture);
2178     if (image->stream)
2179         IStream_Release(image->stream);
2180     GdipFree(image->palette);
2181
2182     return Ok;
2183 }
2184
2185 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
2186 {
2187     GpStatus status;
2188
2189     TRACE("%p\n", image);
2190
2191     status = free_image_data(image);
2192     if (status != Ok) return status;
2193     image->type = ~0;
2194     GdipFree(image);
2195
2196     return Ok;
2197 }
2198
2199 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
2200 {
2201     static int calls;
2202
2203     TRACE("(%p,%p)\n", image, item);
2204
2205     if(!image || !item)
2206         return InvalidParameter;
2207
2208     if (!(calls++))
2209         FIXME("not implemented\n");
2210
2211     return NotImplemented;
2212 }
2213
2214 GpStatus WINGDIPAPI GdipGetImageItemData(GpImage *image, ImageItemData *item)
2215 {
2216     static int calls;
2217
2218     TRACE("(%p,%p)\n", image, item);
2219
2220     if (!(calls++))
2221         FIXME("not implemented\n");
2222
2223     return NotImplemented;
2224 }
2225
2226 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
2227     GpUnit *srcUnit)
2228 {
2229     TRACE("%p %p %p\n", image, srcRect, srcUnit);
2230
2231     if(!image || !srcRect || !srcUnit)
2232         return InvalidParameter;
2233     if(image->type == ImageTypeMetafile){
2234         *srcRect = ((GpMetafile*)image)->bounds;
2235         *srcUnit = ((GpMetafile*)image)->unit;
2236     }
2237     else if(image->type == ImageTypeBitmap){
2238         srcRect->X = srcRect->Y = 0.0;
2239         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
2240         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
2241         *srcUnit = UnitPixel;
2242     }
2243     else{
2244         srcRect->X = srcRect->Y = 0.0;
2245         srcRect->Width = ipicture_pixel_width(image->picture);
2246         srcRect->Height = ipicture_pixel_height(image->picture);
2247         *srcUnit = UnitPixel;
2248     }
2249
2250     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
2251           srcRect->Width, srcRect->Height, *srcUnit);
2252
2253     return Ok;
2254 }
2255
2256 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
2257     REAL *height)
2258 {
2259     TRACE("%p %p %p\n", image, width, height);
2260
2261     if(!image || !height || !width)
2262         return InvalidParameter;
2263
2264     if(image->type == ImageTypeMetafile){
2265         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2266         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2267     }
2268     else if(image->type == ImageTypeBitmap){
2269         *height = ((GpBitmap*)image)->height;
2270         *width = ((GpBitmap*)image)->width;
2271     }
2272     else{
2273         *height = ipicture_pixel_height(image->picture);
2274         *width = ipicture_pixel_width(image->picture);
2275     }
2276
2277     TRACE("returning (%f, %f)\n", *height, *width);
2278     return Ok;
2279 }
2280
2281 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
2282     GpGraphics **graphics)
2283 {
2284     HDC hdc;
2285     GpStatus stat;
2286
2287     TRACE("%p %p\n", image, graphics);
2288
2289     if(!image || !graphics)
2290         return InvalidParameter;
2291
2292     if (image->type == ImageTypeBitmap && ((GpBitmap*)image)->hbitmap)
2293     {
2294         hdc = ((GpBitmap*)image)->hdc;
2295
2296         if(!hdc){
2297             hdc = CreateCompatibleDC(0);
2298             SelectObject(hdc, ((GpBitmap*)image)->hbitmap);
2299             ((GpBitmap*)image)->hdc = hdc;
2300         }
2301
2302         stat = GdipCreateFromHDC(hdc, graphics);
2303
2304         if (stat == Ok)
2305         {
2306             (*graphics)->image = image;
2307             (*graphics)->xres = image->xres;
2308             (*graphics)->yres = image->yres;
2309         }
2310     }
2311     else if (image->type == ImageTypeMetafile)
2312         stat = METAFILE_GetGraphicsContext((GpMetafile*)image, graphics);
2313     else
2314         stat = graphics_from_image(image, graphics);
2315
2316     return stat;
2317 }
2318
2319 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
2320 {
2321     TRACE("%p %p\n", image, height);
2322
2323     if(!image || !height)
2324         return InvalidParameter;
2325
2326     if(image->type == ImageTypeMetafile)
2327         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2328     else if(image->type == ImageTypeBitmap)
2329         *height = ((GpBitmap*)image)->height;
2330     else
2331         *height = ipicture_pixel_height(image->picture);
2332
2333     TRACE("returning %d\n", *height);
2334
2335     return Ok;
2336 }
2337
2338 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
2339 {
2340     if(!image || !res)
2341         return InvalidParameter;
2342
2343     *res = image->xres;
2344
2345     TRACE("(%p) <-- %0.2f\n", image, *res);
2346
2347     return Ok;
2348 }
2349
2350 GpStatus WINGDIPAPI GdipGetImagePaletteSize(GpImage *image, INT *size)
2351 {
2352     TRACE("%p %p\n", image, size);
2353
2354     if(!image || !size)
2355         return InvalidParameter;
2356
2357     if (!image->palette || image->palette->Count == 0)
2358         *size = sizeof(ColorPalette);
2359     else
2360         *size = sizeof(UINT)*2 + sizeof(ARGB)*image->palette->Count;
2361
2362     TRACE("<-- %u\n", *size);
2363
2364     return Ok;
2365 }
2366
2367 /* FIXME: test this function for non-bitmap types */
2368 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
2369 {
2370     TRACE("%p %p\n", image, format);
2371
2372     if(!image || !format)
2373         return InvalidParameter;
2374
2375     if(image->type != ImageTypeBitmap)
2376         *format = PixelFormat24bppRGB;
2377     else
2378         *format = ((GpBitmap*) image)->format;
2379
2380     return Ok;
2381 }
2382
2383 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
2384 {
2385     TRACE("(%p, %p)\n", image, format);
2386
2387     if(!image || !format)
2388         return InvalidParameter;
2389
2390     memcpy(format, &image->format, sizeof(GUID));
2391
2392     return Ok;
2393 }
2394
2395 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
2396 {
2397     TRACE("%p %p\n", image, type);
2398
2399     if(!image || !type)
2400         return InvalidParameter;
2401
2402     *type = image->type;
2403
2404     return Ok;
2405 }
2406
2407 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
2408 {
2409     if(!image || !res)
2410         return InvalidParameter;
2411
2412     *res = image->yres;
2413
2414     TRACE("(%p) <-- %0.2f\n", image, *res);
2415
2416     return Ok;
2417 }
2418
2419 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
2420 {
2421     TRACE("%p %p\n", image, width);
2422
2423     if(!image || !width)
2424         return InvalidParameter;
2425
2426     if(image->type == ImageTypeMetafile)
2427         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2428     else if(image->type == ImageTypeBitmap)
2429         *width = ((GpBitmap*)image)->width;
2430     else
2431         *width = ipicture_pixel_width(image->picture);
2432
2433     TRACE("returning %d\n", *width);
2434
2435     return Ok;
2436 }
2437
2438 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
2439     MetafileHeader * header)
2440 {
2441     static int calls;
2442
2443     TRACE("(%p, %p)\n", metafile, header);
2444
2445     if(!metafile || !header)
2446         return InvalidParameter;
2447
2448     if(!(calls++))
2449         FIXME("not implemented\n");
2450
2451     memset(header, 0, sizeof(MetafileHeader));
2452
2453     return Ok;
2454 }
2455
2456 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromEmf(HENHMETAFILE hEmf,
2457     MetafileHeader *header)
2458 {
2459     static int calls;
2460
2461     if(!hEmf || !header)
2462         return InvalidParameter;
2463
2464     if(!(calls++))
2465         FIXME("not implemented\n");
2466
2467     memset(header, 0, sizeof(MetafileHeader));
2468
2469     return Ok;
2470 }
2471
2472 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromFile(GDIPCONST WCHAR *filename,
2473     MetafileHeader *header)
2474 {
2475     static int calls;
2476
2477     TRACE("(%s,%p)\n", debugstr_w(filename), header);
2478
2479     if(!filename || !header)
2480         return InvalidParameter;
2481
2482     if(!(calls++))
2483         FIXME("not implemented\n");
2484
2485     memset(header, 0, sizeof(MetafileHeader));
2486
2487     return Ok;
2488 }
2489
2490 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromStream(IStream *stream,
2491     MetafileHeader *header)
2492 {
2493     static int calls;
2494
2495     TRACE("(%p,%p)\n", stream, header);
2496
2497     if(!stream || !header)
2498         return InvalidParameter;
2499
2500     if(!(calls++))
2501         FIXME("not implemented\n");
2502
2503     memset(header, 0, sizeof(MetafileHeader));
2504
2505     return Ok;
2506 }
2507
2508 GpStatus WINGDIPAPI GdipGetPropertyCount(GpImage *image, UINT *num)
2509 {
2510     TRACE("(%p, %p)\n", image, num);
2511
2512     if (!image || !num) return InvalidParameter;
2513
2514     *num = 0;
2515
2516     if (image->type == ImageTypeBitmap)
2517     {
2518         if (((GpBitmap *)image)->prop_item)
2519         {
2520             *num = ((GpBitmap *)image)->prop_count;
2521             return Ok;
2522         }
2523
2524         if (((GpBitmap *)image)->metadata_reader)
2525             IWICMetadataReader_GetCount(((GpBitmap *)image)->metadata_reader, num);
2526     }
2527
2528     return Ok;
2529 }
2530
2531 GpStatus WINGDIPAPI GdipGetPropertyIdList(GpImage *image, UINT num, PROPID *list)
2532 {
2533     HRESULT hr;
2534     IWICMetadataReader *reader;
2535     IWICEnumMetadataItem *enumerator;
2536     UINT prop_count, i, items_returned;
2537
2538     TRACE("(%p, %u, %p)\n", image, num, list);
2539
2540     if (!image || !list) return InvalidParameter;
2541
2542     if (image->type != ImageTypeBitmap)
2543     {
2544         FIXME("Not implemented for type %d\n", image->type);
2545         return NotImplemented;
2546     }
2547
2548     if (((GpBitmap *)image)->prop_item)
2549     {
2550         if (num != ((GpBitmap *)image)->prop_count) return InvalidParameter;
2551
2552         for (i = 0; i < num; i++)
2553         {
2554             list[i] = ((GpBitmap *)image)->prop_item[i].id;
2555         }
2556
2557         return Ok;
2558     }
2559
2560     reader = ((GpBitmap *)image)->metadata_reader;
2561     if (!reader)
2562     {
2563         if (num != 0) return InvalidParameter;
2564         return Ok;
2565     }
2566
2567     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2568     if (FAILED(hr)) return hresult_to_status(hr);
2569
2570     if (num != prop_count) return InvalidParameter;
2571
2572     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2573     if (FAILED(hr)) return hresult_to_status(hr);
2574
2575     IWICEnumMetadataItem_Reset(enumerator);
2576
2577     for (i = 0; i < num; i++)
2578     {
2579         PROPVARIANT id;
2580
2581         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, NULL, &items_returned);
2582         if (hr != S_OK) break;
2583
2584         if (id.vt != VT_UI2)
2585         {
2586             FIXME("not supported propvariant type for id: %u\n", id.vt);
2587             list[i] = 0;
2588             continue;
2589         }
2590         list[i] = id.u.uiVal;
2591     }
2592
2593     IWICEnumMetadataItem_Release(enumerator);
2594
2595     return hr == S_OK ? Ok : hresult_to_status(hr);
2596 }
2597
2598 static UINT propvariant_size(PROPVARIANT *value)
2599 {
2600     switch (value->vt & ~VT_VECTOR)
2601     {
2602     case VT_EMPTY:
2603         return 0;
2604     case VT_I1:
2605     case VT_UI1:
2606         if (!(value->vt & VT_VECTOR)) return 1;
2607         return value->u.caub.cElems;
2608     case VT_I2:
2609     case VT_UI2:
2610         if (!(value->vt & VT_VECTOR)) return 2;
2611         return value->u.caui.cElems * 2;
2612     case VT_I4:
2613     case VT_UI4:
2614     case VT_R4:
2615         if (!(value->vt & VT_VECTOR)) return 4;
2616         return value->u.caul.cElems * 4;
2617     case VT_I8:
2618     case VT_UI8:
2619     case VT_R8:
2620         if (!(value->vt & VT_VECTOR)) return 8;
2621         return value->u.cauh.cElems * 8;
2622     case VT_LPSTR:
2623         return value->u.pszVal ? strlen(value->u.pszVal) + 1 : 0;
2624     case VT_BLOB:
2625         return value->u.blob.cbSize;
2626     default:
2627         FIXME("not supported variant type %d\n", value->vt);
2628         return 0;
2629     }
2630 }
2631
2632 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID propid, UINT *size)
2633 {
2634     HRESULT hr;
2635     IWICMetadataReader *reader;
2636     PROPVARIANT id, value;
2637
2638     TRACE("(%p,%#x,%p)\n", image, propid, size);
2639
2640     if (!size || !image) return InvalidParameter;
2641
2642     if (image->type != ImageTypeBitmap)
2643     {
2644         FIXME("Not implemented for type %d\n", image->type);
2645         return NotImplemented;
2646     }
2647
2648     if (((GpBitmap *)image)->prop_item)
2649     {
2650         UINT i;
2651
2652         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2653         {
2654             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2655             {
2656                 *size = sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2657                 return Ok;
2658             }
2659         }
2660
2661         return PropertyNotFound;
2662     }
2663
2664     reader = ((GpBitmap *)image)->metadata_reader;
2665     if (!reader) return PropertyNotFound;
2666
2667     id.vt = VT_UI2;
2668     id.u.uiVal = propid;
2669     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2670     if (FAILED(hr)) return PropertyNotFound;
2671
2672     *size = propvariant_size(&value);
2673     if (*size) *size += sizeof(PropertyItem);
2674     PropVariantClear(&value);
2675
2676     return Ok;
2677 }
2678
2679 #ifndef PropertyTagTypeSByte
2680 #define PropertyTagTypeSByte  6
2681 #define PropertyTagTypeSShort 8
2682 #define PropertyTagTypeFloat  11
2683 #define PropertyTagTypeDouble 12
2684 #endif
2685
2686 static UINT vt_to_itemtype(UINT vt)
2687 {
2688     static const struct
2689     {
2690         UINT vt, type;
2691     } vt2type[] =
2692     {
2693         { VT_I1, PropertyTagTypeSByte },
2694         { VT_UI1, PropertyTagTypeByte },
2695         { VT_I2, PropertyTagTypeSShort },
2696         { VT_UI2, PropertyTagTypeShort },
2697         { VT_I4, PropertyTagTypeSLONG },
2698         { VT_UI4, PropertyTagTypeLong },
2699         { VT_I8, PropertyTagTypeSRational },
2700         { VT_UI8, PropertyTagTypeRational },
2701         { VT_R4, PropertyTagTypeFloat },
2702         { VT_R8, PropertyTagTypeDouble },
2703         { VT_LPSTR, PropertyTagTypeASCII },
2704         { VT_BLOB, PropertyTagTypeUndefined }
2705     };
2706     UINT i;
2707     for (i = 0; i < sizeof(vt2type)/sizeof(vt2type[0]); i++)
2708     {
2709         if (vt2type[i].vt == vt) return vt2type[i].type;
2710     }
2711     FIXME("not supported variant type %u\n", vt);
2712     return 0;
2713 }
2714
2715 static GpStatus propvariant_to_item(PROPVARIANT *value, PropertyItem *item,
2716                                     UINT size, PROPID id)
2717 {
2718     UINT item_size, item_type;
2719
2720     item_size = propvariant_size(value);
2721     if (size != item_size + sizeof(PropertyItem)) return InvalidParameter;
2722
2723     item_type = vt_to_itemtype(value->vt & ~VT_VECTOR);
2724     if (!item_type) return InvalidParameter;
2725
2726     item->value = item + 1;
2727
2728     switch (value->vt & ~VT_VECTOR)
2729     {
2730     case VT_I1:
2731     case VT_UI1:
2732         if (!(value->vt & VT_VECTOR))
2733             *(BYTE *)item->value = value->u.bVal;
2734         else
2735             memcpy(item->value, value->u.caub.pElems, item_size);
2736         break;
2737     case VT_I2:
2738     case VT_UI2:
2739         if (!(value->vt & VT_VECTOR))
2740             *(USHORT *)item->value = value->u.uiVal;
2741         else
2742             memcpy(item->value, value->u.caui.pElems, item_size);
2743         break;
2744     case VT_I4:
2745     case VT_UI4:
2746     case VT_R4:
2747         if (!(value->vt & VT_VECTOR))
2748             *(ULONG *)item->value = value->u.ulVal;
2749         else
2750             memcpy(item->value, value->u.caul.pElems, item_size);
2751         break;
2752     case VT_I8:
2753     case VT_UI8:
2754     case VT_R8:
2755         if (!(value->vt & VT_VECTOR))
2756             *(ULONGLONG *)item->value = value->u.uhVal.QuadPart;
2757         else
2758             memcpy(item->value, value->u.cauh.pElems, item_size);
2759         break;
2760     case VT_LPSTR:
2761         memcpy(item->value, value->u.pszVal, item_size);
2762         break;
2763     case VT_BLOB:
2764         memcpy(item->value, value->u.blob.pBlobData, item_size);
2765         break;
2766     default:
2767         FIXME("not supported variant type %d\n", value->vt);
2768         return InvalidParameter;
2769     }
2770
2771     item->length = item_size;
2772     item->type = item_type;
2773     item->id = id;
2774
2775     return Ok;
2776 }
2777
2778 GpStatus WINGDIPAPI GdipGetPropertyItem(GpImage *image, PROPID propid, UINT size,
2779                                         PropertyItem *buffer)
2780 {
2781     GpStatus stat;
2782     HRESULT hr;
2783     IWICMetadataReader *reader;
2784     PROPVARIANT id, value;
2785
2786     TRACE("(%p,%#x,%u,%p)\n", image, propid, size, buffer);
2787
2788     if (!image || !buffer) return InvalidParameter;
2789
2790     if (image->type != ImageTypeBitmap)
2791     {
2792         FIXME("Not implemented for type %d\n", image->type);
2793         return NotImplemented;
2794     }
2795
2796     if (((GpBitmap *)image)->prop_item)
2797     {
2798         UINT i;
2799
2800         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2801         {
2802             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2803             {
2804                 if (size != sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length)
2805                     return InvalidParameter;
2806
2807                 *buffer = ((GpBitmap *)image)->prop_item[i];
2808                 buffer->value = buffer + 1;
2809                 memcpy(buffer->value, ((GpBitmap *)image)->prop_item[i].value, buffer->length);
2810                 return Ok;
2811             }
2812         }
2813
2814         return PropertyNotFound;
2815     }
2816
2817     reader = ((GpBitmap *)image)->metadata_reader;
2818     if (!reader) return PropertyNotFound;
2819
2820     id.vt = VT_UI2;
2821     id.u.uiVal = propid;
2822     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2823     if (FAILED(hr)) return PropertyNotFound;
2824
2825     stat = propvariant_to_item(&value, buffer, size, propid);
2826     PropVariantClear(&value);
2827
2828     return stat;
2829 }
2830
2831 GpStatus WINGDIPAPI GdipGetPropertySize(GpImage *image, UINT *size, UINT *count)
2832 {
2833     HRESULT hr;
2834     IWICMetadataReader *reader;
2835     IWICEnumMetadataItem *enumerator;
2836     UINT prop_count, prop_size, i;
2837     PROPVARIANT id, value;
2838
2839     TRACE("(%p,%p,%p)\n", image, size, count);
2840
2841     if (!image || !size || !count) return InvalidParameter;
2842
2843     if (image->type != ImageTypeBitmap)
2844     {
2845         FIXME("Not implemented for type %d\n", image->type);
2846         return NotImplemented;
2847     }
2848
2849     if (((GpBitmap *)image)->prop_item)
2850     {
2851         *count = ((GpBitmap *)image)->prop_count;
2852         *size = 0;
2853
2854         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2855         {
2856             *size += sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2857         }
2858
2859         return Ok;
2860     }
2861
2862     reader = ((GpBitmap *)image)->metadata_reader;
2863     if (!reader) return PropertyNotFound;
2864
2865     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2866     if (FAILED(hr)) return hresult_to_status(hr);
2867
2868     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2869     if (FAILED(hr)) return hresult_to_status(hr);
2870
2871     IWICEnumMetadataItem_Reset(enumerator);
2872
2873     prop_size = 0;
2874
2875     PropVariantInit(&id);
2876     PropVariantInit(&value);
2877
2878     for (i = 0; i < prop_count; i++)
2879     {
2880         UINT items_returned, item_size;
2881
2882         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2883         if (hr != S_OK) break;
2884
2885         item_size = propvariant_size(&value);
2886         if (item_size) prop_size += sizeof(PropertyItem) + item_size;
2887
2888         PropVariantClear(&id);
2889         PropVariantClear(&value);
2890     }
2891
2892     IWICEnumMetadataItem_Release(enumerator);
2893
2894     if (hr != S_OK) return PropertyNotFound;
2895
2896     *count = prop_count;
2897     *size = prop_size;
2898     return Ok;
2899 }
2900
2901 GpStatus WINGDIPAPI GdipGetAllPropertyItems(GpImage *image, UINT size,
2902                                             UINT count, PropertyItem *buf)
2903 {
2904     GpStatus status;
2905     HRESULT hr;
2906     IWICMetadataReader *reader;
2907     IWICEnumMetadataItem *enumerator;
2908     UINT prop_count, prop_size, i;
2909     PROPVARIANT id, value;
2910     char *item_value;
2911
2912     TRACE("(%p,%u,%u,%p)\n", image, size, count, buf);
2913
2914     if (!image || !buf) return InvalidParameter;
2915
2916     if (image->type != ImageTypeBitmap)
2917     {
2918         FIXME("Not implemented for type %d\n", image->type);
2919         return NotImplemented;
2920     }
2921
2922     status = GdipGetPropertySize(image, &prop_size, &prop_count);
2923     if (status != Ok) return status;
2924
2925     if (prop_count != count || prop_size != size) return InvalidParameter;
2926
2927     if (((GpBitmap *)image)->prop_item)
2928     {
2929         memcpy(buf, ((GpBitmap *)image)->prop_item, prop_size);
2930
2931         item_value = (char *)(buf + prop_count);
2932
2933         for (i = 0; i < prop_count; i++)
2934         {
2935             buf[i].value = item_value;
2936             item_value += buf[i].length;
2937         }
2938
2939         return Ok;
2940     }
2941
2942     reader = ((GpBitmap *)image)->metadata_reader;
2943     if (!reader) return PropertyNotFound;
2944
2945     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2946     if (FAILED(hr)) return hresult_to_status(hr);
2947
2948     IWICEnumMetadataItem_Reset(enumerator);
2949
2950     item_value = (char *)(buf + prop_count);
2951
2952     PropVariantInit(&id);
2953     PropVariantInit(&value);
2954
2955     for (i = 0; i < prop_count; i++)
2956     {
2957         PropertyItem *item;
2958         UINT items_returned, item_size;
2959
2960         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2961         if (hr != S_OK) break;
2962
2963         if (id.vt != VT_UI2)
2964         {
2965             FIXME("not supported propvariant type for id: %u\n", id.vt);
2966             continue;
2967         }
2968
2969         item_size = propvariant_size(&value);
2970         if (item_size)
2971         {
2972             item = HeapAlloc(GetProcessHeap(), 0, item_size + sizeof(*item));
2973
2974             propvariant_to_item(&value, item, item_size + sizeof(*item), id.u.uiVal);
2975             buf[i].id = item->id;
2976             buf[i].type = item->type;
2977             buf[i].length = item_size;
2978             buf[i].value = item_value;
2979             memcpy(item_value, item->value, item_size);
2980             item_value += item_size;
2981
2982             HeapFree(GetProcessHeap(), 0, item);
2983         }
2984
2985         PropVariantClear(&id);
2986         PropVariantClear(&value);
2987     }
2988
2989     IWICEnumMetadataItem_Release(enumerator);
2990
2991     if (hr != S_OK) return PropertyNotFound;
2992
2993     return Ok;
2994 }
2995
2996 struct image_format_dimension
2997 {
2998     const GUID *format;
2999     const GUID *dimension;
3000 };
3001
3002 static const struct image_format_dimension image_format_dimensions[] =
3003 {
3004     {&ImageFormatGIF, &FrameDimensionTime},
3005     {&ImageFormatIcon, &FrameDimensionResolution},
3006     {NULL}
3007 };
3008
3009 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
3010     GDIPCONST GUID* dimensionID, UINT* count)
3011 {
3012     TRACE("(%p,%s,%p)\n", image, debugstr_guid(dimensionID), count);
3013
3014     if(!image || !count)
3015         return InvalidParameter;
3016
3017     if (!dimensionID ||
3018         IsEqualGUID(dimensionID, &image->format) ||
3019         IsEqualGUID(dimensionID, &FrameDimensionPage) ||
3020         IsEqualGUID(dimensionID, &FrameDimensionTime))
3021     {
3022         *count = image->frame_count;
3023         return Ok;
3024     }
3025
3026     return InvalidParameter;
3027 }
3028
3029 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsCount(GpImage *image,
3030     UINT* count)
3031 {
3032     TRACE("(%p, %p)\n", image, count);
3033
3034     /* Native gdiplus 1.1 does not yet support multiple frame dimensions. */
3035
3036     if(!image || !count)
3037         return InvalidParameter;
3038
3039     *count = 1;
3040
3041     return Ok;
3042 }
3043
3044 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
3045     GUID* dimensionIDs, UINT count)
3046 {
3047     int i;
3048     const GUID *result=NULL;
3049
3050     TRACE("(%p,%p,%u)\n", image, dimensionIDs, count);
3051
3052     if(!image || !dimensionIDs || count != 1)
3053         return InvalidParameter;
3054
3055     for (i=0; image_format_dimensions[i].format; i++)
3056     {
3057         if (IsEqualGUID(&image->format, image_format_dimensions[i].format))
3058         {
3059             result = image_format_dimensions[i].dimension;
3060             break;
3061         }
3062     }
3063
3064     if (!result)
3065         result = &FrameDimensionPage;
3066
3067     memcpy(dimensionIDs, result, sizeof(GUID));
3068
3069     return Ok;
3070 }
3071
3072 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
3073                                           GpImage **image)
3074 {
3075     GpStatus stat;
3076     IStream *stream;
3077
3078     TRACE("(%s) %p\n", debugstr_w(filename), image);
3079
3080     if (!filename || !image)
3081         return InvalidParameter;
3082
3083     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
3084
3085     if (stat != Ok)
3086         return stat;
3087
3088     stat = GdipLoadImageFromStream(stream, image);
3089
3090     IStream_Release(stream);
3091
3092     return stat;
3093 }
3094
3095 /* FIXME: no icm handling */
3096 GpStatus WINGDIPAPI GdipLoadImageFromFileICM(GDIPCONST WCHAR* filename,GpImage **image)
3097 {
3098     TRACE("(%s) %p\n", debugstr_w(filename), image);
3099
3100     return GdipLoadImageFromFile(filename, image);
3101 }
3102
3103 static void add_property(GpBitmap *bitmap, PropertyItem *item)
3104 {
3105     UINT prop_size, prop_count;
3106     PropertyItem *prop_item;
3107
3108     if (bitmap->prop_item == NULL)
3109     {
3110         prop_size = prop_count = 0;
3111         prop_item = GdipAlloc(item->length + sizeof(PropertyItem));
3112         if (!prop_item) return;
3113     }
3114     else
3115     {
3116         UINT i;
3117         char *item_value;
3118
3119         GdipGetPropertySize((GpImage *)bitmap, &prop_size, &prop_count);
3120
3121         prop_item = GdipAlloc(prop_size + item->length + sizeof(PropertyItem));
3122         if (!prop_item) return;
3123         memcpy(prop_item, bitmap->prop_item, sizeof(PropertyItem) * bitmap->prop_count);
3124         prop_size -= sizeof(PropertyItem) * bitmap->prop_count;
3125         memcpy(prop_item + prop_count + 1, bitmap->prop_item + prop_count, prop_size);
3126
3127         item_value = (char *)(prop_item + prop_count + 1);
3128
3129         for (i = 0; i < prop_count; i++)
3130         {
3131             prop_item[i].value = item_value;
3132             item_value += prop_item[i].length;
3133         }
3134     }
3135
3136     prop_item[prop_count].id = item->id;
3137     prop_item[prop_count].type = item->type;
3138     prop_item[prop_count].length = item->length;
3139     prop_item[prop_count].value = (char *)(prop_item + prop_count + 1) + prop_size;
3140     memcpy(prop_item[prop_count].value, item->value, item->length);
3141
3142     GdipFree(bitmap->prop_item);
3143     bitmap->prop_item = prop_item;
3144     bitmap->prop_count++;
3145 }
3146
3147 static BOOL get_bool_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3148 {
3149     HRESULT hr;
3150     GUID format;
3151     PROPVARIANT id, value;
3152     BOOL ret = FALSE;
3153
3154     IWICMetadataReader_GetMetadataFormat(reader, &format);
3155     if (!IsEqualGUID(&format, guid)) return FALSE;
3156
3157     PropVariantInit(&id);
3158     PropVariantInit(&value);
3159
3160     id.vt = VT_LPWSTR;
3161     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3162     if (!id.u.pwszVal) return FALSE;
3163     lstrcpyW(id.u.pwszVal, prop_name);
3164     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3165     if (hr == S_OK && value.vt == VT_BOOL)
3166         ret = value.u.boolVal;
3167
3168     PropVariantClear(&id);
3169     PropVariantClear(&value);
3170
3171     return ret;
3172 }
3173
3174 static PropertyItem *get_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3175 {
3176     HRESULT hr;
3177     GUID format;
3178     PROPVARIANT id, value;
3179     PropertyItem *item = NULL;
3180
3181     IWICMetadataReader_GetMetadataFormat(reader, &format);
3182     if (!IsEqualGUID(&format, guid)) return NULL;
3183
3184     PropVariantInit(&id);
3185     PropVariantInit(&value);
3186
3187     id.vt = VT_LPWSTR;
3188     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3189     if (!id.u.pwszVal) return NULL;
3190     lstrcpyW(id.u.pwszVal, prop_name);
3191     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3192     if (hr == S_OK)
3193     {
3194         UINT item_size = propvariant_size(&value);
3195         if (item_size)
3196         {
3197             item_size += sizeof(*item);
3198             item = GdipAlloc(item_size);
3199             if (propvariant_to_item(&value, item, item_size, 0) != Ok)
3200             {
3201                 GdipFree(item);
3202                 item = NULL;
3203             }
3204         }
3205     }
3206
3207     PropVariantClear(&id);
3208     PropVariantClear(&value);
3209
3210     return item;
3211 }
3212
3213 static PropertyItem *get_gif_comment(IWICMetadataReader *reader)
3214 {
3215     static const WCHAR textentryW[] = { 'T','e','x','t','E','n','t','r','y',0 };
3216     PropertyItem *comment;
3217
3218     comment = get_property(reader, &GUID_MetadataFormatGifComment, textentryW);
3219     if (comment)
3220         comment->id = PropertyTagExifUserComment;
3221
3222     return comment;
3223 }
3224
3225 static PropertyItem *get_gif_loopcount(IWICMetadataReader *reader)
3226 {
3227     static const WCHAR applicationW[] = { 'A','p','p','l','i','c','a','t','i','o','n',0 };
3228     static const WCHAR dataW[] = { 'D','a','t','a',0 };
3229     PropertyItem *appext = NULL, *appdata = NULL, *loop = NULL;
3230
3231     appext = get_property(reader, &GUID_MetadataFormatAPE, applicationW);
3232     if (appext)
3233     {
3234         if (appext->type == PropertyTagTypeByte && appext->length == 11 &&
3235             (!memcmp(appext->value, "NETSCAPE2.0", 11) || !memcmp(appext->value, "ANIMEXTS1.0", 11)))
3236         {
3237             appdata = get_property(reader, &GUID_MetadataFormatAPE, dataW);
3238             if (appdata)
3239             {
3240                 if (appdata->type == PropertyTagTypeByte && appdata->length == 4)
3241                 {
3242                     BYTE *data = appdata->value;
3243                     if (data[0] == 3 && data[1] == 1)
3244                     {
3245                         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3246                         if (loop)
3247                         {
3248                             loop->type = PropertyTagTypeShort;
3249                             loop->id = PropertyTagLoopCount;
3250                             loop->length = sizeof(SHORT);
3251                             loop->value = loop + 1;
3252                             *(SHORT *)loop->value = data[2] | (data[3] << 8);
3253                         }
3254                     }
3255                 }
3256             }
3257         }
3258     }
3259
3260     GdipFree(appext);
3261     GdipFree(appdata);
3262
3263     return loop;
3264 }
3265
3266 static PropertyItem *get_gif_background(IWICMetadataReader *reader)
3267 {
3268     static const WCHAR backgroundW[] = { 'B','a','c','k','g','r','o','u','n','d','C','o','l','o','r','I','n','d','e','x',0 };
3269     PropertyItem *background;
3270
3271     background = get_property(reader, &GUID_MetadataFormatLSD, backgroundW);
3272     if (background)
3273         background->id = PropertyTagIndexBackground;
3274
3275     return background;
3276 }
3277
3278 static PropertyItem *get_gif_palette(IWICBitmapDecoder *decoder, IWICMetadataReader *reader)
3279 {
3280     static const WCHAR global_flagW[] = { 'G','l','o','b','a','l','C','o','l','o','r','T','a','b','l','e','F','l','a','g',0 };
3281     HRESULT hr;
3282     IWICImagingFactory *factory;
3283     IWICPalette *palette;
3284     UINT count = 0;
3285     WICColor colors[256];
3286
3287     if (!get_bool_property(reader, &GUID_MetadataFormatLSD, global_flagW))
3288         return NULL;
3289
3290     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
3291                           &IID_IWICImagingFactory, (void **)&factory);
3292     if (hr != S_OK) return NULL;
3293
3294     hr = IWICImagingFactory_CreatePalette(factory, &palette);
3295     if (hr == S_OK)
3296     {
3297         hr = IWICBitmapDecoder_CopyPalette(decoder, palette);
3298         if (hr == S_OK)
3299             IWICPalette_GetColors(palette, 256, colors, &count);
3300
3301         IWICPalette_Release(palette);
3302     }
3303
3304     IWICImagingFactory_Release(factory);
3305
3306     if (count)
3307     {
3308         PropertyItem *pal;
3309         UINT i;
3310         BYTE *rgb;
3311
3312         pal = GdipAlloc(sizeof(*pal) + count * 3);
3313         if (!pal) return NULL;
3314         pal->type = PropertyTagTypeByte;
3315         pal->id = PropertyTagGlobalPalette;
3316         pal->value = pal + 1;
3317         pal->length = count * 3;
3318
3319         rgb = pal->value;
3320
3321         for (i = 0; i < count; i++)
3322         {
3323             rgb[i*3] = (colors[i] >> 16) & 0xff;
3324             rgb[i*3 + 1] = (colors[i] >> 8) & 0xff;
3325             rgb[i*3 + 2] = colors[i] & 0xff;
3326         }
3327
3328         return pal;
3329     }
3330
3331     return NULL;
3332 }
3333
3334 static PropertyItem *get_gif_transparent_idx(IWICMetadataReader *reader)
3335 {
3336     static const WCHAR transparency_flagW[] = { 'T','r','a','n','s','p','a','r','e','n','c','y','F','l','a','g',0 };
3337     static const WCHAR colorW[] = { 'T','r','a','n','s','p','a','r','e','n','t','C','o','l','o','r','I','n','d','e','x',0 };
3338     PropertyItem *index = NULL;
3339
3340     if (get_bool_property(reader, &GUID_MetadataFormatGCE, transparency_flagW))
3341     {
3342         index = get_property(reader, &GUID_MetadataFormatGCE, colorW);
3343         if (index)
3344             index->id = PropertyTagIndexTransparent;
3345     }
3346     return index;
3347 }
3348
3349 static LONG get_gif_frame_delay(IWICBitmapFrameDecode *frame)
3350 {
3351     static const WCHAR delayW[] = { 'D','e','l','a','y',0 };
3352     HRESULT hr;
3353     IWICMetadataBlockReader *block_reader;
3354     IWICMetadataReader *reader;
3355     UINT block_count, i;
3356     PropertyItem *delay;
3357     LONG value = 0;
3358
3359     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3360     if (hr == S_OK)
3361     {
3362         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3363         if (hr == S_OK)
3364         {
3365             for (i = 0; i < block_count; i++)
3366             {
3367                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3368                 if (hr == S_OK)
3369                 {
3370                     delay = get_property(reader, &GUID_MetadataFormatGCE, delayW);
3371                     if (delay)
3372                     {
3373                         if (delay->type == PropertyTagTypeShort && delay->length == 2)
3374                             value = *(SHORT *)delay->value;
3375
3376                         GdipFree(delay);
3377                     }
3378                     IWICMetadataReader_Release(reader);
3379                 }
3380             }
3381         }
3382         IWICMetadataBlockReader_Release(block_reader);
3383     }
3384
3385     return value;
3386 }
3387
3388 static void gif_metadata_reader(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT active_frame)
3389 {
3390     HRESULT hr;
3391     IWICBitmapFrameDecode *frame;
3392     IWICMetadataBlockReader *block_reader;
3393     IWICMetadataReader *reader;
3394     UINT frame_count, block_count, i;
3395     PropertyItem *delay = NULL, *comment = NULL, *background = NULL;
3396     PropertyItem *transparent_idx = NULL, *loop = NULL, *palette = NULL;
3397
3398     IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3399     if (frame_count > 1)
3400     {
3401         delay = GdipAlloc(sizeof(*delay) + frame_count * sizeof(LONG));
3402         if (delay)
3403         {
3404             LONG *value;
3405
3406             delay->type = PropertyTagTypeLong;
3407             delay->id = PropertyTagFrameDelay;
3408             delay->length = frame_count * sizeof(LONG);
3409             delay->value = delay + 1;
3410
3411             value = delay->value;
3412
3413             for (i = 0; i < frame_count; i++)
3414             {
3415                 hr = IWICBitmapDecoder_GetFrame(decoder, i, &frame);
3416                 if (hr == S_OK)
3417                 {
3418                     value[i] = get_gif_frame_delay(frame);
3419                     IWICBitmapFrameDecode_Release(frame);
3420                 }
3421                 else value[i] = 0;
3422             }
3423         }
3424     }
3425
3426     hr = IWICBitmapDecoder_QueryInterface(decoder, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3427     if (hr == S_OK)
3428     {
3429         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3430         if (hr == S_OK)
3431         {
3432             for (i = 0; i < block_count; i++)
3433             {
3434                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3435                 if (hr == S_OK)
3436                 {
3437                     if (!comment)
3438                         comment = get_gif_comment(reader);
3439
3440                     if (frame_count > 1 && !loop)
3441                         loop = get_gif_loopcount(reader);
3442
3443                     if (!background)
3444                         background = get_gif_background(reader);
3445
3446                     if (!palette)
3447                         palette = get_gif_palette(decoder, reader);
3448
3449                     IWICMetadataReader_Release(reader);
3450                 }
3451             }
3452         }
3453         IWICMetadataBlockReader_Release(block_reader);
3454     }
3455
3456     if (frame_count > 1 && !loop)
3457     {
3458         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3459         if (loop)
3460         {
3461             loop->type = PropertyTagTypeShort;
3462             loop->id = PropertyTagLoopCount;
3463             loop->length = sizeof(SHORT);
3464             loop->value = loop + 1;
3465             *(SHORT *)loop->value = 1;
3466         }
3467     }
3468
3469     if (delay) add_property(bitmap, delay);
3470     if (comment) add_property(bitmap, comment);
3471     if (loop) add_property(bitmap, loop);
3472     if (palette) add_property(bitmap, palette);
3473     if (background) add_property(bitmap, background);
3474
3475     GdipFree(delay);
3476     GdipFree(comment);
3477     GdipFree(loop);
3478     GdipFree(palette);
3479     GdipFree(background);
3480
3481     /* Win7 gdiplus always returns transparent color index from frame 0 */
3482     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
3483     if (hr != S_OK) return;
3484
3485     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3486     if (hr == S_OK)
3487     {
3488         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3489         if (hr == S_OK)
3490         {
3491             for (i = 0; i < block_count; i++)
3492             {
3493                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3494                 if (hr == S_OK)
3495                 {
3496                     if (!transparent_idx)
3497                         transparent_idx = get_gif_transparent_idx(reader);
3498
3499                     IWICMetadataReader_Release(reader);
3500                 }
3501             }
3502         }
3503         IWICMetadataBlockReader_Release(block_reader);
3504     }
3505
3506     if (transparent_idx) add_property(bitmap, transparent_idx);
3507     GdipFree(transparent_idx);
3508
3509     IWICBitmapFrameDecode_Release(frame);
3510 }
3511
3512 typedef void (*metadata_reader_func)(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT frame);
3513
3514 static GpStatus decode_image_wic(IStream *stream, GDIPCONST CLSID *clsid,
3515     UINT active_frame, metadata_reader_func metadata_reader, GpImage **image)
3516 {
3517     GpStatus status=Ok;
3518     GpBitmap *bitmap;
3519     HRESULT hr;
3520     IWICBitmapDecoder *decoder;
3521     IWICBitmapFrameDecode *frame;
3522     IWICBitmapSource *source=NULL;
3523     IWICMetadataBlockReader *block_reader;
3524     WICPixelFormatGUID wic_format;
3525     PixelFormat gdip_format=0;
3526     ColorPalette *palette = NULL;
3527     WICBitmapPaletteType palette_type = WICBitmapPaletteTypeFixedHalftone256;
3528     int i;
3529     UINT width, height, frame_count;
3530     BitmapData lockeddata;
3531     WICRect wrc;
3532     HRESULT initresult;
3533
3534     TRACE("%p,%s,%u,%p\n", stream, wine_dbgstr_guid(clsid), active_frame, image);
3535
3536     initresult = CoInitialize(NULL);
3537
3538     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
3539         &IID_IWICBitmapDecoder, (void**)&decoder);
3540     if (FAILED(hr)) goto end;
3541
3542     hr = IWICBitmapDecoder_Initialize(decoder, stream, WICDecodeMetadataCacheOnLoad);
3543     if (SUCCEEDED(hr))
3544     {
3545         IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3546         hr = IWICBitmapDecoder_GetFrame(decoder, active_frame, &frame);
3547     }
3548
3549     if (SUCCEEDED(hr)) /* got frame */
3550     {
3551         hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &wic_format);
3552
3553         if (SUCCEEDED(hr))
3554         {
3555             IWICBitmapSource *bmp_source;
3556             IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICBitmapSource, (void **)&bmp_source);
3557
3558             for (i=0; pixel_formats[i].wic_format; i++)
3559             {
3560                 if (IsEqualGUID(&wic_format, pixel_formats[i].wic_format))
3561                 {
3562                     source = bmp_source;
3563                     gdip_format = pixel_formats[i].gdip_format;
3564                     palette_type = pixel_formats[i].palette_type;
3565                     break;
3566                 }
3567             }
3568             if (!source)
3569             {
3570                 /* unknown format; fall back on 32bppARGB */
3571                 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, bmp_source, &source);
3572                 gdip_format = PixelFormat32bppARGB;
3573                 IWICBitmapSource_Release(bmp_source);
3574             }
3575             TRACE("%s => %#x\n", wine_dbgstr_guid(&wic_format), gdip_format);
3576         }
3577
3578         if (SUCCEEDED(hr)) /* got source */
3579         {
3580             hr = IWICBitmapSource_GetSize(source, &width, &height);
3581
3582             if (SUCCEEDED(hr))
3583                 status = GdipCreateBitmapFromScan0(width, height, 0, gdip_format,
3584                     NULL, &bitmap);
3585
3586             if (SUCCEEDED(hr) && status == Ok) /* created bitmap */
3587             {
3588                 status = GdipBitmapLockBits(bitmap, NULL, ImageLockModeWrite,
3589                     gdip_format, &lockeddata);
3590                 if (status == Ok) /* locked bitmap */
3591                 {
3592                     wrc.X = 0;
3593                     wrc.Width = width;
3594                     wrc.Height = 1;
3595                     for (i=0; i<height; i++)
3596                     {
3597                         wrc.Y = i;
3598                         hr = IWICBitmapSource_CopyPixels(source, &wrc, abs(lockeddata.Stride),
3599                             abs(lockeddata.Stride), (BYTE*)lockeddata.Scan0+lockeddata.Stride*i);
3600                         if (FAILED(hr)) break;
3601                     }
3602
3603                     GdipBitmapUnlockBits(bitmap, &lockeddata);
3604                 }
3605
3606                 if (SUCCEEDED(hr) && status == Ok)
3607                     *image = (GpImage*)bitmap;
3608                 else
3609                 {
3610                     *image = NULL;
3611                     GdipDisposeImage((GpImage*)bitmap);
3612                 }
3613
3614                 if (SUCCEEDED(hr) && status == Ok)
3615                 {
3616                     double dpix, dpiy;
3617                     hr = IWICBitmapSource_GetResolution(source, &dpix, &dpiy);
3618                     if (SUCCEEDED(hr))
3619                     {
3620                         bitmap->image.xres = dpix;
3621                         bitmap->image.yres = dpiy;
3622                     }
3623                     hr = S_OK;
3624                 }
3625             }
3626
3627             IWICBitmapSource_Release(source);
3628         }
3629
3630         if (SUCCEEDED(hr)) {
3631             bitmap->metadata_reader = NULL;
3632
3633             if (metadata_reader)
3634                 metadata_reader(bitmap, decoder, active_frame);
3635             else if (IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader) == S_OK)
3636             {
3637                 UINT block_count = 0;
3638                 if (IWICMetadataBlockReader_GetCount(block_reader, &block_count) == S_OK && block_count)
3639                     IWICMetadataBlockReader_GetReaderByIndex(block_reader, 0, &bitmap->metadata_reader);
3640                 IWICMetadataBlockReader_Release(block_reader);
3641             }
3642
3643             palette = get_palette(frame, palette_type);
3644             IWICBitmapFrameDecode_Release(frame);
3645         }
3646     }
3647
3648     IWICBitmapDecoder_Release(decoder);
3649
3650 end:
3651     if (SUCCEEDED(initresult)) CoUninitialize();
3652
3653     if (FAILED(hr) && status == Ok) status = hresult_to_status(hr);
3654
3655     if (status == Ok)
3656     {
3657         /* Native GDI+ used to be smarter, but since Win7 it just sets these flags. */
3658         bitmap->image.flags |= ImageFlagsReadOnly|ImageFlagsHasRealPixelSize|ImageFlagsHasRealDPI|ImageFlagsColorSpaceRGB;
3659         bitmap->image.frame_count = frame_count;
3660         bitmap->image.current_frame = active_frame;
3661         bitmap->image.stream = stream;
3662         if (palette)
3663         {
3664             GdipFree(bitmap->image.palette);
3665             bitmap->image.palette = palette;
3666         }
3667         else
3668         {
3669             if (IsEqualGUID(&wic_format, &GUID_WICPixelFormatBlackWhite))
3670                 bitmap->image.palette->Flags = 0;
3671         }
3672         /* Pin the source stream */
3673         IStream_AddRef(stream);
3674         TRACE("=> %p\n", *image);
3675     }
3676
3677     return status;
3678 }
3679
3680 static GpStatus decode_image_icon(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3681 {
3682     return decode_image_wic(stream, &CLSID_WICIcoDecoder, active_frame, NULL, image);
3683 }
3684
3685 static GpStatus decode_image_bmp(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3686 {
3687     GpStatus status;
3688     GpBitmap* bitmap;
3689
3690     status = decode_image_wic(stream, &CLSID_WICBmpDecoder, active_frame, NULL, image);
3691
3692     bitmap = (GpBitmap*)*image;
3693
3694     if (status == Ok && bitmap->format == PixelFormat32bppARGB)
3695     {
3696         /* WIC supports bmp files with alpha, but gdiplus does not */
3697         bitmap->format = PixelFormat32bppRGB;
3698     }
3699
3700     return status;
3701 }
3702
3703 static GpStatus decode_image_jpeg(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3704 {
3705     return decode_image_wic(stream, &CLSID_WICJpegDecoder, active_frame, NULL, image);
3706 }
3707
3708 static GpStatus decode_image_png(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3709 {
3710     return decode_image_wic(stream, &CLSID_WICPngDecoder, active_frame, NULL, image);
3711 }
3712
3713 static GpStatus decode_image_gif(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3714 {
3715     return decode_image_wic(stream, &CLSID_WICGifDecoder, active_frame, gif_metadata_reader, image);
3716 }
3717
3718 static GpStatus decode_image_tiff(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3719 {
3720     return decode_image_wic(stream, &CLSID_WICTiffDecoder, active_frame, NULL, image);
3721 }
3722
3723 static GpStatus decode_image_olepicture_metafile(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3724 {
3725     IPicture *pic;
3726
3727     TRACE("%p %p\n", stream, image);
3728
3729     if(!stream || !image)
3730         return InvalidParameter;
3731
3732     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
3733         (LPVOID*) &pic) != S_OK){
3734         TRACE("Could not load picture\n");
3735         return GenericError;
3736     }
3737
3738     /* FIXME: missing initialization code */
3739     *image = GdipAlloc(sizeof(GpMetafile));
3740     if(!*image) return OutOfMemory;
3741     (*image)->type = ImageTypeMetafile;
3742     (*image)->stream = NULL;
3743     (*image)->picture = pic;
3744     (*image)->flags   = ImageFlagsNone;
3745     (*image)->frame_count = 1;
3746     (*image)->current_frame = 0;
3747     (*image)->palette = NULL;
3748
3749     TRACE("<-- %p\n", *image);
3750
3751     return Ok;
3752 }
3753
3754 typedef GpStatus (*encode_image_func)(GpImage *image, IStream* stream,
3755     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params);
3756
3757 typedef GpStatus (*decode_image_func)(IStream *stream, REFCLSID clsid, UINT active_frame, GpImage **image);
3758
3759 typedef struct image_codec {
3760     ImageCodecInfo info;
3761     encode_image_func encode_func;
3762     decode_image_func decode_func;
3763 } image_codec;
3764
3765 typedef enum {
3766     BMP,
3767     JPEG,
3768     GIF,
3769     TIFF,
3770     EMF,
3771     WMF,
3772     PNG,
3773     ICO,
3774     NUM_CODECS
3775 } ImageFormat;
3776
3777 static const struct image_codec codecs[NUM_CODECS];
3778
3779 static GpStatus get_decoder_info(IStream* stream, const struct image_codec **result)
3780 {
3781     BYTE signature[8];
3782     const BYTE *pattern, *mask;
3783     LARGE_INTEGER seek;
3784     HRESULT hr;
3785     UINT bytesread;
3786     int i, j, sig;
3787
3788     /* seek to the start of the stream */
3789     seek.QuadPart = 0;
3790     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3791     if (FAILED(hr)) return hresult_to_status(hr);
3792
3793     /* read the first 8 bytes */
3794     /* FIXME: This assumes all codecs have signatures <= 8 bytes in length */
3795     hr = IStream_Read(stream, signature, 8, &bytesread);
3796     if (FAILED(hr)) return hresult_to_status(hr);
3797     if (hr == S_FALSE || bytesread == 0) return GenericError;
3798
3799     for (i = 0; i < NUM_CODECS; i++) {
3800         if ((codecs[i].info.Flags & ImageCodecFlagsDecoder) &&
3801             bytesread >= codecs[i].info.SigSize)
3802         {
3803             for (sig=0; sig<codecs[i].info.SigCount; sig++)
3804             {
3805                 pattern = &codecs[i].info.SigPattern[codecs[i].info.SigSize*sig];
3806                 mask = &codecs[i].info.SigMask[codecs[i].info.SigSize*sig];
3807                 for (j=0; j<codecs[i].info.SigSize; j++)
3808                     if ((signature[j] & mask[j]) != pattern[j])
3809                         break;
3810                 if (j == codecs[i].info.SigSize)
3811                 {
3812                     *result = &codecs[i];
3813                     return Ok;
3814                 }
3815             }
3816         }
3817     }
3818
3819     TRACE("no match for %i byte signature %x %x %x %x %x %x %x %x\n", bytesread,
3820         signature[0],signature[1],signature[2],signature[3],
3821         signature[4],signature[5],signature[6],signature[7]);
3822
3823     return GenericError;
3824 }
3825
3826 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image, GDIPCONST GUID *dimensionID,
3827                                                UINT frame)
3828 {
3829     GpStatus stat;
3830     LARGE_INTEGER seek;
3831     HRESULT hr;
3832     const struct image_codec *codec = NULL;
3833     GpImage *new_image;
3834
3835     TRACE("(%p,%s,%u)\n", image, debugstr_guid(dimensionID), frame);
3836
3837     if (!image || !dimensionID)
3838         return InvalidParameter;
3839
3840     if (frame >= image->frame_count)
3841     {
3842         WARN("requested frame %u, but image has only %u\n", frame, image->frame_count);
3843         return InvalidParameter;
3844     }
3845
3846     if (image->type != ImageTypeBitmap && image->type != ImageTypeMetafile)
3847     {
3848         WARN("invalid image type %d\n", image->type);
3849         return InvalidParameter;
3850     }
3851
3852     if (image->current_frame == frame)
3853         return Ok;
3854
3855     if (!image->stream)
3856     {
3857         TRACE("image doesn't have an associated stream\n");
3858         return Ok;
3859     }
3860
3861     /* choose an appropriate image decoder */
3862     stat = get_decoder_info(image->stream, &codec);
3863     if (stat != Ok)
3864     {
3865         WARN("can't find decoder info\n");
3866         return stat;
3867     }
3868
3869     /* seek to the start of the stream */
3870     seek.QuadPart = 0;
3871     hr = IStream_Seek(image->stream, seek, STREAM_SEEK_SET, NULL);
3872     if (FAILED(hr))
3873         return hresult_to_status(hr);
3874
3875     /* call on the image decoder to do the real work */
3876     stat = codec->decode_func(image->stream, &codec->info.Clsid, frame, &new_image);
3877
3878     if (stat == Ok)
3879     {
3880         memcpy(&new_image->format, &codec->info.FormatID, sizeof(GUID));
3881         free_image_data(image);
3882         if (image->type == ImageTypeBitmap)
3883             *(GpBitmap *)image = *(GpBitmap *)new_image;
3884         else if (image->type == ImageTypeMetafile)
3885             *(GpMetafile *)image = *(GpMetafile *)new_image;
3886         new_image->type = ~0;
3887         GdipFree(new_image);
3888         return Ok;
3889     }
3890
3891     return stat;
3892 }
3893
3894 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream *stream, GpImage **image)
3895 {
3896     GpStatus stat;
3897     LARGE_INTEGER seek;
3898     HRESULT hr;
3899     const struct image_codec *codec=NULL;
3900
3901     /* choose an appropriate image decoder */
3902     stat = get_decoder_info(stream, &codec);
3903     if (stat != Ok) return stat;
3904
3905     /* seek to the start of the stream */
3906     seek.QuadPart = 0;
3907     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3908     if (FAILED(hr)) return hresult_to_status(hr);
3909
3910     /* call on the image decoder to do the real work */
3911     stat = codec->decode_func(stream, &codec->info.Clsid, 0, image);
3912
3913     /* take note of the original data format */
3914     if (stat == Ok)
3915     {
3916         memcpy(&(*image)->format, &codec->info.FormatID, sizeof(GUID));
3917         return Ok;
3918     }
3919
3920     return stat;
3921 }
3922
3923 /* FIXME: no ICM */
3924 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
3925 {
3926     TRACE("%p %p\n", stream, image);
3927
3928     return GdipLoadImageFromStream(stream, image);
3929 }
3930
3931 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
3932 {
3933     static int calls;
3934
3935     TRACE("(%p,%u)\n", image, propId);
3936
3937     if(!image)
3938         return InvalidParameter;
3939
3940     if(!(calls++))
3941         FIXME("not implemented\n");
3942
3943     return NotImplemented;
3944 }
3945
3946 GpStatus WINGDIPAPI GdipSetPropertyItem(GpImage *image, GDIPCONST PropertyItem* item)
3947 {
3948     static int calls;
3949
3950     if (!image || !item) return InvalidParameter;
3951
3952     TRACE("(%p,%p:%#x,%u,%u,%p)\n", image, item, item->id, item->type, item->length, item->value);
3953
3954     if(!(calls++))
3955         FIXME("not implemented\n");
3956
3957     return Ok;
3958 }
3959
3960 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
3961                                         GDIPCONST CLSID *clsidEncoder,
3962                                         GDIPCONST EncoderParameters *encoderParams)
3963 {
3964     GpStatus stat;
3965     IStream *stream;
3966
3967     TRACE("%p (%s) %p %p\n", image, debugstr_w(filename), clsidEncoder, encoderParams);
3968
3969     if (!image || !filename|| !clsidEncoder)
3970         return InvalidParameter;
3971
3972     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
3973     if (stat != Ok)
3974         return GenericError;
3975
3976     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
3977
3978     IStream_Release(stream);
3979     return stat;
3980 }
3981
3982 /*************************************************************************
3983  * Encoding functions -
3984  *   These functions encode an image in different image file formats.
3985  */
3986 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
3987 #define BITMAP_FORMAT_JPEG  0xd8ff
3988 #define BITMAP_FORMAT_GIF   0x4947
3989 #define BITMAP_FORMAT_PNG   0x5089
3990 #define BITMAP_FORMAT_APM   0xcdd7
3991
3992 static GpStatus encode_image_WIC(GpImage *image, IStream* stream,
3993     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
3994 {
3995     GpStatus stat;
3996     GpBitmap *bitmap;
3997     IWICBitmapEncoder *encoder;
3998     IWICBitmapFrameEncode *frameencode;
3999     IPropertyBag2 *encoderoptions;
4000     HRESULT hr;
4001     UINT width, height;
4002     PixelFormat gdipformat=0;
4003     WICPixelFormatGUID wicformat;
4004     GpRect rc;
4005     BitmapData lockeddata;
4006     HRESULT initresult;
4007     UINT i;
4008
4009     if (image->type != ImageTypeBitmap)
4010         return GenericError;
4011
4012     bitmap = (GpBitmap*)image;
4013
4014     GdipGetImageWidth(image, &width);
4015     GdipGetImageHeight(image, &height);
4016
4017     rc.X = 0;
4018     rc.Y = 0;
4019     rc.Width = width;
4020     rc.Height = height;
4021
4022     initresult = CoInitialize(NULL);
4023
4024     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
4025         &IID_IWICBitmapEncoder, (void**)&encoder);
4026     if (FAILED(hr))
4027     {
4028         if (SUCCEEDED(initresult)) CoUninitialize();
4029         return hresult_to_status(hr);
4030     }
4031
4032     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
4033
4034     if (SUCCEEDED(hr))
4035     {
4036         hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frameencode, &encoderoptions);
4037     }
4038
4039     if (SUCCEEDED(hr)) /* created frame */
4040     {
4041         hr = IWICBitmapFrameEncode_Initialize(frameencode, encoderoptions);
4042
4043         if (SUCCEEDED(hr))
4044             hr = IWICBitmapFrameEncode_SetSize(frameencode, width, height);
4045
4046         if (SUCCEEDED(hr))
4047             hr = IWICBitmapFrameEncode_SetResolution(frameencode, image->xres, image->yres);
4048
4049         if (SUCCEEDED(hr))
4050         {
4051             for (i=0; pixel_formats[i].wic_format; i++)
4052             {
4053                 if (pixel_formats[i].gdip_format == bitmap->format)
4054                 {
4055                     memcpy(&wicformat, pixel_formats[i].wic_format, sizeof(GUID));
4056                     gdipformat = bitmap->format;
4057                     break;
4058                 }
4059             }
4060             if (!gdipformat)
4061             {
4062                 memcpy(&wicformat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
4063                 gdipformat = PixelFormat32bppARGB;
4064             }
4065
4066             hr = IWICBitmapFrameEncode_SetPixelFormat(frameencode, &wicformat);
4067         }
4068
4069         if (SUCCEEDED(hr))
4070         {
4071             stat = GdipBitmapLockBits(bitmap, &rc, ImageLockModeRead, gdipformat,
4072                 &lockeddata);
4073
4074             if (stat == Ok)
4075             {
4076                 UINT row_size = (lockeddata.Width * PIXELFORMATBPP(gdipformat) + 7)/8;
4077                 BYTE *row;
4078
4079                 /* write one row at a time in case stride is negative */
4080                 row = lockeddata.Scan0;
4081                 for (i=0; i<lockeddata.Height; i++)
4082                 {
4083                     hr = IWICBitmapFrameEncode_WritePixels(frameencode, 1, row_size, row_size, row);
4084                     if (FAILED(hr)) break;
4085                     row += lockeddata.Stride;
4086                 }
4087
4088                 GdipBitmapUnlockBits(bitmap, &lockeddata);
4089             }
4090             else
4091                 hr = E_FAIL;
4092         }
4093
4094         if (SUCCEEDED(hr))
4095             hr = IWICBitmapFrameEncode_Commit(frameencode);
4096
4097         IWICBitmapFrameEncode_Release(frameencode);
4098         IPropertyBag2_Release(encoderoptions);
4099     }
4100
4101     if (SUCCEEDED(hr))
4102         hr = IWICBitmapEncoder_Commit(encoder);
4103
4104     IWICBitmapEncoder_Release(encoder);
4105
4106     if (SUCCEEDED(initresult)) CoUninitialize();
4107
4108     return hresult_to_status(hr);
4109 }
4110
4111 static GpStatus encode_image_BMP(GpImage *image, IStream* stream,
4112     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4113 {
4114     return encode_image_WIC(image, stream, &CLSID_WICBmpEncoder, params);
4115 }
4116
4117 static GpStatus encode_image_tiff(GpImage *image, IStream* stream,
4118     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4119 {
4120     return encode_image_WIC(image, stream, &CLSID_WICTiffEncoder, params);
4121 }
4122
4123 static GpStatus encode_image_png(GpImage *image, IStream* stream,
4124     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4125 {
4126     return encode_image_WIC(image, stream, &CLSID_WICPngEncoder, params);
4127 }
4128
4129 static GpStatus encode_image_jpeg(GpImage *image, IStream* stream,
4130     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4131 {
4132     return encode_image_WIC(image, stream, &CLSID_WICJpegEncoder, params);
4133 }
4134
4135 /*****************************************************************************
4136  * GdipSaveImageToStream [GDIPLUS.@]
4137  */
4138 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
4139     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4140 {
4141     GpStatus stat;
4142     encode_image_func encode_image;
4143     int i;
4144
4145     TRACE("%p %p %p %p\n", image, stream, clsid, params);
4146
4147     if(!image || !stream)
4148         return InvalidParameter;
4149
4150     /* select correct encoder */
4151     encode_image = NULL;
4152     for (i = 0; i < NUM_CODECS; i++) {
4153         if ((codecs[i].info.Flags & ImageCodecFlagsEncoder) &&
4154             IsEqualCLSID(clsid, &codecs[i].info.Clsid))
4155             encode_image = codecs[i].encode_func;
4156     }
4157     if (encode_image == NULL)
4158         return UnknownImageFormat;
4159
4160     stat = encode_image(image, stream, clsid, params);
4161
4162     return stat;
4163 }
4164
4165 /*****************************************************************************
4166  * GdipSaveAdd [GDIPLUS.@]
4167  */
4168 GpStatus WINGDIPAPI GdipSaveAdd(GpImage *image, GDIPCONST EncoderParameters *params)
4169 {
4170     FIXME("(%p,%p): stub\n", image, params);
4171     return Ok;
4172 }
4173
4174 /*****************************************************************************
4175  * GdipGetImagePalette [GDIPLUS.@]
4176  */
4177 GpStatus WINGDIPAPI GdipGetImagePalette(GpImage *image, ColorPalette *palette, INT size)
4178 {
4179     INT count;
4180
4181     TRACE("(%p,%p,%i)\n", image, palette, size);
4182
4183     if (!image || !palette)
4184         return InvalidParameter;
4185
4186     count = image->palette ? image->palette->Count : 0;
4187
4188     if (size < (sizeof(UINT)*2+sizeof(ARGB)*count))
4189     {
4190         TRACE("<-- InsufficientBuffer\n");
4191         return InsufficientBuffer;
4192     }
4193
4194     if (image->palette)
4195     {
4196         palette->Flags = image->palette->Flags;
4197         palette->Count = image->palette->Count;
4198         memcpy(palette->Entries, image->palette->Entries, sizeof(ARGB)*image->palette->Count);
4199     }
4200     else
4201     {
4202         palette->Flags = 0;
4203         palette->Count = 0;
4204     }
4205     return Ok;
4206 }
4207
4208 /*****************************************************************************
4209  * GdipSetImagePalette [GDIPLUS.@]
4210  */
4211 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
4212     GDIPCONST ColorPalette *palette)
4213 {
4214     ColorPalette *new_palette;
4215
4216     TRACE("(%p,%p)\n", image, palette);
4217
4218     if(!image || !palette || palette->Count > 256)
4219         return InvalidParameter;
4220
4221     new_palette = GdipAlloc(2 * sizeof(UINT) + palette->Count * sizeof(ARGB));
4222     if (!new_palette) return OutOfMemory;
4223
4224     GdipFree(image->palette);
4225     image->palette = new_palette;
4226     image->palette->Flags = palette->Flags;
4227     image->palette->Count = palette->Count;
4228     memcpy(image->palette->Entries, palette->Entries, sizeof(ARGB)*palette->Count);
4229
4230     return Ok;
4231 }
4232
4233 /*************************************************************************
4234  * Encoders -
4235  *   Structures that represent which formats we support for encoding.
4236  */
4237
4238 /* ImageCodecInfo creation routines taken from libgdiplus */
4239 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
4240 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
4241 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
4242 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
4243 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
4244 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
4245
4246 static const WCHAR jpeg_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'J','P','E','G', 0};
4247 static const WCHAR jpeg_extension[] = {'*','.','J','P','G',';', '*','.','J','P','E','G',';', '*','.','J','P','E',';', '*','.','J','F','I','F',0};
4248 static const WCHAR jpeg_mimetype[] = {'i','m','a','g','e','/','j','p','e','g', 0};
4249 static const WCHAR jpeg_format[] = {'J','P','E','G',0};
4250 static const BYTE jpeg_sig_pattern[] = { 0xFF, 0xD8 };
4251 static const BYTE jpeg_sig_mask[] = { 0xFF, 0xFF };
4252
4253 static const WCHAR gif_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'G','I','F', 0};
4254 static const WCHAR gif_extension[] = {'*','.','G','I','F',0};
4255 static const WCHAR gif_mimetype[] = {'i','m','a','g','e','/','g','i','f', 0};
4256 static const WCHAR gif_format[] = {'G','I','F',0};
4257 static const BYTE gif_sig_pattern[12] = "GIF87aGIF89a";
4258 static const BYTE gif_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4259
4260 static const WCHAR tiff_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'T','I','F','F', 0};
4261 static const WCHAR tiff_extension[] = {'*','.','T','I','F','F',';','*','.','T','I','F',0};
4262 static const WCHAR tiff_mimetype[] = {'i','m','a','g','e','/','t','i','f','f', 0};
4263 static const WCHAR tiff_format[] = {'T','I','F','F',0};
4264 static const BYTE tiff_sig_pattern[] = {0x49,0x49,42,0,0x4d,0x4d,0,42};
4265 static const BYTE tiff_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4266
4267 static const WCHAR emf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'E','M','F', 0};
4268 static const WCHAR emf_extension[] = {'*','.','E','M','F',0};
4269 static const WCHAR emf_mimetype[] = {'i','m','a','g','e','/','x','-','e','m','f', 0};
4270 static const WCHAR emf_format[] = {'E','M','F',0};
4271 static const BYTE emf_sig_pattern[] = { 0x01, 0x00, 0x00, 0x00 };
4272 static const BYTE emf_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4273
4274 static const WCHAR wmf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'W','M','F', 0};
4275 static const WCHAR wmf_extension[] = {'*','.','W','M','F',0};
4276 static const WCHAR wmf_mimetype[] = {'i','m','a','g','e','/','x','-','w','m','f', 0};
4277 static const WCHAR wmf_format[] = {'W','M','F',0};
4278 static const BYTE wmf_sig_pattern[] = { 0xd7, 0xcd };
4279 static const BYTE wmf_sig_mask[] = { 0xFF, 0xFF };
4280
4281 static const WCHAR png_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'P','N','G', 0};
4282 static const WCHAR png_extension[] = {'*','.','P','N','G',0};
4283 static const WCHAR png_mimetype[] = {'i','m','a','g','e','/','p','n','g', 0};
4284 static const WCHAR png_format[] = {'P','N','G',0};
4285 static const BYTE png_sig_pattern[] = { 137, 80, 78, 71, 13, 10, 26, 10, };
4286 static const BYTE png_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4287
4288 static const WCHAR ico_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'I','C','O', 0};
4289 static const WCHAR ico_extension[] = {'*','.','I','C','O',0};
4290 static const WCHAR ico_mimetype[] = {'i','m','a','g','e','/','x','-','i','c','o','n', 0};
4291 static const WCHAR ico_format[] = {'I','C','O',0};
4292 static const BYTE ico_sig_pattern[] = { 0x00, 0x00, 0x01, 0x00 };
4293 static const BYTE ico_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4294
4295 static const struct image_codec codecs[NUM_CODECS] = {
4296     {
4297         { /* BMP */
4298             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4299             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4300             /* CodecName */          bmp_codecname,
4301             /* DllName */            NULL,
4302             /* FormatDescription */  bmp_format,
4303             /* FilenameExtension */  bmp_extension,
4304             /* MimeType */           bmp_mimetype,
4305             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4306             /* Version */            1,
4307             /* SigCount */           1,
4308             /* SigSize */            2,
4309             /* SigPattern */         bmp_sig_pattern,
4310             /* SigMask */            bmp_sig_mask,
4311         },
4312         encode_image_BMP,
4313         decode_image_bmp
4314     },
4315     {
4316         { /* JPEG */
4317             /* Clsid */              { 0x557cf401, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4318             /* FormatID */           { 0xb96b3caeU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4319             /* CodecName */          jpeg_codecname,
4320             /* DllName */            NULL,
4321             /* FormatDescription */  jpeg_format,
4322             /* FilenameExtension */  jpeg_extension,
4323             /* MimeType */           jpeg_mimetype,
4324             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4325             /* Version */            1,
4326             /* SigCount */           1,
4327             /* SigSize */            2,
4328             /* SigPattern */         jpeg_sig_pattern,
4329             /* SigMask */            jpeg_sig_mask,
4330         },
4331         encode_image_jpeg,
4332         decode_image_jpeg
4333     },
4334     {
4335         { /* GIF */
4336             /* Clsid */              { 0x557cf402, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4337             /* FormatID */           { 0xb96b3cb0U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4338             /* CodecName */          gif_codecname,
4339             /* DllName */            NULL,
4340             /* FormatDescription */  gif_format,
4341             /* FilenameExtension */  gif_extension,
4342             /* MimeType */           gif_mimetype,
4343             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4344             /* Version */            1,
4345             /* SigCount */           2,
4346             /* SigSize */            6,
4347             /* SigPattern */         gif_sig_pattern,
4348             /* SigMask */            gif_sig_mask,
4349         },
4350         NULL,
4351         decode_image_gif
4352     },
4353     {
4354         { /* TIFF */
4355             /* Clsid */              { 0x557cf405, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4356             /* FormatID */           { 0xb96b3cb1U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4357             /* CodecName */          tiff_codecname,
4358             /* DllName */            NULL,
4359             /* FormatDescription */  tiff_format,
4360             /* FilenameExtension */  tiff_extension,
4361             /* MimeType */           tiff_mimetype,
4362             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsEncoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4363             /* Version */            1,
4364             /* SigCount */           2,
4365             /* SigSize */            4,
4366             /* SigPattern */         tiff_sig_pattern,
4367             /* SigMask */            tiff_sig_mask,
4368         },
4369         encode_image_tiff,
4370         decode_image_tiff
4371     },
4372     {
4373         { /* EMF */
4374             /* Clsid */              { 0x557cf403, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4375             /* FormatID */           { 0xb96b3cacU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4376             /* CodecName */          emf_codecname,
4377             /* DllName */            NULL,
4378             /* FormatDescription */  emf_format,
4379             /* FilenameExtension */  emf_extension,
4380             /* MimeType */           emf_mimetype,
4381             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4382             /* Version */            1,
4383             /* SigCount */           1,
4384             /* SigSize */            4,
4385             /* SigPattern */         emf_sig_pattern,
4386             /* SigMask */            emf_sig_mask,
4387         },
4388         NULL,
4389         decode_image_olepicture_metafile
4390     },
4391     {
4392         { /* WMF */
4393             /* Clsid */              { 0x557cf404, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4394             /* FormatID */           { 0xb96b3cadU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4395             /* CodecName */          wmf_codecname,
4396             /* DllName */            NULL,
4397             /* FormatDescription */  wmf_format,
4398             /* FilenameExtension */  wmf_extension,
4399             /* MimeType */           wmf_mimetype,
4400             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4401             /* Version */            1,
4402             /* SigCount */           1,
4403             /* SigSize */            2,
4404             /* SigPattern */         wmf_sig_pattern,
4405             /* SigMask */            wmf_sig_mask,
4406         },
4407         NULL,
4408         decode_image_olepicture_metafile
4409     },
4410     {
4411         { /* PNG */
4412             /* Clsid */              { 0x557cf406, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4413             /* FormatID */           { 0xb96b3cafU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4414             /* CodecName */          png_codecname,
4415             /* DllName */            NULL,
4416             /* FormatDescription */  png_format,
4417             /* FilenameExtension */  png_extension,
4418             /* MimeType */           png_mimetype,
4419             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4420             /* Version */            1,
4421             /* SigCount */           1,
4422             /* SigSize */            8,
4423             /* SigPattern */         png_sig_pattern,
4424             /* SigMask */            png_sig_mask,
4425         },
4426         encode_image_png,
4427         decode_image_png
4428     },
4429     {
4430         { /* ICO */
4431             /* Clsid */              { 0x557cf407, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4432             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4433             /* CodecName */          ico_codecname,
4434             /* DllName */            NULL,
4435             /* FormatDescription */  ico_format,
4436             /* FilenameExtension */  ico_extension,
4437             /* MimeType */           ico_mimetype,
4438             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4439             /* Version */            1,
4440             /* SigCount */           1,
4441             /* SigSize */            4,
4442             /* SigPattern */         ico_sig_pattern,
4443             /* SigMask */            ico_sig_mask,
4444         },
4445         NULL,
4446         decode_image_icon
4447     },
4448 };
4449
4450 /*****************************************************************************
4451  * GdipGetImageDecodersSize [GDIPLUS.@]
4452  */
4453 GpStatus WINGDIPAPI GdipGetImageDecodersSize(UINT *numDecoders, UINT *size)
4454 {
4455     int decoder_count=0;
4456     int i;
4457     TRACE("%p %p\n", numDecoders, size);
4458
4459     if (!numDecoders || !size)
4460         return InvalidParameter;
4461
4462     for (i=0; i<NUM_CODECS; i++)
4463     {
4464         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4465             decoder_count++;
4466     }
4467
4468     *numDecoders = decoder_count;
4469     *size = decoder_count * sizeof(ImageCodecInfo);
4470
4471     return Ok;
4472 }
4473
4474 /*****************************************************************************
4475  * GdipGetImageDecoders [GDIPLUS.@]
4476  */
4477 GpStatus WINGDIPAPI GdipGetImageDecoders(UINT numDecoders, UINT size, ImageCodecInfo *decoders)
4478 {
4479     int i, decoder_count=0;
4480     TRACE("%u %u %p\n", numDecoders, size, decoders);
4481
4482     if (!decoders ||
4483         size != numDecoders * sizeof(ImageCodecInfo))
4484         return GenericError;
4485
4486     for (i=0; i<NUM_CODECS; i++)
4487     {
4488         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4489         {
4490             if (decoder_count == numDecoders) return GenericError;
4491             memcpy(&decoders[decoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4492             decoder_count++;
4493         }
4494     }
4495
4496     if (decoder_count < numDecoders) return GenericError;
4497
4498     return Ok;
4499 }
4500
4501 /*****************************************************************************
4502  * GdipGetImageEncodersSize [GDIPLUS.@]
4503  */
4504 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
4505 {
4506     int encoder_count=0;
4507     int i;
4508     TRACE("%p %p\n", numEncoders, size);
4509
4510     if (!numEncoders || !size)
4511         return InvalidParameter;
4512
4513     for (i=0; i<NUM_CODECS; i++)
4514     {
4515         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4516             encoder_count++;
4517     }
4518
4519     *numEncoders = encoder_count;
4520     *size = encoder_count * sizeof(ImageCodecInfo);
4521
4522     return Ok;
4523 }
4524
4525 /*****************************************************************************
4526  * GdipGetImageEncoders [GDIPLUS.@]
4527  */
4528 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
4529 {
4530     int i, encoder_count=0;
4531     TRACE("%u %u %p\n", numEncoders, size, encoders);
4532
4533     if (!encoders ||
4534         size != numEncoders * sizeof(ImageCodecInfo))
4535         return GenericError;
4536
4537     for (i=0; i<NUM_CODECS; i++)
4538     {
4539         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4540         {
4541             if (encoder_count == numEncoders) return GenericError;
4542             memcpy(&encoders[encoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4543             encoder_count++;
4544         }
4545     }
4546
4547     if (encoder_count < numEncoders) return GenericError;
4548
4549     return Ok;
4550 }
4551
4552 GpStatus WINGDIPAPI GdipGetEncoderParameterListSize(GpImage *image,
4553     GDIPCONST CLSID* clsidEncoder, UINT *size)
4554 {
4555     static int calls;
4556
4557     TRACE("(%p,%s,%p)\n", image, debugstr_guid(clsidEncoder), size);
4558
4559     if(!(calls++))
4560         FIXME("not implemented\n");
4561
4562     *size = 0;
4563
4564     return NotImplemented;
4565 }
4566
4567 static PixelFormat get_16bpp_format(HBITMAP hbm)
4568 {
4569     BITMAPV4HEADER bmh;
4570     HDC hdc;
4571     PixelFormat result;
4572
4573     hdc = CreateCompatibleDC(NULL);
4574
4575     memset(&bmh, 0, sizeof(bmh));
4576     bmh.bV4Size = sizeof(bmh);
4577     bmh.bV4Width = 1;
4578     bmh.bV4Height = 1;
4579     bmh.bV4V4Compression = BI_BITFIELDS;
4580     bmh.bV4BitCount = 16;
4581
4582     GetDIBits(hdc, hbm, 0, 0, NULL, (BITMAPINFO*)&bmh, DIB_RGB_COLORS);
4583
4584     if (bmh.bV4RedMask == 0x7c00 &&
4585         bmh.bV4GreenMask == 0x3e0 &&
4586         bmh.bV4BlueMask == 0x1f)
4587     {
4588         result = PixelFormat16bppRGB555;
4589     }
4590     else if (bmh.bV4RedMask == 0xf800 &&
4591         bmh.bV4GreenMask == 0x7e0 &&
4592         bmh.bV4BlueMask == 0x1f)
4593     {
4594         result = PixelFormat16bppRGB565;
4595     }
4596     else
4597     {
4598         FIXME("unrecognized bitfields %x,%x,%x\n", bmh.bV4RedMask,
4599             bmh.bV4GreenMask, bmh.bV4BlueMask);
4600         result = PixelFormatUndefined;
4601     }
4602
4603     DeleteDC(hdc);
4604
4605     return result;
4606 }
4607
4608 /*****************************************************************************
4609  * GdipCreateBitmapFromHBITMAP [GDIPLUS.@]
4610  */
4611 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
4612 {
4613     BITMAP bm;
4614     GpStatus retval;
4615     PixelFormat format;
4616     BitmapData lockeddata;
4617     INT y;
4618
4619     TRACE("%p %p %p\n", hbm, hpal, bitmap);
4620
4621     if(!hbm || !bitmap)
4622         return InvalidParameter;
4623
4624     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
4625             return InvalidParameter;
4626
4627     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
4628     switch(bm.bmBitsPixel) {
4629         case 1:
4630             format = PixelFormat1bppIndexed;
4631             break;
4632         case 4:
4633             format = PixelFormat4bppIndexed;
4634             break;
4635         case 8:
4636             format = PixelFormat8bppIndexed;
4637             break;
4638         case 16:
4639             format = get_16bpp_format(hbm);
4640             if (format == PixelFormatUndefined)
4641                 return InvalidParameter;
4642             break;
4643         case 24:
4644             format = PixelFormat24bppRGB;
4645             break;
4646         case 32:
4647             format = PixelFormat32bppRGB;
4648             break;
4649         case 48:
4650             format = PixelFormat48bppRGB;
4651             break;
4652         default:
4653             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
4654             return InvalidParameter;
4655     }
4656
4657     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, 0,
4658         format, NULL, bitmap);
4659
4660     if (retval == Ok)
4661     {
4662         retval = GdipBitmapLockBits(*bitmap, NULL, ImageLockModeWrite,
4663             format, &lockeddata);
4664         if (retval == Ok)
4665         {
4666             if (bm.bmBits)
4667             {
4668                 for (y=0; y<bm.bmHeight; y++)
4669                 {
4670                     memcpy((BYTE*)lockeddata.Scan0+lockeddata.Stride*y,
4671                            (BYTE*)bm.bmBits+bm.bmWidthBytes*(bm.bmHeight-1-y),
4672                            bm.bmWidthBytes);
4673                 }
4674             }
4675             else
4676             {
4677                 HDC hdc;
4678                 HBITMAP oldhbm;
4679                 BITMAPINFO *pbmi;
4680                 INT src_height, dst_stride;
4681                 BYTE *dst_bits;
4682
4683                 hdc = CreateCompatibleDC(NULL);
4684                 oldhbm = SelectObject(hdc, hbm);
4685
4686                 pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
4687
4688                 if (pbmi)
4689                 {
4690                     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
4691                     pbmi->bmiHeader.biBitCount = 0;
4692
4693                     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
4694
4695                     src_height = abs(pbmi->bmiHeader.biHeight);
4696
4697                     if (pbmi->bmiHeader.biHeight > 0)
4698                     {
4699                         dst_bits = (BYTE*)lockeddata.Scan0+lockeddata.Stride*(src_height-1);
4700                         dst_stride = -lockeddata.Stride;
4701                     }
4702                     else
4703                     {
4704                         dst_bits = lockeddata.Scan0;
4705                         dst_stride = lockeddata.Stride;
4706                     }
4707
4708                     for (y=0; y<src_height; y++)
4709                     {
4710                         GetDIBits(hdc, hbm, y, 1, dst_bits+dst_stride*y,
4711                             pbmi, DIB_RGB_COLORS);
4712                     }
4713
4714                     GdipFree(pbmi);
4715                 }
4716                 else
4717                     retval = OutOfMemory;
4718
4719                 SelectObject(hdc, oldhbm);
4720                 DeleteDC(hdc);
4721             }
4722
4723             GdipBitmapUnlockBits(*bitmap, &lockeddata);
4724         }
4725
4726         if (retval == Ok && hpal)
4727         {
4728             WORD num_palette_entries;
4729             PALETTEENTRY *palette_entries=NULL;
4730             ColorPalette *palette=NULL;
4731             int i;
4732
4733             if (!GetObjectW(hpal, sizeof(num_palette_entries), &num_palette_entries))
4734                 retval = GenericError;
4735
4736             if (retval == Ok)
4737             {
4738                 palette_entries = GdipAlloc(sizeof(PALETTEENTRY) * num_palette_entries);
4739                 palette = GdipAlloc(sizeof(ColorPalette) + sizeof(ARGB) * (num_palette_entries-1));
4740
4741                 if (!palette_entries || !palette)
4742                     retval = OutOfMemory;
4743             }
4744
4745             if (retval == Ok)
4746             {
4747                 if (!GetPaletteEntries(hpal, 0, num_palette_entries, palette_entries))
4748                     retval = GenericError;
4749             }
4750
4751             if (retval == Ok)
4752             {
4753                 palette->Flags = 0;
4754                 palette->Count = num_palette_entries;
4755
4756                 for (i=0; i<num_palette_entries; i++)
4757                 {
4758                     PALETTEENTRY * entry = &palette_entries[i];
4759                     palette->Entries[i] = 0xff000000 | entry->peRed << 16 |
4760                         entry->peGreen << 8 | entry->peBlue;
4761                 }
4762
4763                 retval = GdipSetImagePalette((GpImage*)*bitmap, palette);
4764             }
4765
4766             GdipFree(palette_entries);
4767             GdipFree(palette);
4768         }
4769
4770         if (retval != Ok)
4771         {
4772             GdipDisposeImage((GpImage*)*bitmap);
4773             *bitmap = NULL;
4774         }
4775     }
4776
4777     return retval;
4778 }
4779
4780 GpStatus WINGDIPAPI GdipDeleteEffect(CGpEffect *effect)
4781 {
4782     FIXME("(%p): stub\n", effect);
4783     /* note: According to Jose Roca's GDI+ Docs, this is not implemented
4784      * in Windows's gdiplus */
4785     return NotImplemented;
4786 }
4787
4788 /*****************************************************************************
4789  * GdipSetEffectParameters [GDIPLUS.@]
4790  */
4791 GpStatus WINGDIPAPI GdipSetEffectParameters(CGpEffect *effect,
4792     const VOID *params, const UINT size)
4793 {
4794     static int calls;
4795
4796     TRACE("(%p,%p,%u)\n", effect, params, size);
4797
4798     if(!(calls++))
4799         FIXME("not implemented\n");
4800
4801     return NotImplemented;
4802 }
4803
4804 /*****************************************************************************
4805  * GdipGetImageFlags [GDIPLUS.@]
4806  */
4807 GpStatus WINGDIPAPI GdipGetImageFlags(GpImage *image, UINT *flags)
4808 {
4809     TRACE("%p %p\n", image, flags);
4810
4811     if(!image || !flags)
4812         return InvalidParameter;
4813
4814     *flags = image->flags;
4815
4816     return Ok;
4817 }
4818
4819 GpStatus WINGDIPAPI GdipTestControl(GpTestControlEnum control, void *param)
4820 {
4821     TRACE("(%d, %p)\n", control, param);
4822
4823     switch(control){
4824         case TestControlForceBilinear:
4825             if(param)
4826                 FIXME("TestControlForceBilinear not handled\n");
4827             break;
4828         case TestControlNoICM:
4829             if(param)
4830                 FIXME("TestControlNoICM not handled\n");
4831             break;
4832         case TestControlGetBuildNumber:
4833             *((DWORD*)param) = 3102;
4834             break;
4835     }
4836
4837     return Ok;
4838 }
4839
4840 GpStatus WINGDIPAPI GdipRecordMetafileFileName(GDIPCONST WCHAR* fileName,
4841                             HDC hdc, EmfType type, GDIPCONST GpRectF *pFrameRect,
4842                             MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc,
4843                             GpMetafile **metafile)
4844 {
4845     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4846                                  frameUnit, debugstr_w(desc), metafile);
4847
4848     return NotImplemented;
4849 }
4850
4851 GpStatus WINGDIPAPI GdipRecordMetafileFileNameI(GDIPCONST WCHAR* fileName, HDC hdc, EmfType type,
4852                             GDIPCONST GpRect *pFrameRect, MetafileFrameUnit frameUnit,
4853                             GDIPCONST WCHAR *desc, GpMetafile **metafile)
4854 {
4855     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4856                                  frameUnit, debugstr_w(desc), metafile);
4857
4858     return NotImplemented;
4859 }
4860
4861 GpStatus WINGDIPAPI GdipImageForceValidation(GpImage *image)
4862 {
4863     TRACE("%p\n", image);
4864
4865     return Ok;
4866 }
4867
4868 /*****************************************************************************
4869  * GdipGetImageThumbnail [GDIPLUS.@]
4870  */
4871 GpStatus WINGDIPAPI GdipGetImageThumbnail(GpImage *image, UINT width, UINT height,
4872                             GpImage **ret_image, GetThumbnailImageAbort cb,
4873                             VOID * cb_data)
4874 {
4875     GpStatus stat;
4876     GpGraphics *graphics;
4877     UINT srcwidth, srcheight;
4878
4879     TRACE("(%p %u %u %p %p %p)\n",
4880         image, width, height, ret_image, cb, cb_data);
4881
4882     if (!image || !ret_image)
4883         return InvalidParameter;
4884
4885     if (!width) width = 120;
4886     if (!height) height = 120;
4887
4888     GdipGetImageWidth(image, &srcwidth);
4889     GdipGetImageHeight(image, &srcheight);
4890
4891     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppPARGB,
4892         NULL, (GpBitmap**)ret_image);
4893
4894     if (stat == Ok)
4895     {
4896         stat = GdipGetImageGraphicsContext(*ret_image, &graphics);
4897
4898         if (stat == Ok)
4899         {
4900             stat = GdipDrawImageRectRectI(graphics, image,
4901                 0, 0, width, height, 0, 0, srcwidth, srcheight, UnitPixel,
4902                 NULL, NULL, NULL);
4903
4904             GdipDeleteGraphics(graphics);
4905         }
4906
4907         if (stat != Ok)
4908         {
4909             GdipDisposeImage(*ret_image);
4910             *ret_image = NULL;
4911         }
4912     }
4913
4914     return stat;
4915 }
4916
4917 /*****************************************************************************
4918  * GdipImageRotateFlip [GDIPLUS.@]
4919  */
4920 GpStatus WINGDIPAPI GdipImageRotateFlip(GpImage *image, RotateFlipType type)
4921 {
4922     GpBitmap *new_bitmap;
4923     GpBitmap *bitmap;
4924     int bpp, bytesperpixel;
4925     int rotate_90, flip_x, flip_y;
4926     int src_x_offset, src_y_offset;
4927     LPBYTE src_origin;
4928     UINT x, y, width, height;
4929     BitmapData src_lock, dst_lock;
4930     GpStatus stat;
4931
4932     TRACE("(%p, %u)\n", image, type);
4933
4934     if (!image)
4935         return InvalidParameter;
4936
4937     rotate_90 = type&1;
4938     flip_x = (type&6) == 2 || (type&6) == 4;
4939     flip_y = (type&3) == 1 || (type&3) == 2;
4940
4941     if (image->type != ImageTypeBitmap)
4942     {
4943         FIXME("Not implemented for type %i\n", image->type);
4944         return NotImplemented;
4945     }
4946
4947     bitmap = (GpBitmap*)image;
4948     bpp = PIXELFORMATBPP(bitmap->format);
4949
4950     if (bpp < 8)
4951     {
4952         FIXME("Not implemented for %i bit images\n", bpp);
4953         return NotImplemented;
4954     }
4955
4956     if (rotate_90)
4957     {
4958         width = bitmap->height;
4959         height = bitmap->width;
4960     }
4961     else
4962     {
4963         width = bitmap->width;
4964         height = bitmap->height;
4965     }
4966
4967     bytesperpixel = bpp/8;
4968
4969     stat = GdipCreateBitmapFromScan0(width, height, 0, bitmap->format, NULL, &new_bitmap);
4970
4971     if (stat != Ok)
4972         return stat;
4973
4974     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format, &src_lock);
4975
4976     if (stat == Ok)
4977     {
4978         stat = GdipBitmapLockBits(new_bitmap, NULL, ImageLockModeWrite, bitmap->format, &dst_lock);
4979
4980         if (stat == Ok)
4981         {
4982             LPBYTE src_row, src_pixel;
4983             LPBYTE dst_row, dst_pixel;
4984
4985             src_origin = src_lock.Scan0;
4986             if (flip_x) src_origin += bytesperpixel * (bitmap->width - 1);
4987             if (flip_y) src_origin += src_lock.Stride * (bitmap->height - 1);
4988
4989             if (rotate_90)
4990             {
4991                 if (flip_y) src_x_offset = -src_lock.Stride;
4992                 else src_x_offset = src_lock.Stride;
4993                 if (flip_x) src_y_offset = -bytesperpixel;
4994                 else src_y_offset = bytesperpixel;
4995             }
4996             else
4997             {
4998                 if (flip_x) src_x_offset = -bytesperpixel;
4999                 else src_x_offset = bytesperpixel;
5000                 if (flip_y) src_y_offset = -src_lock.Stride;
5001                 else src_y_offset = src_lock.Stride;
5002             }
5003
5004             src_row = src_origin;
5005             dst_row = dst_lock.Scan0;
5006             for (y=0; y<height; y++)
5007             {
5008                 src_pixel = src_row;
5009                 dst_pixel = dst_row;
5010                 for (x=0; x<width; x++)
5011                 {
5012                     /* FIXME: This could probably be faster without memcpy. */
5013                     memcpy(dst_pixel, src_pixel, bytesperpixel);
5014                     dst_pixel += bytesperpixel;
5015                     src_pixel += src_x_offset;
5016                 }
5017                 src_row += src_y_offset;
5018                 dst_row += dst_lock.Stride;
5019             }
5020
5021             GdipBitmapUnlockBits(new_bitmap, &dst_lock);
5022         }
5023
5024         GdipBitmapUnlockBits(bitmap, &src_lock);
5025     }
5026
5027     if (stat == Ok)
5028         move_bitmap(bitmap, new_bitmap, FALSE);
5029     else
5030         GdipDisposeImage((GpImage*)new_bitmap);
5031
5032     return stat;
5033 }
5034
5035 /*****************************************************************************
5036  * GdipConvertToEmfPlusToFile [GDIPLUS.@]
5037  */
5038
5039 GpStatus WINGDIPAPI GdipConvertToEmfPlusToFile(const GpGraphics* refGraphics,
5040                                                GpMetafile* metafile, BOOL* conversionSuccess,
5041                                                const WCHAR* filename, EmfType emfType,
5042                                                const WCHAR* description, GpMetafile** out_metafile)
5043 {
5044     FIXME("stub: %p, %p, %p, %p, %u, %p, %p\n", refGraphics, metafile, conversionSuccess, filename, emfType, description, out_metafile);
5045     return NotImplemented;
5046 }