gdiplus: Test the ability to load WMF images.
[wine] / dlls / gdiplus / image.c
1 /*
2  * Copyright (C) 2007 Google (Evan Stade)
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include <stdarg.h>
20
21 #define NONAMELESSUNION
22
23 #include "windef.h"
24 #include "winbase.h"
25 #include "winuser.h"
26 #include "wingdi.h"
27
28 #define COBJMACROS
29 #include "objbase.h"
30 #include "olectl.h"
31 #include "ole2.h"
32
33 #include "initguid.h"
34 #include "wincodec.h"
35 #include "gdiplus.h"
36 #include "gdiplus_private.h"
37 #include "wine/debug.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(gdiplus);
40
41 #define PIXELFORMATBPP(x) ((x) ? ((x) >> 8) & 255 : 24)
42
43 static INT ipicture_pixel_height(IPicture *pic)
44 {
45     HDC hdcref;
46     OLE_YSIZE_HIMETRIC y;
47
48     IPicture_get_Height(pic, &y);
49
50     hdcref = GetDC(0);
51
52     y = MulDiv(y, GetDeviceCaps(hdcref, LOGPIXELSY), INCH_HIMETRIC);
53     ReleaseDC(0, hdcref);
54
55     return y;
56 }
57
58 static INT ipicture_pixel_width(IPicture *pic)
59 {
60     HDC hdcref;
61     OLE_XSIZE_HIMETRIC x;
62
63     IPicture_get_Width(pic, &x);
64
65     hdcref = GetDC(0);
66
67     x = MulDiv(x, GetDeviceCaps(hdcref, LOGPIXELSX), INCH_HIMETRIC);
68
69     ReleaseDC(0, hdcref);
70
71     return x;
72 }
73
74 GpStatus WINGDIPAPI GdipBitmapApplyEffect(GpBitmap* bitmap, CGpEffect* effect,
75     RECT* roi, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
76 {
77     FIXME("(%p %p %p %d %p %p): stub\n", bitmap, effect, roi, useAuxData, auxData, auxDataSize);
78     /*
79      * Note: According to Jose Roca's GDI+ docs, this function is not
80      * implemented in Windows's GDI+.
81      */
82     return NotImplemented;
83 }
84
85 GpStatus WINGDIPAPI GdipBitmapCreateApplyEffect(GpBitmap** inputBitmaps,
86     INT numInputs, CGpEffect* effect, RECT* roi, RECT* outputRect,
87     GpBitmap** outputBitmap, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
88 {
89     FIXME("(%p %d %p %p %p %p %d %p %p): stub\n", inputBitmaps, numInputs, effect, roi, outputRect, outputBitmap, useAuxData, auxData, auxDataSize);
90     /*
91      * Note: According to Jose Roca's GDI+ docs, this function is not
92      * implemented in Windows's GDI+.
93      */
94     return NotImplemented;
95 }
96
97 static inline void getpixel_16bppGrayScale(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
98     const BYTE *row, UINT x)
99 {
100     *r = *g = *b = row[x*2+1];
101     *a = 255;
102 }
103
104 static inline void getpixel_16bppRGB555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
105     const BYTE *row, UINT x)
106 {
107     WORD pixel = *((WORD*)(row)+x);
108     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
109     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
110     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
111     *a = 255;
112 }
113
114 static inline void getpixel_16bppRGB565(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
115     const BYTE *row, UINT x)
116 {
117     WORD pixel = *((WORD*)(row)+x);
118     *r = (pixel>>8&0xf8)|(pixel>>13&0x7);
119     *g = (pixel>>3&0xfc)|(pixel>>9&0x3);
120     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
121     *a = 255;
122 }
123
124 static inline void getpixel_16bppARGB1555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
125     const BYTE *row, UINT x)
126 {
127     WORD pixel = *((WORD*)(row)+x);
128     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
129     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
130     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
131     if ((pixel&0x8000) == 0x8000)
132         *a = 255;
133     else
134         *a = 0;
135 }
136
137 static inline void getpixel_24bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
138     const BYTE *row, UINT x)
139 {
140     *r = row[x*3+2];
141     *g = row[x*3+1];
142     *b = row[x*3];
143     *a = 255;
144 }
145
146 static inline void getpixel_32bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
147     const BYTE *row, UINT x)
148 {
149     *r = row[x*4+2];
150     *g = row[x*4+1];
151     *b = row[x*4];
152     *a = 255;
153 }
154
155 static inline void getpixel_32bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
156     const BYTE *row, UINT x)
157 {
158     *r = row[x*4+2];
159     *g = row[x*4+1];
160     *b = row[x*4];
161     *a = row[x*4+3];
162 }
163
164 static inline void getpixel_32bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
165     const BYTE *row, UINT x)
166 {
167     *a = row[x*4+3];
168     if (*a == 0)
169         *r = *g = *b = 0;
170     else
171     {
172         *r = row[x*4+2] * 255 / *a;
173         *g = row[x*4+1] * 255 / *a;
174         *b = row[x*4] * 255 / *a;
175     }
176 }
177
178 static inline void getpixel_48bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
179     const BYTE *row, UINT x)
180 {
181     *r = row[x*6+5];
182     *g = row[x*6+3];
183     *b = row[x*6+1];
184     *a = 255;
185 }
186
187 static inline void getpixel_64bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
188     const BYTE *row, UINT x)
189 {
190     *r = row[x*8+5];
191     *g = row[x*8+3];
192     *b = row[x*8+1];
193     *a = row[x*8+7];
194 }
195
196 static inline void getpixel_64bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
197     const BYTE *row, UINT x)
198 {
199     *a = row[x*8+7];
200     if (*a == 0)
201         *r = *g = *b = 0;
202     else
203     {
204         *r = row[x*8+5] * 255 / *a;
205         *g = row[x*8+3] * 255 / *a;
206         *b = row[x*8+1] * 255 / *a;
207     }
208 }
209
210 GpStatus WINGDIPAPI GdipBitmapGetPixel(GpBitmap* bitmap, INT x, INT y,
211     ARGB *color)
212 {
213     BYTE r, g, b, a;
214     BYTE *row;
215     TRACE("%p %d %d %p\n", bitmap, x, y, color);
216
217     if(!bitmap || !color ||
218        x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
219         return InvalidParameter;
220
221     row = bitmap->bits+bitmap->stride*y;
222
223     switch (bitmap->format)
224     {
225         case PixelFormat16bppGrayScale:
226             getpixel_16bppGrayScale(&r,&g,&b,&a,row,x);
227             break;
228         case PixelFormat16bppRGB555:
229             getpixel_16bppRGB555(&r,&g,&b,&a,row,x);
230             break;
231         case PixelFormat16bppRGB565:
232             getpixel_16bppRGB565(&r,&g,&b,&a,row,x);
233             break;
234         case PixelFormat16bppARGB1555:
235             getpixel_16bppARGB1555(&r,&g,&b,&a,row,x);
236             break;
237         case PixelFormat24bppRGB:
238             getpixel_24bppRGB(&r,&g,&b,&a,row,x);
239             break;
240         case PixelFormat32bppRGB:
241             getpixel_32bppRGB(&r,&g,&b,&a,row,x);
242             break;
243         case PixelFormat32bppARGB:
244             getpixel_32bppARGB(&r,&g,&b,&a,row,x);
245             break;
246         case PixelFormat32bppPARGB:
247             getpixel_32bppPARGB(&r,&g,&b,&a,row,x);
248             break;
249         case PixelFormat48bppRGB:
250             getpixel_48bppRGB(&r,&g,&b,&a,row,x);
251             break;
252         case PixelFormat64bppARGB:
253             getpixel_64bppARGB(&r,&g,&b,&a,row,x);
254             break;
255         case PixelFormat64bppPARGB:
256             getpixel_64bppPARGB(&r,&g,&b,&a,row,x);
257             break;
258         default:
259             FIXME("not implemented for format 0x%x\n", bitmap->format);
260             return NotImplemented;
261     }
262
263     *color = a<<24|r<<16|g<<8|b;
264
265     return Ok;
266 }
267
268 static inline void setpixel_16bppGrayScale(BYTE r, BYTE g, BYTE b, BYTE a,
269     BYTE *row, UINT x)
270 {
271     *((WORD*)(row)+x) = (r+g+b)*85;
272 }
273
274 static inline void setpixel_16bppRGB555(BYTE r, BYTE g, BYTE b, BYTE a,
275     BYTE *row, UINT x)
276 {
277     *((WORD*)(row)+x) = (r<<7&0x7c00)|
278                         (g<<2&0x03e0)|
279                         (b>>3&0x001f);
280 }
281
282 static inline void setpixel_16bppRGB565(BYTE r, BYTE g, BYTE b, BYTE a,
283     BYTE *row, UINT x)
284 {
285     *((WORD*)(row)+x) = (r<<8&0xf800)|
286                          (g<<3&0x07e0)|
287                          (b>>3&0x001f);
288 }
289
290 static inline void setpixel_16bppARGB1555(BYTE r, BYTE g, BYTE b, BYTE a,
291     BYTE *row, UINT x)
292 {
293     *((WORD*)(row)+x) = (a<<8&0x8000)|
294                         (r<<7&0x7c00)|
295                         (g<<2&0x03e0)|
296                         (b>>3&0x001f);
297 }
298
299 static inline void setpixel_24bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
300     BYTE *row, UINT x)
301 {
302     row[x*3+2] = r;
303     row[x*3+1] = g;
304     row[x*3] = b;
305 }
306
307 static inline void setpixel_32bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
308     BYTE *row, UINT x)
309 {
310     *((DWORD*)(row)+x) = (r<<16)|(g<<8)|b;
311 }
312
313 static inline void setpixel_32bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
314     BYTE *row, UINT x)
315 {
316     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
317 }
318
319 static inline void setpixel_32bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
320     BYTE *row, UINT x)
321 {
322     r = r * a / 255;
323     g = g * a / 255;
324     b = b * a / 255;
325     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
326 }
327
328 static inline void setpixel_48bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
329     BYTE *row, UINT x)
330 {
331     row[x*6+5] = row[x*6+4] = r;
332     row[x*6+3] = row[x*6+2] = g;
333     row[x*6+1] = row[x*6] = b;
334 }
335
336 static inline void setpixel_64bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
337     BYTE *row, UINT x)
338 {
339     UINT64 a64=a, r64=r, g64=g, b64=b;
340     *((UINT64*)(row)+x) = (a64<<56)|(a64<<48)|(r64<<40)|(r64<<32)|(g64<<24)|(g64<<16)|(b64<<8)|b64;
341 }
342
343 static inline void setpixel_64bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
344     BYTE *row, UINT x)
345 {
346     UINT64 a64, r64, g64, b64;
347     a64 = a * 257;
348     r64 = r * a / 255;
349     g64 = g * a / 255;
350     b64 = b * a / 255;
351     *((UINT64*)(row)+x) = (a64<<48)|(r64<<32)|(g64<<16)|b64;
352 }
353
354 GpStatus WINGDIPAPI GdipBitmapSetPixel(GpBitmap* bitmap, INT x, INT y,
355     ARGB color)
356 {
357     BYTE a, r, g, b;
358     BYTE *row;
359     TRACE("bitmap:%p, x:%d, y:%d, color:%08x\n", bitmap, x, y, color);
360
361     if(!bitmap || x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
362         return InvalidParameter;
363
364     a = color>>24;
365     r = color>>16;
366     g = color>>8;
367     b = color;
368
369     row = bitmap->bits + bitmap->stride * y;
370
371     switch (bitmap->format)
372     {
373         case PixelFormat16bppGrayScale:
374             setpixel_16bppGrayScale(r,g,b,a,row,x);
375             break;
376         case PixelFormat16bppRGB555:
377             setpixel_16bppRGB555(r,g,b,a,row,x);
378             break;
379         case PixelFormat16bppRGB565:
380             setpixel_16bppRGB565(r,g,b,a,row,x);
381             break;
382         case PixelFormat16bppARGB1555:
383             setpixel_16bppARGB1555(r,g,b,a,row,x);
384             break;
385         case PixelFormat24bppRGB:
386             setpixel_24bppRGB(r,g,b,a,row,x);
387             break;
388         case PixelFormat32bppRGB:
389             setpixel_32bppRGB(r,g,b,a,row,x);
390             break;
391         case PixelFormat32bppARGB:
392             setpixel_32bppARGB(r,g,b,a,row,x);
393             break;
394         case PixelFormat32bppPARGB:
395             setpixel_32bppPARGB(r,g,b,a,row,x);
396             break;
397         case PixelFormat48bppRGB:
398             setpixel_48bppRGB(r,g,b,a,row,x);
399             break;
400         case PixelFormat64bppARGB:
401             setpixel_64bppARGB(r,g,b,a,row,x);
402             break;
403         case PixelFormat64bppPARGB:
404             setpixel_64bppPARGB(r,g,b,a,row,x);
405             break;
406         default:
407             FIXME("not implemented for format 0x%x\n", bitmap->format);
408             return NotImplemented;
409     }
410
411     return Ok;
412 }
413
414 /* This function returns a pointer to an array of pixels that represents the
415  * bitmap. The *entire* bitmap is locked according to the lock mode specified by
416  * flags.  It is correct behavior that a user who calls this function with write
417  * privileges can write to the whole bitmap (not just the area in rect).
418  *
419  * FIXME: only used portion of format is bits per pixel. */
420 GpStatus WINGDIPAPI GdipBitmapLockBits(GpBitmap* bitmap, GDIPCONST GpRect* rect,
421     UINT flags, PixelFormat format, BitmapData* lockeddata)
422 {
423     BOOL bm_is_selected;
424     INT stride, bitspp = PIXELFORMATBPP(format);
425     HDC hdc;
426     HBITMAP hbm, old = NULL;
427     BITMAPINFO *pbmi;
428     BYTE *buff = NULL;
429     UINT abs_height;
430     GpRect act_rect; /* actual rect to be used */
431
432     TRACE("%p %p %d %d %p\n", bitmap, rect, flags, format, lockeddata);
433
434     if(!lockeddata || !bitmap)
435         return InvalidParameter;
436
437     if(rect){
438         if(rect->X < 0 || rect->Y < 0 || (rect->X + rect->Width > bitmap->width) ||
439           (rect->Y + rect->Height > bitmap->height) || !flags)
440             return InvalidParameter;
441
442         act_rect = *rect;
443     }
444     else{
445         act_rect.X = act_rect.Y = 0;
446         act_rect.Width  = bitmap->width;
447         act_rect.Height = bitmap->height;
448     }
449
450     if(flags & ImageLockModeUserInputBuf)
451         return NotImplemented;
452
453     if(bitmap->lockmode)
454         return WrongState;
455
456     if (bitmap->bits && bitmap->format == format)
457     {
458         /* no conversion is necessary; just use the bits directly */
459         lockeddata->Width = act_rect.Width;
460         lockeddata->Height = act_rect.Height;
461         lockeddata->PixelFormat = format;
462         lockeddata->Reserved = flags;
463         lockeddata->Stride = bitmap->stride;
464         lockeddata->Scan0 = bitmap->bits + (bitspp / 8) * act_rect.X +
465                             bitmap->stride * act_rect.Y;
466
467         bitmap->lockmode = flags;
468         bitmap->numlocks++;
469
470         return Ok;
471     }
472
473     hbm = bitmap->hbitmap;
474     hdc = bitmap->hdc;
475     bm_is_selected = (hdc != 0);
476
477     pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
478     if (!pbmi)
479         return OutOfMemory;
480     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
481     pbmi->bmiHeader.biBitCount = 0;
482
483     if(!bm_is_selected){
484         hdc = CreateCompatibleDC(0);
485         old = SelectObject(hdc, hbm);
486     }
487
488     /* fill out bmi */
489     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
490
491     abs_height = abs(pbmi->bmiHeader.biHeight);
492     stride = pbmi->bmiHeader.biWidth * bitspp / 8;
493     stride = (stride + 3) & ~3;
494
495     buff = GdipAlloc(stride * abs_height);
496
497     pbmi->bmiHeader.biBitCount = bitspp;
498
499     if(buff)
500         GetDIBits(hdc, hbm, 0, abs_height, buff, pbmi, DIB_RGB_COLORS);
501
502     if(!bm_is_selected){
503         SelectObject(hdc, old);
504         DeleteDC(hdc);
505     }
506
507     if(!buff){
508         GdipFree(pbmi);
509         return OutOfMemory;
510     }
511
512     lockeddata->Width  = act_rect.Width;
513     lockeddata->Height = act_rect.Height;
514     lockeddata->PixelFormat = format;
515     lockeddata->Reserved = flags;
516
517     if(pbmi->bmiHeader.biHeight > 0){
518         lockeddata->Stride = -stride;
519         lockeddata->Scan0  = buff + (bitspp / 8) * act_rect.X +
520                              stride * (abs_height - 1 - act_rect.Y);
521     }
522     else{
523         lockeddata->Stride = stride;
524         lockeddata->Scan0  = buff + (bitspp / 8) * act_rect.X + stride * act_rect.Y;
525     }
526
527     bitmap->lockmode = flags;
528     bitmap->numlocks++;
529
530     bitmap->bitmapbits = buff;
531
532     GdipFree(pbmi);
533     return Ok;
534 }
535
536 GpStatus WINGDIPAPI GdipBitmapSetResolution(GpBitmap* bitmap, REAL xdpi, REAL ydpi)
537 {
538     FIXME("(%p, %.2f, %.2f)\n", bitmap, xdpi, ydpi);
539
540     return NotImplemented;
541 }
542
543 GpStatus WINGDIPAPI GdipBitmapUnlockBits(GpBitmap* bitmap,
544     BitmapData* lockeddata)
545 {
546     HDC hdc;
547     HBITMAP hbm, old = NULL;
548     BOOL bm_is_selected;
549     BITMAPINFO *pbmi;
550
551     if(!bitmap || !lockeddata)
552         return InvalidParameter;
553
554     if(!bitmap->lockmode)
555         return WrongState;
556
557     if(lockeddata->Reserved & ImageLockModeUserInputBuf)
558         return NotImplemented;
559
560     if(lockeddata->Reserved & ImageLockModeRead){
561         if(!(--bitmap->numlocks))
562             bitmap->lockmode = 0;
563
564         GdipFree(bitmap->bitmapbits);
565         bitmap->bitmapbits = NULL;
566         return Ok;
567     }
568
569     if (!bitmap->bitmapbits)
570     {
571         /* we passed a direct reference; no need to do anything */
572         bitmap->lockmode = 0;
573         return Ok;
574     }
575
576     hbm = bitmap->hbitmap;
577     hdc = bitmap->hdc;
578     bm_is_selected = (hdc != 0);
579
580     pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
581     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
582     pbmi->bmiHeader.biBitCount = 0;
583
584     if(!bm_is_selected){
585         hdc = CreateCompatibleDC(0);
586         old = SelectObject(hdc, hbm);
587     }
588
589     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
590     pbmi->bmiHeader.biBitCount = PIXELFORMATBPP(lockeddata->PixelFormat);
591     SetDIBits(hdc, hbm, 0, abs(pbmi->bmiHeader.biHeight),
592               bitmap->bitmapbits, pbmi, DIB_RGB_COLORS);
593
594     if(!bm_is_selected){
595         SelectObject(hdc, old);
596         DeleteDC(hdc);
597     }
598
599     GdipFree(pbmi);
600     GdipFree(bitmap->bitmapbits);
601     bitmap->bitmapbits = NULL;
602     bitmap->lockmode = 0;
603
604     return Ok;
605 }
606
607 GpStatus WINGDIPAPI GdipCloneBitmapArea(REAL x, REAL y, REAL width, REAL height,
608     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
609 {
610     BitmapData lockeddata_src, lockeddata_dst;
611     int i;
612     UINT row_size;
613     Rect area;
614     GpStatus stat;
615
616     TRACE("(%f,%f,%f,%f,%i,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
617
618     if (!srcBitmap || !dstBitmap || srcBitmap->image.type != ImageTypeBitmap ||
619         x < 0 || y < 0 ||
620         x + width > srcBitmap->width || y + height > srcBitmap->height)
621     {
622         TRACE("<-- InvalidParameter\n");
623         return InvalidParameter;
624     }
625
626     if (format == PixelFormatDontCare)
627         format = srcBitmap->format;
628
629     area.X = roundr(x);
630     area.Y = roundr(y);
631     area.Width = roundr(width);
632     area.Height = roundr(height);
633
634     stat = GdipBitmapLockBits(srcBitmap, &area, ImageLockModeRead, format,
635         &lockeddata_src);
636     if (stat != Ok) return stat;
637
638     stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
639         0, lockeddata_src.PixelFormat, NULL, dstBitmap);
640     if (stat == Ok)
641     {
642         stat = GdipBitmapLockBits(*dstBitmap, NULL, ImageLockModeWrite,
643             lockeddata_src.PixelFormat, &lockeddata_dst);
644
645         if (stat == Ok)
646         {
647             /* copy the image data */
648             row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
649             for (i=0; i<lockeddata_src.Height; i++)
650                 memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
651                        (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
652                        row_size);
653
654             GdipBitmapUnlockBits(*dstBitmap, &lockeddata_dst);
655         }
656
657         if (stat != Ok)
658             GdipDisposeImage((GpImage*)*dstBitmap);
659     }
660
661     GdipBitmapUnlockBits(srcBitmap, &lockeddata_src);
662
663     if (stat != Ok)
664     {
665         *dstBitmap = NULL;
666     }
667
668     return stat;
669 }
670
671 GpStatus WINGDIPAPI GdipCloneBitmapAreaI(INT x, INT y, INT width, INT height,
672     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
673 {
674     TRACE("(%i,%i,%i,%i,%i,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
675
676     return GdipCloneBitmapArea(x, y, width, height, format, srcBitmap, dstBitmap);
677 }
678
679 GpStatus WINGDIPAPI GdipCloneImage(GpImage *image, GpImage **cloneImage)
680 {
681     GpStatus stat = GenericError;
682
683     TRACE("%p, %p\n", image, cloneImage);
684
685     if (!image || !cloneImage)
686         return InvalidParameter;
687
688     if (image->picture)
689     {
690         IStream* stream;
691         HRESULT hr;
692         INT size;
693         LARGE_INTEGER move;
694
695         hr = CreateStreamOnHGlobal(0, TRUE, &stream);
696         if (FAILED(hr))
697             return GenericError;
698
699         hr = IPicture_SaveAsFile(image->picture, stream, FALSE, &size);
700         if(FAILED(hr))
701         {
702             WARN("Failed to save image on stream\n");
703             goto out;
704         }
705
706         /* Set seek pointer back to the beginning of the picture */
707         move.QuadPart = 0;
708         hr = IStream_Seek(stream, move, STREAM_SEEK_SET, NULL);
709         if (FAILED(hr))
710             goto out;
711
712         stat = GdipLoadImageFromStream(stream, cloneImage);
713         if (stat != Ok) WARN("Failed to load image from stream\n");
714
715     out:
716         IStream_Release(stream);
717         return stat;
718     }
719     else if (image->type == ImageTypeBitmap)
720     {
721         GpBitmap *bitmap = (GpBitmap*)image;
722         BitmapData lockeddata_src, lockeddata_dst;
723         int i;
724         UINT row_size;
725
726         stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format,
727             &lockeddata_src);
728         if (stat != Ok) return stat;
729
730         stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
731             0, lockeddata_src.PixelFormat, NULL, (GpBitmap**)cloneImage);
732         if (stat == Ok)
733         {
734             stat = GdipBitmapLockBits((GpBitmap*)*cloneImage, NULL, ImageLockModeWrite,
735                 lockeddata_src.PixelFormat, &lockeddata_dst);
736
737             if (stat == Ok)
738             {
739                 /* copy the image data */
740                 row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
741                 for (i=0; i<lockeddata_src.Height; i++)
742                     memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
743                            (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
744                            row_size);
745
746                 GdipBitmapUnlockBits((GpBitmap*)*cloneImage, &lockeddata_dst);
747             }
748
749             if (stat != Ok)
750                 GdipDisposeImage(*cloneImage);
751         }
752
753         GdipBitmapUnlockBits(bitmap, &lockeddata_src);
754
755         if (stat != Ok)
756         {
757             *cloneImage = NULL;
758         }
759         else memcpy(&(*cloneImage)->format, &image->format, sizeof(GUID));
760
761         return stat;
762     }
763     else
764     {
765         ERR("GpImage with no IPicture or bitmap?!\n");
766         return NotImplemented;
767     }
768 }
769
770 GpStatus WINGDIPAPI GdipCreateBitmapFromFile(GDIPCONST WCHAR* filename,
771     GpBitmap **bitmap)
772 {
773     GpStatus stat;
774     IStream *stream;
775
776     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
777
778     if(!filename || !bitmap)
779         return InvalidParameter;
780
781     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
782
783     if(stat != Ok)
784         return stat;
785
786     stat = GdipCreateBitmapFromStream(stream, bitmap);
787
788     IStream_Release(stream);
789
790     return stat;
791 }
792
793 GpStatus WINGDIPAPI GdipCreateBitmapFromGdiDib(GDIPCONST BITMAPINFO* info,
794                                                VOID *bits, GpBitmap **bitmap)
795 {
796     DWORD height, stride;
797     PixelFormat format;
798
799     FIXME("(%p, %p, %p) - partially implemented\n", info, bits, bitmap);
800
801     height = abs(info->bmiHeader.biHeight);
802     stride = ((info->bmiHeader.biWidth * info->bmiHeader.biBitCount + 31) >> 3) & ~3;
803
804     if(info->bmiHeader.biHeight > 0) /* bottom-up */
805     {
806         bits = (BYTE*)bits + (height - 1) * stride;
807         stride = -stride;
808     }
809
810     switch(info->bmiHeader.biBitCount) {
811     case 1:
812         format = PixelFormat1bppIndexed;
813         break;
814     case 4:
815         format = PixelFormat4bppIndexed;
816         break;
817     case 8:
818         format = PixelFormat8bppIndexed;
819         break;
820     case 24:
821         format = PixelFormat24bppRGB;
822         break;
823     default:
824         FIXME("don't know how to handle %d bpp\n", info->bmiHeader.biBitCount);
825         *bitmap = NULL;
826         return InvalidParameter;
827     }
828
829     return GdipCreateBitmapFromScan0(info->bmiHeader.biWidth, height, stride, format,
830                                      bits, bitmap);
831
832 }
833
834 /* FIXME: no icm */
835 GpStatus WINGDIPAPI GdipCreateBitmapFromFileICM(GDIPCONST WCHAR* filename,
836     GpBitmap **bitmap)
837 {
838     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
839
840     return GdipCreateBitmapFromFile(filename, bitmap);
841 }
842
843 GpStatus WINGDIPAPI GdipCreateBitmapFromResource(HINSTANCE hInstance,
844     GDIPCONST WCHAR* lpBitmapName, GpBitmap** bitmap)
845 {
846     HBITMAP hbm;
847     GpStatus stat = InvalidParameter;
848
849     TRACE("%p (%s) %p\n", hInstance, debugstr_w(lpBitmapName), bitmap);
850
851     if(!lpBitmapName || !bitmap)
852         return InvalidParameter;
853
854     /* load DIB */
855     hbm = LoadImageW(hInstance, lpBitmapName, IMAGE_BITMAP, 0, 0,
856                      LR_CREATEDIBSECTION);
857
858     if(hbm){
859         stat = GdipCreateBitmapFromHBITMAP(hbm, NULL, bitmap);
860         DeleteObject(hbm);
861     }
862
863     return stat;
864 }
865
866 GpStatus WINGDIPAPI GdipCreateHBITMAPFromBitmap(GpBitmap* bitmap,
867     HBITMAP* hbmReturn, ARGB background)
868 {
869     GpStatus stat;
870     HBITMAP result, oldbitmap;
871     UINT width, height;
872     HDC hdc;
873     GpGraphics *graphics;
874     BITMAPINFOHEADER bih;
875     void *bits;
876     TRACE("(%p,%p,%x)\n", bitmap, hbmReturn, background);
877
878     if (!bitmap || !hbmReturn) return InvalidParameter;
879
880     GdipGetImageWidth((GpImage*)bitmap, &width);
881     GdipGetImageHeight((GpImage*)bitmap, &height);
882
883     bih.biSize = sizeof(bih);
884     bih.biWidth = width;
885     bih.biHeight = height;
886     bih.biPlanes = 1;
887     bih.biBitCount = 32;
888     bih.biCompression = BI_RGB;
889     bih.biSizeImage = 0;
890     bih.biXPelsPerMeter = 0;
891     bih.biYPelsPerMeter = 0;
892     bih.biClrUsed = 0;
893     bih.biClrImportant = 0;
894
895     hdc = CreateCompatibleDC(NULL);
896     if (!hdc) return GenericError;
897
898     result = CreateDIBSection(hdc, (BITMAPINFO*)&bih, DIB_RGB_COLORS, &bits,
899         NULL, 0);
900
901     if (result)
902     {
903         oldbitmap = SelectObject(hdc, result);
904
905         stat = GdipCreateFromHDC(hdc, &graphics);
906         if (stat == Ok)
907         {
908             stat = GdipGraphicsClear(graphics, background);
909
910             if (stat == Ok)
911                 stat = GdipDrawImage(graphics, (GpImage*)bitmap, 0, 0);
912
913             GdipDeleteGraphics(graphics);
914         }
915
916         SelectObject(hdc, oldbitmap);
917     }
918     else
919         stat = GenericError;
920
921     DeleteDC(hdc);
922
923     if (stat != Ok && result)
924     {
925         DeleteObject(result);
926         result = NULL;
927     }
928
929     *hbmReturn = result;
930
931     return stat;
932 }
933
934 GpStatus WINGDIPAPI GdipConvertToEmfPlus(const GpGraphics* ref,
935     GpMetafile* metafile, BOOL* succ, EmfType emfType,
936     const WCHAR* description, GpMetafile** out_metafile)
937 {
938     static int calls;
939
940     if(!ref || !metafile || !out_metafile)
941         return InvalidParameter;
942
943     *succ = FALSE;
944     *out_metafile = NULL;
945
946     if(!(calls++))
947         FIXME("not implemented\n");
948
949     return NotImplemented;
950 }
951
952 /* FIXME: this should create a bitmap in the given size with the attributes
953  * (resolution etc.) of the graphics object */
954 GpStatus WINGDIPAPI GdipCreateBitmapFromGraphics(INT width, INT height,
955     GpGraphics* target, GpBitmap** bitmap)
956 {
957     static int calls;
958     GpStatus ret;
959
960     if(!target || !bitmap)
961         return InvalidParameter;
962
963     if(!(calls++))
964         FIXME("hacked stub\n");
965
966     ret = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat24bppRGB,
967                                     NULL, bitmap);
968
969     return ret;
970 }
971
972 GpStatus WINGDIPAPI GdipCreateBitmapFromHICON(HICON hicon, GpBitmap** bitmap)
973 {
974     GpStatus stat;
975     ICONINFO iinfo;
976     BITMAP bm;
977     int ret;
978     UINT width, height;
979     GpRect rect;
980     BitmapData lockeddata;
981     HDC screendc;
982     BOOL has_alpha;
983     int x, y;
984     BYTE *bits;
985     BITMAPINFOHEADER bih;
986     DWORD *src;
987     BYTE *dst_row;
988     DWORD *dst;
989
990     TRACE("%p, %p\n", hicon, bitmap);
991
992     if(!bitmap || !GetIconInfo(hicon, &iinfo))
993         return InvalidParameter;
994
995     /* get the size of the icon */
996     ret = GetObjectA(iinfo.hbmColor ? iinfo.hbmColor : iinfo.hbmMask, sizeof(bm), &bm);
997     if (ret == 0) {
998         DeleteObject(iinfo.hbmColor);
999         DeleteObject(iinfo.hbmMask);
1000         return GenericError;
1001     }
1002
1003     width = bm.bmWidth;
1004
1005     if (iinfo.hbmColor)
1006         height = abs(bm.bmHeight);
1007     else /* combined bitmap + mask */
1008         height = abs(bm.bmHeight) / 2;
1009
1010     bits = HeapAlloc(GetProcessHeap(), 0, 4*width*height);
1011     if (!bits) {
1012         DeleteObject(iinfo.hbmColor);
1013         DeleteObject(iinfo.hbmMask);
1014         return OutOfMemory;
1015     }
1016
1017     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppARGB, NULL, bitmap);
1018     if (stat != Ok) {
1019         DeleteObject(iinfo.hbmColor);
1020         DeleteObject(iinfo.hbmMask);
1021         HeapFree(GetProcessHeap(), 0, bits);
1022         return stat;
1023     }
1024
1025     rect.X = 0;
1026     rect.Y = 0;
1027     rect.Width = width;
1028     rect.Height = height;
1029
1030     stat = GdipBitmapLockBits(*bitmap, &rect, ImageLockModeWrite, PixelFormat32bppARGB, &lockeddata);
1031     if (stat != Ok) {
1032         DeleteObject(iinfo.hbmColor);
1033         DeleteObject(iinfo.hbmMask);
1034         HeapFree(GetProcessHeap(), 0, bits);
1035         GdipDisposeImage((GpImage*)*bitmap);
1036         return stat;
1037     }
1038
1039     bih.biSize = sizeof(bih);
1040     bih.biWidth = width;
1041     bih.biHeight = -height;
1042     bih.biPlanes = 1;
1043     bih.biBitCount = 32;
1044     bih.biCompression = BI_RGB;
1045     bih.biSizeImage = 0;
1046     bih.biXPelsPerMeter = 0;
1047     bih.biYPelsPerMeter = 0;
1048     bih.biClrUsed = 0;
1049     bih.biClrImportant = 0;
1050
1051     screendc = GetDC(0);
1052     if (iinfo.hbmColor)
1053     {
1054         GetDIBits(screendc, iinfo.hbmColor, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1055
1056         if (bm.bmBitsPixel == 32)
1057         {
1058             has_alpha = FALSE;
1059
1060             /* If any pixel has a non-zero alpha, ignore hbmMask */
1061             src = (DWORD*)bits;
1062             for (x=0; x<width && !has_alpha; x++)
1063                 for (y=0; y<height && !has_alpha; y++)
1064                     if ((*src++ & 0xff000000) != 0)
1065                         has_alpha = TRUE;
1066         }
1067         else has_alpha = FALSE;
1068     }
1069     else
1070     {
1071         GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1072         has_alpha = FALSE;
1073     }
1074
1075     /* copy the image data to the Bitmap */
1076     src = (DWORD*)bits;
1077     dst_row = lockeddata.Scan0;
1078     for (y=0; y<height; y++)
1079     {
1080         memcpy(dst_row, src, width*4);
1081         src += width;
1082         dst_row += lockeddata.Stride;
1083     }
1084
1085     if (!has_alpha)
1086     {
1087         if (iinfo.hbmMask)
1088         {
1089             /* read alpha data from the mask */
1090             if (iinfo.hbmColor)
1091                 GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1092             else
1093                 GetDIBits(screendc, iinfo.hbmMask, height, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1094
1095             src = (DWORD*)bits;
1096             dst_row = lockeddata.Scan0;
1097             for (y=0; y<height; y++)
1098             {
1099                 dst = (DWORD*)dst_row;
1100                 for (x=0; x<height; x++)
1101                 {
1102                     DWORD src_value = *src++;
1103                     if (src_value)
1104                         *dst++ = 0;
1105                     else
1106                         *dst++ |= 0xff000000;
1107                 }
1108                 dst_row += lockeddata.Stride;
1109             }
1110         }
1111         else
1112         {
1113             /* set constant alpha of 255 */
1114             dst_row = bits;
1115             for (y=0; y<height; y++)
1116             {
1117                 dst = (DWORD*)dst_row;
1118                 for (x=0; x<height; x++)
1119                     *dst++ |= 0xff000000;
1120                 dst_row += lockeddata.Stride;
1121             }
1122         }
1123     }
1124
1125     ReleaseDC(0, screendc);
1126
1127     DeleteObject(iinfo.hbmColor);
1128     DeleteObject(iinfo.hbmMask);
1129
1130     GdipBitmapUnlockBits(*bitmap, &lockeddata);
1131
1132     HeapFree(GetProcessHeap(), 0, bits);
1133
1134     return Ok;
1135 }
1136
1137 static void generate_halftone_palette(ARGB *entries, UINT count)
1138 {
1139     static const BYTE halftone_values[6]={0x00,0x33,0x66,0x99,0xcc,0xff};
1140     UINT i;
1141
1142     for (i=0; i<8 && i<count; i++)
1143     {
1144         entries[i] = 0xff000000;
1145         if (i&1) entries[i] |= 0x800000;
1146         if (i&2) entries[i] |= 0x8000;
1147         if (i&4) entries[i] |= 0x80;
1148     }
1149
1150     if (8 < count)
1151         entries[i] = 0xffc0c0c0;
1152
1153     for (i=9; i<16 && i<count; i++)
1154     {
1155         entries[i] = 0xff000000;
1156         if (i&1) entries[i] |= 0xff0000;
1157         if (i&2) entries[i] |= 0xff00;
1158         if (i&4) entries[i] |= 0xff;
1159     }
1160
1161     for (i=16; i<40 && i<count; i++)
1162     {
1163         entries[i] = 0;
1164     }
1165
1166     for (i=40; i<256 && i<count; i++)
1167     {
1168         entries[i] = 0xff000000;
1169         entries[i] |= halftone_values[(i-40)%6];
1170         entries[i] |= halftone_values[((i-40)/6)%6] << 8;
1171         entries[i] |= halftone_values[((i-40)/36)%6] << 16;
1172     }
1173 }
1174
1175 GpStatus WINGDIPAPI GdipCreateBitmapFromScan0(INT width, INT height, INT stride,
1176     PixelFormat format, BYTE* scan0, GpBitmap** bitmap)
1177 {
1178     BITMAPINFOHEADER bmih;
1179     HBITMAP hbitmap;
1180     INT row_size, dib_stride;
1181     HDC hdc;
1182     BYTE *bits;
1183     int i;
1184
1185     TRACE("%d %d %d %d %p %p\n", width, height, stride, format, scan0, bitmap);
1186
1187     if (!bitmap) return InvalidParameter;
1188
1189     if(width <= 0 || height <= 0 || (scan0 && (stride % 4))){
1190         *bitmap = NULL;
1191         return InvalidParameter;
1192     }
1193
1194     if(scan0 && !stride)
1195         return InvalidParameter;
1196
1197     row_size = (width * PIXELFORMATBPP(format)+7) / 8;
1198     dib_stride = (row_size + 3) & ~3;
1199
1200     if(stride == 0)
1201         stride = dib_stride;
1202
1203     bmih.biSize = sizeof(BITMAPINFOHEADER);
1204     bmih.biWidth = width;
1205     bmih.biHeight = -height;
1206     bmih.biPlanes = 1;
1207     /* FIXME: use the rest of the data from format */
1208     bmih.biBitCount = PIXELFORMATBPP(format);
1209     bmih.biCompression = BI_RGB;
1210     bmih.biSizeImage = 0;
1211     bmih.biXPelsPerMeter = 0;
1212     bmih.biYPelsPerMeter = 0;
1213     bmih.biClrUsed = 0;
1214     bmih.biClrImportant = 0;
1215
1216     hdc = CreateCompatibleDC(NULL);
1217     if (!hdc) return GenericError;
1218
1219     hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, (void**)&bits,
1220         NULL, 0);
1221
1222     DeleteDC(hdc);
1223
1224     if (!hbitmap) return GenericError;
1225
1226     /* copy bits to the dib if necessary */
1227     /* FIXME: should reference the bits instead of copying them */
1228     if (scan0)
1229         for (i=0; i<height; i++)
1230             memcpy(bits+i*dib_stride, scan0+i*stride, row_size);
1231
1232     *bitmap = GdipAlloc(sizeof(GpBitmap));
1233     if(!*bitmap)
1234     {
1235         DeleteObject(hbitmap);
1236         return OutOfMemory;
1237     }
1238
1239     (*bitmap)->image.type = ImageTypeBitmap;
1240     memcpy(&(*bitmap)->image.format, &ImageFormatMemoryBMP, sizeof(GUID));
1241     (*bitmap)->image.flags = ImageFlagsNone;
1242     (*bitmap)->image.palette_flags = 0;
1243     (*bitmap)->image.palette_count = 0;
1244     (*bitmap)->image.palette_size = 0;
1245     (*bitmap)->image.palette_entries = NULL;
1246     (*bitmap)->width = width;
1247     (*bitmap)->height = height;
1248     (*bitmap)->format = format;
1249     (*bitmap)->image.picture = NULL;
1250     (*bitmap)->hbitmap = hbitmap;
1251     (*bitmap)->hdc = NULL;
1252     (*bitmap)->bits = bits;
1253     (*bitmap)->stride = dib_stride;
1254
1255     if (format == PixelFormat1bppIndexed ||
1256         format == PixelFormat4bppIndexed ||
1257         format == PixelFormat8bppIndexed)
1258     {
1259         (*bitmap)->image.palette_size = (*bitmap)->image.palette_count = 1 << PIXELFORMATBPP(format);
1260         (*bitmap)->image.palette_entries = GdipAlloc(sizeof(ARGB) * ((*bitmap)->image.palette_size));
1261
1262         if (!(*bitmap)->image.palette_entries)
1263         {
1264             GdipDisposeImage(&(*bitmap)->image);
1265             *bitmap = NULL;
1266             return OutOfMemory;
1267         }
1268
1269         if (format == PixelFormat1bppIndexed)
1270         {
1271             (*bitmap)->image.palette_flags = PaletteFlagsGrayScale;
1272             (*bitmap)->image.palette_entries[0] = 0xff000000;
1273             (*bitmap)->image.palette_entries[1] = 0xffffffff;
1274         }
1275         else
1276         {
1277             if (format == PixelFormat8bppIndexed)
1278                 (*bitmap)->image.palette_flags = PaletteFlagsHalftone;
1279
1280             generate_halftone_palette((*bitmap)->image.palette_entries,
1281                 (*bitmap)->image.palette_count);
1282         }
1283     }
1284
1285     TRACE("<-- %p\n", *bitmap);
1286
1287     return Ok;
1288 }
1289
1290 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
1291     GpBitmap **bitmap)
1292 {
1293     GpStatus stat;
1294
1295     TRACE("%p %p\n", stream, bitmap);
1296
1297     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
1298
1299     if(stat != Ok)
1300         return stat;
1301
1302     if((*bitmap)->image.type != ImageTypeBitmap){
1303         GdipDisposeImage(&(*bitmap)->image);
1304         *bitmap = NULL;
1305         return GenericError; /* FIXME: what error to return? */
1306     }
1307
1308     return Ok;
1309 }
1310
1311 /* FIXME: no icm */
1312 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
1313     GpBitmap **bitmap)
1314 {
1315     TRACE("%p %p\n", stream, bitmap);
1316
1317     return GdipCreateBitmapFromStream(stream, bitmap);
1318 }
1319
1320 GpStatus WINGDIPAPI GdipCreateCachedBitmap(GpBitmap *bitmap, GpGraphics *graphics,
1321     GpCachedBitmap **cachedbmp)
1322 {
1323     GpStatus stat;
1324
1325     TRACE("%p %p %p\n", bitmap, graphics, cachedbmp);
1326
1327     if(!bitmap || !graphics || !cachedbmp)
1328         return InvalidParameter;
1329
1330     *cachedbmp = GdipAlloc(sizeof(GpCachedBitmap));
1331     if(!*cachedbmp)
1332         return OutOfMemory;
1333
1334     stat = GdipCloneImage(&(bitmap->image), &(*cachedbmp)->image);
1335     if(stat != Ok){
1336         GdipFree(*cachedbmp);
1337         return stat;
1338     }
1339
1340     return Ok;
1341 }
1342
1343 GpStatus WINGDIPAPI GdipCreateHICONFromBitmap(GpBitmap *bitmap, HICON *hicon)
1344 {
1345     FIXME("(%p, %p)\n", bitmap, hicon);
1346
1347     return NotImplemented;
1348 }
1349
1350 GpStatus WINGDIPAPI GdipDeleteCachedBitmap(GpCachedBitmap *cachedbmp)
1351 {
1352     TRACE("%p\n", cachedbmp);
1353
1354     if(!cachedbmp)
1355         return InvalidParameter;
1356
1357     GdipDisposeImage(cachedbmp->image);
1358     GdipFree(cachedbmp);
1359
1360     return Ok;
1361 }
1362
1363 GpStatus WINGDIPAPI GdipDrawCachedBitmap(GpGraphics *graphics,
1364     GpCachedBitmap *cachedbmp, INT x, INT y)
1365 {
1366     TRACE("%p %p %d %d\n", graphics, cachedbmp, x, y);
1367
1368     if(!graphics || !cachedbmp)
1369         return InvalidParameter;
1370
1371     return GdipDrawImage(graphics, cachedbmp->image, (REAL)x, (REAL)y);
1372 }
1373
1374 GpStatus WINGDIPAPI GdipEmfToWmfBits(HENHMETAFILE hemf, UINT cbData16,
1375     LPBYTE pData16, INT iMapMode, INT eFlags)
1376 {
1377     FIXME("(%p, %d, %p, %d, %d): stub\n", hemf, cbData16, pData16, iMapMode, eFlags);
1378     return NotImplemented;
1379 }
1380
1381 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
1382 {
1383     TRACE("%p\n", image);
1384
1385     if(!image)
1386         return InvalidParameter;
1387
1388     if (image->picture)
1389         IPicture_Release(image->picture);
1390     if (image->type == ImageTypeBitmap)
1391     {
1392         GdipFree(((GpBitmap*)image)->bitmapbits);
1393         DeleteDC(((GpBitmap*)image)->hdc);
1394     }
1395     GdipFree(image->palette_entries);
1396     GdipFree(image);
1397
1398     return Ok;
1399 }
1400
1401 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
1402 {
1403     if(!image || !item)
1404         return InvalidParameter;
1405
1406     return NotImplemented;
1407 }
1408
1409 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
1410     GpUnit *srcUnit)
1411 {
1412     TRACE("%p %p %p\n", image, srcRect, srcUnit);
1413
1414     if(!image || !srcRect || !srcUnit)
1415         return InvalidParameter;
1416     if(image->type == ImageTypeMetafile){
1417         *srcRect = ((GpMetafile*)image)->bounds;
1418         *srcUnit = ((GpMetafile*)image)->unit;
1419     }
1420     else if(image->type == ImageTypeBitmap){
1421         srcRect->X = srcRect->Y = 0.0;
1422         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
1423         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
1424         *srcUnit = UnitPixel;
1425     }
1426     else{
1427         srcRect->X = srcRect->Y = 0.0;
1428         srcRect->Width = ipicture_pixel_width(image->picture);
1429         srcRect->Height = ipicture_pixel_height(image->picture);
1430         *srcUnit = UnitPixel;
1431     }
1432
1433     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
1434           srcRect->Width, srcRect->Height, *srcUnit);
1435
1436     return Ok;
1437 }
1438
1439 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
1440     REAL *height)
1441 {
1442     TRACE("%p %p %p\n", image, width, height);
1443
1444     if(!image || !height || !width)
1445         return InvalidParameter;
1446
1447     if(image->type == ImageTypeMetafile){
1448         HDC hdc = GetDC(0);
1449
1450         *height = convert_unit(hdc, ((GpMetafile*)image)->unit) *
1451                         ((GpMetafile*)image)->bounds.Height;
1452
1453         *width = convert_unit(hdc, ((GpMetafile*)image)->unit) *
1454                         ((GpMetafile*)image)->bounds.Width;
1455
1456         ReleaseDC(0, hdc);
1457     }
1458
1459     else if(image->type == ImageTypeBitmap){
1460         *height = ((GpBitmap*)image)->height;
1461         *width = ((GpBitmap*)image)->width;
1462     }
1463     else{
1464         *height = ipicture_pixel_height(image->picture);
1465         *width = ipicture_pixel_width(image->picture);
1466     }
1467
1468     TRACE("returning (%f, %f)\n", *height, *width);
1469     return Ok;
1470 }
1471
1472 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
1473     GpGraphics **graphics)
1474 {
1475     HDC hdc;
1476
1477     TRACE("%p %p\n", image, graphics);
1478
1479     if(!image || !graphics)
1480         return InvalidParameter;
1481
1482     if(image->type != ImageTypeBitmap){
1483         FIXME("not implemented for image type %d\n", image->type);
1484         return NotImplemented;
1485     }
1486
1487     hdc = ((GpBitmap*)image)->hdc;
1488
1489     if(!hdc){
1490         hdc = CreateCompatibleDC(0);
1491         SelectObject(hdc, ((GpBitmap*)image)->hbitmap);
1492         ((GpBitmap*)image)->hdc = hdc;
1493     }
1494
1495     return GdipCreateFromHDC(hdc, graphics);
1496 }
1497
1498 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
1499 {
1500     TRACE("%p %p\n", image, height);
1501
1502     if(!image || !height)
1503         return InvalidParameter;
1504
1505     if(image->type == ImageTypeMetafile){
1506         HDC hdc = GetDC(0);
1507
1508         *height = roundr(convert_unit(hdc, ((GpMetafile*)image)->unit) *
1509                         ((GpMetafile*)image)->bounds.Height);
1510
1511         ReleaseDC(0, hdc);
1512     }
1513     else if(image->type == ImageTypeBitmap)
1514         *height = ((GpBitmap*)image)->height;
1515     else
1516         *height = ipicture_pixel_height(image->picture);
1517
1518     TRACE("returning %d\n", *height);
1519
1520     return Ok;
1521 }
1522
1523 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
1524 {
1525     static int calls;
1526
1527     if(!image || !res)
1528         return InvalidParameter;
1529
1530     if(!(calls++))
1531         FIXME("not implemented\n");
1532
1533     return NotImplemented;
1534 }
1535
1536 GpStatus WINGDIPAPI GdipGetImagePaletteSize(GpImage *image, INT *size)
1537 {
1538     TRACE("%p %p\n", image, size);
1539
1540     if(!image || !size)
1541         return InvalidParameter;
1542
1543     if (image->palette_count == 0)
1544         *size = sizeof(ColorPalette);
1545     else
1546         *size = sizeof(UINT)*2 + sizeof(ARGB)*image->palette_count;
1547
1548     TRACE("<-- %u\n", *size);
1549
1550     return Ok;
1551 }
1552
1553 /* FIXME: test this function for non-bitmap types */
1554 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
1555 {
1556     TRACE("%p %p\n", image, format);
1557
1558     if(!image || !format)
1559         return InvalidParameter;
1560
1561     if(image->type != ImageTypeBitmap)
1562         *format = PixelFormat24bppRGB;
1563     else
1564         *format = ((GpBitmap*) image)->format;
1565
1566     return Ok;
1567 }
1568
1569 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
1570 {
1571     if(!image || !format)
1572         return InvalidParameter;
1573
1574     memcpy(format, &image->format, sizeof(GUID));
1575
1576     return Ok;
1577 }
1578
1579 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
1580 {
1581     TRACE("%p %p\n", image, type);
1582
1583     if(!image || !type)
1584         return InvalidParameter;
1585
1586     *type = image->type;
1587
1588     return Ok;
1589 }
1590
1591 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
1592 {
1593     static int calls;
1594
1595     if(!image || !res)
1596         return InvalidParameter;
1597
1598     if(!(calls++))
1599         FIXME("not implemented\n");
1600
1601     return NotImplemented;
1602 }
1603
1604 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
1605 {
1606     TRACE("%p %p\n", image, width);
1607
1608     if(!image || !width)
1609         return InvalidParameter;
1610
1611     if(image->type == ImageTypeMetafile){
1612         HDC hdc = GetDC(0);
1613
1614         *width = roundr(convert_unit(hdc, ((GpMetafile*)image)->unit) *
1615                         ((GpMetafile*)image)->bounds.Width);
1616
1617         ReleaseDC(0, hdc);
1618     }
1619     else if(image->type == ImageTypeBitmap)
1620         *width = ((GpBitmap*)image)->width;
1621     else
1622         *width = ipicture_pixel_width(image->picture);
1623
1624     TRACE("returning %d\n", *width);
1625
1626     return Ok;
1627 }
1628
1629 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
1630     MetafileHeader * header)
1631 {
1632     static int calls;
1633
1634     if(!metafile || !header)
1635         return InvalidParameter;
1636
1637     if(!(calls++))
1638         FIXME("not implemented\n");
1639
1640     return Ok;
1641 }
1642
1643 GpStatus WINGDIPAPI GdipGetAllPropertyItems(GpImage *image, UINT size,
1644     UINT num, PropertyItem* items)
1645 {
1646     static int calls;
1647
1648     if(!(calls++))
1649         FIXME("not implemented\n");
1650
1651     return InvalidParameter;
1652 }
1653
1654 GpStatus WINGDIPAPI GdipGetPropertyCount(GpImage *image, UINT* num)
1655 {
1656     static int calls;
1657
1658     if(!(calls++))
1659         FIXME("not implemented\n");
1660
1661     return InvalidParameter;
1662 }
1663
1664 GpStatus WINGDIPAPI GdipGetPropertyIdList(GpImage *image, UINT num, PROPID* list)
1665 {
1666     static int calls;
1667
1668     if(!(calls++))
1669         FIXME("not implemented\n");
1670
1671     return InvalidParameter;
1672 }
1673
1674 GpStatus WINGDIPAPI GdipGetPropertyItem(GpImage *image, PROPID id, UINT size,
1675     PropertyItem* buffer)
1676 {
1677     static int calls;
1678
1679     if(!(calls++))
1680         FIXME("not implemented\n");
1681
1682     return InvalidParameter;
1683 }
1684
1685 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID pid,
1686     UINT* size)
1687 {
1688     static int calls;
1689
1690     TRACE("%p %x %p\n", image, pid, size);
1691
1692     if(!size || !image)
1693         return InvalidParameter;
1694
1695     if(!(calls++))
1696         FIXME("not implemented\n");
1697
1698     return NotImplemented;
1699 }
1700
1701 GpStatus WINGDIPAPI GdipGetPropertySize(GpImage *image, UINT* size, UINT* num)
1702 {
1703     static int calls;
1704
1705     if(!(calls++))
1706         FIXME("not implemented\n");
1707
1708     return InvalidParameter;
1709 }
1710
1711 struct image_format_dimension
1712 {
1713     const GUID *format;
1714     const GUID *dimension;
1715 };
1716
1717 struct image_format_dimension image_format_dimensions[] =
1718 {
1719     {&ImageFormatGIF, &FrameDimensionTime},
1720     {&ImageFormatIcon, &FrameDimensionResolution},
1721     {NULL}
1722 };
1723
1724 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
1725     GDIPCONST GUID* dimensionID, UINT* count)
1726 {
1727     static int calls;
1728
1729     if(!image || !dimensionID || !count)
1730         return InvalidParameter;
1731
1732     if(!(calls++))
1733         FIXME("not implemented\n");
1734
1735     return NotImplemented;
1736 }
1737
1738 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsCount(GpImage *image,
1739     UINT* count)
1740 {
1741     /* Native gdiplus 1.1 does not yet support multiple frame dimensions. */
1742
1743     if(!image || !count)
1744         return InvalidParameter;
1745
1746     *count = 1;
1747
1748     return Ok;
1749 }
1750
1751 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
1752     GUID* dimensionIDs, UINT count)
1753 {
1754     int i;
1755     const GUID *result=NULL;
1756
1757     TRACE("(%p,%p,%u)\n", image, dimensionIDs, count);
1758
1759     if(!image || !dimensionIDs || count != 1)
1760         return InvalidParameter;
1761
1762     for (i=0; image_format_dimensions[i].format; i++)
1763     {
1764         if (IsEqualGUID(&image->format, image_format_dimensions[i].format))
1765         {
1766             result = image_format_dimensions[i].dimension;
1767             break;
1768         }
1769     }
1770
1771     if (!result)
1772         result = &FrameDimensionPage;
1773
1774     memcpy(dimensionIDs, result, sizeof(GUID));
1775
1776     return Ok;
1777 }
1778
1779 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image,
1780     GDIPCONST GUID* dimensionID, UINT frameidx)
1781 {
1782     static int calls;
1783
1784     if(!image || !dimensionID)
1785         return InvalidParameter;
1786
1787     if(!(calls++))
1788         FIXME("not implemented\n");
1789
1790     return Ok;
1791 }
1792
1793 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
1794                                           GpImage **image)
1795 {
1796     GpStatus stat;
1797     IStream *stream;
1798
1799     TRACE("(%s) %p\n", debugstr_w(filename), image);
1800
1801     if (!filename || !image)
1802         return InvalidParameter;
1803
1804     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
1805
1806     if (stat != Ok)
1807         return stat;
1808
1809     stat = GdipLoadImageFromStream(stream, image);
1810
1811     IStream_Release(stream);
1812
1813     return stat;
1814 }
1815
1816 /* FIXME: no icm handling */
1817 GpStatus WINGDIPAPI GdipLoadImageFromFileICM(GDIPCONST WCHAR* filename,GpImage **image)
1818 {
1819     TRACE("(%s) %p\n", debugstr_w(filename), image);
1820
1821     return GdipLoadImageFromFile(filename, image);
1822 }
1823
1824 static const WICPixelFormatGUID *wic_pixel_formats[] = {
1825     &GUID_WICPixelFormat16bppBGR555,
1826     &GUID_WICPixelFormat24bppBGR,
1827     &GUID_WICPixelFormat32bppBGR,
1828     &GUID_WICPixelFormat32bppBGRA,
1829     &GUID_WICPixelFormat32bppPBGRA,
1830     NULL
1831 };
1832
1833 static const PixelFormat wic_gdip_formats[] = {
1834     PixelFormat16bppRGB555,
1835     PixelFormat24bppRGB,
1836     PixelFormat32bppRGB,
1837     PixelFormat32bppARGB,
1838     PixelFormat32bppPARGB,
1839 };
1840
1841 static GpStatus decode_image_wic(IStream* stream, REFCLSID clsid, GpImage **image)
1842 {
1843     GpStatus status=Ok;
1844     GpBitmap *bitmap;
1845     HRESULT hr;
1846     IWICBitmapDecoder *decoder;
1847     IWICBitmapFrameDecode *frame;
1848     IWICBitmapSource *source=NULL;
1849     WICPixelFormatGUID wic_format;
1850     PixelFormat gdip_format=0;
1851     int i;
1852     UINT width, height;
1853     BitmapData lockeddata;
1854     WICRect wrc;
1855     HRESULT initresult;
1856
1857     initresult = CoInitialize(NULL);
1858
1859     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
1860         &IID_IWICBitmapDecoder, (void**)&decoder);
1861     if (FAILED(hr)) goto end;
1862
1863     hr = IWICBitmapDecoder_Initialize(decoder, (IStream*)stream, WICDecodeMetadataCacheOnLoad);
1864     if (SUCCEEDED(hr))
1865         hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
1866
1867     if (SUCCEEDED(hr)) /* got frame */
1868     {
1869         hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &wic_format);
1870
1871         if (SUCCEEDED(hr))
1872         {
1873             for (i=0; wic_pixel_formats[i]; i++)
1874             {
1875                 if (IsEqualGUID(&wic_format, wic_pixel_formats[i]))
1876                 {
1877                     source = (IWICBitmapSource*)frame;
1878                     IWICBitmapSource_AddRef(source);
1879                     gdip_format = wic_gdip_formats[i];
1880                     break;
1881                 }
1882             }
1883             if (!source)
1884             {
1885                 /* unknown format; fall back on 32bppARGB */
1886                 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)frame, &source);
1887                 gdip_format = PixelFormat32bppARGB;
1888             }
1889         }
1890
1891         if (SUCCEEDED(hr)) /* got source */
1892         {
1893             hr = IWICBitmapSource_GetSize(source, &width, &height);
1894
1895             if (SUCCEEDED(hr))
1896                 status = GdipCreateBitmapFromScan0(width, height, 0, gdip_format,
1897                     NULL, &bitmap);
1898
1899             if (SUCCEEDED(hr) && status == Ok) /* created bitmap */
1900             {
1901                 status = GdipBitmapLockBits(bitmap, NULL, ImageLockModeWrite,
1902                     gdip_format, &lockeddata);
1903                 if (status == Ok) /* locked bitmap */
1904                 {
1905                     wrc.X = 0;
1906                     wrc.Width = width;
1907                     wrc.Height = 1;
1908                     for (i=0; i<height; i++)
1909                     {
1910                         wrc.Y = i;
1911                         hr = IWICBitmapSource_CopyPixels(source, &wrc, abs(lockeddata.Stride),
1912                             abs(lockeddata.Stride), (BYTE*)lockeddata.Scan0+lockeddata.Stride*i);
1913                         if (FAILED(hr)) break;
1914                     }
1915
1916                     GdipBitmapUnlockBits(bitmap, &lockeddata);
1917                 }
1918
1919                 if (SUCCEEDED(hr) && status == Ok)
1920                     *image = (GpImage*)bitmap;
1921                 else
1922                 {
1923                     *image = NULL;
1924                     GdipDisposeImage((GpImage*)bitmap);
1925                 }
1926             }
1927
1928             IWICBitmapSource_Release(source);
1929         }
1930
1931         IWICBitmapFrameDecode_Release(frame);
1932     }
1933
1934     IWICBitmapDecoder_Release(decoder);
1935
1936 end:
1937     if (SUCCEEDED(initresult)) CoUninitialize();
1938
1939     if (FAILED(hr) && status == Ok) status = hresult_to_status(hr);
1940
1941     return status;
1942 }
1943
1944 static GpStatus decode_image_icon(IStream* stream, REFCLSID clsid, GpImage **image)
1945 {
1946     return decode_image_wic(stream, &CLSID_WICIcoDecoder, image);
1947 }
1948
1949 static GpStatus decode_image_bmp(IStream* stream, REFCLSID clsid, GpImage **image)
1950 {
1951     GpStatus status;
1952     GpBitmap* bitmap;
1953
1954     status = decode_image_wic(stream, &CLSID_WICBmpDecoder, image);
1955
1956     bitmap = (GpBitmap*)*image;
1957
1958     if (status == Ok && bitmap->format == PixelFormat32bppARGB)
1959     {
1960         /* WIC supports bmp files with alpha, but gdiplus does not */
1961         bitmap->format = PixelFormat32bppRGB;
1962     }
1963
1964     return status;
1965 }
1966
1967 static GpStatus decode_image_jpeg(IStream* stream, REFCLSID clsid, GpImage **image)
1968 {
1969     return decode_image_wic(stream, &CLSID_WICJpegDecoder, image);
1970 }
1971
1972 static GpStatus decode_image_png(IStream* stream, REFCLSID clsid, GpImage **image)
1973 {
1974     return decode_image_wic(stream, &CLSID_WICPngDecoder, image);
1975 }
1976
1977 static GpStatus decode_image_gif(IStream* stream, REFCLSID clsid, GpImage **image)
1978 {
1979     return decode_image_wic(stream, &CLSID_WICGifDecoder, image);
1980 }
1981
1982 static GpStatus decode_image_olepicture_metafile(IStream* stream, REFCLSID clsid, GpImage **image)
1983 {
1984     IPicture *pic;
1985
1986     TRACE("%p %p\n", stream, image);
1987
1988     if(!stream || !image)
1989         return InvalidParameter;
1990
1991     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
1992         (LPVOID*) &pic) != S_OK){
1993         TRACE("Could not load picture\n");
1994         return GenericError;
1995     }
1996
1997     /* FIXME: missing initialization code */
1998     *image = GdipAlloc(sizeof(GpMetafile));
1999     if(!*image) return OutOfMemory;
2000     (*image)->type = ImageTypeMetafile;
2001     (*image)->picture = pic;
2002     (*image)->flags   = ImageFlagsNone;
2003     (*image)->palette_flags = 0;
2004     (*image)->palette_count = 0;
2005     (*image)->palette_size = 0;
2006     (*image)->palette_entries = NULL;
2007
2008     TRACE("<-- %p\n", *image);
2009
2010     return Ok;
2011 }
2012
2013 typedef GpStatus (*encode_image_func)(GpImage *image, IStream* stream,
2014     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params);
2015
2016 typedef GpStatus (*decode_image_func)(IStream *stream, REFCLSID clsid, GpImage** image);
2017
2018 typedef struct image_codec {
2019     ImageCodecInfo info;
2020     encode_image_func encode_func;
2021     decode_image_func decode_func;
2022 } image_codec;
2023
2024 typedef enum {
2025     BMP,
2026     JPEG,
2027     GIF,
2028     EMF,
2029     WMF,
2030     PNG,
2031     ICO,
2032     NUM_CODECS
2033 } ImageFormat;
2034
2035 static const struct image_codec codecs[NUM_CODECS];
2036
2037 static GpStatus get_decoder_info(IStream* stream, const struct image_codec **result)
2038 {
2039     BYTE signature[8];
2040     LARGE_INTEGER seek;
2041     HRESULT hr;
2042     UINT bytesread;
2043     int i, j;
2044
2045     /* seek to the start of the stream */
2046     seek.QuadPart = 0;
2047     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
2048     if (FAILED(hr)) return hresult_to_status(hr);
2049
2050     /* read the first 8 bytes */
2051     /* FIXME: This assumes all codecs have one signature <= 8 bytes in length */
2052     hr = IStream_Read(stream, signature, 8, &bytesread);
2053     if (FAILED(hr)) return hresult_to_status(hr);
2054     if (hr == S_FALSE || bytesread == 0) return GenericError;
2055
2056     for (i = 0; i < NUM_CODECS; i++) {
2057         if ((codecs[i].info.Flags & ImageCodecFlagsDecoder) &&
2058             bytesread >= codecs[i].info.SigSize)
2059         {
2060             for (j=0; j<codecs[i].info.SigSize; j++)
2061                 if ((signature[j] & codecs[i].info.SigMask[j]) != codecs[i].info.SigPattern[j])
2062                     break;
2063             if (j == codecs[i].info.SigSize)
2064             {
2065                 *result = &codecs[i];
2066                 return Ok;
2067             }
2068         }
2069     }
2070
2071     TRACE("no match for %i byte signature %x %x %x %x %x %x %x %x\n", bytesread,
2072         signature[0],signature[1],signature[2],signature[3],
2073         signature[4],signature[5],signature[6],signature[7]);
2074
2075     return GenericError;
2076 }
2077
2078 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream* stream, GpImage **image)
2079 {
2080     GpStatus stat;
2081     LARGE_INTEGER seek;
2082     HRESULT hr;
2083     const struct image_codec *codec=NULL;
2084
2085     /* choose an appropriate image decoder */
2086     stat = get_decoder_info(stream, &codec);
2087     if (stat != Ok) return stat;
2088
2089     /* seek to the start of the stream */
2090     seek.QuadPart = 0;
2091     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
2092     if (FAILED(hr)) return hresult_to_status(hr);
2093
2094     /* call on the image decoder to do the real work */
2095     stat = codec->decode_func(stream, &codec->info.Clsid, image);
2096
2097     /* take note of the original data format */
2098     if (stat == Ok)
2099     {
2100         memcpy(&(*image)->format, &codec->info.FormatID, sizeof(GUID));
2101     }
2102
2103     return stat;
2104 }
2105
2106 /* FIXME: no ICM */
2107 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
2108 {
2109     TRACE("%p %p\n", stream, image);
2110
2111     return GdipLoadImageFromStream(stream, image);
2112 }
2113
2114 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
2115 {
2116     static int calls;
2117
2118     if(!image)
2119         return InvalidParameter;
2120
2121     if(!(calls++))
2122         FIXME("not implemented\n");
2123
2124     return NotImplemented;
2125 }
2126
2127 GpStatus WINGDIPAPI GdipSetPropertyItem(GpImage *image, GDIPCONST PropertyItem* item)
2128 {
2129     static int calls;
2130
2131     if(!(calls++))
2132         FIXME("not implemented\n");
2133
2134     return NotImplemented;
2135 }
2136
2137 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
2138                                         GDIPCONST CLSID *clsidEncoder,
2139                                         GDIPCONST EncoderParameters *encoderParams)
2140 {
2141     GpStatus stat;
2142     IStream *stream;
2143
2144     TRACE("%p (%s) %p %p\n", image, debugstr_w(filename), clsidEncoder, encoderParams);
2145
2146     if (!image || !filename|| !clsidEncoder)
2147         return InvalidParameter;
2148
2149     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
2150     if (stat != Ok)
2151         return GenericError;
2152
2153     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
2154
2155     IStream_Release(stream);
2156     return stat;
2157 }
2158
2159 /*************************************************************************
2160  * Encoding functions -
2161  *   These functions encode an image in different image file formats.
2162  */
2163 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
2164 #define BITMAP_FORMAT_JPEG  0xd8ff
2165 #define BITMAP_FORMAT_GIF   0x4947
2166 #define BITMAP_FORMAT_PNG   0x5089
2167 #define BITMAP_FORMAT_APM   0xcdd7
2168
2169 static GpStatus encode_image_WIC(GpImage *image, IStream* stream,
2170     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
2171 {
2172     GpStatus stat;
2173     GpBitmap *bitmap;
2174     IWICBitmapEncoder *encoder;
2175     IWICBitmapFrameEncode *frameencode;
2176     IPropertyBag2 *encoderoptions;
2177     HRESULT hr;
2178     UINT width, height;
2179     PixelFormat gdipformat=0;
2180     WICPixelFormatGUID wicformat;
2181     GpRect rc;
2182     BitmapData lockeddata;
2183     HRESULT initresult;
2184     UINT i;
2185
2186     if (image->type != ImageTypeBitmap)
2187         return GenericError;
2188
2189     bitmap = (GpBitmap*)image;
2190
2191     GdipGetImageWidth(image, &width);
2192     GdipGetImageHeight(image, &height);
2193
2194     rc.X = 0;
2195     rc.Y = 0;
2196     rc.Width = width;
2197     rc.Height = height;
2198
2199     initresult = CoInitialize(NULL);
2200
2201     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
2202         &IID_IWICBitmapEncoder, (void**)&encoder);
2203     if (FAILED(hr))
2204     {
2205         if (SUCCEEDED(initresult)) CoUninitialize();
2206         return hresult_to_status(hr);
2207     }
2208
2209     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
2210
2211     if (SUCCEEDED(hr))
2212     {
2213         hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frameencode, &encoderoptions);
2214     }
2215
2216     if (SUCCEEDED(hr)) /* created frame */
2217     {
2218         hr = IWICBitmapFrameEncode_Initialize(frameencode, encoderoptions);
2219
2220         if (SUCCEEDED(hr))
2221             hr = IWICBitmapFrameEncode_SetSize(frameencode, width, height);
2222
2223         if (SUCCEEDED(hr))
2224             /* FIXME: use the resolution from the image */
2225             hr = IWICBitmapFrameEncode_SetResolution(frameencode, 96.0, 96.0);
2226
2227         if (SUCCEEDED(hr))
2228         {
2229             for (i=0; wic_pixel_formats[i]; i++)
2230             {
2231                 if (wic_gdip_formats[i] == bitmap->format)
2232                     break;
2233             }
2234             if (wic_pixel_formats[i])
2235                 memcpy(&wicformat, wic_pixel_formats[i], sizeof(GUID));
2236             else
2237                 memcpy(&wicformat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
2238
2239             hr = IWICBitmapFrameEncode_SetPixelFormat(frameencode, &wicformat);
2240
2241             for (i=0; wic_pixel_formats[i]; i++)
2242             {
2243                 if (IsEqualGUID(&wicformat, wic_pixel_formats[i]))
2244                     break;
2245             }
2246             if (wic_pixel_formats[i])
2247                 gdipformat = wic_gdip_formats[i];
2248             else
2249             {
2250                 ERR("cannot provide pixel format %s\n", debugstr_guid(&wicformat));
2251                 hr = E_FAIL;
2252             }
2253         }
2254
2255         if (SUCCEEDED(hr))
2256         {
2257             stat = GdipBitmapLockBits(bitmap, &rc, ImageLockModeRead, gdipformat,
2258                 &lockeddata);
2259
2260             if (stat == Ok)
2261             {
2262                 UINT row_size = (lockeddata.Width * PIXELFORMATBPP(gdipformat) + 7)/8;
2263                 BYTE *row;
2264
2265                 /* write one row at a time in case stride is negative */
2266                 row = lockeddata.Scan0;
2267                 for (i=0; i<lockeddata.Height; i++)
2268                 {
2269                     hr = IWICBitmapFrameEncode_WritePixels(frameencode, 1, row_size, row_size, row);
2270                     if (FAILED(hr)) break;
2271                     row += lockeddata.Stride;
2272                 }
2273
2274                 GdipBitmapUnlockBits(bitmap, &lockeddata);
2275             }
2276             else
2277                 hr = E_FAIL;
2278         }
2279
2280         if (SUCCEEDED(hr))
2281             hr = IWICBitmapFrameEncode_Commit(frameencode);
2282
2283         IWICBitmapFrameEncode_Release(frameencode);
2284         IPropertyBag2_Release(encoderoptions);
2285     }
2286
2287     if (SUCCEEDED(hr))
2288         hr = IWICBitmapEncoder_Commit(encoder);
2289
2290     IWICBitmapEncoder_Release(encoder);
2291
2292     if (SUCCEEDED(initresult)) CoUninitialize();
2293
2294     return hresult_to_status(hr);
2295 }
2296
2297 static GpStatus encode_image_BMP(GpImage *image, IStream* stream,
2298     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
2299 {
2300     return encode_image_WIC(image, stream, &CLSID_WICBmpEncoder, params);
2301 }
2302
2303 static GpStatus encode_image_png(GpImage *image, IStream* stream,
2304     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
2305 {
2306     return encode_image_WIC(image, stream, &CLSID_WICPngEncoder, params);
2307 }
2308
2309 /*****************************************************************************
2310  * GdipSaveImageToStream [GDIPLUS.@]
2311  */
2312 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
2313     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
2314 {
2315     GpStatus stat;
2316     encode_image_func encode_image;
2317     int i;
2318
2319     TRACE("%p %p %p %p\n", image, stream, clsid, params);
2320
2321     if(!image || !stream)
2322         return InvalidParameter;
2323
2324     /* select correct encoder */
2325     encode_image = NULL;
2326     for (i = 0; i < NUM_CODECS; i++) {
2327         if ((codecs[i].info.Flags & ImageCodecFlagsEncoder) &&
2328             IsEqualCLSID(clsid, &codecs[i].info.Clsid))
2329             encode_image = codecs[i].encode_func;
2330     }
2331     if (encode_image == NULL)
2332         return UnknownImageFormat;
2333
2334     stat = encode_image(image, stream, clsid, params);
2335
2336     return stat;
2337 }
2338
2339 /*****************************************************************************
2340  * GdipGetImagePalette [GDIPLUS.@]
2341  */
2342 GpStatus WINGDIPAPI GdipGetImagePalette(GpImage *image, ColorPalette *palette, INT size)
2343 {
2344     TRACE("(%p,%p,%i)\n", image, palette, size);
2345
2346     if (!image || !palette)
2347         return InvalidParameter;
2348
2349     if (size < (sizeof(UINT)*2+sizeof(ARGB)*image->palette_count))
2350     {
2351         TRACE("<-- InsufficientBuffer\n");
2352         return InsufficientBuffer;
2353     }
2354
2355     palette->Flags = image->palette_flags;
2356     palette->Count = image->palette_count;
2357     memcpy(palette->Entries, image->palette_entries, sizeof(ARGB)*image->palette_count);
2358
2359     return Ok;
2360 }
2361
2362 /*****************************************************************************
2363  * GdipSetImagePalette [GDIPLUS.@]
2364  */
2365 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
2366     GDIPCONST ColorPalette *palette)
2367 {
2368     TRACE("(%p,%p)\n", image, palette);
2369
2370     if(!image || !palette || palette->Count > 256)
2371         return InvalidParameter;
2372
2373     if (palette->Count > image->palette_size)
2374     {
2375         ARGB *new_palette;
2376
2377         new_palette = GdipAlloc(sizeof(ARGB) * palette->Count);
2378         if (!new_palette) return OutOfMemory;
2379
2380         GdipFree(image->palette_entries);
2381         image->palette_entries = new_palette;
2382         image->palette_size = palette->Count;
2383     }
2384
2385     image->palette_flags = palette->Flags;
2386     image->palette_count = palette->Count;
2387     memcpy(image->palette_entries, palette->Entries, sizeof(ARGB)*palette->Count);
2388
2389     return Ok;
2390 }
2391
2392 /*************************************************************************
2393  * Encoders -
2394  *   Structures that represent which formats we support for encoding.
2395  */
2396
2397 /* ImageCodecInfo creation routines taken from libgdiplus */
2398 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
2399 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
2400 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
2401 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
2402 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
2403 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
2404
2405 static const WCHAR jpeg_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'J','P','E','G', 0};
2406 static const WCHAR jpeg_extension[] = {'*','.','J','P','G',';', '*','.','J','P','E','G',';', '*','.','J','P','E',';', '*','.','J','F','I','F',0};
2407 static const WCHAR jpeg_mimetype[] = {'i','m','a','g','e','/','j','p','e','g', 0};
2408 static const WCHAR jpeg_format[] = {'J','P','E','G',0};
2409 static const BYTE jpeg_sig_pattern[] = { 0xFF, 0xD8 };
2410 static const BYTE jpeg_sig_mask[] = { 0xFF, 0xFF };
2411
2412 static const WCHAR gif_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'G','I','F', 0};
2413 static const WCHAR gif_extension[] = {'*','.','G','I','F',0};
2414 static const WCHAR gif_mimetype[] = {'i','m','a','g','e','/','g','i','f', 0};
2415 static const WCHAR gif_format[] = {'G','I','F',0};
2416 static const BYTE gif_sig_pattern[4] = "GIF8";
2417 static const BYTE gif_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
2418
2419 static const WCHAR emf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'E','M','F', 0};
2420 static const WCHAR emf_extension[] = {'*','.','E','M','F',0};
2421 static const WCHAR emf_mimetype[] = {'i','m','a','g','e','/','x','-','e','m','f', 0};
2422 static const WCHAR emf_format[] = {'E','M','F',0};
2423 static const BYTE emf_sig_pattern[] = { 0x01, 0x00, 0x00, 0x00 };
2424 static const BYTE emf_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
2425
2426 static const WCHAR wmf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'W','M','F', 0};
2427 static const WCHAR wmf_extension[] = {'*','.','W','M','F',0};
2428 static const WCHAR wmf_mimetype[] = {'i','m','a','g','e','/','x','-','w','m','f', 0};
2429 static const WCHAR wmf_format[] = {'W','M','F',0};
2430 static const BYTE wmf_sig_pattern[] = { 0xd7, 0xcd };
2431 static const BYTE wmf_sig_mask[] = { 0xFF, 0xFF };
2432
2433 static const WCHAR png_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'P','N','G', 0};
2434 static const WCHAR png_extension[] = {'*','.','P','N','G',0};
2435 static const WCHAR png_mimetype[] = {'i','m','a','g','e','/','p','n','g', 0};
2436 static const WCHAR png_format[] = {'P','N','G',0};
2437 static const BYTE png_sig_pattern[] = { 137, 80, 78, 71, 13, 10, 26, 10, };
2438 static const BYTE png_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
2439
2440 static const WCHAR ico_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'I','C','O', 0};
2441 static const WCHAR ico_extension[] = {'*','.','I','C','O',0};
2442 static const WCHAR ico_mimetype[] = {'i','m','a','g','e','/','x','-','i','c','o','n', 0};
2443 static const WCHAR ico_format[] = {'I','C','O',0};
2444 static const BYTE ico_sig_pattern[] = { 0x00, 0x00, 0x01, 0x00 };
2445 static const BYTE ico_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
2446
2447 static const struct image_codec codecs[NUM_CODECS] = {
2448     {
2449         { /* BMP */
2450             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2451             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2452             /* CodecName */          bmp_codecname,
2453             /* DllName */            NULL,
2454             /* FormatDescription */  bmp_format,
2455             /* FilenameExtension */  bmp_extension,
2456             /* MimeType */           bmp_mimetype,
2457             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
2458             /* Version */            1,
2459             /* SigCount */           1,
2460             /* SigSize */            2,
2461             /* SigPattern */         bmp_sig_pattern,
2462             /* SigMask */            bmp_sig_mask,
2463         },
2464         encode_image_BMP,
2465         decode_image_bmp
2466     },
2467     {
2468         { /* JPEG */
2469             /* Clsid */              { 0x557cf401, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2470             /* FormatID */           { 0xb96b3caeU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2471             /* CodecName */          jpeg_codecname,
2472             /* DllName */            NULL,
2473             /* FormatDescription */  jpeg_format,
2474             /* FilenameExtension */  jpeg_extension,
2475             /* MimeType */           jpeg_mimetype,
2476             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
2477             /* Version */            1,
2478             /* SigCount */           1,
2479             /* SigSize */            2,
2480             /* SigPattern */         jpeg_sig_pattern,
2481             /* SigMask */            jpeg_sig_mask,
2482         },
2483         NULL,
2484         decode_image_jpeg
2485     },
2486     {
2487         { /* GIF */
2488             /* Clsid */              { 0x557cf402, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2489             /* FormatID */           { 0xb96b3cb0U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2490             /* CodecName */          gif_codecname,
2491             /* DllName */            NULL,
2492             /* FormatDescription */  gif_format,
2493             /* FilenameExtension */  gif_extension,
2494             /* MimeType */           gif_mimetype,
2495             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
2496             /* Version */            1,
2497             /* SigCount */           1,
2498             /* SigSize */            4,
2499             /* SigPattern */         gif_sig_pattern,
2500             /* SigMask */            gif_sig_mask,
2501         },
2502         NULL,
2503         decode_image_gif
2504     },
2505     {
2506         { /* EMF */
2507             /* Clsid */              { 0x557cf403, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2508             /* FormatID */           { 0xb96b3cacU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2509             /* CodecName */          emf_codecname,
2510             /* DllName */            NULL,
2511             /* FormatDescription */  emf_format,
2512             /* FilenameExtension */  emf_extension,
2513             /* MimeType */           emf_mimetype,
2514             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
2515             /* Version */            1,
2516             /* SigCount */           1,
2517             /* SigSize */            4,
2518             /* SigPattern */         emf_sig_pattern,
2519             /* SigMask */            emf_sig_mask,
2520         },
2521         NULL,
2522         decode_image_olepicture_metafile
2523     },
2524     {
2525         { /* WMF */
2526             /* Clsid */              { 0x557cf404, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2527             /* FormatID */           { 0xb96b3cadU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2528             /* CodecName */          wmf_codecname,
2529             /* DllName */            NULL,
2530             /* FormatDescription */  wmf_format,
2531             /* FilenameExtension */  wmf_extension,
2532             /* MimeType */           wmf_mimetype,
2533             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
2534             /* Version */            1,
2535             /* SigCount */           1,
2536             /* SigSize */            2,
2537             /* SigPattern */         wmf_sig_pattern,
2538             /* SigMask */            wmf_sig_mask,
2539         },
2540         NULL,
2541         decode_image_olepicture_metafile
2542     },
2543     {
2544         { /* PNG */
2545             /* Clsid */              { 0x557cf406, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2546             /* FormatID */           { 0xb96b3cafU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2547             /* CodecName */          png_codecname,
2548             /* DllName */            NULL,
2549             /* FormatDescription */  png_format,
2550             /* FilenameExtension */  png_extension,
2551             /* MimeType */           png_mimetype,
2552             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
2553             /* Version */            1,
2554             /* SigCount */           1,
2555             /* SigSize */            8,
2556             /* SigPattern */         png_sig_pattern,
2557             /* SigMask */            png_sig_mask,
2558         },
2559         encode_image_png,
2560         decode_image_png
2561     },
2562     {
2563         { /* ICO */
2564             /* Clsid */              { 0x557cf407, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
2565             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
2566             /* CodecName */          ico_codecname,
2567             /* DllName */            NULL,
2568             /* FormatDescription */  ico_format,
2569             /* FilenameExtension */  ico_extension,
2570             /* MimeType */           ico_mimetype,
2571             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
2572             /* Version */            1,
2573             /* SigCount */           1,
2574             /* SigSize */            4,
2575             /* SigPattern */         ico_sig_pattern,
2576             /* SigMask */            ico_sig_mask,
2577         },
2578         NULL,
2579         decode_image_icon
2580     },
2581 };
2582
2583 /*****************************************************************************
2584  * GdipGetImageDecodersSize [GDIPLUS.@]
2585  */
2586 GpStatus WINGDIPAPI GdipGetImageDecodersSize(UINT *numDecoders, UINT *size)
2587 {
2588     int decoder_count=0;
2589     int i;
2590     TRACE("%p %p\n", numDecoders, size);
2591
2592     if (!numDecoders || !size)
2593         return InvalidParameter;
2594
2595     for (i=0; i<NUM_CODECS; i++)
2596     {
2597         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
2598             decoder_count++;
2599     }
2600
2601     *numDecoders = decoder_count;
2602     *size = decoder_count * sizeof(ImageCodecInfo);
2603
2604     return Ok;
2605 }
2606
2607 /*****************************************************************************
2608  * GdipGetImageDecoders [GDIPLUS.@]
2609  */
2610 GpStatus WINGDIPAPI GdipGetImageDecoders(UINT numDecoders, UINT size, ImageCodecInfo *decoders)
2611 {
2612     int i, decoder_count=0;
2613     TRACE("%u %u %p\n", numDecoders, size, decoders);
2614
2615     if (!decoders ||
2616         size != numDecoders * sizeof(ImageCodecInfo))
2617         return GenericError;
2618
2619     for (i=0; i<NUM_CODECS; i++)
2620     {
2621         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
2622         {
2623             if (decoder_count == numDecoders) return GenericError;
2624             memcpy(&decoders[decoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
2625             decoder_count++;
2626         }
2627     }
2628
2629     if (decoder_count < numDecoders) return GenericError;
2630
2631     return Ok;
2632 }
2633
2634 /*****************************************************************************
2635  * GdipGetImageEncodersSize [GDIPLUS.@]
2636  */
2637 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
2638 {
2639     int encoder_count=0;
2640     int i;
2641     TRACE("%p %p\n", numEncoders, size);
2642
2643     if (!numEncoders || !size)
2644         return InvalidParameter;
2645
2646     for (i=0; i<NUM_CODECS; i++)
2647     {
2648         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
2649             encoder_count++;
2650     }
2651
2652     *numEncoders = encoder_count;
2653     *size = encoder_count * sizeof(ImageCodecInfo);
2654
2655     return Ok;
2656 }
2657
2658 /*****************************************************************************
2659  * GdipGetImageEncoders [GDIPLUS.@]
2660  */
2661 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
2662 {
2663     int i, encoder_count=0;
2664     TRACE("%u %u %p\n", numEncoders, size, encoders);
2665
2666     if (!encoders ||
2667         size != numEncoders * sizeof(ImageCodecInfo))
2668         return GenericError;
2669
2670     for (i=0; i<NUM_CODECS; i++)
2671     {
2672         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
2673         {
2674             if (encoder_count == numEncoders) return GenericError;
2675             memcpy(&encoders[encoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
2676             encoder_count++;
2677         }
2678     }
2679
2680     if (encoder_count < numEncoders) return GenericError;
2681
2682     return Ok;
2683 }
2684
2685 /*****************************************************************************
2686  * GdipCreateBitmapFromHBITMAP [GDIPLUS.@]
2687  */
2688 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
2689 {
2690     BITMAP bm;
2691     GpStatus retval;
2692     PixelFormat format;
2693     BitmapData lockeddata;
2694     INT y;
2695
2696     TRACE("%p %p %p\n", hbm, hpal, bitmap);
2697
2698     if(!hbm || !bitmap)
2699         return InvalidParameter;
2700
2701     /* TODO: Support for device-dependent bitmaps */
2702     if(hpal){
2703         FIXME("no support for device-dependent bitmaps\n");
2704         return NotImplemented;
2705     }
2706
2707     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
2708             return InvalidParameter;
2709
2710     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
2711     switch(bm.bmBitsPixel) {
2712         case 1:
2713             format = PixelFormat1bppIndexed;
2714             break;
2715         case 4:
2716             format = PixelFormat4bppIndexed;
2717             break;
2718         case 8:
2719             format = PixelFormat8bppIndexed;
2720             break;
2721         case 24:
2722             format = PixelFormat24bppRGB;
2723             break;
2724         case 32:
2725             format = PixelFormat32bppRGB;
2726             break;
2727         case 48:
2728             format = PixelFormat48bppRGB;
2729             break;
2730         default:
2731             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
2732             return InvalidParameter;
2733     }
2734
2735     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, 0,
2736         format, NULL, bitmap);
2737
2738     if (retval == Ok)
2739     {
2740         retval = GdipBitmapLockBits(*bitmap, NULL, ImageLockModeWrite,
2741             format, &lockeddata);
2742         if (retval == Ok)
2743         {
2744             if (bm.bmBits)
2745             {
2746                 for (y=0; y<bm.bmHeight; y++)
2747                 {
2748                     memcpy((BYTE*)lockeddata.Scan0+lockeddata.Stride*y,
2749                            (BYTE*)bm.bmBits+bm.bmWidthBytes*(bm.bmHeight-1-y),
2750                            bm.bmWidthBytes);
2751                 }
2752             }
2753             else
2754             {
2755                 HDC hdc;
2756                 HBITMAP oldhbm;
2757                 BITMAPINFO *pbmi;
2758                 INT src_height, dst_stride;
2759                 BYTE *dst_bits;
2760
2761                 hdc = CreateCompatibleDC(NULL);
2762                 oldhbm = SelectObject(hdc, hbm);
2763
2764                 pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2765
2766                 if (pbmi)
2767                 {
2768                     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2769                     pbmi->bmiHeader.biBitCount = 0;
2770
2771                     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
2772
2773                     src_height = abs(pbmi->bmiHeader.biHeight);
2774
2775                     if (pbmi->bmiHeader.biHeight > 0)
2776                     {
2777                         dst_bits = (BYTE*)lockeddata.Scan0+lockeddata.Stride*(src_height-1);
2778                         dst_stride = -lockeddata.Stride;
2779                     }
2780                     else
2781                     {
2782                         dst_bits = lockeddata.Scan0;
2783                         dst_stride = lockeddata.Stride;
2784                     }
2785
2786                     for (y=0; y<src_height; y++)
2787                     {
2788                         GetDIBits(hdc, hbm, y, 1, dst_bits+dst_stride*y,
2789                             pbmi, DIB_RGB_COLORS);
2790                     }
2791
2792                     GdipFree(pbmi);
2793                 }
2794                 else
2795                     retval = OutOfMemory;
2796
2797                 SelectObject(hdc, oldhbm);
2798                 DeleteDC(hdc);
2799             }
2800
2801             GdipBitmapUnlockBits(*bitmap, &lockeddata);
2802         }
2803     }
2804
2805     return retval;
2806 }
2807
2808 GpStatus WINGDIPAPI GdipDeleteEffect(CGpEffect *effect)
2809 {
2810     FIXME("(%p): stub\n", effect);
2811     /* note: According to Jose Roca's GDI+ Docs, this is not implemented
2812      * in Windows's gdiplus */
2813     return NotImplemented;
2814 }
2815
2816 /*****************************************************************************
2817  * GdipSetEffectParameters [GDIPLUS.@]
2818  */
2819 GpStatus WINGDIPAPI GdipSetEffectParameters(CGpEffect *effect,
2820     const VOID *params, const UINT size)
2821 {
2822     static int calls;
2823
2824     if(!(calls++))
2825         FIXME("not implemented\n");
2826
2827     return NotImplemented;
2828 }
2829
2830 /*****************************************************************************
2831  * GdipGetImageFlags [GDIPLUS.@]
2832  */
2833 GpStatus WINGDIPAPI GdipGetImageFlags(GpImage *image, UINT *flags)
2834 {
2835     TRACE("%p %p\n", image, flags);
2836
2837     if(!image || !flags)
2838         return InvalidParameter;
2839
2840     *flags = image->flags;
2841
2842     return Ok;
2843 }
2844
2845 GpStatus WINGDIPAPI GdipTestControl(GpTestControlEnum control, void *param)
2846 {
2847     TRACE("(%d, %p)\n", control, param);
2848
2849     switch(control){
2850         case TestControlForceBilinear:
2851             if(param)
2852                 FIXME("TestControlForceBilinear not handled\n");
2853             break;
2854         case TestControlNoICM:
2855             if(param)
2856                 FIXME("TestControlNoICM not handled\n");
2857             break;
2858         case TestControlGetBuildNumber:
2859             *((DWORD*)param) = 3102;
2860             break;
2861     }
2862
2863     return Ok;
2864 }
2865
2866 GpStatus WINGDIPAPI GdipRecordMetafileFileName(GDIPCONST WCHAR* fileName,
2867                             HDC hdc, EmfType type, GDIPCONST GpRectF *pFrameRect,
2868                             MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc,
2869                             GpMetafile **metafile)
2870 {
2871     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
2872                                  frameUnit, debugstr_w(desc), metafile);
2873
2874     return NotImplemented;
2875 }
2876
2877 GpStatus WINGDIPAPI GdipRecordMetafileFileNameI(GDIPCONST WCHAR* fileName, HDC hdc, EmfType type,
2878                             GDIPCONST GpRect *pFrameRect, MetafileFrameUnit frameUnit,
2879                             GDIPCONST WCHAR *desc, GpMetafile **metafile)
2880 {
2881     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
2882                                  frameUnit, debugstr_w(desc), metafile);
2883
2884     return NotImplemented;
2885 }
2886
2887 GpStatus WINGDIPAPI GdipImageForceValidation(GpImage *image)
2888 {
2889     FIXME("%p\n", image);
2890
2891     return Ok;
2892 }
2893
2894 /*****************************************************************************
2895  * GdipGetImageThumbnail [GDIPLUS.@]
2896  */
2897 GpStatus WINGDIPAPI GdipGetImageThumbnail(GpImage *image, UINT width, UINT height,
2898                             GpImage **ret_image, GetThumbnailImageAbort cb,
2899                             VOID * cb_data)
2900 {
2901     FIXME("(%p %u %u %p %p %p) stub\n",
2902         image, width, height, ret_image, cb, cb_data);
2903     return NotImplemented;
2904 }
2905
2906 /*****************************************************************************
2907  * GdipImageRotateFlip [GDIPLUS.@]
2908  */
2909 GpStatus WINGDIPAPI GdipImageRotateFlip(GpImage *image, RotateFlipType type)
2910 {
2911     FIXME("(%p %u) stub\n", image, type);
2912     return NotImplemented;
2913 }