user32: Add more dialog with edit control tests.
[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 #include "windef.h"
22 #include "winbase.h"
23 #include "winuser.h"
24 #include "wingdi.h"
25
26 #define COBJMACROS
27 #include "objbase.h"
28 #include "olectl.h"
29 #include "ole2.h"
30
31 #include "gdiplus.h"
32 #include "gdiplus_private.h"
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(gdiplus);
36
37 #define PIXELFORMATBPP(x) ((x) ? ((x) >> 8) & 255 : 24)
38
39 static INT ipicture_pixel_height(IPicture *pic)
40 {
41     HDC hdcref;
42     OLE_YSIZE_HIMETRIC y;
43
44     IPicture_get_Height(pic, &y);
45
46     hdcref = GetDC(0);
47
48     y = MulDiv(y, GetDeviceCaps(hdcref, LOGPIXELSY), INCH_HIMETRIC);
49     ReleaseDC(0, hdcref);
50
51     return y;
52 }
53
54 static INT ipicture_pixel_width(IPicture *pic)
55 {
56     HDC hdcref;
57     OLE_XSIZE_HIMETRIC x;
58
59     IPicture_get_Width(pic, &x);
60
61     hdcref = GetDC(0);
62
63     x = MulDiv(x, GetDeviceCaps(hdcref, LOGPIXELSX), INCH_HIMETRIC);
64
65     ReleaseDC(0, hdcref);
66
67     return x;
68 }
69
70 GpStatus WINGDIPAPI GdipBitmapGetPixel(GpBitmap* bitmap, INT x, INT y,
71     ARGB *color)
72 {
73     static int calls;
74     TRACE("%p %d %d %p\n", bitmap, x, y, color);
75
76     if(!bitmap || !color)
77         return InvalidParameter;
78
79     if(!(calls++))
80         FIXME("not implemented\n");
81
82     *color = 0xdeadbeef;
83
84     return NotImplemented;
85 }
86
87 /* This function returns a pointer to an array of pixels that represents the
88  * bitmap. The *entire* bitmap is locked according to the lock mode specified by
89  * flags.  It is correct behavior that a user who calls this function with write
90  * privileges can write to the whole bitmap (not just the area in rect).
91  *
92  * FIXME: only used portion of format is bits per pixel. */
93 GpStatus WINGDIPAPI GdipBitmapLockBits(GpBitmap* bitmap, GDIPCONST GpRect* rect,
94     UINT flags, PixelFormat format, BitmapData* lockeddata)
95 {
96     BOOL bm_is_selected;
97     INT stride, bitspp = PIXELFORMATBPP(format);
98     OLE_HANDLE hbm;
99     HDC hdc;
100     HBITMAP old = NULL;
101     BITMAPINFO bmi;
102     BYTE *buff = NULL;
103     UINT abs_height;
104
105     TRACE("%p %p %d %d %p\n", bitmap, rect, flags, format, lockeddata);
106
107     if(!lockeddata || !bitmap || !rect)
108         return InvalidParameter;
109
110     if(rect->X < 0 || rect->Y < 0 || (rect->X + rect->Width > bitmap->width) ||
111        (rect->Y + rect->Height > bitmap->height) || !flags)
112         return InvalidParameter;
113
114     if(flags & ImageLockModeUserInputBuf)
115         return NotImplemented;
116
117     if(bitmap->lockmode)
118         return WrongState;
119
120     IPicture_get_Handle(bitmap->image.picture, &hbm);
121     IPicture_get_CurDC(bitmap->image.picture, &hdc);
122     bm_is_selected = (hdc != 0);
123
124     bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
125     bmi.bmiHeader.biBitCount = 0;
126
127     if(!bm_is_selected){
128         hdc = CreateCompatibleDC(0);
129         old = SelectObject(hdc, (HBITMAP)hbm);
130     }
131
132     /* fill out bmi */
133     GetDIBits(hdc, (HBITMAP)hbm, 0, 0, NULL, &bmi, DIB_RGB_COLORS);
134
135     abs_height = abs(bmi.bmiHeader.biHeight);
136     stride = bmi.bmiHeader.biWidth * bitspp / 8;
137     stride = (stride + 3) & ~3;
138
139     buff = GdipAlloc(stride * abs_height);
140
141     bmi.bmiHeader.biBitCount = bitspp;
142
143     if(buff)
144         GetDIBits(hdc, (HBITMAP)hbm, 0, abs_height, buff, &bmi, DIB_RGB_COLORS);
145
146     if(!bm_is_selected){
147         SelectObject(hdc, old);
148         DeleteDC(hdc);
149     }
150
151     if(!buff)
152         return OutOfMemory;
153
154     lockeddata->Width = rect->Width;
155     lockeddata->Height = rect->Height;
156     lockeddata->PixelFormat = format;
157     lockeddata->Reserved = flags;
158
159     if(bmi.bmiHeader.biHeight > 0){
160         lockeddata->Stride = -stride;
161         lockeddata->Scan0 = buff + (bitspp / 8) * rect->X +
162                             stride * (abs_height - 1 - rect->Y);
163     }
164     else{
165         lockeddata->Stride = stride;
166         lockeddata->Scan0 = buff + (bitspp / 8) * rect->X + stride * rect->Y;
167     }
168
169     bitmap->lockmode = flags;
170     bitmap->numlocks++;
171
172     bitmap->bitmapbits = buff;
173
174     return Ok;
175 }
176
177 GpStatus WINGDIPAPI GdipBitmapUnlockBits(GpBitmap* bitmap,
178     BitmapData* lockeddata)
179 {
180     OLE_HANDLE hbm;
181     HDC hdc;
182     HBITMAP old = NULL;
183     BOOL bm_is_selected;
184     BITMAPINFO bmi;
185
186     if(!bitmap || !lockeddata)
187         return InvalidParameter;
188
189     if(!bitmap->lockmode)
190         return WrongState;
191
192     if(lockeddata->Reserved & ImageLockModeUserInputBuf)
193         return NotImplemented;
194
195     if(lockeddata->Reserved & ImageLockModeRead){
196         if(!(--bitmap->numlocks))
197             bitmap->lockmode = 0;
198
199         GdipFree(bitmap->bitmapbits);
200         bitmap->bitmapbits = NULL;
201         return Ok;
202     }
203
204     IPicture_get_Handle(bitmap->image.picture, &hbm);
205     IPicture_get_CurDC(bitmap->image.picture, &hdc);
206     bm_is_selected = (hdc != 0);
207
208     bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
209     bmi.bmiHeader.biBitCount = 0;
210
211     if(!bm_is_selected){
212         hdc = CreateCompatibleDC(0);
213         old = SelectObject(hdc, (HBITMAP)hbm);
214     }
215
216     GetDIBits(hdc, (HBITMAP)hbm, 0, 0, NULL, &bmi, DIB_RGB_COLORS);
217     bmi.bmiHeader.biBitCount = PIXELFORMATBPP(lockeddata->PixelFormat);
218     SetDIBits(hdc, (HBITMAP)hbm, 0, abs(bmi.bmiHeader.biHeight),
219               bitmap->bitmapbits, &bmi, DIB_RGB_COLORS);
220
221     if(!bm_is_selected){
222         SelectObject(hdc, old);
223         DeleteDC(hdc);
224     }
225
226     GdipFree(bitmap->bitmapbits);
227     bitmap->bitmapbits = NULL;
228     bitmap->lockmode = 0;
229
230     return Ok;
231 }
232
233 GpStatus WINGDIPAPI GdipCreateBitmapFromFile(GDIPCONST WCHAR* filename,
234     GpBitmap **bitmap)
235 {
236     GpStatus stat;
237     IStream *stream;
238
239     if(!filename || !bitmap)
240         return InvalidParameter;
241
242     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
243
244     if(stat != Ok)
245         return stat;
246
247     stat = GdipCreateBitmapFromStream(stream, bitmap);
248
249     IStream_Release(stream);
250
251     return stat;
252 }
253
254 /* FIXME: no icm */
255 GpStatus WINGDIPAPI GdipCreateBitmapFromFileICM(GDIPCONST WCHAR* filename,
256     GpBitmap **bitmap)
257 {
258     return GdipCreateBitmapFromFile(filename, bitmap);
259 }
260
261 GpStatus WINGDIPAPI GdipCreateHBITMAPFromBitmap(GpBitmap* bitmap,
262     HBITMAP* hbmReturn, ARGB background)
263 {
264     FIXME("stub\n");
265
266     hbmReturn = NULL;
267
268     return NotImplemented;
269 }
270
271 GpStatus WINGDIPAPI GdipConvertToEmfPlus(const GpGraphics* ref,
272     GpMetafile* metafile, BOOL* succ, EmfType emfType,
273     const WCHAR* description, GpMetafile** out_metafile)
274 {
275     static int calls;
276
277     if(!ref || !metafile || !out_metafile)
278         return InvalidParameter;
279
280     *succ = FALSE;
281     *out_metafile = NULL;
282
283     if(!(calls++))
284         FIXME("not implemented\n");
285
286     return NotImplemented;
287 }
288
289 /* FIXME: this should create a bitmap in the given size with the attributes
290  * (resolution etc.) of the graphics object */
291 GpStatus WINGDIPAPI GdipCreateBitmapFromGraphics(INT width, INT height,
292     GpGraphics* target, GpBitmap** bitmap)
293 {
294     static int calls;
295     GpStatus ret;
296
297     if(!target || !bitmap)
298         return InvalidParameter;
299
300     if(!(calls++))
301         FIXME("hacked stub\n");
302
303     ret = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat24bppRGB,
304                                     NULL, bitmap);
305
306     return ret;
307 }
308
309 GpStatus WINGDIPAPI GdipCreateBitmapFromScan0(INT width, INT height, INT stride,
310     PixelFormat format, BYTE* scan0, GpBitmap** bitmap)
311 {
312     BITMAPFILEHEADER *bmfh;
313     BITMAPINFOHEADER *bmih;
314     BYTE *buff;
315     INT datalen, size;
316     IStream *stream;
317
318     TRACE("%d %d %d %d %p %p\n", width, height, stride, format, scan0, bitmap);
319
320     if(!bitmap || width <= 0 || height <= 0 || (scan0 && (stride % 4))){
321         *bitmap = NULL;
322         return InvalidParameter;
323     }
324
325     if(scan0 && !stride)
326         return InvalidParameter;
327
328     /* FIXME: windows allows negative stride (reads backwards from scan0) */
329     if(stride < 0){
330         FIXME("negative stride\n");
331         return InvalidParameter;
332     }
333
334     *bitmap = GdipAlloc(sizeof(GpBitmap));
335     if(!*bitmap)    return OutOfMemory;
336
337     if(stride == 0){
338         stride = width * (PIXELFORMATBPP(format) / 8);
339         stride = (stride + 3) & ~3;
340     }
341
342     datalen = abs(stride * height);
343     size = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + datalen;
344     buff = GdipAlloc(size);
345     if(!buff){
346         GdipFree(*bitmap);
347         return OutOfMemory;
348     }
349
350     bmfh = (BITMAPFILEHEADER*) buff;
351     bmih = (BITMAPINFOHEADER*) (bmfh + 1);
352
353     bmfh->bfType    = (((WORD)'M') << 8) + (WORD)'B';
354     bmfh->bfSize    = size;
355     bmfh->bfOffBits = size - datalen;
356
357     bmih->biSize            = sizeof(BITMAPINFOHEADER);
358     bmih->biWidth           = width;
359     bmih->biHeight          = -height;
360     /* FIXME: use the rest of the data from format */
361     bmih->biBitCount        = PIXELFORMATBPP(format);
362     bmih->biCompression     = BI_RGB;
363     bmih->biSizeImage       = datalen;
364
365     if(scan0)
366         memcpy(bmih + 1, scan0, datalen);
367     else
368         memset(bmih + 1, 0, datalen);
369
370     if(CreateStreamOnHGlobal(buff, TRUE, &stream) != S_OK){
371         ERR("could not make stream\n");
372         GdipFree(*bitmap);
373         GdipFree(buff);
374         return GenericError;
375     }
376
377     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
378         (LPVOID*) &((*bitmap)->image.picture)) != S_OK){
379         TRACE("Could not load picture\n");
380         IStream_Release(stream);
381         GdipFree(*bitmap);
382         GdipFree(buff);
383         return GenericError;
384     }
385
386     (*bitmap)->image.type = ImageTypeBitmap;
387     (*bitmap)->width = width;
388     (*bitmap)->height = height;
389     (*bitmap)->format = format;
390
391     return Ok;
392 }
393
394 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
395     GpBitmap **bitmap)
396 {
397     GpStatus stat;
398
399     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
400
401     if(stat != Ok)
402         return stat;
403
404     if((*bitmap)->image.type != ImageTypeBitmap){
405         IPicture_Release((*bitmap)->image.picture);
406         GdipFree(bitmap);
407         return GenericError; /* FIXME: what error to return? */
408     }
409
410     return Ok;
411 }
412
413 /* FIXME: no icm */
414 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
415     GpBitmap **bitmap)
416 {
417     return GdipCreateBitmapFromStream(stream, bitmap);
418 }
419
420 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
421 {
422     HDC hdc;
423
424     if(!image)
425         return InvalidParameter;
426
427     IPicture_get_CurDC(image->picture, &hdc);
428     DeleteDC(hdc);
429     IPicture_Release(image->picture);
430     if (image->type == ImageTypeBitmap)
431         GdipFree(((GpBitmap*)image)->bitmapbits);
432     GdipFree(image);
433
434     return Ok;
435 }
436
437 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
438 {
439     if(!image || !item)
440         return InvalidParameter;
441
442     return NotImplemented;
443 }
444
445 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
446     GpUnit *srcUnit)
447 {
448     if(!image || !srcRect || !srcUnit)
449         return InvalidParameter;
450     if(image->type == ImageTypeMetafile){
451         *srcRect = ((GpMetafile*)image)->bounds;
452         *srcUnit = ((GpMetafile*)image)->unit;
453     }
454     else if(image->type == ImageTypeBitmap){
455         srcRect->X = srcRect->Y = 0.0;
456         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
457         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
458         *srcUnit = UnitPixel;
459     }
460     else{
461         srcRect->X = srcRect->Y = 0.0;
462         srcRect->Width = ipicture_pixel_width(image->picture);
463         srcRect->Height = ipicture_pixel_height(image->picture);
464         *srcUnit = UnitPixel;
465     }
466
467     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
468           srcRect->Width, srcRect->Height, *srcUnit);
469
470     return Ok;
471 }
472
473 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
474     REAL *height)
475 {
476     if(!image || !height || !width)
477         return InvalidParameter;
478
479     if(image->type == ImageTypeMetafile){
480         HDC hdc = GetDC(0);
481
482         *height = convert_unit(hdc, ((GpMetafile*)image)->unit) *
483                         ((GpMetafile*)image)->bounds.Height;
484
485         *width = convert_unit(hdc, ((GpMetafile*)image)->unit) *
486                         ((GpMetafile*)image)->bounds.Width;
487
488         ReleaseDC(0, hdc);
489     }
490
491     else if(image->type == ImageTypeBitmap){
492         *height = ((GpBitmap*)image)->height;
493         *width = ((GpBitmap*)image)->width;
494     }
495     else{
496         *height = ipicture_pixel_height(image->picture);
497         *width = ipicture_pixel_width(image->picture);
498     }
499
500     TRACE("returning (%f, %f)\n", *height, *width);
501     return Ok;
502 }
503
504 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
505     GpGraphics **graphics)
506 {
507     HDC hdc;
508
509     if(!image || !graphics)
510         return InvalidParameter;
511
512     if(image->type != ImageTypeBitmap){
513         FIXME("not implemented for image type %d\n", image->type);
514         return NotImplemented;
515     }
516
517     IPicture_get_CurDC(image->picture, &hdc);
518
519     if(!hdc){
520         hdc = CreateCompatibleDC(0);
521         IPicture_SelectPicture(image->picture, hdc, NULL, NULL);
522     }
523
524     return GdipCreateFromHDC(hdc, graphics);
525 }
526
527 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
528 {
529     if(!image || !height)
530         return InvalidParameter;
531
532     if(image->type == ImageTypeMetafile){
533         HDC hdc = GetDC(0);
534
535         *height = roundr(convert_unit(hdc, ((GpMetafile*)image)->unit) *
536                         ((GpMetafile*)image)->bounds.Height);
537
538         ReleaseDC(0, hdc);
539     }
540     else if(image->type == ImageTypeBitmap)
541         *height = ((GpBitmap*)image)->height;
542     else
543         *height = ipicture_pixel_height(image->picture);
544
545     TRACE("returning %d\n", *height);
546
547     return Ok;
548 }
549
550 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
551 {
552     static int calls;
553
554     if(!image || !res)
555         return InvalidParameter;
556
557     if(!(calls++))
558         FIXME("not implemented\n");
559
560     return NotImplemented;
561 }
562
563 /* FIXME: test this function for non-bitmap types */
564 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
565 {
566     if(!image || !format)
567         return InvalidParameter;
568
569     if(image->type != ImageTypeBitmap)
570         *format = PixelFormat24bppRGB;
571     else
572         *format = ((GpBitmap*) image)->format;
573
574     return Ok;
575 }
576
577 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
578 {
579     static int calls;
580
581     if(!image || !format)
582         return InvalidParameter;
583
584     if(!(calls++))
585         FIXME("not implemented\n");
586
587     return NotImplemented;
588 }
589
590 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
591 {
592     if(!image || !type)
593         return InvalidParameter;
594
595     *type = image->type;
596
597     return Ok;
598 }
599
600 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
601 {
602     static int calls;
603
604     if(!image || !res)
605         return InvalidParameter;
606
607     if(!(calls++))
608         FIXME("not implemented\n");
609
610     return NotImplemented;
611 }
612
613 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
614 {
615     if(!image || !width)
616         return InvalidParameter;
617
618     if(image->type == ImageTypeMetafile){
619         HDC hdc = GetDC(0);
620
621         *width = roundr(convert_unit(hdc, ((GpMetafile*)image)->unit) *
622                         ((GpMetafile*)image)->bounds.Width);
623
624         ReleaseDC(0, hdc);
625     }
626     else if(image->type == ImageTypeBitmap)
627         *width = ((GpBitmap*)image)->width;
628     else
629         *width = ipicture_pixel_width(image->picture);
630
631     TRACE("returning %d\n", *width);
632
633     return Ok;
634 }
635
636 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
637     MetafileHeader * header)
638 {
639     static int calls;
640
641     if(!metafile || !header)
642         return InvalidParameter;
643
644     if(!(calls++))
645         FIXME("not implemented\n");
646
647     return Ok;
648 }
649
650 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID pid,
651     UINT* size)
652 {
653     static int calls;
654
655     TRACE("%p %x %p\n", image, pid, size);
656
657     if(!size || !image)
658         return InvalidParameter;
659
660     if(!(calls++))
661         FIXME("not implemented\n");
662
663     return NotImplemented;
664 }
665
666 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
667     GDIPCONST GUID* dimensionID, UINT* count)
668 {
669     static int calls;
670
671     if(!image || !dimensionID || !count)
672         return InvalidParameter;
673
674     if(!(calls++))
675         FIXME("not implemented\n");
676
677     return NotImplemented;
678 }
679
680 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
681     GUID* dimensionIDs, UINT count)
682 {
683     static int calls;
684
685     if(!image || !dimensionIDs)
686         return InvalidParameter;
687
688     if(!(calls++))
689         FIXME("not implemented\n");
690
691     return Ok;
692 }
693
694 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image,
695     GDIPCONST GUID* dimensionID, UINT frameidx)
696 {
697     static int calls;
698
699     if(!image || !dimensionID)
700         return InvalidParameter;
701
702     if(!(calls++))
703         FIXME("not implemented\n");
704
705     return Ok;
706 }
707
708 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
709                                           GpImage **image)
710 {
711     GpStatus stat;
712     IStream *stream;
713
714     if (!filename || !image)
715         return InvalidParameter;
716
717     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
718
719     if (stat != Ok)
720         return stat;
721
722     stat = GdipLoadImageFromStream(stream, image);
723
724     IStream_Release(stream);
725
726     return stat;
727 }
728
729 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream* stream, GpImage **image)
730 {
731     IPicture *pic;
732     short type;
733
734     if(!stream || !image)
735         return InvalidParameter;
736
737     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
738         (LPVOID*) &pic) != S_OK){
739         TRACE("Could not load picture\n");
740         return GenericError;
741     }
742
743     IPicture_get_Type(pic, &type);
744
745     if(type == PICTYPE_BITMAP){
746         BITMAPINFO bmi;
747         BITMAPCOREHEADER* bmch;
748         OLE_HANDLE hbm;
749         HDC hdc;
750
751         *image = GdipAlloc(sizeof(GpBitmap));
752         if(!*image) return OutOfMemory;
753         (*image)->type = ImageTypeBitmap;
754
755         (*((GpBitmap**) image))->width = ipicture_pixel_width(pic);
756         (*((GpBitmap**) image))->height = ipicture_pixel_height(pic);
757
758         /* get the pixel format */
759         IPicture_get_Handle(pic, &hbm);
760         IPicture_get_CurDC(pic, &hdc);
761
762         bmch = (BITMAPCOREHEADER*) (&bmi.bmiHeader);
763         bmch->bcSize = sizeof(BITMAPCOREHEADER);
764
765         if(!hdc){
766             HBITMAP old;
767             hdc = CreateCompatibleDC(0);
768             old = SelectObject(hdc, (HBITMAP)hbm);
769             GetDIBits(hdc, (HBITMAP)hbm, 0, 0, NULL, &bmi, DIB_RGB_COLORS);
770             SelectObject(hdc, old);
771             DeleteDC(hdc);
772         }
773         else
774             GetDIBits(hdc, (HBITMAP)hbm, 0, 0, NULL, &bmi, DIB_RGB_COLORS);
775
776         (*((GpBitmap**) image))->format = (bmch->bcBitCount << 8) | PixelFormatGDI;
777     }
778     else if(type == PICTYPE_METAFILE || type == PICTYPE_ENHMETAFILE){
779         /* FIXME: missing initialization code */
780         *image = GdipAlloc(sizeof(GpMetafile));
781         if(!*image) return OutOfMemory;
782         (*image)->type = ImageTypeMetafile;
783     }
784     else{
785         *image = GdipAlloc(sizeof(GpImage));
786         if(!*image) return OutOfMemory;
787         (*image)->type = ImageTypeUnknown;
788     }
789
790     (*image)->picture = pic;
791
792     return Ok;
793 }
794
795 /* FIXME: no ICM */
796 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
797 {
798     return GdipLoadImageFromStream(stream, image);
799 }
800
801 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
802 {
803     static int calls;
804
805     if(!image)
806         return InvalidParameter;
807
808     if(!(calls++))
809         FIXME("not implemented\n");
810
811     return NotImplemented;
812 }
813
814 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
815                                         GDIPCONST CLSID *clsidEncoder,
816                                         GDIPCONST EncoderParameters *encoderParams)
817 {
818     GpStatus stat;
819     IStream *stream;
820
821     if (!image || !filename|| !clsidEncoder)
822         return InvalidParameter;
823
824     if (!(image->picture))
825         return InvalidParameter;
826
827     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
828     if (stat != Ok)
829         return GenericError;
830
831     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
832
833     IStream_Release(stream);
834     return stat;
835 }
836
837 /*************************************************************************
838  * Encoding functions -
839  *   These functions encode an image in different image file formats.
840  */
841 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
842 #define BITMAP_FORMAT_JPEG  0xd8ff
843 #define BITMAP_FORMAT_GIF   0x4947
844 #define BITMAP_FORMAT_PNG   0x5089
845 #define BITMAP_FORMAT_APM   0xcdd7
846
847 static GpStatus encode_image_BMP(LPVOID bitmap_bits, LPBITMAPINFO bitmap_info,
848                                  void **output, unsigned int *output_size)
849 {
850     int num_palette_entries;
851     BITMAPFILEHEADER *bmp_file_hdr;
852     BITMAPINFO *bmp_info_hdr;
853
854     if (bitmap_info->bmiHeader.biClrUsed) {
855         num_palette_entries = bitmap_info->bmiHeader.biClrUsed;
856         if (num_palette_entries > 256) num_palette_entries = 256;
857     } else {
858         if (bitmap_info->bmiHeader.biBitCount <= 8)
859             num_palette_entries = 1 << bitmap_info->bmiHeader.biBitCount;
860         else
861             num_palette_entries = 0;
862     }
863
864     *output_size =
865         sizeof(BITMAPFILEHEADER) +
866         sizeof(BITMAPINFOHEADER) +
867         num_palette_entries * sizeof(RGBQUAD) +
868         bitmap_info->bmiHeader.biSizeImage;
869
870     *output = GdipAlloc(*output_size);
871
872     bmp_file_hdr = (BITMAPFILEHEADER*) *output;
873     bmp_file_hdr->bfType = BITMAP_FORMAT_BMP;
874     bmp_file_hdr->bfSize = *output_size;
875     bmp_file_hdr->bfOffBits =
876         sizeof(BITMAPFILEHEADER) +
877         sizeof(BITMAPINFOHEADER) +
878         num_palette_entries * sizeof (RGBQUAD);
879
880     bmp_info_hdr = (BITMAPINFO*) ((unsigned char*)(*output) + sizeof(BITMAPFILEHEADER));
881     memcpy(bmp_info_hdr, bitmap_info, sizeof(BITMAPINFOHEADER) + num_palette_entries * sizeof(RGBQUAD));
882     memcpy((unsigned char *)(*output) +
883            sizeof(BITMAPFILEHEADER) +
884            sizeof(BITMAPINFOHEADER) +
885            num_palette_entries * sizeof(RGBQUAD),
886            bitmap_bits, bitmap_info->bmiHeader.biSizeImage);
887
888     return Ok;
889 }
890
891 typedef GpStatus encode_image_func(LPVOID bitmap_bits, LPBITMAPINFO bitmap_info,
892                                    void **output, unsigned int *output_size);
893
894 typedef enum {
895     BMP,
896     NUM_ENCODERS_SUPPORTED
897 } ImageFormat;
898
899 static const ImageCodecInfo codecs[NUM_ENCODERS_SUPPORTED];
900 static encode_image_func *const encode_image_funcs[NUM_ENCODERS_SUPPORTED] = {
901     encode_image_BMP,
902 };
903
904 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
905     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
906 {
907     GpStatus stat;
908     HRESULT hr;
909     short type;
910     HBITMAP hbmp;
911     HBITMAP old_hbmp;
912     HDC hdc;
913     int bm_is_selected;
914     BITMAPINFO bmp_info;
915     LPVOID bmp_bits;
916     encode_image_func* encode_image;
917     LPVOID output;
918     unsigned int output_size;
919     unsigned int dummy;
920     int i;
921
922     old_hbmp = 0;
923     output = NULL;
924     output_size = 0;
925
926     if(!image || !stream)
927         return InvalidParameter;
928
929     if (!image->picture)
930         return GenericError;
931
932     hr = IPicture_get_Type(image->picture, &type);
933     if (FAILED(hr) || type != PICTYPE_BITMAP)
934         return GenericError;
935
936     /* select correct encoder */
937     encode_image = NULL;
938     for (i = 0; i < NUM_ENCODERS_SUPPORTED; i++) {
939         if (IsEqualCLSID(clsid, &codecs[i].Clsid))
940             encode_image = encode_image_funcs[i];
941     }
942     if (encode_image == NULL)
943         return UnknownImageFormat;
944
945     /* extract underlying hbitmap representation from the IPicture */
946     hr = IPicture_get_Handle(image->picture, (OLE_HANDLE*)&hbmp);
947     if (FAILED(hr) || !hbmp)
948         return GenericError;
949     hr = IPicture_get_CurDC(image->picture, &hdc);
950     if (FAILED(hr))
951         return GenericError;
952     bm_is_selected = (hdc != 0);
953     if (!bm_is_selected) {
954         hdc = CreateCompatibleDC(0);
955         old_hbmp = SelectObject(hdc, hbmp);
956     }
957
958     /* get bits from HBITMAP */
959     bmp_info.bmiHeader.biSize = sizeof(bmp_info.bmiHeader);
960     bmp_info.bmiHeader.biBitCount = 0;
961     GetDIBits(hdc, hbmp, 0, 0, NULL, &bmp_info, DIB_RGB_COLORS);
962
963     bmp_bits = GdipAlloc(bmp_info.bmiHeader.biSizeImage);
964
965     if (bmp_bits)
966         GetDIBits(hdc, hbmp, 0, abs(bmp_info.bmiHeader.biHeight), bmp_bits, &bmp_info, DIB_RGB_COLORS);
967
968     if (!bm_is_selected) {
969         SelectObject(hdc, old_hbmp);
970         DeleteDC(hdc);
971     }
972
973     if (!bmp_bits)
974         return OutOfMemory;
975
976     stat = encode_image(bmp_bits, &bmp_info, &output, &output_size);
977     if (stat == Ok)
978         IStream_Write(stream, output, output_size, &dummy);
979
980     GdipFree(output);
981     GdipFree(bmp_bits);
982
983     return stat;
984 }
985
986 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
987     GDIPCONST ColorPalette *palette)
988 {
989     static int calls;
990
991     if(!image || !palette)
992         return InvalidParameter;
993
994     if(!(calls++))
995         FIXME("not implemented\n");
996
997     return NotImplemented;
998 }
999
1000 /*************************************************************************
1001  * Encoders -
1002  *   Structures that represent which formats we support for encoding.
1003  */
1004
1005 /* ImageCodecInfo creation routines taken from libgdiplus */
1006 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
1007 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
1008 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
1009 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
1010 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
1011 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
1012
1013 static const ImageCodecInfo codecs[NUM_ENCODERS_SUPPORTED] =
1014     {
1015         { /* BMP */
1016             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
1017             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
1018             /* CodecName */          bmp_codecname,
1019             /* DllName */            NULL,
1020             /* FormatDescription */  bmp_format,
1021             /* FilenameExtension */  bmp_extension,
1022             /* MimeType */           bmp_mimetype,
1023             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
1024             /* Version */            1,
1025             /* SigCount */           1,
1026             /* SigSize */            2,
1027             /* SigPattern */         bmp_sig_pattern,
1028             /* SigMask */            bmp_sig_mask,
1029         },
1030     };
1031
1032 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
1033 {
1034     if (!numEncoders || !size)
1035         return InvalidParameter;
1036
1037     *numEncoders = NUM_ENCODERS_SUPPORTED;
1038     *size = sizeof (codecs);
1039
1040     return Ok;
1041 }
1042
1043 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
1044 {
1045     if (!encoders ||
1046         (numEncoders != NUM_ENCODERS_SUPPORTED) ||
1047         (size != sizeof (codecs)))
1048         return GenericError;
1049
1050     memcpy(encoders, codecs, sizeof (codecs));
1051
1052     return Ok;
1053 }
1054 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
1055 {
1056     BITMAP bm;
1057     GpStatus retval;
1058     PixelFormat format;
1059
1060     if(!hbm || !bitmap)
1061         return InvalidParameter;
1062
1063     /* TODO: Support for device-dependent bitmaps */
1064     if(hpal){
1065         FIXME("no support for device-dependent bitmaps\n");
1066         return NotImplemented;
1067     }
1068
1069     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
1070             return InvalidParameter;
1071
1072     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
1073     switch(bm.bmBitsPixel) {
1074         case 1:
1075             format = PixelFormat1bppIndexed;
1076             break;
1077         case 4:
1078             format = PixelFormat4bppIndexed;
1079             break;
1080         case 8:
1081             format = PixelFormat8bppIndexed;
1082             break;
1083         case 24:
1084             format = PixelFormat24bppRGB;
1085             break;
1086         case 48:
1087             format = PixelFormat48bppRGB;
1088             break;
1089         default:
1090             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
1091             return InvalidParameter;
1092     }
1093
1094     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, bm.bmWidthBytes,
1095         format, bm.bmBits, bitmap);
1096
1097     return retval;
1098 }