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