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