Release 1.5.29.
[wine] / dlls / gdiplus / graphics.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 #include <math.h>
21 #include <limits.h>
22
23 #include "windef.h"
24 #include "winbase.h"
25 #include "winuser.h"
26 #include "wingdi.h"
27 #include "wine/unicode.h"
28
29 #define COBJMACROS
30 #include "objbase.h"
31 #include "ocidl.h"
32 #include "olectl.h"
33 #include "ole2.h"
34
35 #include "winreg.h"
36 #include "shlwapi.h"
37
38 #include "gdiplus.h"
39 #include "gdiplus_private.h"
40 #include "wine/debug.h"
41 #include "wine/list.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(gdiplus);
44
45 /* looks-right constants */
46 #define ANCHOR_WIDTH (2.0)
47 #define MAX_ITERS (50)
48
49 static GpStatus draw_driver_string(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
50                                    GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
51                                    GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
52                                    INT flags, GDIPCONST GpMatrix *matrix);
53
54 /* Converts from gdiplus path point type to gdi path point type. */
55 static BYTE convert_path_point_type(BYTE type)
56 {
57     BYTE ret;
58
59     switch(type & PathPointTypePathTypeMask){
60         case PathPointTypeBezier:
61             ret = PT_BEZIERTO;
62             break;
63         case PathPointTypeLine:
64             ret = PT_LINETO;
65             break;
66         case PathPointTypeStart:
67             ret = PT_MOVETO;
68             break;
69         default:
70             ERR("Bad point type\n");
71             return 0;
72     }
73
74     if(type & PathPointTypeCloseSubpath)
75         ret |= PT_CLOSEFIGURE;
76
77     return ret;
78 }
79
80 static COLORREF get_gdi_brush_color(const GpBrush *brush)
81 {
82     ARGB argb;
83
84     switch (brush->bt)
85     {
86         case BrushTypeSolidColor:
87         {
88             const GpSolidFill *sf = (const GpSolidFill *)brush;
89             argb = sf->color;
90             break;
91         }
92         case BrushTypeHatchFill:
93         {
94             const GpHatch *hatch = (const GpHatch *)brush;
95             argb = hatch->forecol;
96             break;
97         }
98         case BrushTypeLinearGradient:
99         {
100             const GpLineGradient *line = (const GpLineGradient *)brush;
101             argb = line->startcolor;
102             break;
103         }
104         case BrushTypePathGradient:
105         {
106             const GpPathGradient *grad = (const GpPathGradient *)brush;
107             argb = grad->centercolor;
108             break;
109         }
110         default:
111             FIXME("unhandled brush type %d\n", brush->bt);
112             argb = 0;
113             break;
114     }
115     return ARGB2COLORREF(argb);
116 }
117
118 static HBITMAP create_hatch_bitmap(const GpHatch *hatch)
119 {
120     HBITMAP hbmp;
121     BITMAPINFOHEADER bmih;
122     DWORD *bits;
123     int x, y;
124
125     bmih.biSize = sizeof(bmih);
126     bmih.biWidth = 8;
127     bmih.biHeight = 8;
128     bmih.biPlanes = 1;
129     bmih.biBitCount = 32;
130     bmih.biCompression = BI_RGB;
131     bmih.biSizeImage = 0;
132
133     hbmp = CreateDIBSection(0, (BITMAPINFO *)&bmih, DIB_RGB_COLORS, (void **)&bits, NULL, 0);
134     if (hbmp)
135     {
136         const char *hatch_data;
137
138         if (get_hatch_data(hatch->hatchstyle, &hatch_data) == Ok)
139         {
140             for (y = 0; y < 8; y++)
141             {
142                 for (x = 0; x < 8; x++)
143                 {
144                     if (hatch_data[y] & (0x80 >> x))
145                         bits[y * 8 + x] = hatch->forecol;
146                     else
147                         bits[y * 8 + x] = hatch->backcol;
148                 }
149             }
150         }
151         else
152         {
153             FIXME("Unimplemented hatch style %d\n", hatch->hatchstyle);
154
155             for (y = 0; y < 64; y++)
156                 bits[y] = hatch->forecol;
157         }
158     }
159
160     return hbmp;
161 }
162
163 static GpStatus create_gdi_logbrush(const GpBrush *brush, LOGBRUSH *lb)
164 {
165     switch (brush->bt)
166     {
167         case BrushTypeSolidColor:
168         {
169             const GpSolidFill *sf = (const GpSolidFill *)brush;
170             lb->lbStyle = BS_SOLID;
171             lb->lbColor = ARGB2COLORREF(sf->color);
172             lb->lbHatch = 0;
173             return Ok;
174         }
175
176         case BrushTypeHatchFill:
177         {
178             const GpHatch *hatch = (const GpHatch *)brush;
179             HBITMAP hbmp;
180
181             hbmp = create_hatch_bitmap(hatch);
182             if (!hbmp) return OutOfMemory;
183
184             lb->lbStyle = BS_PATTERN;
185             lb->lbColor = 0;
186             lb->lbHatch = (ULONG_PTR)hbmp;
187             return Ok;
188         }
189
190         default:
191             FIXME("unhandled brush type %d\n", brush->bt);
192             lb->lbStyle = BS_SOLID;
193             lb->lbColor = get_gdi_brush_color(brush);
194             lb->lbHatch = 0;
195             return Ok;
196     }
197 }
198
199 static GpStatus free_gdi_logbrush(LOGBRUSH *lb)
200 {
201     switch (lb->lbStyle)
202     {
203         case BS_PATTERN:
204             DeleteObject((HGDIOBJ)(ULONG_PTR)lb->lbHatch);
205             break;
206     }
207     return Ok;
208 }
209
210 static HBRUSH create_gdi_brush(const GpBrush *brush)
211 {
212     LOGBRUSH lb;
213     HBRUSH gdibrush;
214
215     if (create_gdi_logbrush(brush, &lb) != Ok) return 0;
216
217     gdibrush = CreateBrushIndirect(&lb);
218     free_gdi_logbrush(&lb);
219
220     return gdibrush;
221 }
222
223 static INT prepare_dc(GpGraphics *graphics, GpPen *pen)
224 {
225     LOGBRUSH lb;
226     HPEN gdipen;
227     REAL width;
228     INT save_state, i, numdashes;
229     GpPointF pt[2];
230     DWORD dash_array[MAX_DASHLEN];
231
232     save_state = SaveDC(graphics->hdc);
233
234     EndPath(graphics->hdc);
235
236     if(pen->unit == UnitPixel){
237         width = pen->width;
238     }
239     else{
240         /* Get an estimate for the amount the pen width is affected by the world
241          * transform. (This is similar to what some of the wine drivers do.) */
242         pt[0].X = 0.0;
243         pt[0].Y = 0.0;
244         pt[1].X = 1.0;
245         pt[1].Y = 1.0;
246         GdipTransformMatrixPoints(&graphics->worldtrans, pt, 2);
247         width = sqrt((pt[1].X - pt[0].X) * (pt[1].X - pt[0].X) +
248                      (pt[1].Y - pt[0].Y) * (pt[1].Y - pt[0].Y)) / sqrt(2.0);
249
250         width *= units_to_pixels(pen->width, pen->unit == UnitWorld ? graphics->unit : pen->unit, graphics->xres);
251     }
252
253     if(pen->dash == DashStyleCustom){
254         numdashes = min(pen->numdashes, MAX_DASHLEN);
255
256         TRACE("dashes are: ");
257         for(i = 0; i < numdashes; i++){
258             dash_array[i] = gdip_round(width * pen->dashes[i]);
259             TRACE("%d, ", dash_array[i]);
260         }
261         TRACE("\n and the pen style is %x\n", pen->style);
262
263         create_gdi_logbrush(pen->brush, &lb);
264         gdipen = ExtCreatePen(pen->style, gdip_round(width), &lb,
265                               numdashes, dash_array);
266         free_gdi_logbrush(&lb);
267     }
268     else
269     {
270         create_gdi_logbrush(pen->brush, &lb);
271         gdipen = ExtCreatePen(pen->style, gdip_round(width), &lb, 0, NULL);
272         free_gdi_logbrush(&lb);
273     }
274
275     SelectObject(graphics->hdc, gdipen);
276
277     return save_state;
278 }
279
280 static void restore_dc(GpGraphics *graphics, INT state)
281 {
282     DeleteObject(SelectObject(graphics->hdc, GetStockObject(NULL_PEN)));
283     RestoreDC(graphics->hdc, state);
284 }
285
286 static GpStatus get_graphics_transform(GpGraphics *graphics, GpCoordinateSpace dst_space,
287         GpCoordinateSpace src_space, GpMatrix *matrix);
288
289 /* This helper applies all the changes that the points listed in ptf need in
290  * order to be drawn on the device context.  In the end, this should include at
291  * least:
292  *  -scaling by page unit
293  *  -applying world transformation
294  *  -converting from float to int
295  * Native gdiplus uses gdi32 to do all this (via SetMapMode, SetViewportExtEx,
296  * SetWindowExtEx, SetWorldTransform, etc.) but we cannot because we are using
297  * gdi to draw, and these functions would irreparably mess with line widths.
298  */
299 static void transform_and_round_points(GpGraphics *graphics, POINT *pti,
300     GpPointF *ptf, INT count)
301 {
302     REAL scale_x, scale_y;
303     GpMatrix matrix;
304     int i;
305
306     scale_x = units_to_pixels(1.0, graphics->unit, graphics->xres);
307     scale_y = units_to_pixels(1.0, graphics->unit, graphics->yres);
308
309     /* apply page scale */
310     if(graphics->unit != UnitDisplay)
311     {
312         scale_x *= graphics->scale;
313         scale_y *= graphics->scale;
314     }
315
316     matrix = graphics->worldtrans;
317     GdipScaleMatrix(&matrix, scale_x, scale_y, MatrixOrderAppend);
318     GdipTransformMatrixPoints(&matrix, ptf, count);
319
320     for(i = 0; i < count; i++){
321         pti[i].x = gdip_round(ptf[i].X);
322         pti[i].y = gdip_round(ptf[i].Y);
323     }
324 }
325
326 static void gdi_alpha_blend(GpGraphics *graphics, INT dst_x, INT dst_y, INT dst_width, INT dst_height,
327                             HDC hdc, INT src_x, INT src_y, INT src_width, INT src_height)
328 {
329     if (GetDeviceCaps(graphics->hdc, SHADEBLENDCAPS) == SB_NONE)
330     {
331         TRACE("alpha blending not supported by device, fallback to StretchBlt\n");
332
333         StretchBlt(graphics->hdc, dst_x, dst_y, dst_width, dst_height,
334                    hdc, src_x, src_y, src_width, src_height, SRCCOPY);
335     }
336     else
337     {
338         BLENDFUNCTION bf;
339
340         bf.BlendOp = AC_SRC_OVER;
341         bf.BlendFlags = 0;
342         bf.SourceConstantAlpha = 255;
343         bf.AlphaFormat = AC_SRC_ALPHA;
344
345         GdiAlphaBlend(graphics->hdc, dst_x, dst_y, dst_width, dst_height,
346                       hdc, src_x, src_y, src_width, src_height, bf);
347     }
348 }
349
350 static GpStatus get_clip_hrgn(GpGraphics *graphics, HRGN *hrgn)
351 {
352     return GdipGetRegionHRgn(graphics->clip, NULL, hrgn);
353 }
354
355 /* Draw non-premultiplied ARGB data to the given graphics object */
356 static GpStatus alpha_blend_bmp_pixels(GpGraphics *graphics, INT dst_x, INT dst_y,
357     const BYTE *src, INT src_width, INT src_height, INT src_stride)
358 {
359     GpBitmap *dst_bitmap = (GpBitmap*)graphics->image;
360     INT x, y;
361
362     for (x=0; x<src_width; x++)
363     {
364         for (y=0; y<src_height; y++)
365         {
366             ARGB dst_color, src_color;
367             GdipBitmapGetPixel(dst_bitmap, x+dst_x, y+dst_y, &dst_color);
368             src_color = ((ARGB*)(src + src_stride * y))[x];
369             GdipBitmapSetPixel(dst_bitmap, x+dst_x, y+dst_y, color_over(dst_color, src_color));
370         }
371     }
372
373     return Ok;
374 }
375
376 static GpStatus alpha_blend_hdc_pixels(GpGraphics *graphics, INT dst_x, INT dst_y,
377     const BYTE *src, INT src_width, INT src_height, INT src_stride)
378 {
379     HDC hdc;
380     HBITMAP hbitmap;
381     BITMAPINFOHEADER bih;
382     BYTE *temp_bits;
383
384     hdc = CreateCompatibleDC(0);
385
386     bih.biSize = sizeof(BITMAPINFOHEADER);
387     bih.biWidth = src_width;
388     bih.biHeight = -src_height;
389     bih.biPlanes = 1;
390     bih.biBitCount = 32;
391     bih.biCompression = BI_RGB;
392     bih.biSizeImage = 0;
393     bih.biXPelsPerMeter = 0;
394     bih.biYPelsPerMeter = 0;
395     bih.biClrUsed = 0;
396     bih.biClrImportant = 0;
397
398     hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bih, DIB_RGB_COLORS,
399         (void**)&temp_bits, NULL, 0);
400
401     if (GetDeviceCaps(graphics->hdc, SHADEBLENDCAPS) == SB_NONE)
402         memcpy(temp_bits, src, src_width * src_height * 4);
403     else
404         convert_32bppARGB_to_32bppPARGB(src_width, src_height, temp_bits,
405                                         4 * src_width, src, src_stride);
406
407     SelectObject(hdc, hbitmap);
408     gdi_alpha_blend(graphics, dst_x, dst_y, src_width, src_height,
409                     hdc, 0, 0, src_width, src_height);
410     DeleteDC(hdc);
411     DeleteObject(hbitmap);
412
413     return Ok;
414 }
415
416 static GpStatus alpha_blend_pixels_hrgn(GpGraphics *graphics, INT dst_x, INT dst_y,
417     const BYTE *src, INT src_width, INT src_height, INT src_stride, HRGN hregion)
418 {
419     GpStatus stat=Ok;
420
421     if (graphics->image && graphics->image->type == ImageTypeBitmap)
422     {
423         DWORD i;
424         int size;
425         RGNDATA *rgndata;
426         RECT *rects;
427         HRGN hrgn, visible_rgn;
428
429         hrgn = CreateRectRgn(dst_x, dst_y, dst_x + src_width, dst_y + src_height);
430         if (!hrgn)
431             return OutOfMemory;
432
433         stat = get_clip_hrgn(graphics, &visible_rgn);
434         if (stat != Ok)
435         {
436             DeleteObject(hrgn);
437             return stat;
438         }
439
440         if (visible_rgn)
441         {
442             CombineRgn(hrgn, hrgn, visible_rgn, RGN_AND);
443             DeleteObject(visible_rgn);
444         }
445
446         if (hregion)
447             CombineRgn(hrgn, hrgn, hregion, RGN_AND);
448
449         size = GetRegionData(hrgn, 0, NULL);
450
451         rgndata = GdipAlloc(size);
452         if (!rgndata)
453         {
454             DeleteObject(hrgn);
455             return OutOfMemory;
456         }
457
458         GetRegionData(hrgn, size, rgndata);
459
460         rects = (RECT*)rgndata->Buffer;
461
462         for (i=0; stat == Ok && i<rgndata->rdh.nCount; i++)
463         {
464             stat = alpha_blend_bmp_pixels(graphics, rects[i].left, rects[i].top,
465                 &src[(rects[i].left - dst_x) * 4 + (rects[i].top - dst_y) * src_stride],
466                 rects[i].right - rects[i].left, rects[i].bottom - rects[i].top,
467                 src_stride);
468         }
469
470         GdipFree(rgndata);
471
472         DeleteObject(hrgn);
473
474         return stat;
475     }
476     else if (graphics->image && graphics->image->type == ImageTypeMetafile)
477     {
478         ERR("This should not be used for metafiles; fix caller\n");
479         return NotImplemented;
480     }
481     else
482     {
483         HRGN hrgn;
484         int save;
485
486         stat = get_clip_hrgn(graphics, &hrgn);
487
488         if (stat != Ok)
489             return stat;
490
491         save = SaveDC(graphics->hdc);
492
493         if (hrgn)
494             ExtSelectClipRgn(graphics->hdc, hrgn, RGN_AND);
495
496         if (hregion)
497             ExtSelectClipRgn(graphics->hdc, hregion, RGN_AND);
498
499         stat = alpha_blend_hdc_pixels(graphics, dst_x, dst_y, src, src_width,
500             src_height, src_stride);
501
502         RestoreDC(graphics->hdc, save);
503
504         DeleteObject(hrgn);
505
506         return stat;
507     }
508 }
509
510 static GpStatus alpha_blend_pixels(GpGraphics *graphics, INT dst_x, INT dst_y,
511     const BYTE *src, INT src_width, INT src_height, INT src_stride)
512 {
513     return alpha_blend_pixels_hrgn(graphics, dst_x, dst_y, src, src_width, src_height, src_stride, NULL);
514 }
515
516 static ARGB blend_colors(ARGB start, ARGB end, REAL position)
517 {
518     ARGB result=0;
519     ARGB i;
520     INT a1, a2, a3;
521
522     a1 = (start >> 24) & 0xff;
523     a2 = (end >> 24) & 0xff;
524
525     a3 = (int)(a1*(1.0f - position)+a2*(position));
526
527     result |= a3 << 24;
528
529     for (i=0xff; i<=0xff0000; i = i << 8)
530         result |= (int)((start&i)*(1.0f - position)+(end&i)*(position))&i;
531     return result;
532 }
533
534 static ARGB blend_line_gradient(GpLineGradient* brush, REAL position)
535 {
536     REAL blendfac;
537
538     /* clamp to between 0.0 and 1.0, using the wrap mode */
539     if (brush->wrap == WrapModeTile)
540     {
541         position = fmodf(position, 1.0f);
542         if (position < 0.0f) position += 1.0f;
543     }
544     else /* WrapModeFlip* */
545     {
546         position = fmodf(position, 2.0f);
547         if (position < 0.0f) position += 2.0f;
548         if (position > 1.0f) position = 2.0f - position;
549     }
550
551     if (brush->blendcount == 1)
552         blendfac = position;
553     else
554     {
555         int i=1;
556         REAL left_blendpos, left_blendfac, right_blendpos, right_blendfac;
557         REAL range;
558
559         /* locate the blend positions surrounding this position */
560         while (position > brush->blendpos[i])
561             i++;
562
563         /* interpolate between the blend positions */
564         left_blendpos = brush->blendpos[i-1];
565         left_blendfac = brush->blendfac[i-1];
566         right_blendpos = brush->blendpos[i];
567         right_blendfac = brush->blendfac[i];
568         range = right_blendpos - left_blendpos;
569         blendfac = (left_blendfac * (right_blendpos - position) +
570                     right_blendfac * (position - left_blendpos)) / range;
571     }
572
573     if (brush->pblendcount == 0)
574         return blend_colors(brush->startcolor, brush->endcolor, blendfac);
575     else
576     {
577         int i=1;
578         ARGB left_blendcolor, right_blendcolor;
579         REAL left_blendpos, right_blendpos;
580
581         /* locate the blend colors surrounding this position */
582         while (blendfac > brush->pblendpos[i])
583             i++;
584
585         /* interpolate between the blend colors */
586         left_blendpos = brush->pblendpos[i-1];
587         left_blendcolor = brush->pblendcolor[i-1];
588         right_blendpos = brush->pblendpos[i];
589         right_blendcolor = brush->pblendcolor[i];
590         blendfac = (blendfac - left_blendpos) / (right_blendpos - left_blendpos);
591         return blend_colors(left_blendcolor, right_blendcolor, blendfac);
592     }
593 }
594
595 static ARGB transform_color(ARGB color, const ColorMatrix *matrix)
596 {
597     REAL val[5], res[4];
598     int i, j;
599     unsigned char a, r, g, b;
600
601     val[0] = ((color >> 16) & 0xff) / 255.0; /* red */
602     val[1] = ((color >> 8) & 0xff) / 255.0; /* green */
603     val[2] = (color & 0xff) / 255.0; /* blue */
604     val[3] = ((color >> 24) & 0xff) / 255.0; /* alpha */
605     val[4] = 1.0; /* translation */
606
607     for (i=0; i<4; i++)
608     {
609         res[i] = 0.0;
610
611         for (j=0; j<5; j++)
612             res[i] += matrix->m[j][i] * val[j];
613     }
614
615     a = min(max(floorf(res[3]*255.0), 0.0), 255.0);
616     r = min(max(floorf(res[0]*255.0), 0.0), 255.0);
617     g = min(max(floorf(res[1]*255.0), 0.0), 255.0);
618     b = min(max(floorf(res[2]*255.0), 0.0), 255.0);
619
620     return (a << 24) | (r << 16) | (g << 8) | b;
621 }
622
623 static int color_is_gray(ARGB color)
624 {
625     unsigned char r, g, b;
626
627     r = (color >> 16) & 0xff;
628     g = (color >> 8) & 0xff;
629     b = color & 0xff;
630
631     return (r == g) && (g == b);
632 }
633
634 static void apply_image_attributes(const GpImageAttributes *attributes, LPBYTE data,
635     UINT width, UINT height, INT stride, ColorAdjustType type)
636 {
637     UINT x, y;
638     INT i;
639
640     if (attributes->colorkeys[type].enabled ||
641         attributes->colorkeys[ColorAdjustTypeDefault].enabled)
642     {
643         const struct color_key *key;
644         BYTE min_blue, min_green, min_red;
645         BYTE max_blue, max_green, max_red;
646
647         if (attributes->colorkeys[type].enabled)
648             key = &attributes->colorkeys[type];
649         else
650             key = &attributes->colorkeys[ColorAdjustTypeDefault];
651
652         min_blue = key->low&0xff;
653         min_green = (key->low>>8)&0xff;
654         min_red = (key->low>>16)&0xff;
655
656         max_blue = key->high&0xff;
657         max_green = (key->high>>8)&0xff;
658         max_red = (key->high>>16)&0xff;
659
660         for (x=0; x<width; x++)
661             for (y=0; y<height; y++)
662             {
663                 ARGB *src_color;
664                 BYTE blue, green, red;
665                 src_color = (ARGB*)(data + stride * y + sizeof(ARGB) * x);
666                 blue = *src_color&0xff;
667                 green = (*src_color>>8)&0xff;
668                 red = (*src_color>>16)&0xff;
669                 if (blue >= min_blue && green >= min_green && red >= min_red &&
670                     blue <= max_blue && green <= max_green && red <= max_red)
671                     *src_color = 0x00000000;
672             }
673     }
674
675     if (attributes->colorremaptables[type].enabled ||
676         attributes->colorremaptables[ColorAdjustTypeDefault].enabled)
677     {
678         const struct color_remap_table *table;
679
680         if (attributes->colorremaptables[type].enabled)
681             table = &attributes->colorremaptables[type];
682         else
683             table = &attributes->colorremaptables[ColorAdjustTypeDefault];
684
685         for (x=0; x<width; x++)
686             for (y=0; y<height; y++)
687             {
688                 ARGB *src_color;
689                 src_color = (ARGB*)(data + stride * y + sizeof(ARGB) * x);
690                 for (i=0; i<table->mapsize; i++)
691                 {
692                     if (*src_color == table->colormap[i].oldColor.Argb)
693                     {
694                         *src_color = table->colormap[i].newColor.Argb;
695                         break;
696                     }
697                 }
698             }
699     }
700
701     if (attributes->colormatrices[type].enabled ||
702         attributes->colormatrices[ColorAdjustTypeDefault].enabled)
703     {
704         const struct color_matrix *colormatrices;
705
706         if (attributes->colormatrices[type].enabled)
707             colormatrices = &attributes->colormatrices[type];
708         else
709             colormatrices = &attributes->colormatrices[ColorAdjustTypeDefault];
710
711         for (x=0; x<width; x++)
712             for (y=0; y<height; y++)
713             {
714                 ARGB *src_color;
715                 src_color = (ARGB*)(data + stride * y + sizeof(ARGB) * x);
716
717                 if (colormatrices->flags == ColorMatrixFlagsDefault ||
718                     !color_is_gray(*src_color))
719                 {
720                     *src_color = transform_color(*src_color, &colormatrices->colormatrix);
721                 }
722                 else if (colormatrices->flags == ColorMatrixFlagsAltGray)
723                 {
724                     *src_color = transform_color(*src_color, &colormatrices->graymatrix);
725                 }
726             }
727     }
728
729     if (attributes->gamma_enabled[type] ||
730         attributes->gamma_enabled[ColorAdjustTypeDefault])
731     {
732         REAL gamma;
733
734         if (attributes->gamma_enabled[type])
735             gamma = attributes->gamma[type];
736         else
737             gamma = attributes->gamma[ColorAdjustTypeDefault];
738
739         for (x=0; x<width; x++)
740             for (y=0; y<height; y++)
741             {
742                 ARGB *src_color;
743                 BYTE blue, green, red;
744                 src_color = (ARGB*)(data + stride * y + sizeof(ARGB) * x);
745
746                 blue = *src_color&0xff;
747                 green = (*src_color>>8)&0xff;
748                 red = (*src_color>>16)&0xff;
749
750                 /* FIXME: We should probably use a table for this. */
751                 blue = floorf(powf(blue / 255.0, gamma) * 255.0);
752                 green = floorf(powf(green / 255.0, gamma) * 255.0);
753                 red = floorf(powf(red / 255.0, gamma) * 255.0);
754
755                 *src_color = (*src_color & 0xff000000) | (red << 16) | (green << 8) | blue;
756             }
757     }
758 }
759
760 /* Given a bitmap and its source rectangle, find the smallest rectangle in the
761  * bitmap that contains all the pixels we may need to draw it. */
762 static void get_bitmap_sample_size(InterpolationMode interpolation, WrapMode wrap,
763     GpBitmap* bitmap, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight,
764     GpRect *rect)
765 {
766     INT left, top, right, bottom;
767
768     switch (interpolation)
769     {
770     case InterpolationModeHighQualityBilinear:
771     case InterpolationModeHighQualityBicubic:
772     /* FIXME: Include a greater range for the prefilter? */
773     case InterpolationModeBicubic:
774     case InterpolationModeBilinear:
775         left = (INT)(floorf(srcx));
776         top = (INT)(floorf(srcy));
777         right = (INT)(ceilf(srcx+srcwidth));
778         bottom = (INT)(ceilf(srcy+srcheight));
779         break;
780     case InterpolationModeNearestNeighbor:
781     default:
782         left = gdip_round(srcx);
783         top = gdip_round(srcy);
784         right = gdip_round(srcx+srcwidth);
785         bottom = gdip_round(srcy+srcheight);
786         break;
787     }
788
789     if (wrap == WrapModeClamp)
790     {
791         if (left < 0)
792             left = 0;
793         if (top < 0)
794             top = 0;
795         if (right >= bitmap->width)
796             right = bitmap->width-1;
797         if (bottom >= bitmap->height)
798             bottom = bitmap->height-1;
799     }
800     else
801     {
802         /* In some cases we can make the rectangle smaller here, but the logic
803          * is hard to get right, and tiling suggests we're likely to use the
804          * entire source image. */
805         if (left < 0 || right >= bitmap->width)
806         {
807             left = 0;
808             right = bitmap->width-1;
809         }
810
811         if (top < 0 || bottom >= bitmap->height)
812         {
813             top = 0;
814             bottom = bitmap->height-1;
815         }
816     }
817
818     rect->X = left;
819     rect->Y = top;
820     rect->Width = right - left + 1;
821     rect->Height = bottom - top + 1;
822 }
823
824 static ARGB sample_bitmap_pixel(GDIPCONST GpRect *src_rect, LPBYTE bits, UINT width,
825     UINT height, INT x, INT y, GDIPCONST GpImageAttributes *attributes)
826 {
827     if (attributes->wrap == WrapModeClamp)
828     {
829         if (x < 0 || y < 0 || x >= width || y >= height)
830             return attributes->outside_color;
831     }
832     else
833     {
834         /* Tiling. Make sure co-ordinates are positive as it simplifies the math. */
835         if (x < 0)
836             x = width*2 + x % (width * 2);
837         if (y < 0)
838             y = height*2 + y % (height * 2);
839
840         if ((attributes->wrap & 1) == 1)
841         {
842             /* Flip X */
843             if ((x / width) % 2 == 0)
844                 x = x % width;
845             else
846                 x = width - 1 - x % width;
847         }
848         else
849             x = x % width;
850
851         if ((attributes->wrap & 2) == 2)
852         {
853             /* Flip Y */
854             if ((y / height) % 2 == 0)
855                 y = y % height;
856             else
857                 y = height - 1 - y % height;
858         }
859         else
860             y = y % height;
861     }
862
863     if (x < src_rect->X || y < src_rect->Y || x >= src_rect->X + src_rect->Width || y >= src_rect->Y + src_rect->Height)
864     {
865         ERR("out of range pixel requested\n");
866         return 0xffcd0084;
867     }
868
869     return ((DWORD*)(bits))[(x - src_rect->X) + (y - src_rect->Y) * src_rect->Width];
870 }
871
872 static ARGB resample_bitmap_pixel(GDIPCONST GpRect *src_rect, LPBYTE bits, UINT width,
873     UINT height, GpPointF *point, GDIPCONST GpImageAttributes *attributes,
874     InterpolationMode interpolation, PixelOffsetMode offset_mode)
875 {
876     static int fixme;
877
878     switch (interpolation)
879     {
880     default:
881         if (!fixme++)
882             FIXME("Unimplemented interpolation %i\n", interpolation);
883         /* fall-through */
884     case InterpolationModeBilinear:
885     {
886         REAL leftxf, topyf;
887         INT leftx, rightx, topy, bottomy;
888         ARGB topleft, topright, bottomleft, bottomright;
889         ARGB top, bottom;
890         float x_offset;
891
892         leftxf = floorf(point->X);
893         leftx = (INT)leftxf;
894         rightx = (INT)ceilf(point->X);
895         topyf = floorf(point->Y);
896         topy = (INT)topyf;
897         bottomy = (INT)ceilf(point->Y);
898
899         if (leftx == rightx && topy == bottomy)
900             return sample_bitmap_pixel(src_rect, bits, width, height,
901                 leftx, topy, attributes);
902
903         topleft = sample_bitmap_pixel(src_rect, bits, width, height,
904             leftx, topy, attributes);
905         topright = sample_bitmap_pixel(src_rect, bits, width, height,
906             rightx, topy, attributes);
907         bottomleft = sample_bitmap_pixel(src_rect, bits, width, height,
908             leftx, bottomy, attributes);
909         bottomright = sample_bitmap_pixel(src_rect, bits, width, height,
910             rightx, bottomy, attributes);
911
912         x_offset = point->X - leftxf;
913         top = blend_colors(topleft, topright, x_offset);
914         bottom = blend_colors(bottomleft, bottomright, x_offset);
915
916         return blend_colors(top, bottom, point->Y - topyf);
917     }
918     case InterpolationModeNearestNeighbor:
919     {
920         FLOAT pixel_offset;
921         switch (offset_mode)
922         {
923         default:
924         case PixelOffsetModeNone:
925         case PixelOffsetModeHighSpeed:
926             pixel_offset = 0.5;
927             break;
928
929         case PixelOffsetModeHalf:
930         case PixelOffsetModeHighQuality:
931             pixel_offset = 0.0;
932             break;
933         }
934         return sample_bitmap_pixel(src_rect, bits, width, height,
935             floorf(point->X + pixel_offset), floorf(point->Y + pixel_offset), attributes);
936     }
937
938     }
939 }
940
941 static REAL intersect_line_scanline(const GpPointF *p1, const GpPointF *p2, REAL y)
942 {
943     return (p1->X - p2->X) * (p2->Y - y) / (p2->Y - p1->Y) + p2->X;
944 }
945
946 static INT brush_can_fill_path(GpBrush *brush)
947 {
948     switch (brush->bt)
949     {
950     case BrushTypeSolidColor:
951         return 1;
952     case BrushTypeHatchFill:
953     {
954         GpHatch *hatch = (GpHatch*)brush;
955         return ((hatch->forecol & 0xff000000) == 0xff000000) &&
956                ((hatch->backcol & 0xff000000) == 0xff000000);
957     }
958     case BrushTypeLinearGradient:
959     case BrushTypeTextureFill:
960     /* Gdi32 isn't much help with these, so we should use brush_fill_pixels instead. */
961     default:
962         return 0;
963     }
964 }
965
966 static void brush_fill_path(GpGraphics *graphics, GpBrush* brush)
967 {
968     switch (brush->bt)
969     {
970     case BrushTypeSolidColor:
971     {
972         GpSolidFill *fill = (GpSolidFill*)brush;
973         HBITMAP bmp = ARGB2BMP(fill->color);
974
975         if (bmp)
976         {
977             RECT rc;
978             /* partially transparent fill */
979
980             SelectClipPath(graphics->hdc, RGN_AND);
981             if (GetClipBox(graphics->hdc, &rc) != NULLREGION)
982             {
983                 HDC hdc = CreateCompatibleDC(NULL);
984
985                 if (!hdc) break;
986
987                 SelectObject(hdc, bmp);
988                 gdi_alpha_blend(graphics, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
989                                 hdc, 0, 0, 1, 1);
990                 DeleteDC(hdc);
991             }
992
993             DeleteObject(bmp);
994             break;
995         }
996         /* else fall through */
997     }
998     default:
999     {
1000         HBRUSH gdibrush, old_brush;
1001
1002         gdibrush = create_gdi_brush(brush);
1003         if (!gdibrush) return;
1004
1005         old_brush = SelectObject(graphics->hdc, gdibrush);
1006         FillPath(graphics->hdc);
1007         SelectObject(graphics->hdc, old_brush);
1008         DeleteObject(gdibrush);
1009         break;
1010     }
1011     }
1012 }
1013
1014 static INT brush_can_fill_pixels(GpBrush *brush)
1015 {
1016     switch (brush->bt)
1017     {
1018     case BrushTypeSolidColor:
1019     case BrushTypeHatchFill:
1020     case BrushTypeLinearGradient:
1021     case BrushTypeTextureFill:
1022     case BrushTypePathGradient:
1023         return 1;
1024     default:
1025         return 0;
1026     }
1027 }
1028
1029 static GpStatus brush_fill_pixels(GpGraphics *graphics, GpBrush *brush,
1030     DWORD *argb_pixels, GpRect *fill_area, UINT cdwStride)
1031 {
1032     switch (brush->bt)
1033     {
1034     case BrushTypeSolidColor:
1035     {
1036         int x, y;
1037         GpSolidFill *fill = (GpSolidFill*)brush;
1038         for (x=0; x<fill_area->Width; x++)
1039             for (y=0; y<fill_area->Height; y++)
1040                 argb_pixels[x + y*cdwStride] = fill->color;
1041         return Ok;
1042     }
1043     case BrushTypeHatchFill:
1044     {
1045         int x, y;
1046         GpHatch *fill = (GpHatch*)brush;
1047         const char *hatch_data;
1048
1049         if (get_hatch_data(fill->hatchstyle, &hatch_data) != Ok)
1050             return NotImplemented;
1051
1052         for (x=0; x<fill_area->Width; x++)
1053             for (y=0; y<fill_area->Height; y++)
1054             {
1055                 int hx, hy;
1056
1057                 /* FIXME: Account for the rendering origin */
1058                 hx = (x + fill_area->X) % 8;
1059                 hy = (y + fill_area->Y) % 8;
1060
1061                 if ((hatch_data[7-hy] & (0x80 >> hx)) != 0)
1062                     argb_pixels[x + y*cdwStride] = fill->forecol;
1063                 else
1064                     argb_pixels[x + y*cdwStride] = fill->backcol;
1065             }
1066
1067         return Ok;
1068     }
1069     case BrushTypeLinearGradient:
1070     {
1071         GpLineGradient *fill = (GpLineGradient*)brush;
1072         GpPointF draw_points[3], line_points[3];
1073         GpStatus stat;
1074         static const GpRectF box_1 = { 0.0, 0.0, 1.0, 1.0 };
1075         GpMatrix *world_to_gradient; /* FIXME: Store this in the brush? */
1076         int x, y;
1077
1078         draw_points[0].X = fill_area->X;
1079         draw_points[0].Y = fill_area->Y;
1080         draw_points[1].X = fill_area->X+1;
1081         draw_points[1].Y = fill_area->Y;
1082         draw_points[2].X = fill_area->X;
1083         draw_points[2].Y = fill_area->Y+1;
1084
1085         /* Transform the points to a co-ordinate space where X is the point's
1086          * position in the gradient, 0.0 being the start point and 1.0 the
1087          * end point. */
1088         stat = GdipTransformPoints(graphics, CoordinateSpaceWorld,
1089             CoordinateSpaceDevice, draw_points, 3);
1090
1091         if (stat == Ok)
1092         {
1093             line_points[0] = fill->startpoint;
1094             line_points[1] = fill->endpoint;
1095             line_points[2].X = fill->startpoint.X + (fill->startpoint.Y - fill->endpoint.Y);
1096             line_points[2].Y = fill->startpoint.Y + (fill->endpoint.X - fill->startpoint.X);
1097
1098             stat = GdipCreateMatrix3(&box_1, line_points, &world_to_gradient);
1099         }
1100
1101         if (stat == Ok)
1102         {
1103             stat = GdipInvertMatrix(world_to_gradient);
1104
1105             if (stat == Ok)
1106                 stat = GdipTransformMatrixPoints(world_to_gradient, draw_points, 3);
1107
1108             GdipDeleteMatrix(world_to_gradient);
1109         }
1110
1111         if (stat == Ok)
1112         {
1113             REAL x_delta = draw_points[1].X - draw_points[0].X;
1114             REAL y_delta = draw_points[2].X - draw_points[0].X;
1115
1116             for (y=0; y<fill_area->Height; y++)
1117             {
1118                 for (x=0; x<fill_area->Width; x++)
1119                 {
1120                     REAL pos = draw_points[0].X + x * x_delta + y * y_delta;
1121
1122                     argb_pixels[x + y*cdwStride] = blend_line_gradient(fill, pos);
1123                 }
1124             }
1125         }
1126
1127         return stat;
1128     }
1129     case BrushTypeTextureFill:
1130     {
1131         GpTexture *fill = (GpTexture*)brush;
1132         GpPointF draw_points[3];
1133         GpStatus stat;
1134         int x, y;
1135         GpBitmap *bitmap;
1136         int src_stride;
1137         GpRect src_area;
1138
1139         if (fill->image->type != ImageTypeBitmap)
1140         {
1141             FIXME("metafile texture brushes not implemented\n");
1142             return NotImplemented;
1143         }
1144
1145         bitmap = (GpBitmap*)fill->image;
1146         src_stride = sizeof(ARGB) * bitmap->width;
1147
1148         src_area.X = src_area.Y = 0;
1149         src_area.Width = bitmap->width;
1150         src_area.Height = bitmap->height;
1151
1152         draw_points[0].X = fill_area->X;
1153         draw_points[0].Y = fill_area->Y;
1154         draw_points[1].X = fill_area->X+1;
1155         draw_points[1].Y = fill_area->Y;
1156         draw_points[2].X = fill_area->X;
1157         draw_points[2].Y = fill_area->Y+1;
1158
1159         /* Transform the points to the co-ordinate space of the bitmap. */
1160         stat = GdipTransformPoints(graphics, CoordinateSpaceWorld,
1161             CoordinateSpaceDevice, draw_points, 3);
1162
1163         if (stat == Ok)
1164         {
1165             GpMatrix world_to_texture = fill->transform;
1166
1167             stat = GdipInvertMatrix(&world_to_texture);
1168             if (stat == Ok)
1169                 stat = GdipTransformMatrixPoints(&world_to_texture, draw_points, 3);
1170         }
1171
1172         if (stat == Ok && !fill->bitmap_bits)
1173         {
1174             BitmapData lockeddata;
1175
1176             fill->bitmap_bits = GdipAlloc(sizeof(ARGB) * bitmap->width * bitmap->height);
1177             if (!fill->bitmap_bits)
1178                 stat = OutOfMemory;
1179
1180             if (stat == Ok)
1181             {
1182                 lockeddata.Width = bitmap->width;
1183                 lockeddata.Height = bitmap->height;
1184                 lockeddata.Stride = src_stride;
1185                 lockeddata.PixelFormat = PixelFormat32bppARGB;
1186                 lockeddata.Scan0 = fill->bitmap_bits;
1187
1188                 stat = GdipBitmapLockBits(bitmap, &src_area, ImageLockModeRead|ImageLockModeUserInputBuf,
1189                     PixelFormat32bppARGB, &lockeddata);
1190             }
1191
1192             if (stat == Ok)
1193                 stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
1194
1195             if (stat == Ok)
1196                 apply_image_attributes(fill->imageattributes, fill->bitmap_bits,
1197                     bitmap->width, bitmap->height,
1198                     src_stride, ColorAdjustTypeBitmap);
1199
1200             if (stat != Ok)
1201             {
1202                 GdipFree(fill->bitmap_bits);
1203                 fill->bitmap_bits = NULL;
1204             }
1205         }
1206
1207         if (stat == Ok)
1208         {
1209             REAL x_dx = draw_points[1].X - draw_points[0].X;
1210             REAL x_dy = draw_points[1].Y - draw_points[0].Y;
1211             REAL y_dx = draw_points[2].X - draw_points[0].X;
1212             REAL y_dy = draw_points[2].Y - draw_points[0].Y;
1213
1214             for (y=0; y<fill_area->Height; y++)
1215             {
1216                 for (x=0; x<fill_area->Width; x++)
1217                 {
1218                     GpPointF point;
1219                     point.X = draw_points[0].X + x * x_dx + y * y_dx;
1220                     point.Y = draw_points[0].Y + y * x_dy + y * y_dy;
1221
1222                     argb_pixels[x + y*cdwStride] = resample_bitmap_pixel(
1223                         &src_area, fill->bitmap_bits, bitmap->width, bitmap->height,
1224                         &point, fill->imageattributes, graphics->interpolation,
1225                         graphics->pixeloffset);
1226                 }
1227             }
1228         }
1229
1230         return stat;
1231     }
1232     case BrushTypePathGradient:
1233     {
1234         GpPathGradient *fill = (GpPathGradient*)brush;
1235         GpPath *flat_path;
1236         GpMatrix world_to_device;
1237         GpStatus stat;
1238         int i, figure_start=0;
1239         GpPointF start_point, end_point, center_point;
1240         BYTE type;
1241         REAL min_yf, max_yf, line1_xf, line2_xf;
1242         INT min_y, max_y, min_x, max_x;
1243         INT x, y;
1244         ARGB outer_color;
1245         static int transform_fixme_once;
1246
1247         if (fill->focus.X != 0.0 || fill->focus.Y != 0.0)
1248         {
1249             static int once;
1250             if (!once++)
1251                 FIXME("path gradient focus not implemented\n");
1252         }
1253
1254         if (fill->gamma)
1255         {
1256             static int once;
1257             if (!once++)
1258                 FIXME("path gradient gamma correction not implemented\n");
1259         }
1260
1261         if (fill->blendcount)
1262         {
1263             static int once;
1264             if (!once++)
1265                 FIXME("path gradient blend not implemented\n");
1266         }
1267
1268         if (fill->pblendcount)
1269         {
1270             static int once;
1271             if (!once++)
1272                 FIXME("path gradient preset blend not implemented\n");
1273         }
1274
1275         if (!transform_fixme_once)
1276         {
1277             BOOL is_identity=TRUE;
1278             GdipIsMatrixIdentity(&fill->transform, &is_identity);
1279             if (!is_identity)
1280             {
1281                 FIXME("path gradient transform not implemented\n");
1282                 transform_fixme_once = 1;
1283             }
1284         }
1285
1286         stat = GdipClonePath(fill->path, &flat_path);
1287
1288         if (stat != Ok)
1289             return stat;
1290
1291         stat = get_graphics_transform(graphics, CoordinateSpaceDevice,
1292             CoordinateSpaceWorld, &world_to_device);
1293         if (stat == Ok)
1294         {
1295             stat = GdipTransformPath(flat_path, &world_to_device);
1296
1297             if (stat == Ok)
1298             {
1299                 center_point = fill->center;
1300                 stat = GdipTransformMatrixPoints(&world_to_device, &center_point, 1);
1301             }
1302
1303             if (stat == Ok)
1304                 stat = GdipFlattenPath(flat_path, NULL, 0.5);
1305         }
1306
1307         if (stat != Ok)
1308         {
1309             GdipDeletePath(flat_path);
1310             return stat;
1311         }
1312
1313         for (i=0; i<flat_path->pathdata.Count; i++)
1314         {
1315             int start_center_line=0, end_center_line=0;
1316             int seen_start=0, seen_end=0, seen_center=0;
1317             REAL center_distance;
1318             ARGB start_color, end_color;
1319             REAL dy, dx;
1320
1321             type = flat_path->pathdata.Types[i];
1322
1323             if ((type&PathPointTypePathTypeMask) == PathPointTypeStart)
1324                 figure_start = i;
1325
1326             start_point = flat_path->pathdata.Points[i];
1327
1328             start_color = fill->surroundcolors[min(i, fill->surroundcolorcount-1)];
1329
1330             if ((type&PathPointTypeCloseSubpath) == PathPointTypeCloseSubpath || i+1 >= flat_path->pathdata.Count)
1331             {
1332                 end_point = flat_path->pathdata.Points[figure_start];
1333                 end_color = fill->surroundcolors[min(figure_start, fill->surroundcolorcount-1)];
1334             }
1335             else if ((flat_path->pathdata.Types[i+1] & PathPointTypePathTypeMask) == PathPointTypeLine)
1336             {
1337                 end_point = flat_path->pathdata.Points[i+1];
1338                 end_color = fill->surroundcolors[min(i+1, fill->surroundcolorcount-1)];
1339             }
1340             else
1341                 continue;
1342
1343             outer_color = start_color;
1344
1345             min_yf = center_point.Y;
1346             if (min_yf > start_point.Y) min_yf = start_point.Y;
1347             if (min_yf > end_point.Y) min_yf = end_point.Y;
1348
1349             if (min_yf < fill_area->Y)
1350                 min_y = fill_area->Y;
1351             else
1352                 min_y = (INT)ceil(min_yf);
1353
1354             max_yf = center_point.Y;
1355             if (max_yf < start_point.Y) max_yf = start_point.Y;
1356             if (max_yf < end_point.Y) max_yf = end_point.Y;
1357
1358             if (max_yf > fill_area->Y + fill_area->Height)
1359                 max_y = fill_area->Y + fill_area->Height;
1360             else
1361                 max_y = (INT)ceil(max_yf);
1362
1363             dy = end_point.Y - start_point.Y;
1364             dx = end_point.X - start_point.X;
1365
1366             /* This is proportional to the distance from start-end line to center point. */
1367             center_distance = dy * (start_point.X - center_point.X) +
1368                 dx * (center_point.Y - start_point.Y);
1369
1370             for (y=min_y; y<max_y; y++)
1371             {
1372                 REAL yf = (REAL)y;
1373
1374                 if (!seen_start && yf >= start_point.Y)
1375                 {
1376                     seen_start = 1;
1377                     start_center_line ^= 1;
1378                 }
1379                 if (!seen_end && yf >= end_point.Y)
1380                 {
1381                     seen_end = 1;
1382                     end_center_line ^= 1;
1383                 }
1384                 if (!seen_center && yf >= center_point.Y)
1385                 {
1386                     seen_center = 1;
1387                     start_center_line ^= 1;
1388                     end_center_line ^= 1;
1389                 }
1390
1391                 if (start_center_line)
1392                     line1_xf = intersect_line_scanline(&start_point, &center_point, yf);
1393                 else
1394                     line1_xf = intersect_line_scanline(&start_point, &end_point, yf);
1395
1396                 if (end_center_line)
1397                     line2_xf = intersect_line_scanline(&end_point, &center_point, yf);
1398                 else
1399                     line2_xf = intersect_line_scanline(&start_point, &end_point, yf);
1400
1401                 if (line1_xf < line2_xf)
1402                 {
1403                     min_x = (INT)ceil(line1_xf);
1404                     max_x = (INT)ceil(line2_xf);
1405                 }
1406                 else
1407                 {
1408                     min_x = (INT)ceil(line2_xf);
1409                     max_x = (INT)ceil(line1_xf);
1410                 }
1411
1412                 if (min_x < fill_area->X)
1413                     min_x = fill_area->X;
1414                 if (max_x > fill_area->X + fill_area->Width)
1415                     max_x = fill_area->X + fill_area->Width;
1416
1417                 for (x=min_x; x<max_x; x++)
1418                 {
1419                     REAL xf = (REAL)x;
1420                     REAL distance;
1421
1422                     if (start_color != end_color)
1423                     {
1424                         REAL blend_amount, pdy, pdx;
1425                         pdy = yf - center_point.Y;
1426                         pdx = xf - center_point.X;
1427                         blend_amount = ( (center_point.Y - start_point.Y) * pdx + (start_point.X - center_point.X) * pdy ) / ( dy * pdx - dx * pdy );
1428                         outer_color = blend_colors(start_color, end_color, blend_amount);
1429                     }
1430
1431                     distance = (end_point.Y - start_point.Y) * (start_point.X - xf) +
1432                         (end_point.X - start_point.X) * (yf - start_point.Y);
1433
1434                     distance = distance / center_distance;
1435
1436                     argb_pixels[(x-fill_area->X) + (y-fill_area->Y)*cdwStride] =
1437                         blend_colors(outer_color, fill->centercolor, distance);
1438                 }
1439             }
1440         }
1441
1442         GdipDeletePath(flat_path);
1443         return stat;
1444     }
1445     default:
1446         return NotImplemented;
1447     }
1448 }
1449
1450 /* Draws the linecap the specified color and size on the hdc.  The linecap is in
1451  * direction of the line from x1, y1 to x2, y2 and is anchored on x2, y2. Probably
1452  * should not be called on an hdc that has a path you care about. */
1453 static void draw_cap(GpGraphics *graphics, COLORREF color, GpLineCap cap, REAL size,
1454     const GpCustomLineCap *custom, REAL x1, REAL y1, REAL x2, REAL y2)
1455 {
1456     HGDIOBJ oldbrush = NULL, oldpen = NULL;
1457     GpMatrix matrix;
1458     HBRUSH brush = NULL;
1459     HPEN pen = NULL;
1460     PointF ptf[4], *custptf = NULL;
1461     POINT pt[4], *custpt = NULL;
1462     BYTE *tp = NULL;
1463     REAL theta, dsmall, dbig, dx, dy = 0.0;
1464     INT i, count;
1465     LOGBRUSH lb;
1466     BOOL customstroke;
1467
1468     if((x1 == x2) && (y1 == y2))
1469         return;
1470
1471     theta = gdiplus_atan2(y2 - y1, x2 - x1);
1472
1473     customstroke = (cap == LineCapCustom) && custom && (!custom->fill);
1474     if(!customstroke){
1475         brush = CreateSolidBrush(color);
1476         lb.lbStyle = BS_SOLID;
1477         lb.lbColor = color;
1478         lb.lbHatch = 0;
1479         pen = ExtCreatePen(PS_GEOMETRIC | PS_SOLID | PS_ENDCAP_FLAT |
1480                            PS_JOIN_MITER, 1, &lb, 0,
1481                            NULL);
1482         oldbrush = SelectObject(graphics->hdc, brush);
1483         oldpen = SelectObject(graphics->hdc, pen);
1484     }
1485
1486     switch(cap){
1487         case LineCapFlat:
1488             break;
1489         case LineCapSquare:
1490         case LineCapSquareAnchor:
1491         case LineCapDiamondAnchor:
1492             size = size * (cap & LineCapNoAnchor ? ANCHOR_WIDTH : 1.0) / 2.0;
1493             if(cap == LineCapDiamondAnchor){
1494                 dsmall = cos(theta + M_PI_2) * size;
1495                 dbig = sin(theta + M_PI_2) * size;
1496             }
1497             else{
1498                 dsmall = cos(theta + M_PI_4) * size;
1499                 dbig = sin(theta + M_PI_4) * size;
1500             }
1501
1502             ptf[0].X = x2 - dsmall;
1503             ptf[1].X = x2 + dbig;
1504
1505             ptf[0].Y = y2 - dbig;
1506             ptf[3].Y = y2 + dsmall;
1507
1508             ptf[1].Y = y2 - dsmall;
1509             ptf[2].Y = y2 + dbig;
1510
1511             ptf[3].X = x2 - dbig;
1512             ptf[2].X = x2 + dsmall;
1513
1514             transform_and_round_points(graphics, pt, ptf, 4);
1515             Polygon(graphics->hdc, pt, 4);
1516
1517             break;
1518         case LineCapArrowAnchor:
1519             size = size * 4.0 / sqrt(3.0);
1520
1521             dx = cos(M_PI / 6.0 + theta) * size;
1522             dy = sin(M_PI / 6.0 + theta) * size;
1523
1524             ptf[0].X = x2 - dx;
1525             ptf[0].Y = y2 - dy;
1526
1527             dx = cos(- M_PI / 6.0 + theta) * size;
1528             dy = sin(- M_PI / 6.0 + theta) * size;
1529
1530             ptf[1].X = x2 - dx;
1531             ptf[1].Y = y2 - dy;
1532
1533             ptf[2].X = x2;
1534             ptf[2].Y = y2;
1535
1536             transform_and_round_points(graphics, pt, ptf, 3);
1537             Polygon(graphics->hdc, pt, 3);
1538
1539             break;
1540         case LineCapRoundAnchor:
1541             dx = dy = ANCHOR_WIDTH * size / 2.0;
1542
1543             ptf[0].X = x2 - dx;
1544             ptf[0].Y = y2 - dy;
1545             ptf[1].X = x2 + dx;
1546             ptf[1].Y = y2 + dy;
1547
1548             transform_and_round_points(graphics, pt, ptf, 2);
1549             Ellipse(graphics->hdc, pt[0].x, pt[0].y, pt[1].x, pt[1].y);
1550
1551             break;
1552         case LineCapTriangle:
1553             size = size / 2.0;
1554             dx = cos(M_PI_2 + theta) * size;
1555             dy = sin(M_PI_2 + theta) * size;
1556
1557             ptf[0].X = x2 - dx;
1558             ptf[0].Y = y2 - dy;
1559             ptf[1].X = x2 + dx;
1560             ptf[1].Y = y2 + dy;
1561
1562             dx = cos(theta) * size;
1563             dy = sin(theta) * size;
1564
1565             ptf[2].X = x2 + dx;
1566             ptf[2].Y = y2 + dy;
1567
1568             transform_and_round_points(graphics, pt, ptf, 3);
1569             Polygon(graphics->hdc, pt, 3);
1570
1571             break;
1572         case LineCapRound:
1573             dx = dy = size / 2.0;
1574
1575             ptf[0].X = x2 - dx;
1576             ptf[0].Y = y2 - dy;
1577             ptf[1].X = x2 + dx;
1578             ptf[1].Y = y2 + dy;
1579
1580             dx = -cos(M_PI_2 + theta) * size;
1581             dy = -sin(M_PI_2 + theta) * size;
1582
1583             ptf[2].X = x2 - dx;
1584             ptf[2].Y = y2 - dy;
1585             ptf[3].X = x2 + dx;
1586             ptf[3].Y = y2 + dy;
1587
1588             transform_and_round_points(graphics, pt, ptf, 4);
1589             Pie(graphics->hdc, pt[0].x, pt[0].y, pt[1].x, pt[1].y, pt[2].x,
1590                 pt[2].y, pt[3].x, pt[3].y);
1591
1592             break;
1593         case LineCapCustom:
1594             if(!custom)
1595                 break;
1596
1597             count = custom->pathdata.Count;
1598             custptf = GdipAlloc(count * sizeof(PointF));
1599             custpt = GdipAlloc(count * sizeof(POINT));
1600             tp = GdipAlloc(count);
1601
1602             if(!custptf || !custpt || !tp)
1603                 goto custend;
1604
1605             memcpy(custptf, custom->pathdata.Points, count * sizeof(PointF));
1606
1607             GdipSetMatrixElements(&matrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
1608             GdipScaleMatrix(&matrix, size, size, MatrixOrderAppend);
1609             GdipRotateMatrix(&matrix, (180.0 / M_PI) * (theta - M_PI_2),
1610                              MatrixOrderAppend);
1611             GdipTranslateMatrix(&matrix, x2, y2, MatrixOrderAppend);
1612             GdipTransformMatrixPoints(&matrix, custptf, count);
1613
1614             transform_and_round_points(graphics, custpt, custptf, count);
1615
1616             for(i = 0; i < count; i++)
1617                 tp[i] = convert_path_point_type(custom->pathdata.Types[i]);
1618
1619             if(custom->fill){
1620                 BeginPath(graphics->hdc);
1621                 PolyDraw(graphics->hdc, custpt, tp, count);
1622                 EndPath(graphics->hdc);
1623                 StrokeAndFillPath(graphics->hdc);
1624             }
1625             else
1626                 PolyDraw(graphics->hdc, custpt, tp, count);
1627
1628 custend:
1629             GdipFree(custptf);
1630             GdipFree(custpt);
1631             GdipFree(tp);
1632             break;
1633         default:
1634             break;
1635     }
1636
1637     if(!customstroke){
1638         SelectObject(graphics->hdc, oldbrush);
1639         SelectObject(graphics->hdc, oldpen);
1640         DeleteObject(brush);
1641         DeleteObject(pen);
1642     }
1643 }
1644
1645 /* Shortens the line by the given percent by changing x2, y2.
1646  * If percent is > 1.0 then the line will change direction.
1647  * If percent is negative it can lengthen the line. */
1648 static void shorten_line_percent(REAL x1, REAL  y1, REAL *x2, REAL *y2, REAL percent)
1649 {
1650     REAL dist, theta, dx, dy;
1651
1652     if((y1 == *y2) && (x1 == *x2))
1653         return;
1654
1655     dist = sqrt((*x2 - x1) * (*x2 - x1) + (*y2 - y1) * (*y2 - y1)) * -percent;
1656     theta = gdiplus_atan2((*y2 - y1), (*x2 - x1));
1657     dx = cos(theta) * dist;
1658     dy = sin(theta) * dist;
1659
1660     *x2 = *x2 + dx;
1661     *y2 = *y2 + dy;
1662 }
1663
1664 /* Shortens the line by the given amount by changing x2, y2.
1665  * If the amount is greater than the distance, the line will become length 0.
1666  * If the amount is negative, it can lengthen the line. */
1667 static void shorten_line_amt(REAL x1, REAL y1, REAL *x2, REAL *y2, REAL amt)
1668 {
1669     REAL dx, dy, percent;
1670
1671     dx = *x2 - x1;
1672     dy = *y2 - y1;
1673     if(dx == 0 && dy == 0)
1674         return;
1675
1676     percent = amt / sqrt(dx * dx + dy * dy);
1677     if(percent >= 1.0){
1678         *x2 = x1;
1679         *y2 = y1;
1680         return;
1681     }
1682
1683     shorten_line_percent(x1, y1, x2, y2, percent);
1684 }
1685
1686 /* Conducts a linear search to find the bezier points that will back off
1687  * the endpoint of the curve by a distance of amt. Linear search works
1688  * better than binary in this case because there are multiple solutions,
1689  * and binary searches often find a bad one. I don't think this is what
1690  * Windows does but short of rendering the bezier without GDI's help it's
1691  * the best we can do. If rev then work from the start of the passed points
1692  * instead of the end. */
1693 static void shorten_bezier_amt(GpPointF * pt, REAL amt, BOOL rev)
1694 {
1695     GpPointF origpt[4];
1696     REAL percent = 0.00, dx, dy, origx, origy, diff = -1.0;
1697     INT i, first = 0, second = 1, third = 2, fourth = 3;
1698
1699     if(rev){
1700         first = 3;
1701         second = 2;
1702         third = 1;
1703         fourth = 0;
1704     }
1705
1706     origx = pt[fourth].X;
1707     origy = pt[fourth].Y;
1708     memcpy(origpt, pt, sizeof(GpPointF) * 4);
1709
1710     for(i = 0; (i < MAX_ITERS) && (diff < amt); i++){
1711         /* reset bezier points to original values */
1712         memcpy(pt, origpt, sizeof(GpPointF) * 4);
1713         /* Perform magic on bezier points. Order is important here.*/
1714         shorten_line_percent(pt[third].X, pt[third].Y, &pt[fourth].X, &pt[fourth].Y, percent);
1715         shorten_line_percent(pt[second].X, pt[second].Y, &pt[third].X, &pt[third].Y, percent);
1716         shorten_line_percent(pt[third].X, pt[third].Y, &pt[fourth].X, &pt[fourth].Y, percent);
1717         shorten_line_percent(pt[first].X, pt[first].Y, &pt[second].X, &pt[second].Y, percent);
1718         shorten_line_percent(pt[second].X, pt[second].Y, &pt[third].X, &pt[third].Y, percent);
1719         shorten_line_percent(pt[third].X, pt[third].Y, &pt[fourth].X, &pt[fourth].Y, percent);
1720
1721         dx = pt[fourth].X - origx;
1722         dy = pt[fourth].Y - origy;
1723
1724         diff = sqrt(dx * dx + dy * dy);
1725         percent += 0.0005 * amt;
1726     }
1727 }
1728
1729 /* Draws a combination of bezier curves and lines between points. */
1730 static GpStatus draw_poly(GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF * pt,
1731     GDIPCONST BYTE * types, INT count, BOOL caps)
1732 {
1733     POINT *pti = GdipAlloc(count * sizeof(POINT));
1734     BYTE *tp = GdipAlloc(count);
1735     GpPointF *ptcopy = GdipAlloc(count * sizeof(GpPointF));
1736     INT i, j;
1737     GpStatus status = GenericError;
1738
1739     if(!count){
1740         status = Ok;
1741         goto end;
1742     }
1743     if(!pti || !tp || !ptcopy){
1744         status = OutOfMemory;
1745         goto end;
1746     }
1747
1748     for(i = 1; i < count; i++){
1749         if((types[i] & PathPointTypePathTypeMask) == PathPointTypeBezier){
1750             if((i + 2 >= count) || !(types[i + 1] & PathPointTypeBezier)
1751                 || !(types[i + 1] & PathPointTypeBezier)){
1752                 ERR("Bad bezier points\n");
1753                 goto end;
1754             }
1755             i += 2;
1756         }
1757     }
1758
1759     memcpy(ptcopy, pt, count * sizeof(GpPointF));
1760
1761     /* If we are drawing caps, go through the points and adjust them accordingly,
1762      * and draw the caps. */
1763     if(caps){
1764         switch(types[count - 1] & PathPointTypePathTypeMask){
1765             case PathPointTypeBezier:
1766                 if(pen->endcap == LineCapArrowAnchor)
1767                     shorten_bezier_amt(&ptcopy[count - 4], pen->width, FALSE);
1768                 else if((pen->endcap == LineCapCustom) && pen->customend)
1769                     shorten_bezier_amt(&ptcopy[count - 4],
1770                                        pen->width * pen->customend->inset, FALSE);
1771
1772                 draw_cap(graphics, get_gdi_brush_color(pen->brush), pen->endcap, pen->width, pen->customend,
1773                     pt[count - 1].X - (ptcopy[count - 1].X - ptcopy[count - 2].X),
1774                     pt[count - 1].Y - (ptcopy[count - 1].Y - ptcopy[count - 2].Y),
1775                     pt[count - 1].X, pt[count - 1].Y);
1776
1777                 break;
1778             case PathPointTypeLine:
1779                 if(pen->endcap == LineCapArrowAnchor)
1780                     shorten_line_amt(ptcopy[count - 2].X, ptcopy[count - 2].Y,
1781                                      &ptcopy[count - 1].X, &ptcopy[count - 1].Y,
1782                                      pen->width);
1783                 else if((pen->endcap == LineCapCustom) && pen->customend)
1784                     shorten_line_amt(ptcopy[count - 2].X, ptcopy[count - 2].Y,
1785                                      &ptcopy[count - 1].X, &ptcopy[count - 1].Y,
1786                                      pen->customend->inset * pen->width);
1787
1788                 draw_cap(graphics, get_gdi_brush_color(pen->brush), pen->endcap, pen->width, pen->customend,
1789                          pt[count - 2].X, pt[count - 2].Y, pt[count - 1].X,
1790                          pt[count - 1].Y);
1791
1792                 break;
1793             default:
1794                 ERR("Bad path last point\n");
1795                 goto end;
1796         }
1797
1798         /* Find start of points */
1799         for(j = 1; j < count && ((types[j] & PathPointTypePathTypeMask)
1800             == PathPointTypeStart); j++);
1801
1802         switch(types[j] & PathPointTypePathTypeMask){
1803             case PathPointTypeBezier:
1804                 if(pen->startcap == LineCapArrowAnchor)
1805                     shorten_bezier_amt(&ptcopy[j - 1], pen->width, TRUE);
1806                 else if((pen->startcap == LineCapCustom) && pen->customstart)
1807                     shorten_bezier_amt(&ptcopy[j - 1],
1808                                        pen->width * pen->customstart->inset, TRUE);
1809
1810                 draw_cap(graphics, get_gdi_brush_color(pen->brush), pen->startcap, pen->width, pen->customstart,
1811                     pt[j - 1].X - (ptcopy[j - 1].X - ptcopy[j].X),
1812                     pt[j - 1].Y - (ptcopy[j - 1].Y - ptcopy[j].Y),
1813                     pt[j - 1].X, pt[j - 1].Y);
1814
1815                 break;
1816             case PathPointTypeLine:
1817                 if(pen->startcap == LineCapArrowAnchor)
1818                     shorten_line_amt(ptcopy[j].X, ptcopy[j].Y,
1819                                      &ptcopy[j - 1].X, &ptcopy[j - 1].Y,
1820                                      pen->width);
1821                 else if((pen->startcap == LineCapCustom) && pen->customstart)
1822                     shorten_line_amt(ptcopy[j].X, ptcopy[j].Y,
1823                                      &ptcopy[j - 1].X, &ptcopy[j - 1].Y,
1824                                      pen->customstart->inset * pen->width);
1825
1826                 draw_cap(graphics, get_gdi_brush_color(pen->brush), pen->startcap, pen->width, pen->customstart,
1827                          pt[j].X, pt[j].Y, pt[j - 1].X,
1828                          pt[j - 1].Y);
1829
1830                 break;
1831             default:
1832                 ERR("Bad path points\n");
1833                 goto end;
1834         }
1835     }
1836
1837     transform_and_round_points(graphics, pti, ptcopy, count);
1838
1839     for(i = 0; i < count; i++){
1840         tp[i] = convert_path_point_type(types[i]);
1841     }
1842
1843     PolyDraw(graphics->hdc, pti, tp, count);
1844
1845     status = Ok;
1846
1847 end:
1848     GdipFree(pti);
1849     GdipFree(ptcopy);
1850     GdipFree(tp);
1851
1852     return status;
1853 }
1854
1855 GpStatus trace_path(GpGraphics *graphics, GpPath *path)
1856 {
1857     GpStatus result;
1858
1859     BeginPath(graphics->hdc);
1860     result = draw_poly(graphics, NULL, path->pathdata.Points,
1861                        path->pathdata.Types, path->pathdata.Count, FALSE);
1862     EndPath(graphics->hdc);
1863     return result;
1864 }
1865
1866 typedef struct _GraphicsContainerItem {
1867     struct list entry;
1868     GraphicsContainer contid;
1869
1870     SmoothingMode smoothing;
1871     CompositingQuality compqual;
1872     InterpolationMode interpolation;
1873     CompositingMode compmode;
1874     TextRenderingHint texthint;
1875     REAL scale;
1876     GpUnit unit;
1877     PixelOffsetMode pixeloffset;
1878     UINT textcontrast;
1879     GpMatrix worldtrans;
1880     GpRegion* clip;
1881     INT origin_x, origin_y;
1882 } GraphicsContainerItem;
1883
1884 static GpStatus init_container(GraphicsContainerItem** container,
1885         GDIPCONST GpGraphics* graphics){
1886     GpStatus sts;
1887
1888     *container = GdipAlloc(sizeof(GraphicsContainerItem));
1889     if(!(*container))
1890         return OutOfMemory;
1891
1892     (*container)->contid = graphics->contid + 1;
1893
1894     (*container)->smoothing = graphics->smoothing;
1895     (*container)->compqual = graphics->compqual;
1896     (*container)->interpolation = graphics->interpolation;
1897     (*container)->compmode = graphics->compmode;
1898     (*container)->texthint = graphics->texthint;
1899     (*container)->scale = graphics->scale;
1900     (*container)->unit = graphics->unit;
1901     (*container)->textcontrast = graphics->textcontrast;
1902     (*container)->pixeloffset = graphics->pixeloffset;
1903     (*container)->origin_x = graphics->origin_x;
1904     (*container)->origin_y = graphics->origin_y;
1905     (*container)->worldtrans = graphics->worldtrans;
1906
1907     sts = GdipCloneRegion(graphics->clip, &(*container)->clip);
1908     if(sts != Ok){
1909         GdipFree(*container);
1910         *container = NULL;
1911         return sts;
1912     }
1913
1914     return Ok;
1915 }
1916
1917 static void delete_container(GraphicsContainerItem* container)
1918 {
1919     GdipDeleteRegion(container->clip);
1920     GdipFree(container);
1921 }
1922
1923 static GpStatus restore_container(GpGraphics* graphics,
1924         GDIPCONST GraphicsContainerItem* container){
1925     GpStatus sts;
1926     GpRegion *newClip;
1927
1928     sts = GdipCloneRegion(container->clip, &newClip);
1929     if(sts != Ok) return sts;
1930
1931     graphics->worldtrans = container->worldtrans;
1932
1933     GdipDeleteRegion(graphics->clip);
1934     graphics->clip = newClip;
1935
1936     graphics->contid = container->contid - 1;
1937
1938     graphics->smoothing = container->smoothing;
1939     graphics->compqual = container->compqual;
1940     graphics->interpolation = container->interpolation;
1941     graphics->compmode = container->compmode;
1942     graphics->texthint = container->texthint;
1943     graphics->scale = container->scale;
1944     graphics->unit = container->unit;
1945     graphics->textcontrast = container->textcontrast;
1946     graphics->pixeloffset = container->pixeloffset;
1947     graphics->origin_x = container->origin_x;
1948     graphics->origin_y = container->origin_y;
1949
1950     return Ok;
1951 }
1952
1953 static GpStatus get_graphics_bounds(GpGraphics* graphics, GpRectF* rect)
1954 {
1955     RECT wnd_rect;
1956     GpStatus stat=Ok;
1957     GpUnit unit;
1958
1959     if(graphics->hwnd) {
1960         if(!GetClientRect(graphics->hwnd, &wnd_rect))
1961             return GenericError;
1962
1963         rect->X = wnd_rect.left;
1964         rect->Y = wnd_rect.top;
1965         rect->Width = wnd_rect.right - wnd_rect.left;
1966         rect->Height = wnd_rect.bottom - wnd_rect.top;
1967     }else if (graphics->image){
1968         stat = GdipGetImageBounds(graphics->image, rect, &unit);
1969         if (stat == Ok && unit != UnitPixel)
1970             FIXME("need to convert from unit %i\n", unit);
1971     }else if (GetObjectType(graphics->hdc) == OBJ_MEMDC){
1972         HBITMAP hbmp;
1973         BITMAP bmp;
1974
1975         rect->X = 0;
1976         rect->Y = 0;
1977
1978         hbmp = GetCurrentObject(graphics->hdc, OBJ_BITMAP);
1979         if (hbmp && GetObjectW(hbmp, sizeof(bmp), &bmp))
1980         {
1981             rect->Width = bmp.bmWidth;
1982             rect->Height = bmp.bmHeight;
1983         }
1984         else
1985         {
1986             /* FIXME: ??? */
1987             rect->Width = 1;
1988             rect->Height = 1;
1989         }
1990     }else{
1991         rect->X = 0;
1992         rect->Y = 0;
1993         rect->Width = GetDeviceCaps(graphics->hdc, HORZRES);
1994         rect->Height = GetDeviceCaps(graphics->hdc, VERTRES);
1995     }
1996
1997     return stat;
1998 }
1999
2000 /* on success, rgn will contain the region of the graphics object which
2001  * is visible after clipping has been applied */
2002 static GpStatus get_visible_clip_region(GpGraphics *graphics, GpRegion *rgn)
2003 {
2004     GpStatus stat;
2005     GpRectF rectf;
2006     GpRegion* tmp;
2007
2008     if((stat = get_graphics_bounds(graphics, &rectf)) != Ok)
2009         return stat;
2010
2011     if((stat = GdipCreateRegion(&tmp)) != Ok)
2012         return stat;
2013
2014     if((stat = GdipCombineRegionRect(tmp, &rectf, CombineModeReplace)) != Ok)
2015         goto end;
2016
2017     if((stat = GdipCombineRegionRegion(tmp, graphics->clip, CombineModeIntersect)) != Ok)
2018         goto end;
2019
2020     stat = GdipCombineRegionRegion(rgn, tmp, CombineModeReplace);
2021
2022 end:
2023     GdipDeleteRegion(tmp);
2024     return stat;
2025 }
2026
2027 void get_log_fontW(const GpFont *font, GpGraphics *graphics, LOGFONTW *lf)
2028 {
2029     REAL height;
2030
2031     if (font->unit == UnitPixel)
2032     {
2033         height = units_to_pixels(font->emSize, graphics->unit, graphics->yres);
2034     }
2035     else
2036     {
2037         if (graphics->unit == UnitDisplay || graphics->unit == UnitPixel)
2038             height = units_to_pixels(font->emSize, font->unit, graphics->xres);
2039         else
2040             height = units_to_pixels(font->emSize, font->unit, graphics->yres);
2041     }
2042
2043     lf->lfHeight = -(height + 0.5);
2044     lf->lfWidth = 0;
2045     lf->lfEscapement = 0;
2046     lf->lfOrientation = 0;
2047     lf->lfWeight = font->otm.otmTextMetrics.tmWeight;
2048     lf->lfItalic = font->otm.otmTextMetrics.tmItalic ? 1 : 0;
2049     lf->lfUnderline = font->otm.otmTextMetrics.tmUnderlined ? 1 : 0;
2050     lf->lfStrikeOut = font->otm.otmTextMetrics.tmStruckOut ? 1 : 0;
2051     lf->lfCharSet = font->otm.otmTextMetrics.tmCharSet;
2052     lf->lfOutPrecision = OUT_DEFAULT_PRECIS;
2053     lf->lfClipPrecision = CLIP_DEFAULT_PRECIS;
2054     lf->lfQuality = DEFAULT_QUALITY;
2055     lf->lfPitchAndFamily = 0;
2056     strcpyW(lf->lfFaceName, font->family->FamilyName);
2057 }
2058
2059 static void get_font_hfont(GpGraphics *graphics, GDIPCONST GpFont *font,
2060                            GDIPCONST GpStringFormat *format, HFONT *hfont,
2061                            GDIPCONST GpMatrix *matrix)
2062 {
2063     HDC hdc = CreateCompatibleDC(0);
2064     GpPointF pt[3];
2065     REAL angle, rel_width, rel_height, font_height;
2066     LOGFONTW lfw;
2067     HFONT unscaled_font;
2068     TEXTMETRICW textmet;
2069
2070     if (font->unit == UnitPixel)
2071         font_height = font->emSize;
2072     else
2073     {
2074         REAL unit_scale, res;
2075
2076         res = (graphics->unit == UnitDisplay || graphics->unit == UnitPixel) ? graphics->xres : graphics->yres;
2077         unit_scale = units_scale(font->unit, graphics->unit, res);
2078
2079         font_height = font->emSize * unit_scale;
2080     }
2081
2082     pt[0].X = 0.0;
2083     pt[0].Y = 0.0;
2084     pt[1].X = 1.0;
2085     pt[1].Y = 0.0;
2086     pt[2].X = 0.0;
2087     pt[2].Y = 1.0;
2088     if (matrix)
2089     {
2090         GpMatrix xform = *matrix;
2091         GdipTransformMatrixPoints(&xform, pt, 3);
2092     }
2093     if (graphics)
2094         GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
2095     angle = -gdiplus_atan2((pt[1].Y - pt[0].Y), (pt[1].X - pt[0].X));
2096     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
2097                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
2098     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
2099                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
2100
2101     get_log_fontW(font, graphics, &lfw);
2102     lfw.lfHeight = gdip_round(font_height * rel_height);
2103     unscaled_font = CreateFontIndirectW(&lfw);
2104
2105     SelectObject(hdc, unscaled_font);
2106     GetTextMetricsW(hdc, &textmet);
2107
2108     lfw.lfWidth = gdip_round(textmet.tmAveCharWidth * rel_width / rel_height);
2109     lfw.lfEscapement = lfw.lfOrientation = gdip_round((angle / M_PI) * 1800.0);
2110
2111     *hfont = CreateFontIndirectW(&lfw);
2112
2113     DeleteDC(hdc);
2114     DeleteObject(unscaled_font);
2115 }
2116
2117 GpStatus WINGDIPAPI GdipCreateFromHDC(HDC hdc, GpGraphics **graphics)
2118 {
2119     TRACE("(%p, %p)\n", hdc, graphics);
2120
2121     return GdipCreateFromHDC2(hdc, NULL, graphics);
2122 }
2123
2124 GpStatus WINGDIPAPI GdipCreateFromHDC2(HDC hdc, HANDLE hDevice, GpGraphics **graphics)
2125 {
2126     GpStatus retval;
2127     HBITMAP hbitmap;
2128     DIBSECTION dib;
2129
2130     TRACE("(%p, %p, %p)\n", hdc, hDevice, graphics);
2131
2132     if(hDevice != NULL)
2133         FIXME("Don't know how to handle parameter hDevice\n");
2134
2135     if(hdc == NULL)
2136         return OutOfMemory;
2137
2138     if(graphics == NULL)
2139         return InvalidParameter;
2140
2141     *graphics = GdipAlloc(sizeof(GpGraphics));
2142     if(!*graphics)  return OutOfMemory;
2143
2144     GdipSetMatrixElements(&(*graphics)->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
2145
2146     if((retval = GdipCreateRegion(&(*graphics)->clip)) != Ok){
2147         GdipFree(*graphics);
2148         return retval;
2149     }
2150
2151     hbitmap = GetCurrentObject(hdc, OBJ_BITMAP);
2152     if (hbitmap && GetObjectW(hbitmap, sizeof(dib), &dib) == sizeof(dib) &&
2153         dib.dsBmih.biBitCount == 32 && dib.dsBmih.biCompression == BI_RGB)
2154     {
2155         (*graphics)->alpha_hdc = 1;
2156     }
2157
2158     (*graphics)->hdc = hdc;
2159     (*graphics)->hwnd = WindowFromDC(hdc);
2160     (*graphics)->owndc = FALSE;
2161     (*graphics)->smoothing = SmoothingModeDefault;
2162     (*graphics)->compqual = CompositingQualityDefault;
2163     (*graphics)->interpolation = InterpolationModeBilinear;
2164     (*graphics)->pixeloffset = PixelOffsetModeDefault;
2165     (*graphics)->compmode = CompositingModeSourceOver;
2166     (*graphics)->unit = UnitDisplay;
2167     (*graphics)->scale = 1.0;
2168     (*graphics)->xres = GetDeviceCaps(hdc, LOGPIXELSX);
2169     (*graphics)->yres = GetDeviceCaps(hdc, LOGPIXELSY);
2170     (*graphics)->busy = FALSE;
2171     (*graphics)->textcontrast = 4;
2172     list_init(&(*graphics)->containers);
2173     (*graphics)->contid = 0;
2174
2175     TRACE("<-- %p\n", *graphics);
2176
2177     return Ok;
2178 }
2179
2180 GpStatus graphics_from_image(GpImage *image, GpGraphics **graphics)
2181 {
2182     GpStatus retval;
2183
2184     *graphics = GdipAlloc(sizeof(GpGraphics));
2185     if(!*graphics)  return OutOfMemory;
2186
2187     GdipSetMatrixElements(&(*graphics)->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
2188
2189     if((retval = GdipCreateRegion(&(*graphics)->clip)) != Ok){
2190         GdipFree(*graphics);
2191         return retval;
2192     }
2193
2194     (*graphics)->hdc = NULL;
2195     (*graphics)->hwnd = NULL;
2196     (*graphics)->owndc = FALSE;
2197     (*graphics)->image = image;
2198     /* We have to store the image type here because the image may be freed
2199      * before GdipDeleteGraphics is called, and metafiles need special treatment. */
2200     (*graphics)->image_type = image->type;
2201     (*graphics)->smoothing = SmoothingModeDefault;
2202     (*graphics)->compqual = CompositingQualityDefault;
2203     (*graphics)->interpolation = InterpolationModeBilinear;
2204     (*graphics)->pixeloffset = PixelOffsetModeDefault;
2205     (*graphics)->compmode = CompositingModeSourceOver;
2206     (*graphics)->unit = UnitDisplay;
2207     (*graphics)->scale = 1.0;
2208     (*graphics)->xres = image->xres;
2209     (*graphics)->yres = image->yres;
2210     (*graphics)->busy = FALSE;
2211     (*graphics)->textcontrast = 4;
2212     list_init(&(*graphics)->containers);
2213     (*graphics)->contid = 0;
2214
2215     TRACE("<-- %p\n", *graphics);
2216
2217     return Ok;
2218 }
2219
2220 GpStatus WINGDIPAPI GdipCreateFromHWND(HWND hwnd, GpGraphics **graphics)
2221 {
2222     GpStatus ret;
2223     HDC hdc;
2224
2225     TRACE("(%p, %p)\n", hwnd, graphics);
2226
2227     hdc = GetDC(hwnd);
2228
2229     if((ret = GdipCreateFromHDC(hdc, graphics)) != Ok)
2230     {
2231         ReleaseDC(hwnd, hdc);
2232         return ret;
2233     }
2234
2235     (*graphics)->hwnd = hwnd;
2236     (*graphics)->owndc = TRUE;
2237
2238     return Ok;
2239 }
2240
2241 /* FIXME: no icm handling */
2242 GpStatus WINGDIPAPI GdipCreateFromHWNDICM(HWND hwnd, GpGraphics **graphics)
2243 {
2244     TRACE("(%p, %p)\n", hwnd, graphics);
2245
2246     return GdipCreateFromHWND(hwnd, graphics);
2247 }
2248
2249 GpStatus WINGDIPAPI GdipCreateMetafileFromEmf(HENHMETAFILE hemf, BOOL delete,
2250     GpMetafile **metafile)
2251 {
2252     ENHMETAHEADER header;
2253     MetafileType metafile_type;
2254
2255     TRACE("(%p,%i,%p)\n", hemf, delete, metafile);
2256
2257     if(!hemf || !metafile)
2258         return InvalidParameter;
2259
2260     if (GetEnhMetaFileHeader(hemf, sizeof(header), &header) == 0)
2261         return GenericError;
2262
2263     metafile_type = METAFILE_GetEmfType(hemf);
2264
2265     if (metafile_type == MetafileTypeInvalid)
2266         return GenericError;
2267
2268     *metafile = GdipAlloc(sizeof(GpMetafile));
2269     if (!*metafile)
2270         return OutOfMemory;
2271
2272     (*metafile)->image.type = ImageTypeMetafile;
2273     (*metafile)->image.format = ImageFormatEMF;
2274     (*metafile)->image.frame_count = 1;
2275     (*metafile)->image.xres = (REAL)header.szlDevice.cx;
2276     (*metafile)->image.yres = (REAL)header.szlDevice.cy;
2277     (*metafile)->bounds.X = (REAL)header.rclBounds.left;
2278     (*metafile)->bounds.Y = (REAL)header.rclBounds.top;
2279     (*metafile)->bounds.Width = (REAL)(header.rclBounds.right - header.rclBounds.left);
2280     (*metafile)->bounds.Height = (REAL)(header.rclBounds.bottom - header.rclBounds.top);
2281     (*metafile)->unit = UnitPixel;
2282     (*metafile)->metafile_type = metafile_type;
2283     (*metafile)->hemf = hemf;
2284     (*metafile)->preserve_hemf = !delete;
2285
2286     TRACE("<-- %p\n", *metafile);
2287
2288     return Ok;
2289 }
2290
2291 GpStatus WINGDIPAPI GdipCreateMetafileFromWmf(HMETAFILE hwmf, BOOL delete,
2292     GDIPCONST WmfPlaceableFileHeader * placeable, GpMetafile **metafile)
2293 {
2294     UINT read;
2295     BYTE *copy;
2296     HENHMETAFILE hemf;
2297     GpStatus retval = Ok;
2298
2299     TRACE("(%p, %d, %p, %p)\n", hwmf, delete, placeable, metafile);
2300
2301     if(!hwmf || !metafile || !placeable)
2302         return InvalidParameter;
2303
2304     *metafile = NULL;
2305     read = GetMetaFileBitsEx(hwmf, 0, NULL);
2306     if(!read)
2307         return GenericError;
2308     copy = GdipAlloc(read);
2309     GetMetaFileBitsEx(hwmf, read, copy);
2310
2311     hemf = SetWinMetaFileBits(read, copy, NULL, NULL);
2312     GdipFree(copy);
2313
2314     /* FIXME: We should store and use hwmf instead of converting to hemf */
2315     retval = GdipCreateMetafileFromEmf(hemf, TRUE, metafile);
2316
2317     if (retval == Ok)
2318     {
2319         (*metafile)->image.xres = (REAL)placeable->Inch;
2320         (*metafile)->image.yres = (REAL)placeable->Inch;
2321         (*metafile)->bounds.X = ((REAL)placeable->BoundingBox.Left) / ((REAL)placeable->Inch);
2322         (*metafile)->bounds.Y = ((REAL)placeable->BoundingBox.Top) / ((REAL)placeable->Inch);
2323         (*metafile)->bounds.Width = (REAL)(placeable->BoundingBox.Right -
2324                                            placeable->BoundingBox.Left);
2325         (*metafile)->bounds.Height = (REAL)(placeable->BoundingBox.Bottom -
2326                                             placeable->BoundingBox.Top);
2327         (*metafile)->metafile_type = MetafileTypeWmfPlaceable;
2328         (*metafile)->image.format = ImageFormatWMF;
2329
2330         if (delete) DeleteMetaFile(hwmf);
2331     }
2332     else
2333         DeleteEnhMetaFile(hemf);
2334     return retval;
2335 }
2336
2337 GpStatus WINGDIPAPI GdipCreateMetafileFromWmfFile(GDIPCONST WCHAR *file,
2338     GDIPCONST WmfPlaceableFileHeader * placeable, GpMetafile **metafile)
2339 {
2340     HMETAFILE hmf = GetMetaFileW(file);
2341
2342     TRACE("(%s, %p, %p)\n", debugstr_w(file), placeable, metafile);
2343
2344     if(!hmf) return InvalidParameter;
2345
2346     return GdipCreateMetafileFromWmf(hmf, TRUE, placeable, metafile);
2347 }
2348
2349 GpStatus WINGDIPAPI GdipCreateMetafileFromFile(GDIPCONST WCHAR *file,
2350     GpMetafile **metafile)
2351 {
2352     FIXME("(%p, %p): stub\n", file, metafile);
2353     return NotImplemented;
2354 }
2355
2356 GpStatus WINGDIPAPI GdipCreateMetafileFromStream(IStream *stream,
2357     GpMetafile **metafile)
2358 {
2359     FIXME("(%p, %p): stub\n", stream, metafile);
2360     return NotImplemented;
2361 }
2362
2363 GpStatus WINGDIPAPI GdipCreateStreamOnFile(GDIPCONST WCHAR * filename,
2364     UINT access, IStream **stream)
2365 {
2366     DWORD dwMode;
2367     HRESULT ret;
2368
2369     TRACE("(%s, %u, %p)\n", debugstr_w(filename), access, stream);
2370
2371     if(!stream || !filename)
2372         return InvalidParameter;
2373
2374     if(access & GENERIC_WRITE)
2375         dwMode = STGM_SHARE_DENY_WRITE | STGM_WRITE | STGM_CREATE;
2376     else if(access & GENERIC_READ)
2377         dwMode = STGM_SHARE_DENY_WRITE | STGM_READ | STGM_FAILIFTHERE;
2378     else
2379         return InvalidParameter;
2380
2381     ret = SHCreateStreamOnFileW(filename, dwMode, stream);
2382
2383     return hresult_to_status(ret);
2384 }
2385
2386 GpStatus WINGDIPAPI GdipDeleteGraphics(GpGraphics *graphics)
2387 {
2388     GraphicsContainerItem *cont, *next;
2389     GpStatus stat;
2390     TRACE("(%p)\n", graphics);
2391
2392     if(!graphics) return InvalidParameter;
2393     if(graphics->busy) return ObjectBusy;
2394
2395     if (graphics->image && graphics->image_type == ImageTypeMetafile)
2396     {
2397         stat = METAFILE_GraphicsDeleted((GpMetafile*)graphics->image);
2398         if (stat != Ok)
2399             return stat;
2400     }
2401
2402     if(graphics->owndc)
2403         ReleaseDC(graphics->hwnd, graphics->hdc);
2404
2405     LIST_FOR_EACH_ENTRY_SAFE(cont, next, &graphics->containers, GraphicsContainerItem, entry){
2406         list_remove(&cont->entry);
2407         delete_container(cont);
2408     }
2409
2410     GdipDeleteRegion(graphics->clip);
2411     GdipFree(graphics);
2412
2413     return Ok;
2414 }
2415
2416 GpStatus WINGDIPAPI GdipDrawArc(GpGraphics *graphics, GpPen *pen, REAL x,
2417     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
2418 {
2419     GpStatus status;
2420     GpPath *path;
2421
2422     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y,
2423           width, height, startAngle, sweepAngle);
2424
2425     if(!graphics || !pen || width <= 0 || height <= 0)
2426         return InvalidParameter;
2427
2428     if(graphics->busy)
2429         return ObjectBusy;
2430
2431     status = GdipCreatePath(FillModeAlternate, &path);
2432     if (status != Ok) return status;
2433
2434     status = GdipAddPathArc(path, x, y, width, height, startAngle, sweepAngle);
2435     if (status == Ok)
2436         status = GdipDrawPath(graphics, pen, path);
2437
2438     GdipDeletePath(path);
2439     return status;
2440 }
2441
2442 GpStatus WINGDIPAPI GdipDrawArcI(GpGraphics *graphics, GpPen *pen, INT x,
2443     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
2444 {
2445     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n", graphics, pen, x, y,
2446           width, height, startAngle, sweepAngle);
2447
2448     return GdipDrawArc(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
2449 }
2450
2451 GpStatus WINGDIPAPI GdipDrawBezier(GpGraphics *graphics, GpPen *pen, REAL x1,
2452     REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)
2453 {
2454     GpPointF pt[4];
2455
2456     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x1, y1,
2457           x2, y2, x3, y3, x4, y4);
2458
2459     if(!graphics || !pen)
2460         return InvalidParameter;
2461
2462     if(graphics->busy)
2463         return ObjectBusy;
2464
2465     pt[0].X = x1;
2466     pt[0].Y = y1;
2467     pt[1].X = x2;
2468     pt[1].Y = y2;
2469     pt[2].X = x3;
2470     pt[2].Y = y3;
2471     pt[3].X = x4;
2472     pt[3].Y = y4;
2473     return GdipDrawBeziers(graphics, pen, pt, 4);
2474 }
2475
2476 GpStatus WINGDIPAPI GdipDrawBezierI(GpGraphics *graphics, GpPen *pen, INT x1,
2477     INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
2478 {
2479     TRACE("(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d)\n", graphics, pen, x1, y1,
2480           x2, y2, x3, y3, x4, y4);
2481
2482     return GdipDrawBezier(graphics, pen, (REAL)x1, (REAL)y1, (REAL)x2, (REAL)y2, (REAL)x3, (REAL)y3, (REAL)x4, (REAL)y4);
2483 }
2484
2485 GpStatus WINGDIPAPI GdipDrawBeziers(GpGraphics *graphics, GpPen *pen,
2486     GDIPCONST GpPointF *points, INT count)
2487 {
2488     GpStatus status;
2489     GpPath *path;
2490
2491     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2492
2493     if(!graphics || !pen || !points || (count <= 0))
2494         return InvalidParameter;
2495
2496     if(graphics->busy)
2497         return ObjectBusy;
2498
2499     status = GdipCreatePath(FillModeAlternate, &path);
2500     if (status != Ok) return status;
2501
2502     status = GdipAddPathBeziers(path, points, count);
2503     if (status == Ok)
2504         status = GdipDrawPath(graphics, pen, path);
2505
2506     GdipDeletePath(path);
2507     return status;
2508 }
2509
2510 GpStatus WINGDIPAPI GdipDrawBeziersI(GpGraphics *graphics, GpPen *pen,
2511     GDIPCONST GpPoint *points, INT count)
2512 {
2513     GpPointF *pts;
2514     GpStatus ret;
2515     INT i;
2516
2517     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2518
2519     if(!graphics || !pen || !points || (count <= 0))
2520         return InvalidParameter;
2521
2522     if(graphics->busy)
2523         return ObjectBusy;
2524
2525     pts = GdipAlloc(sizeof(GpPointF) * count);
2526     if(!pts)
2527         return OutOfMemory;
2528
2529     for(i = 0; i < count; i++){
2530         pts[i].X = (REAL)points[i].X;
2531         pts[i].Y = (REAL)points[i].Y;
2532     }
2533
2534     ret = GdipDrawBeziers(graphics,pen,pts,count);
2535
2536     GdipFree(pts);
2537
2538     return ret;
2539 }
2540
2541 GpStatus WINGDIPAPI GdipDrawClosedCurve(GpGraphics *graphics, GpPen *pen,
2542     GDIPCONST GpPointF *points, INT count)
2543 {
2544     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2545
2546     return GdipDrawClosedCurve2(graphics, pen, points, count, 1.0);
2547 }
2548
2549 GpStatus WINGDIPAPI GdipDrawClosedCurveI(GpGraphics *graphics, GpPen *pen,
2550     GDIPCONST GpPoint *points, INT count)
2551 {
2552     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2553
2554     return GdipDrawClosedCurve2I(graphics, pen, points, count, 1.0);
2555 }
2556
2557 GpStatus WINGDIPAPI GdipDrawClosedCurve2(GpGraphics *graphics, GpPen *pen,
2558     GDIPCONST GpPointF *points, INT count, REAL tension)
2559 {
2560     GpPath *path;
2561     GpStatus status;
2562
2563     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2564
2565     if(!graphics || !pen || !points || count <= 0)
2566         return InvalidParameter;
2567
2568     if(graphics->busy)
2569         return ObjectBusy;
2570
2571     status = GdipCreatePath(FillModeAlternate, &path);
2572     if (status != Ok) return status;
2573
2574     status = GdipAddPathClosedCurve2(path, points, count, tension);
2575     if (status == Ok)
2576         status = GdipDrawPath(graphics, pen, path);
2577
2578     GdipDeletePath(path);
2579
2580     return status;
2581 }
2582
2583 GpStatus WINGDIPAPI GdipDrawClosedCurve2I(GpGraphics *graphics, GpPen *pen,
2584     GDIPCONST GpPoint *points, INT count, REAL tension)
2585 {
2586     GpPointF *ptf;
2587     GpStatus stat;
2588     INT i;
2589
2590     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2591
2592     if(!points || count <= 0)
2593         return InvalidParameter;
2594
2595     ptf = GdipAlloc(sizeof(GpPointF)*count);
2596     if(!ptf)
2597         return OutOfMemory;
2598
2599     for(i = 0; i < count; i++){
2600         ptf[i].X = (REAL)points[i].X;
2601         ptf[i].Y = (REAL)points[i].Y;
2602     }
2603
2604     stat = GdipDrawClosedCurve2(graphics, pen, ptf, count, tension);
2605
2606     GdipFree(ptf);
2607
2608     return stat;
2609 }
2610
2611 GpStatus WINGDIPAPI GdipDrawCurve(GpGraphics *graphics, GpPen *pen,
2612     GDIPCONST GpPointF *points, INT count)
2613 {
2614     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2615
2616     return GdipDrawCurve2(graphics,pen,points,count,1.0);
2617 }
2618
2619 GpStatus WINGDIPAPI GdipDrawCurveI(GpGraphics *graphics, GpPen *pen,
2620     GDIPCONST GpPoint *points, INT count)
2621 {
2622     GpPointF *pointsF;
2623     GpStatus ret;
2624     INT i;
2625
2626     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2627
2628     if(!points)
2629         return InvalidParameter;
2630
2631     pointsF = GdipAlloc(sizeof(GpPointF)*count);
2632     if(!pointsF)
2633         return OutOfMemory;
2634
2635     for(i = 0; i < count; i++){
2636         pointsF[i].X = (REAL)points[i].X;
2637         pointsF[i].Y = (REAL)points[i].Y;
2638     }
2639
2640     ret = GdipDrawCurve(graphics,pen,pointsF,count);
2641     GdipFree(pointsF);
2642
2643     return ret;
2644 }
2645
2646 /* Approximates cardinal spline with Bezier curves. */
2647 GpStatus WINGDIPAPI GdipDrawCurve2(GpGraphics *graphics, GpPen *pen,
2648     GDIPCONST GpPointF *points, INT count, REAL tension)
2649 {
2650     GpPath *path;
2651     GpStatus status;
2652
2653     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2654
2655     if(!graphics || !pen)
2656         return InvalidParameter;
2657
2658     if(graphics->busy)
2659         return ObjectBusy;
2660
2661     if(count < 2)
2662         return InvalidParameter;
2663
2664     status = GdipCreatePath(FillModeAlternate, &path);
2665     if (status != Ok) return status;
2666
2667     status = GdipAddPathCurve2(path, points, count, tension);
2668     if (status == Ok)
2669         status = GdipDrawPath(graphics, pen, path);
2670
2671     GdipDeletePath(path);
2672     return status;
2673 }
2674
2675 GpStatus WINGDIPAPI GdipDrawCurve2I(GpGraphics *graphics, GpPen *pen,
2676     GDIPCONST GpPoint *points, INT count, REAL tension)
2677 {
2678     GpPointF *pointsF;
2679     GpStatus ret;
2680     INT i;
2681
2682     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2683
2684     if(!points)
2685         return InvalidParameter;
2686
2687     pointsF = GdipAlloc(sizeof(GpPointF)*count);
2688     if(!pointsF)
2689         return OutOfMemory;
2690
2691     for(i = 0; i < count; i++){
2692         pointsF[i].X = (REAL)points[i].X;
2693         pointsF[i].Y = (REAL)points[i].Y;
2694     }
2695
2696     ret = GdipDrawCurve2(graphics,pen,pointsF,count,tension);
2697     GdipFree(pointsF);
2698
2699     return ret;
2700 }
2701
2702 GpStatus WINGDIPAPI GdipDrawCurve3(GpGraphics *graphics, GpPen *pen,
2703     GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments,
2704     REAL tension)
2705 {
2706     TRACE("(%p, %p, %p, %d, %d, %d, %.2f)\n", graphics, pen, points, count, offset, numberOfSegments, tension);
2707
2708     if(offset >= count || numberOfSegments > count - offset - 1 || numberOfSegments <= 0){
2709         return InvalidParameter;
2710     }
2711
2712     return GdipDrawCurve2(graphics, pen, points + offset, numberOfSegments + 1, tension);
2713 }
2714
2715 GpStatus WINGDIPAPI GdipDrawCurve3I(GpGraphics *graphics, GpPen *pen,
2716     GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments,
2717     REAL tension)
2718 {
2719     TRACE("(%p, %p, %p, %d, %d, %d, %.2f)\n", graphics, pen, points, count, offset, numberOfSegments, tension);
2720
2721     if(count < 0){
2722         return OutOfMemory;
2723     }
2724
2725     if(offset >= count || numberOfSegments > count - offset - 1 || numberOfSegments <= 0){
2726         return InvalidParameter;
2727     }
2728
2729     return GdipDrawCurve2I(graphics, pen, points + offset, numberOfSegments + 1, tension);
2730 }
2731
2732 GpStatus WINGDIPAPI GdipDrawEllipse(GpGraphics *graphics, GpPen *pen, REAL x,
2733     REAL y, REAL width, REAL height)
2734 {
2735     GpPath *path;
2736     GpStatus status;
2737
2738     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y, width, height);
2739
2740     if(!graphics || !pen)
2741         return InvalidParameter;
2742
2743     if(graphics->busy)
2744         return ObjectBusy;
2745
2746     status = GdipCreatePath(FillModeAlternate, &path);
2747     if (status != Ok) return status;
2748
2749     status = GdipAddPathEllipse(path, x, y, width, height);
2750     if (status == Ok)
2751         status = GdipDrawPath(graphics, pen, path);
2752
2753     GdipDeletePath(path);
2754     return status;
2755 }
2756
2757 GpStatus WINGDIPAPI GdipDrawEllipseI(GpGraphics *graphics, GpPen *pen, INT x,
2758     INT y, INT width, INT height)
2759 {
2760     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x, y, width, height);
2761
2762     return GdipDrawEllipse(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
2763 }
2764
2765
2766 GpStatus WINGDIPAPI GdipDrawImage(GpGraphics *graphics, GpImage *image, REAL x, REAL y)
2767 {
2768     UINT width, height;
2769
2770     TRACE("(%p, %p, %.2f, %.2f)\n", graphics, image, x, y);
2771
2772     if(!graphics || !image)
2773         return InvalidParameter;
2774
2775     GdipGetImageWidth(image, &width);
2776     GdipGetImageHeight(image, &height);
2777
2778     return GdipDrawImagePointRect(graphics, image, x, y,
2779                                   0.0, 0.0, (REAL)width, (REAL)height, UnitPixel);
2780 }
2781
2782 GpStatus WINGDIPAPI GdipDrawImageI(GpGraphics *graphics, GpImage *image, INT x,
2783     INT y)
2784 {
2785     TRACE("(%p, %p, %d, %d)\n", graphics, image, x, y);
2786
2787     return GdipDrawImage(graphics, image, (REAL)x, (REAL)y);
2788 }
2789
2790 GpStatus WINGDIPAPI GdipDrawImagePointRect(GpGraphics *graphics, GpImage *image,
2791     REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight,
2792     GpUnit srcUnit)
2793 {
2794     GpPointF points[3];
2795     REAL scale_x, scale_y, width, height;
2796
2797     TRACE("(%p, %p, %f, %f, %f, %f, %f, %f, %d)\n", graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
2798
2799     if (!graphics || !image) return InvalidParameter;
2800
2801     scale_x = units_scale(srcUnit, graphics->unit, graphics->xres);
2802     scale_x *= graphics->xres / image->xres;
2803     scale_y = units_scale(srcUnit, graphics->unit, graphics->yres);
2804     scale_y *= graphics->yres / image->yres;
2805     width = srcwidth * scale_x;
2806     height = srcheight * scale_y;
2807
2808     points[0].X = points[2].X = x;
2809     points[0].Y = points[1].Y = y;
2810     points[1].X = x + width;
2811     points[2].Y = y + height;
2812
2813     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
2814         srcwidth, srcheight, srcUnit, NULL, NULL, NULL);
2815 }
2816
2817 GpStatus WINGDIPAPI GdipDrawImagePointRectI(GpGraphics *graphics, GpImage *image,
2818     INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight,
2819     GpUnit srcUnit)
2820 {
2821     return GdipDrawImagePointRect(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
2822 }
2823
2824 GpStatus WINGDIPAPI GdipDrawImagePoints(GpGraphics *graphics, GpImage *image,
2825     GDIPCONST GpPointF *dstpoints, INT count)
2826 {
2827     UINT width, height;
2828
2829     TRACE("(%p, %p, %p, %d)\n", graphics, image, dstpoints, count);
2830
2831     if(!image)
2832         return InvalidParameter;
2833
2834     GdipGetImageWidth(image, &width);
2835     GdipGetImageHeight(image, &height);
2836
2837     return GdipDrawImagePointsRect(graphics, image, dstpoints, count, 0, 0,
2838         width, height, UnitPixel, NULL, NULL, NULL);
2839 }
2840
2841 GpStatus WINGDIPAPI GdipDrawImagePointsI(GpGraphics *graphics, GpImage *image,
2842     GDIPCONST GpPoint *dstpoints, INT count)
2843 {
2844     GpPointF ptf[3];
2845
2846     TRACE("(%p, %p, %p, %d)\n", graphics, image, dstpoints, count);
2847
2848     if (count != 3 || !dstpoints)
2849         return InvalidParameter;
2850
2851     ptf[0].X = (REAL)dstpoints[0].X;
2852     ptf[0].Y = (REAL)dstpoints[0].Y;
2853     ptf[1].X = (REAL)dstpoints[1].X;
2854     ptf[1].Y = (REAL)dstpoints[1].Y;
2855     ptf[2].X = (REAL)dstpoints[2].X;
2856     ptf[2].Y = (REAL)dstpoints[2].Y;
2857
2858     return GdipDrawImagePoints(graphics, image, ptf, count);
2859 }
2860
2861 static BOOL CALLBACK play_metafile_proc(EmfPlusRecordType record_type, unsigned int flags,
2862     unsigned int dataSize, const unsigned char *pStr, void *userdata)
2863 {
2864     GdipPlayMetafileRecord(userdata, record_type, flags, dataSize, pStr);
2865     return TRUE;
2866 }
2867
2868 GpStatus WINGDIPAPI GdipDrawImagePointsRect(GpGraphics *graphics, GpImage *image,
2869      GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth,
2870      REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes,
2871      DrawImageAbort callback, VOID * callbackData)
2872 {
2873     GpPointF ptf[4];
2874     POINT pti[4];
2875     GpStatus stat;
2876
2877     TRACE("(%p, %p, %p, %d, %f, %f, %f, %f, %d, %p, %p, %p)\n", graphics, image, points,
2878           count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback,
2879           callbackData);
2880
2881     if (count > 3)
2882         return NotImplemented;
2883
2884     if(!graphics || !image || !points || count != 3)
2885          return InvalidParameter;
2886
2887     TRACE("%s %s %s\n", debugstr_pointf(&points[0]), debugstr_pointf(&points[1]),
2888         debugstr_pointf(&points[2]));
2889
2890     memcpy(ptf, points, 3 * sizeof(GpPointF));
2891     ptf[3].X = ptf[2].X + ptf[1].X - ptf[0].X;
2892     ptf[3].Y = ptf[2].Y + ptf[1].Y - ptf[0].Y;
2893     if (!srcwidth || !srcheight || ptf[3].X == ptf[0].X || ptf[3].Y == ptf[0].Y)
2894         return Ok;
2895     transform_and_round_points(graphics, pti, ptf, 4);
2896
2897     TRACE("%s %s %s %s\n", wine_dbgstr_point(&pti[0]), wine_dbgstr_point(&pti[1]),
2898         wine_dbgstr_point(&pti[2]), wine_dbgstr_point(&pti[3]));
2899
2900     srcx = units_to_pixels(srcx, srcUnit, image->xres);
2901     srcy = units_to_pixels(srcy, srcUnit, image->yres);
2902     srcwidth = units_to_pixels(srcwidth, srcUnit, image->xres);
2903     srcheight = units_to_pixels(srcheight, srcUnit, image->yres);
2904     TRACE("src pixels: %f,%f %fx%f\n", srcx, srcy, srcwidth, srcheight);
2905
2906     if (image->picture)
2907     {
2908         if (!graphics->hdc)
2909         {
2910             FIXME("graphics object has no HDC\n");
2911         }
2912
2913         if(IPicture_Render(image->picture, graphics->hdc,
2914             pti[0].x, pti[0].y, pti[1].x - pti[0].x, pti[2].y - pti[0].y,
2915             srcx, srcy, srcwidth, srcheight, NULL) != S_OK)
2916         {
2917             if(callback)
2918                 callback(callbackData);
2919             return GenericError;
2920         }
2921     }
2922     else if (image->type == ImageTypeBitmap)
2923     {
2924         GpBitmap* bitmap = (GpBitmap*)image;
2925         int use_software=0;
2926
2927         TRACE("graphics: %.2fx%.2f dpi, fmt %#x, scale %f, image: %.2fx%.2f dpi, fmt %#x, color %08x\n",
2928             graphics->xres, graphics->yres,
2929             graphics->image && graphics->image->type == ImageTypeBitmap ? ((GpBitmap *)graphics->image)->format : 0,
2930             graphics->scale, image->xres, image->yres, bitmap->format,
2931             imageAttributes ? imageAttributes->outside_color : 0);
2932
2933         if (imageAttributes || graphics->alpha_hdc ||
2934             (graphics->image && graphics->image->type == ImageTypeBitmap) ||
2935             ptf[1].Y != ptf[0].Y || ptf[2].X != ptf[0].X ||
2936             ptf[1].X - ptf[0].X != srcwidth || ptf[2].Y - ptf[0].Y != srcheight ||
2937             srcx < 0 || srcy < 0 ||
2938             srcx + srcwidth > bitmap->width || srcy + srcheight > bitmap->height)
2939             use_software = 1;
2940
2941         if (use_software)
2942         {
2943             RECT dst_area;
2944             GpRect src_area;
2945             int i, x, y, src_stride, dst_stride;
2946             GpMatrix dst_to_src;
2947             REAL m11, m12, m21, m22, mdx, mdy;
2948             LPBYTE src_data, dst_data;
2949             BitmapData lockeddata;
2950             InterpolationMode interpolation = graphics->interpolation;
2951             PixelOffsetMode offset_mode = graphics->pixeloffset;
2952             GpPointF dst_to_src_points[3] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}};
2953             REAL x_dx, x_dy, y_dx, y_dy;
2954             static const GpImageAttributes defaultImageAttributes = {WrapModeClamp, 0, FALSE};
2955
2956             if (!imageAttributes)
2957                 imageAttributes = &defaultImageAttributes;
2958
2959             dst_area.left = dst_area.right = pti[0].x;
2960             dst_area.top = dst_area.bottom = pti[0].y;
2961             for (i=1; i<4; i++)
2962             {
2963                 if (dst_area.left > pti[i].x) dst_area.left = pti[i].x;
2964                 if (dst_area.right < pti[i].x) dst_area.right = pti[i].x;
2965                 if (dst_area.top > pti[i].y) dst_area.top = pti[i].y;
2966                 if (dst_area.bottom < pti[i].y) dst_area.bottom = pti[i].y;
2967             }
2968
2969             TRACE("dst_area: %s\n", wine_dbgstr_rect(&dst_area));
2970
2971             m11 = (ptf[1].X - ptf[0].X) / srcwidth;
2972             m21 = (ptf[2].X - ptf[0].X) / srcheight;
2973             mdx = ptf[0].X - m11 * srcx - m21 * srcy;
2974             m12 = (ptf[1].Y - ptf[0].Y) / srcwidth;
2975             m22 = (ptf[2].Y - ptf[0].Y) / srcheight;
2976             mdy = ptf[0].Y - m12 * srcx - m22 * srcy;
2977
2978             GdipSetMatrixElements(&dst_to_src, m11, m12, m21, m22, mdx, mdy);
2979
2980             stat = GdipInvertMatrix(&dst_to_src);
2981             if (stat != Ok) return stat;
2982
2983             dst_data = GdipAlloc(sizeof(ARGB) * (dst_area.right - dst_area.left) * (dst_area.bottom - dst_area.top));
2984             if (!dst_data) return OutOfMemory;
2985
2986             dst_stride = sizeof(ARGB) * (dst_area.right - dst_area.left);
2987
2988             get_bitmap_sample_size(interpolation, imageAttributes->wrap,
2989                 bitmap, srcx, srcy, srcwidth, srcheight, &src_area);
2990
2991             TRACE("src_area: %d x %d\n", src_area.Width, src_area.Height);
2992
2993             src_data = GdipAlloc(sizeof(ARGB) * src_area.Width * src_area.Height);
2994             if (!src_data)
2995             {
2996                 GdipFree(dst_data);
2997                 return OutOfMemory;
2998             }
2999             src_stride = sizeof(ARGB) * src_area.Width;
3000
3001             /* Read the bits we need from the source bitmap into an ARGB buffer. */
3002             lockeddata.Width = src_area.Width;
3003             lockeddata.Height = src_area.Height;
3004             lockeddata.Stride = src_stride;
3005             lockeddata.PixelFormat = PixelFormat32bppARGB;
3006             lockeddata.Scan0 = src_data;
3007
3008             stat = GdipBitmapLockBits(bitmap, &src_area, ImageLockModeRead|ImageLockModeUserInputBuf,
3009                 PixelFormat32bppARGB, &lockeddata);
3010
3011             if (stat == Ok)
3012                 stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
3013
3014             if (stat != Ok)
3015             {
3016                 if (src_data != dst_data)
3017                     GdipFree(src_data);
3018                 GdipFree(dst_data);
3019                 return stat;
3020             }
3021
3022             apply_image_attributes(imageAttributes, src_data,
3023                 src_area.Width, src_area.Height,
3024                 src_stride, ColorAdjustTypeBitmap);
3025
3026             /* Transform the bits as needed to the destination. */
3027             GdipTransformMatrixPoints(&dst_to_src, dst_to_src_points, 3);
3028
3029             x_dx = dst_to_src_points[1].X - dst_to_src_points[0].X;
3030             x_dy = dst_to_src_points[1].Y - dst_to_src_points[0].Y;
3031             y_dx = dst_to_src_points[2].X - dst_to_src_points[0].X;
3032             y_dy = dst_to_src_points[2].Y - dst_to_src_points[0].Y;
3033
3034             for (x=dst_area.left; x<dst_area.right; x++)
3035             {
3036                 for (y=dst_area.top; y<dst_area.bottom; y++)
3037                 {
3038                     GpPointF src_pointf;
3039                     ARGB *dst_color;
3040
3041                     src_pointf.X = dst_to_src_points[0].X + x * x_dx + y * y_dx;
3042                     src_pointf.Y = dst_to_src_points[0].Y + x * x_dy + y * y_dy;
3043
3044                     dst_color = (ARGB*)(dst_data + dst_stride * (y - dst_area.top) + sizeof(ARGB) * (x - dst_area.left));
3045
3046                     if (src_pointf.X >= srcx && src_pointf.X < srcx + srcwidth && src_pointf.Y >= srcy && src_pointf.Y < srcy+srcheight)
3047                         *dst_color = resample_bitmap_pixel(&src_area, src_data, bitmap->width, bitmap->height, &src_pointf,
3048                                                            imageAttributes, interpolation, offset_mode);
3049                     else
3050                         *dst_color = 0;
3051                 }
3052             }
3053
3054             GdipFree(src_data);
3055
3056             stat = alpha_blend_pixels(graphics, dst_area.left, dst_area.top,
3057                 dst_data, dst_area.right - dst_area.left, dst_area.bottom - dst_area.top, dst_stride);
3058
3059             GdipFree(dst_data);
3060
3061             return stat;
3062         }
3063         else
3064         {
3065             HDC hdc;
3066             int temp_hdc=0, temp_bitmap=0;
3067             HBITMAP hbitmap, old_hbm=NULL;
3068
3069             if (!(bitmap->format == PixelFormat16bppRGB555 ||
3070                   bitmap->format == PixelFormat24bppRGB ||
3071                   bitmap->format == PixelFormat32bppRGB ||
3072                   bitmap->format == PixelFormat32bppPARGB))
3073             {
3074                 BITMAPINFOHEADER bih;
3075                 BYTE *temp_bits;
3076                 PixelFormat dst_format;
3077
3078                 /* we can't draw a bitmap of this format directly */
3079                 hdc = CreateCompatibleDC(0);
3080                 temp_hdc = 1;
3081                 temp_bitmap = 1;
3082
3083                 bih.biSize = sizeof(BITMAPINFOHEADER);
3084                 bih.biWidth = bitmap->width;
3085                 bih.biHeight = -bitmap->height;
3086                 bih.biPlanes = 1;
3087                 bih.biBitCount = 32;
3088                 bih.biCompression = BI_RGB;
3089                 bih.biSizeImage = 0;
3090                 bih.biXPelsPerMeter = 0;
3091                 bih.biYPelsPerMeter = 0;
3092                 bih.biClrUsed = 0;
3093                 bih.biClrImportant = 0;
3094
3095                 hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bih, DIB_RGB_COLORS,
3096                     (void**)&temp_bits, NULL, 0);
3097
3098                 if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3099                     dst_format = PixelFormat32bppPARGB;
3100                 else
3101                     dst_format = PixelFormat32bppRGB;
3102
3103                 convert_pixels(bitmap->width, bitmap->height,
3104                     bitmap->width*4, temp_bits, dst_format,
3105                     bitmap->stride, bitmap->bits, bitmap->format,
3106                     bitmap->image.palette);
3107             }
3108             else
3109             {
3110                 if (bitmap->hbitmap)
3111                     hbitmap = bitmap->hbitmap;
3112                 else
3113                 {
3114                     GdipCreateHBITMAPFromBitmap(bitmap, &hbitmap, 0);
3115                     temp_bitmap = 1;
3116                 }
3117
3118                 hdc = bitmap->hdc;
3119                 temp_hdc = (hdc == 0);
3120             }
3121
3122             if (temp_hdc)
3123             {
3124                 if (!hdc) hdc = CreateCompatibleDC(0);
3125                 old_hbm = SelectObject(hdc, hbitmap);
3126             }
3127
3128             if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3129             {
3130                 gdi_alpha_blend(graphics, pti[0].x, pti[0].y, pti[1].x - pti[0].x, pti[2].y - pti[0].y,
3131                                 hdc, srcx, srcy, srcwidth, srcheight);
3132             }
3133             else
3134             {
3135                 StretchBlt(graphics->hdc, pti[0].x, pti[0].y, pti[1].x-pti[0].x, pti[2].y-pti[0].y,
3136                     hdc, srcx, srcy, srcwidth, srcheight, SRCCOPY);
3137             }
3138
3139             if (temp_hdc)
3140             {
3141                 SelectObject(hdc, old_hbm);
3142                 DeleteDC(hdc);
3143             }
3144
3145             if (temp_bitmap)
3146                 DeleteObject(hbitmap);
3147         }
3148     }
3149     else if (image->type == ImageTypeMetafile && ((GpMetafile*)image)->hemf)
3150     {
3151         GpRectF rc;
3152
3153         rc.X = srcx;
3154         rc.Y = srcy;
3155         rc.Width = srcwidth;
3156         rc.Height = srcheight;
3157
3158         return GdipEnumerateMetafileSrcRectDestPoints(graphics, (GpMetafile*)image,
3159             points, count, &rc, srcUnit, play_metafile_proc, image, imageAttributes);
3160     }
3161     else
3162     {
3163         WARN("GpImage with nothing we can draw (metafile in wrong state?)\n");
3164         return InvalidParameter;
3165     }
3166
3167     return Ok;
3168 }
3169
3170 GpStatus WINGDIPAPI GdipDrawImagePointsRectI(GpGraphics *graphics, GpImage *image,
3171      GDIPCONST GpPoint *points, INT count, INT srcx, INT srcy, INT srcwidth,
3172      INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes,
3173      DrawImageAbort callback, VOID * callbackData)
3174 {
3175     GpPointF pointsF[3];
3176     INT i;
3177
3178     TRACE("(%p, %p, %p, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n", graphics, image, points, count,
3179           srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback,
3180           callbackData);
3181
3182     if(!points || count!=3)
3183         return InvalidParameter;
3184
3185     for(i = 0; i < count; i++){
3186         pointsF[i].X = (REAL)points[i].X;
3187         pointsF[i].Y = (REAL)points[i].Y;
3188     }
3189
3190     return GdipDrawImagePointsRect(graphics, image, pointsF, count, (REAL)srcx, (REAL)srcy,
3191                                    (REAL)srcwidth, (REAL)srcheight, srcUnit, imageAttributes,
3192                                    callback, callbackData);
3193 }
3194
3195 GpStatus WINGDIPAPI GdipDrawImageRectRect(GpGraphics *graphics, GpImage *image,
3196     REAL dstx, REAL dsty, REAL dstwidth, REAL dstheight, REAL srcx, REAL srcy,
3197     REAL srcwidth, REAL srcheight, GpUnit srcUnit,
3198     GDIPCONST GpImageAttributes* imageattr, DrawImageAbort callback,
3199     VOID * callbackData)
3200 {
3201     GpPointF points[3];
3202
3203     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %d, %p, %p, %p)\n",
3204           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3205           srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3206
3207     points[0].X = dstx;
3208     points[0].Y = dsty;
3209     points[1].X = dstx + dstwidth;
3210     points[1].Y = dsty;
3211     points[2].X = dstx;
3212     points[2].Y = dsty + dstheight;
3213
3214     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3215                srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3216 }
3217
3218 GpStatus WINGDIPAPI GdipDrawImageRectRectI(GpGraphics *graphics, GpImage *image,
3219         INT dstx, INT dsty, INT dstwidth, INT dstheight, INT srcx, INT srcy,
3220         INT srcwidth, INT srcheight, GpUnit srcUnit,
3221         GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback,
3222         VOID * callbackData)
3223 {
3224     GpPointF points[3];
3225
3226     TRACE("(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n",
3227           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3228           srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3229
3230     points[0].X = dstx;
3231     points[0].Y = dsty;
3232     points[1].X = dstx + dstwidth;
3233     points[1].Y = dsty;
3234     points[2].X = dstx;
3235     points[2].Y = dsty + dstheight;
3236
3237     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3238                srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3239 }
3240
3241 GpStatus WINGDIPAPI GdipDrawImageRect(GpGraphics *graphics, GpImage *image,
3242     REAL x, REAL y, REAL width, REAL height)
3243 {
3244     RectF bounds;
3245     GpUnit unit;
3246     GpStatus ret;
3247
3248     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, image, x, y, width, height);
3249
3250     if(!graphics || !image)
3251         return InvalidParameter;
3252
3253     ret = GdipGetImageBounds(image, &bounds, &unit);
3254     if(ret != Ok)
3255         return ret;
3256
3257     return GdipDrawImageRectRect(graphics, image, x, y, width, height,
3258                                  bounds.X, bounds.Y, bounds.Width, bounds.Height,
3259                                  unit, NULL, NULL, NULL);
3260 }
3261
3262 GpStatus WINGDIPAPI GdipDrawImageRectI(GpGraphics *graphics, GpImage *image,
3263     INT x, INT y, INT width, INT height)
3264 {
3265     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, image, x, y, width, height);
3266
3267     return GdipDrawImageRect(graphics, image, (REAL)x, (REAL)y, (REAL)width, (REAL)height);
3268 }
3269
3270 GpStatus WINGDIPAPI GdipDrawLine(GpGraphics *graphics, GpPen *pen, REAL x1,
3271     REAL y1, REAL x2, REAL y2)
3272 {
3273     GpPointF pt[2];
3274
3275     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x1, y1, x2, y2);
3276
3277     pt[0].X = x1;
3278     pt[0].Y = y1;
3279     pt[1].X = x2;
3280     pt[1].Y = y2;
3281     return GdipDrawLines(graphics, pen, pt, 2);
3282 }
3283
3284 GpStatus WINGDIPAPI GdipDrawLineI(GpGraphics *graphics, GpPen *pen, INT x1,
3285     INT y1, INT x2, INT y2)
3286 {
3287     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x1, y1, x2, y2);
3288
3289     return GdipDrawLine(graphics, pen, (REAL)x1, (REAL)y1, (REAL)x2, (REAL)y2);
3290 }
3291
3292 GpStatus WINGDIPAPI GdipDrawLines(GpGraphics *graphics, GpPen *pen, GDIPCONST
3293     GpPointF *points, INT count)
3294 {
3295     GpStatus status;
3296     GpPath *path;
3297
3298     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3299
3300     if(!pen || !graphics || (count < 2))
3301         return InvalidParameter;
3302
3303     if(graphics->busy)
3304         return ObjectBusy;
3305
3306     status = GdipCreatePath(FillModeAlternate, &path);
3307     if (status != Ok) return status;
3308
3309     status = GdipAddPathLine2(path, points, count);
3310     if (status == Ok)
3311         status = GdipDrawPath(graphics, pen, path);
3312
3313     GdipDeletePath(path);
3314     return status;
3315 }
3316
3317 GpStatus WINGDIPAPI GdipDrawLinesI(GpGraphics *graphics, GpPen *pen, GDIPCONST
3318     GpPoint *points, INT count)
3319 {
3320     GpStatus retval;
3321     GpPointF *ptf;
3322     int i;
3323
3324     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3325
3326     ptf = GdipAlloc(count * sizeof(GpPointF));
3327     if(!ptf) return OutOfMemory;
3328
3329     for(i = 0; i < count; i ++){
3330         ptf[i].X = (REAL) points[i].X;
3331         ptf[i].Y = (REAL) points[i].Y;
3332     }
3333
3334     retval = GdipDrawLines(graphics, pen, ptf, count);
3335
3336     GdipFree(ptf);
3337     return retval;
3338 }
3339
3340 GpStatus WINGDIPAPI GdipDrawPath(GpGraphics *graphics, GpPen *pen, GpPath *path)
3341 {
3342     INT save_state;
3343     GpStatus retval;
3344
3345     TRACE("(%p, %p, %p)\n", graphics, pen, path);
3346
3347     if(!pen || !graphics)
3348         return InvalidParameter;
3349
3350     if(graphics->busy)
3351         return ObjectBusy;
3352
3353     if (!graphics->hdc)
3354     {
3355         FIXME("graphics object has no HDC\n");
3356         return Ok;
3357     }
3358
3359     save_state = prepare_dc(graphics, pen);
3360
3361     retval = draw_poly(graphics, pen, path->pathdata.Points,
3362                        path->pathdata.Types, path->pathdata.Count, TRUE);
3363
3364     restore_dc(graphics, save_state);
3365
3366     return retval;
3367 }
3368
3369 GpStatus WINGDIPAPI GdipDrawPie(GpGraphics *graphics, GpPen *pen, REAL x,
3370     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
3371 {
3372     GpStatus status;
3373     GpPath *path;
3374
3375     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y,
3376             width, height, startAngle, sweepAngle);
3377
3378     if(!graphics || !pen)
3379         return InvalidParameter;
3380
3381     if(graphics->busy)
3382         return ObjectBusy;
3383
3384     status = GdipCreatePath(FillModeAlternate, &path);
3385     if (status != Ok) return status;
3386
3387     status = GdipAddPathPie(path, x, y, width, height, startAngle, sweepAngle);
3388     if (status == Ok)
3389         status = GdipDrawPath(graphics, pen, path);
3390
3391     GdipDeletePath(path);
3392     return status;
3393 }
3394
3395 GpStatus WINGDIPAPI GdipDrawPieI(GpGraphics *graphics, GpPen *pen, INT x,
3396     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
3397 {
3398     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n", graphics, pen, x, y,
3399             width, height, startAngle, sweepAngle);
3400
3401     return GdipDrawPie(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
3402 }
3403
3404 GpStatus WINGDIPAPI GdipDrawRectangle(GpGraphics *graphics, GpPen *pen, REAL x,
3405     REAL y, REAL width, REAL height)
3406 {
3407     GpStatus status;
3408     GpPath *path;
3409
3410     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y, width, height);
3411
3412     if(!pen || !graphics)
3413         return InvalidParameter;
3414
3415     if(graphics->busy)
3416         return ObjectBusy;
3417
3418     status = GdipCreatePath(FillModeAlternate, &path);
3419     if (status != Ok) return status;
3420
3421     status = GdipAddPathRectangle(path, x, y, width, height);
3422     if (status == Ok)
3423         status = GdipDrawPath(graphics, pen, path);
3424
3425     GdipDeletePath(path);
3426     return status;
3427 }
3428
3429 GpStatus WINGDIPAPI GdipDrawRectangleI(GpGraphics *graphics, GpPen *pen, INT x,
3430     INT y, INT width, INT height)
3431 {
3432     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x, y, width, height);
3433
3434     return GdipDrawRectangle(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3435 }
3436
3437 GpStatus WINGDIPAPI GdipDrawRectangles(GpGraphics *graphics, GpPen *pen,
3438     GDIPCONST GpRectF* rects, INT count)
3439 {
3440     GpStatus status;
3441     GpPath *path;
3442
3443     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3444
3445     if(!graphics || !pen || !rects || count < 1)
3446         return InvalidParameter;
3447
3448     if(graphics->busy)
3449         return ObjectBusy;
3450
3451     status = GdipCreatePath(FillModeAlternate, &path);
3452     if (status != Ok) return status;
3453
3454     status = GdipAddPathRectangles(path, rects, count);
3455     if (status == Ok)
3456         status = GdipDrawPath(graphics, pen, path);
3457
3458     GdipDeletePath(path);
3459     return status;
3460 }
3461
3462 GpStatus WINGDIPAPI GdipDrawRectanglesI(GpGraphics *graphics, GpPen *pen,
3463     GDIPCONST GpRect* rects, INT count)
3464 {
3465     GpRectF *rectsF;
3466     GpStatus ret;
3467     INT i;
3468
3469     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3470
3471     if(!rects || count<=0)
3472         return InvalidParameter;
3473
3474     rectsF = GdipAlloc(sizeof(GpRectF) * count);
3475     if(!rectsF)
3476         return OutOfMemory;
3477
3478     for(i = 0;i < count;i++){
3479         rectsF[i].X      = (REAL)rects[i].X;
3480         rectsF[i].Y      = (REAL)rects[i].Y;
3481         rectsF[i].Width  = (REAL)rects[i].Width;
3482         rectsF[i].Height = (REAL)rects[i].Height;
3483     }
3484
3485     ret = GdipDrawRectangles(graphics, pen, rectsF, count);
3486     GdipFree(rectsF);
3487
3488     return ret;
3489 }
3490
3491 GpStatus WINGDIPAPI GdipFillClosedCurve2(GpGraphics *graphics, GpBrush *brush,
3492     GDIPCONST GpPointF *points, INT count, REAL tension, GpFillMode fill)
3493 {
3494     GpPath *path;
3495     GpStatus status;
3496
3497     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3498             count, tension, fill);
3499
3500     if(!graphics || !brush || !points)
3501         return InvalidParameter;
3502
3503     if(graphics->busy)
3504         return ObjectBusy;
3505
3506     if(count == 1)    /* Do nothing */
3507         return Ok;
3508
3509     status = GdipCreatePath(fill, &path);
3510     if (status != Ok) return status;
3511
3512     status = GdipAddPathClosedCurve2(path, points, count, tension);
3513     if (status == Ok)
3514         status = GdipFillPath(graphics, brush, path);
3515
3516     GdipDeletePath(path);
3517     return status;
3518 }
3519
3520 GpStatus WINGDIPAPI GdipFillClosedCurve2I(GpGraphics *graphics, GpBrush *brush,
3521     GDIPCONST GpPoint *points, INT count, REAL tension, GpFillMode fill)
3522 {
3523     GpPointF *ptf;
3524     GpStatus stat;
3525     INT i;
3526
3527     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3528             count, tension, fill);
3529
3530     if(!points || count == 0)
3531         return InvalidParameter;
3532
3533     if(count == 1)    /* Do nothing */
3534         return Ok;
3535
3536     ptf = GdipAlloc(sizeof(GpPointF)*count);
3537     if(!ptf)
3538         return OutOfMemory;
3539
3540     for(i = 0;i < count;i++){
3541         ptf[i].X = (REAL)points[i].X;
3542         ptf[i].Y = (REAL)points[i].Y;
3543     }
3544
3545     stat = GdipFillClosedCurve2(graphics, brush, ptf, count, tension, fill);
3546
3547     GdipFree(ptf);
3548
3549     return stat;
3550 }
3551
3552 GpStatus WINGDIPAPI GdipFillClosedCurve(GpGraphics *graphics, GpBrush *brush,
3553     GDIPCONST GpPointF *points, INT count)
3554 {
3555     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3556     return GdipFillClosedCurve2(graphics, brush, points, count,
3557                0.5f, FillModeAlternate);
3558 }
3559
3560 GpStatus WINGDIPAPI GdipFillClosedCurveI(GpGraphics *graphics, GpBrush *brush,
3561     GDIPCONST GpPoint *points, INT count)
3562 {
3563     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3564     return GdipFillClosedCurve2I(graphics, brush, points, count,
3565                0.5f, FillModeAlternate);
3566 }
3567
3568 GpStatus WINGDIPAPI GdipFillEllipse(GpGraphics *graphics, GpBrush *brush, REAL x,
3569     REAL y, REAL width, REAL height)
3570 {
3571     GpStatus stat;
3572     GpPath *path;
3573
3574     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
3575
3576     if(!graphics || !brush)
3577         return InvalidParameter;
3578
3579     if(graphics->busy)
3580         return ObjectBusy;
3581
3582     stat = GdipCreatePath(FillModeAlternate, &path);
3583
3584     if (stat == Ok)
3585     {
3586         stat = GdipAddPathEllipse(path, x, y, width, height);
3587
3588         if (stat == Ok)
3589             stat = GdipFillPath(graphics, brush, path);
3590
3591         GdipDeletePath(path);
3592     }
3593
3594     return stat;
3595 }
3596
3597 GpStatus WINGDIPAPI GdipFillEllipseI(GpGraphics *graphics, GpBrush *brush, INT x,
3598     INT y, INT width, INT height)
3599 {
3600     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
3601
3602     return GdipFillEllipse(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3603 }
3604
3605 static GpStatus GDI32_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3606 {
3607     INT save_state;
3608     GpStatus retval;
3609
3610     if(!graphics->hdc || !brush_can_fill_path(brush))
3611         return NotImplemented;
3612
3613     save_state = SaveDC(graphics->hdc);
3614     EndPath(graphics->hdc);
3615     SetPolyFillMode(graphics->hdc, (path->fill == FillModeAlternate ? ALTERNATE
3616                                                                     : WINDING));
3617
3618     BeginPath(graphics->hdc);
3619     retval = draw_poly(graphics, NULL, path->pathdata.Points,
3620                        path->pathdata.Types, path->pathdata.Count, FALSE);
3621
3622     if(retval != Ok)
3623         goto end;
3624
3625     EndPath(graphics->hdc);
3626     brush_fill_path(graphics, brush);
3627
3628     retval = Ok;
3629
3630 end:
3631     RestoreDC(graphics->hdc, save_state);
3632
3633     return retval;
3634 }
3635
3636 static GpStatus SOFTWARE_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3637 {
3638     GpStatus stat;
3639     GpRegion *rgn;
3640
3641     if (!brush_can_fill_pixels(brush))
3642         return NotImplemented;
3643
3644     /* FIXME: This could probably be done more efficiently without regions. */
3645
3646     stat = GdipCreateRegionPath(path, &rgn);
3647
3648     if (stat == Ok)
3649     {
3650         stat = GdipFillRegion(graphics, brush, rgn);
3651
3652         GdipDeleteRegion(rgn);
3653     }
3654
3655     return stat;
3656 }
3657
3658 GpStatus WINGDIPAPI GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3659 {
3660     GpStatus stat = NotImplemented;
3661
3662     TRACE("(%p, %p, %p)\n", graphics, brush, path);
3663
3664     if(!brush || !graphics || !path)
3665         return InvalidParameter;
3666
3667     if(graphics->busy)
3668         return ObjectBusy;
3669
3670     if (!graphics->image && !graphics->alpha_hdc)
3671         stat = GDI32_GdipFillPath(graphics, brush, path);
3672
3673     if (stat == NotImplemented)
3674         stat = SOFTWARE_GdipFillPath(graphics, brush, path);
3675
3676     if (stat == NotImplemented)
3677     {
3678         FIXME("Not implemented for brushtype %i\n", brush->bt);
3679         stat = Ok;
3680     }
3681
3682     return stat;
3683 }
3684
3685 GpStatus WINGDIPAPI GdipFillPie(GpGraphics *graphics, GpBrush *brush, REAL x,
3686     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
3687 {
3688     GpStatus stat;
3689     GpPath *path;
3690
3691     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n",
3692             graphics, brush, x, y, width, height, startAngle, sweepAngle);
3693
3694     if(!graphics || !brush)
3695         return InvalidParameter;
3696
3697     if(graphics->busy)
3698         return ObjectBusy;
3699
3700     stat = GdipCreatePath(FillModeAlternate, &path);
3701
3702     if (stat == Ok)
3703     {
3704         stat = GdipAddPathPie(path, x, y, width, height, startAngle, sweepAngle);
3705
3706         if (stat == Ok)
3707             stat = GdipFillPath(graphics, brush, path);
3708
3709         GdipDeletePath(path);
3710     }
3711
3712     return stat;
3713 }
3714
3715 GpStatus WINGDIPAPI GdipFillPieI(GpGraphics *graphics, GpBrush *brush, INT x,
3716     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
3717 {
3718     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n",
3719             graphics, brush, x, y, width, height, startAngle, sweepAngle);
3720
3721     return GdipFillPie(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
3722 }
3723
3724 GpStatus WINGDIPAPI GdipFillPolygon(GpGraphics *graphics, GpBrush *brush,
3725     GDIPCONST GpPointF *points, INT count, GpFillMode fillMode)
3726 {
3727     GpStatus stat;
3728     GpPath *path;
3729
3730     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
3731
3732     if(!graphics || !brush || !points || !count)
3733         return InvalidParameter;
3734
3735     if(graphics->busy)
3736         return ObjectBusy;
3737
3738     stat = GdipCreatePath(fillMode, &path);
3739
3740     if (stat == Ok)
3741     {
3742         stat = GdipAddPathPolygon(path, points, count);
3743
3744         if (stat == Ok)
3745             stat = GdipFillPath(graphics, brush, path);
3746
3747         GdipDeletePath(path);
3748     }
3749
3750     return stat;
3751 }
3752
3753 GpStatus WINGDIPAPI GdipFillPolygonI(GpGraphics *graphics, GpBrush *brush,
3754     GDIPCONST GpPoint *points, INT count, GpFillMode fillMode)
3755 {
3756     GpStatus stat;
3757     GpPath *path;
3758
3759     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
3760
3761     if(!graphics || !brush || !points || !count)
3762         return InvalidParameter;
3763
3764     if(graphics->busy)
3765         return ObjectBusy;
3766
3767     stat = GdipCreatePath(fillMode, &path);
3768
3769     if (stat == Ok)
3770     {
3771         stat = GdipAddPathPolygonI(path, points, count);
3772
3773         if (stat == Ok)
3774             stat = GdipFillPath(graphics, brush, path);
3775
3776         GdipDeletePath(path);
3777     }
3778
3779     return stat;
3780 }
3781
3782 GpStatus WINGDIPAPI GdipFillPolygon2(GpGraphics *graphics, GpBrush *brush,
3783     GDIPCONST GpPointF *points, INT count)
3784 {
3785     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3786
3787     return GdipFillPolygon(graphics, brush, points, count, FillModeAlternate);
3788 }
3789
3790 GpStatus WINGDIPAPI GdipFillPolygon2I(GpGraphics *graphics, GpBrush *brush,
3791     GDIPCONST GpPoint *points, INT count)
3792 {
3793     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3794
3795     return GdipFillPolygonI(graphics, brush, points, count, FillModeAlternate);
3796 }
3797
3798 GpStatus WINGDIPAPI GdipFillRectangle(GpGraphics *graphics, GpBrush *brush,
3799     REAL x, REAL y, REAL width, REAL height)
3800 {
3801     GpStatus stat;
3802     GpPath *path;
3803
3804     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
3805
3806     if(!graphics || !brush)
3807         return InvalidParameter;
3808
3809     if(graphics->busy)
3810         return ObjectBusy;
3811
3812     stat = GdipCreatePath(FillModeAlternate, &path);
3813
3814     if (stat == Ok)
3815     {
3816         stat = GdipAddPathRectangle(path, x, y, width, height);
3817
3818         if (stat == Ok)
3819             stat = GdipFillPath(graphics, brush, path);
3820
3821         GdipDeletePath(path);
3822     }
3823
3824     return stat;
3825 }
3826
3827 GpStatus WINGDIPAPI GdipFillRectangleI(GpGraphics *graphics, GpBrush *brush,
3828     INT x, INT y, INT width, INT height)
3829 {
3830     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
3831
3832     return GdipFillRectangle(graphics, brush, x, y, width, height);
3833 }
3834
3835 GpStatus WINGDIPAPI GdipFillRectangles(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRectF *rects,
3836     INT count)
3837 {
3838     GpStatus status;
3839     GpPath *path;
3840
3841     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
3842
3843     if(!rects)
3844         return InvalidParameter;
3845
3846     status = GdipCreatePath(FillModeAlternate, &path);
3847     if (status != Ok) return status;
3848
3849     status = GdipAddPathRectangles(path, rects, count);
3850     if (status == Ok)
3851         status = GdipFillPath(graphics, brush, path);
3852
3853     GdipDeletePath(path);
3854     return status;
3855 }
3856
3857 GpStatus WINGDIPAPI GdipFillRectanglesI(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRect *rects,
3858     INT count)
3859 {
3860     GpRectF *rectsF;
3861     GpStatus ret;
3862     INT i;
3863
3864     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
3865
3866     if(!rects || count <= 0)
3867         return InvalidParameter;
3868
3869     rectsF = GdipAlloc(sizeof(GpRectF)*count);
3870     if(!rectsF)
3871         return OutOfMemory;
3872
3873     for(i = 0; i < count; i++){
3874         rectsF[i].X      = (REAL)rects[i].X;
3875         rectsF[i].Y      = (REAL)rects[i].Y;
3876         rectsF[i].X      = (REAL)rects[i].Width;
3877         rectsF[i].Height = (REAL)rects[i].Height;
3878     }
3879
3880     ret = GdipFillRectangles(graphics,brush,rectsF,count);
3881     GdipFree(rectsF);
3882
3883     return ret;
3884 }
3885
3886 static GpStatus GDI32_GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
3887     GpRegion* region)
3888 {
3889     INT save_state;
3890     GpStatus status;
3891     HRGN hrgn;
3892     RECT rc;
3893
3894     if(!graphics->hdc || !brush_can_fill_path(brush))
3895         return NotImplemented;
3896
3897     status = GdipGetRegionHRgn(region, graphics, &hrgn);
3898     if(status != Ok)
3899         return status;
3900
3901     save_state = SaveDC(graphics->hdc);
3902     EndPath(graphics->hdc);
3903
3904     ExtSelectClipRgn(graphics->hdc, hrgn, RGN_AND);
3905
3906     if (GetClipBox(graphics->hdc, &rc) != NULLREGION)
3907     {
3908         BeginPath(graphics->hdc);
3909         Rectangle(graphics->hdc, rc.left, rc.top, rc.right, rc.bottom);
3910         EndPath(graphics->hdc);
3911
3912         brush_fill_path(graphics, brush);
3913     }
3914
3915     RestoreDC(graphics->hdc, save_state);
3916
3917     DeleteObject(hrgn);
3918
3919     return Ok;
3920 }
3921
3922 static GpStatus SOFTWARE_GdipFillRegion(GpGraphics *graphics, GpBrush *brush,
3923     GpRegion* region)
3924 {
3925     GpStatus stat;
3926     GpRegion *temp_region;
3927     GpMatrix world_to_device;
3928     GpRectF graphics_bounds;
3929     DWORD *pixel_data;
3930     HRGN hregion;
3931     RECT bound_rect;
3932     GpRect gp_bound_rect;
3933
3934     if (!brush_can_fill_pixels(brush))
3935         return NotImplemented;
3936
3937     stat = get_graphics_bounds(graphics, &graphics_bounds);
3938
3939     if (stat == Ok)
3940         stat = GdipCloneRegion(region, &temp_region);
3941
3942     if (stat == Ok)
3943     {
3944         stat = get_graphics_transform(graphics, CoordinateSpaceDevice,
3945             CoordinateSpaceWorld, &world_to_device);
3946
3947         if (stat == Ok)
3948             stat = GdipTransformRegion(temp_region, &world_to_device);
3949
3950         if (stat == Ok)
3951             stat = GdipCombineRegionRect(temp_region, &graphics_bounds, CombineModeIntersect);
3952
3953         if (stat == Ok)
3954             stat = GdipGetRegionHRgn(temp_region, NULL, &hregion);
3955
3956         GdipDeleteRegion(temp_region);
3957     }
3958
3959     if (stat == Ok && GetRgnBox(hregion, &bound_rect) == NULLREGION)
3960     {
3961         DeleteObject(hregion);
3962         return Ok;
3963     }
3964
3965     if (stat == Ok)
3966     {
3967         gp_bound_rect.X = bound_rect.left;
3968         gp_bound_rect.Y = bound_rect.top;
3969         gp_bound_rect.Width = bound_rect.right - bound_rect.left;
3970         gp_bound_rect.Height = bound_rect.bottom - bound_rect.top;
3971
3972         pixel_data = GdipAlloc(sizeof(*pixel_data) * gp_bound_rect.Width * gp_bound_rect.Height);
3973         if (!pixel_data)
3974             stat = OutOfMemory;
3975
3976         if (stat == Ok)
3977         {
3978             stat = brush_fill_pixels(graphics, brush, pixel_data,
3979                 &gp_bound_rect, gp_bound_rect.Width);
3980
3981             if (stat == Ok)
3982                 stat = alpha_blend_pixels_hrgn(graphics, gp_bound_rect.X,
3983                     gp_bound_rect.Y, (BYTE*)pixel_data, gp_bound_rect.Width,
3984                     gp_bound_rect.Height, gp_bound_rect.Width * 4, hregion);
3985
3986             GdipFree(pixel_data);
3987         }
3988
3989         DeleteObject(hregion);
3990     }
3991
3992     return stat;
3993 }
3994
3995 /*****************************************************************************
3996  * GdipFillRegion [GDIPLUS.@]
3997  */
3998 GpStatus WINGDIPAPI GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
3999         GpRegion* region)
4000 {
4001     GpStatus stat = NotImplemented;
4002
4003     TRACE("(%p, %p, %p)\n", graphics, brush, region);
4004
4005     if (!(graphics && brush && region))
4006         return InvalidParameter;
4007
4008     if(graphics->busy)
4009         return ObjectBusy;
4010
4011     if (!graphics->image && !graphics->alpha_hdc)
4012         stat = GDI32_GdipFillRegion(graphics, brush, region);
4013
4014     if (stat == NotImplemented)
4015         stat = SOFTWARE_GdipFillRegion(graphics, brush, region);
4016
4017     if (stat == NotImplemented)
4018     {
4019         FIXME("not implemented for brushtype %i\n", brush->bt);
4020         stat = Ok;
4021     }
4022
4023     return stat;
4024 }
4025
4026 GpStatus WINGDIPAPI GdipFlush(GpGraphics *graphics, GpFlushIntention intention)
4027 {
4028     TRACE("(%p,%u)\n", graphics, intention);
4029
4030     if(!graphics)
4031         return InvalidParameter;
4032
4033     if(graphics->busy)
4034         return ObjectBusy;
4035
4036     /* We have no internal operation queue, so there's no need to clear it. */
4037
4038     if (graphics->hdc)
4039         GdiFlush();
4040
4041     return Ok;
4042 }
4043
4044 /*****************************************************************************
4045  * GdipGetClipBounds [GDIPLUS.@]
4046  */
4047 GpStatus WINGDIPAPI GdipGetClipBounds(GpGraphics *graphics, GpRectF *rect)
4048 {
4049     TRACE("(%p, %p)\n", graphics, rect);
4050
4051     if(!graphics)
4052         return InvalidParameter;
4053
4054     if(graphics->busy)
4055         return ObjectBusy;
4056
4057     return GdipGetRegionBounds(graphics->clip, graphics, rect);
4058 }
4059
4060 /*****************************************************************************
4061  * GdipGetClipBoundsI [GDIPLUS.@]
4062  */
4063 GpStatus WINGDIPAPI GdipGetClipBoundsI(GpGraphics *graphics, GpRect *rect)
4064 {
4065     TRACE("(%p, %p)\n", graphics, rect);
4066
4067     if(!graphics)
4068         return InvalidParameter;
4069
4070     if(graphics->busy)
4071         return ObjectBusy;
4072
4073     return GdipGetRegionBoundsI(graphics->clip, graphics, rect);
4074 }
4075
4076 /* FIXME: Compositing mode is not used anywhere except the getter/setter. */
4077 GpStatus WINGDIPAPI GdipGetCompositingMode(GpGraphics *graphics,
4078     CompositingMode *mode)
4079 {
4080     TRACE("(%p, %p)\n", graphics, mode);
4081
4082     if(!graphics || !mode)
4083         return InvalidParameter;
4084
4085     if(graphics->busy)
4086         return ObjectBusy;
4087
4088     *mode = graphics->compmode;
4089
4090     return Ok;
4091 }
4092
4093 /* FIXME: Compositing quality is not used anywhere except the getter/setter. */
4094 GpStatus WINGDIPAPI GdipGetCompositingQuality(GpGraphics *graphics,
4095     CompositingQuality *quality)
4096 {
4097     TRACE("(%p, %p)\n", graphics, quality);
4098
4099     if(!graphics || !quality)
4100         return InvalidParameter;
4101
4102     if(graphics->busy)
4103         return ObjectBusy;
4104
4105     *quality = graphics->compqual;
4106
4107     return Ok;
4108 }
4109
4110 /* FIXME: Interpolation mode is not used anywhere except the getter/setter. */
4111 GpStatus WINGDIPAPI GdipGetInterpolationMode(GpGraphics *graphics,
4112     InterpolationMode *mode)
4113 {
4114     TRACE("(%p, %p)\n", graphics, mode);
4115
4116     if(!graphics || !mode)
4117         return InvalidParameter;
4118
4119     if(graphics->busy)
4120         return ObjectBusy;
4121
4122     *mode = graphics->interpolation;
4123
4124     return Ok;
4125 }
4126
4127 /* FIXME: Need to handle color depths less than 24bpp */
4128 GpStatus WINGDIPAPI GdipGetNearestColor(GpGraphics *graphics, ARGB* argb)
4129 {
4130     FIXME("(%p, %p): Passing color unmodified\n", graphics, argb);
4131
4132     if(!graphics || !argb)
4133         return InvalidParameter;
4134
4135     if(graphics->busy)
4136         return ObjectBusy;
4137
4138     return Ok;
4139 }
4140
4141 GpStatus WINGDIPAPI GdipGetPageScale(GpGraphics *graphics, REAL *scale)
4142 {
4143     TRACE("(%p, %p)\n", graphics, scale);
4144
4145     if(!graphics || !scale)
4146         return InvalidParameter;
4147
4148     if(graphics->busy)
4149         return ObjectBusy;
4150
4151     *scale = graphics->scale;
4152
4153     return Ok;
4154 }
4155
4156 GpStatus WINGDIPAPI GdipGetPageUnit(GpGraphics *graphics, GpUnit *unit)
4157 {
4158     TRACE("(%p, %p)\n", graphics, unit);
4159
4160     if(!graphics || !unit)
4161         return InvalidParameter;
4162
4163     if(graphics->busy)
4164         return ObjectBusy;
4165
4166     *unit = graphics->unit;
4167
4168     return Ok;
4169 }
4170
4171 /* FIXME: Pixel offset mode is not used anywhere except the getter/setter. */
4172 GpStatus WINGDIPAPI GdipGetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
4173     *mode)
4174 {
4175     TRACE("(%p, %p)\n", graphics, mode);
4176
4177     if(!graphics || !mode)
4178         return InvalidParameter;
4179
4180     if(graphics->busy)
4181         return ObjectBusy;
4182
4183     *mode = graphics->pixeloffset;
4184
4185     return Ok;
4186 }
4187
4188 /* FIXME: Smoothing mode is not used anywhere except the getter/setter. */
4189 GpStatus WINGDIPAPI GdipGetSmoothingMode(GpGraphics *graphics, SmoothingMode *mode)
4190 {
4191     TRACE("(%p, %p)\n", graphics, mode);
4192
4193     if(!graphics || !mode)
4194         return InvalidParameter;
4195
4196     if(graphics->busy)
4197         return ObjectBusy;
4198
4199     *mode = graphics->smoothing;
4200
4201     return Ok;
4202 }
4203
4204 GpStatus WINGDIPAPI GdipGetTextContrast(GpGraphics *graphics, UINT *contrast)
4205 {
4206     TRACE("(%p, %p)\n", graphics, contrast);
4207
4208     if(!graphics || !contrast)
4209         return InvalidParameter;
4210
4211     *contrast = graphics->textcontrast;
4212
4213     return Ok;
4214 }
4215
4216 /* FIXME: Text rendering hint is not used anywhere except the getter/setter. */
4217 GpStatus WINGDIPAPI GdipGetTextRenderingHint(GpGraphics *graphics,
4218     TextRenderingHint *hint)
4219 {
4220     TRACE("(%p, %p)\n", graphics, hint);
4221
4222     if(!graphics || !hint)
4223         return InvalidParameter;
4224
4225     if(graphics->busy)
4226         return ObjectBusy;
4227
4228     *hint = graphics->texthint;
4229
4230     return Ok;
4231 }
4232
4233 GpStatus WINGDIPAPI GdipGetVisibleClipBounds(GpGraphics *graphics, GpRectF *rect)
4234 {
4235     GpRegion *clip_rgn;
4236     GpStatus stat;
4237
4238     TRACE("(%p, %p)\n", graphics, rect);
4239
4240     if(!graphics || !rect)
4241         return InvalidParameter;
4242
4243     if(graphics->busy)
4244         return ObjectBusy;
4245
4246     /* intersect window and graphics clipping regions */
4247     if((stat = GdipCreateRegion(&clip_rgn)) != Ok)
4248         return stat;
4249
4250     if((stat = get_visible_clip_region(graphics, clip_rgn)) != Ok)
4251         goto cleanup;
4252
4253     /* get bounds of the region */
4254     stat = GdipGetRegionBounds(clip_rgn, graphics, rect);
4255
4256 cleanup:
4257     GdipDeleteRegion(clip_rgn);
4258
4259     return stat;
4260 }
4261
4262 GpStatus WINGDIPAPI GdipGetVisibleClipBoundsI(GpGraphics *graphics, GpRect *rect)
4263 {
4264     GpRectF rectf;
4265     GpStatus stat;
4266
4267     TRACE("(%p, %p)\n", graphics, rect);
4268
4269     if(!graphics || !rect)
4270         return InvalidParameter;
4271
4272     if((stat = GdipGetVisibleClipBounds(graphics, &rectf)) == Ok)
4273     {
4274         rect->X = gdip_round(rectf.X);
4275         rect->Y = gdip_round(rectf.Y);
4276         rect->Width  = gdip_round(rectf.Width);
4277         rect->Height = gdip_round(rectf.Height);
4278     }
4279
4280     return stat;
4281 }
4282
4283 GpStatus WINGDIPAPI GdipGetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
4284 {
4285     TRACE("(%p, %p)\n", graphics, matrix);
4286
4287     if(!graphics || !matrix)
4288         return InvalidParameter;
4289
4290     if(graphics->busy)
4291         return ObjectBusy;
4292
4293     *matrix = graphics->worldtrans;
4294     return Ok;
4295 }
4296
4297 GpStatus WINGDIPAPI GdipGraphicsClear(GpGraphics *graphics, ARGB color)
4298 {
4299     GpSolidFill *brush;
4300     GpStatus stat;
4301     GpRectF wnd_rect;
4302
4303     TRACE("(%p, %x)\n", graphics, color);
4304
4305     if(!graphics)
4306         return InvalidParameter;
4307
4308     if(graphics->busy)
4309         return ObjectBusy;
4310
4311     if((stat = GdipCreateSolidFill(color, &brush)) != Ok)
4312         return stat;
4313
4314     if((stat = get_graphics_bounds(graphics, &wnd_rect)) != Ok){
4315         GdipDeleteBrush((GpBrush*)brush);
4316         return stat;
4317     }
4318
4319     GdipFillRectangle(graphics, (GpBrush*)brush, wnd_rect.X, wnd_rect.Y,
4320                                                  wnd_rect.Width, wnd_rect.Height);
4321
4322     GdipDeleteBrush((GpBrush*)brush);
4323
4324     return Ok;
4325 }
4326
4327 GpStatus WINGDIPAPI GdipIsClipEmpty(GpGraphics *graphics, BOOL *res)
4328 {
4329     TRACE("(%p, %p)\n", graphics, res);
4330
4331     if(!graphics || !res)
4332         return InvalidParameter;
4333
4334     return GdipIsEmptyRegion(graphics->clip, graphics, res);
4335 }
4336
4337 GpStatus WINGDIPAPI GdipIsVisiblePoint(GpGraphics *graphics, REAL x, REAL y, BOOL *result)
4338 {
4339     GpStatus stat;
4340     GpRegion* rgn;
4341     GpPointF pt;
4342
4343     TRACE("(%p, %.2f, %.2f, %p)\n", graphics, x, y, result);
4344
4345     if(!graphics || !result)
4346         return InvalidParameter;
4347
4348     if(graphics->busy)
4349         return ObjectBusy;
4350
4351     pt.X = x;
4352     pt.Y = y;
4353     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4354                    CoordinateSpaceWorld, &pt, 1)) != Ok)
4355         return stat;
4356
4357     if((stat = GdipCreateRegion(&rgn)) != Ok)
4358         return stat;
4359
4360     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4361         goto cleanup;
4362
4363     stat = GdipIsVisibleRegionPoint(rgn, pt.X, pt.Y, graphics, result);
4364
4365 cleanup:
4366     GdipDeleteRegion(rgn);
4367     return stat;
4368 }
4369
4370 GpStatus WINGDIPAPI GdipIsVisiblePointI(GpGraphics *graphics, INT x, INT y, BOOL *result)
4371 {
4372     return GdipIsVisiblePoint(graphics, (REAL)x, (REAL)y, result);
4373 }
4374
4375 GpStatus WINGDIPAPI GdipIsVisibleRect(GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, BOOL *result)
4376 {
4377     GpStatus stat;
4378     GpRegion* rgn;
4379     GpPointF pts[2];
4380
4381     TRACE("(%p %.2f %.2f %.2f %.2f %p)\n", graphics, x, y, width, height, result);
4382
4383     if(!graphics || !result)
4384         return InvalidParameter;
4385
4386     if(graphics->busy)
4387         return ObjectBusy;
4388
4389     pts[0].X = x;
4390     pts[0].Y = y;
4391     pts[1].X = x + width;
4392     pts[1].Y = y + height;
4393
4394     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4395                     CoordinateSpaceWorld, pts, 2)) != Ok)
4396         return stat;
4397
4398     pts[1].X -= pts[0].X;
4399     pts[1].Y -= pts[0].Y;
4400
4401     if((stat = GdipCreateRegion(&rgn)) != Ok)
4402         return stat;
4403
4404     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4405         goto cleanup;
4406
4407     stat = GdipIsVisibleRegionRect(rgn, pts[0].X, pts[0].Y, pts[1].X, pts[1].Y, graphics, result);
4408
4409 cleanup:
4410     GdipDeleteRegion(rgn);
4411     return stat;
4412 }
4413
4414 GpStatus WINGDIPAPI GdipIsVisibleRectI(GpGraphics *graphics, INT x, INT y, INT width, INT height, BOOL *result)
4415 {
4416     return GdipIsVisibleRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, result);
4417 }
4418
4419 GpStatus gdip_format_string(HDC hdc,
4420     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
4421     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format, int ignore_empty_clip,
4422     gdip_format_string_callback callback, void *user_data)
4423 {
4424     WCHAR* stringdup;
4425     int sum = 0, height = 0, fit, fitcpy, i, j, lret, nwidth,
4426         nheight, lineend, lineno = 0;
4427     RectF bounds;
4428     StringAlignment halign;
4429     GpStatus stat = Ok;
4430     SIZE size;
4431     HotkeyPrefix hkprefix;
4432     INT *hotkeyprefix_offsets=NULL;
4433     INT hotkeyprefix_count=0;
4434     INT hotkeyprefix_pos=0, hotkeyprefix_end_pos=0;
4435     int seen_prefix=0;
4436
4437     if(length == -1) length = lstrlenW(string);
4438
4439     stringdup = GdipAlloc((length + 1) * sizeof(WCHAR));
4440     if(!stringdup) return OutOfMemory;
4441
4442     nwidth = rect->Width;
4443     nheight = rect->Height;
4444     if (ignore_empty_clip)
4445     {
4446         if (!nwidth) nwidth = INT_MAX;
4447         if (!nheight) nheight = INT_MAX;
4448     }
4449
4450     if (format)
4451         hkprefix = format->hkprefix;
4452     else
4453         hkprefix = HotkeyPrefixNone;
4454
4455     if (hkprefix == HotkeyPrefixShow)
4456     {
4457         for (i=0; i<length; i++)
4458         {
4459             if (string[i] == '&')
4460                 hotkeyprefix_count++;
4461         }
4462     }
4463
4464     if (hotkeyprefix_count)
4465         hotkeyprefix_offsets = GdipAlloc(sizeof(INT) * hotkeyprefix_count);
4466
4467     hotkeyprefix_count = 0;
4468
4469     for(i = 0, j = 0; i < length; i++){
4470         /* FIXME: This makes the indexes passed to callback inaccurate. */
4471         if(!isprintW(string[i]) && (string[i] != '\n'))
4472             continue;
4473
4474         /* FIXME: tabs should be handled using tabstops from stringformat */
4475         if (string[i] == '\t')
4476             continue;
4477
4478         if (seen_prefix && hkprefix == HotkeyPrefixShow && string[i] != '&')
4479             hotkeyprefix_offsets[hotkeyprefix_count++] = j;
4480         else if (!seen_prefix && hkprefix != HotkeyPrefixNone && string[i] == '&')
4481         {
4482             seen_prefix = 1;
4483             continue;
4484         }
4485
4486         seen_prefix = 0;
4487
4488         stringdup[j] = string[i];
4489         j++;
4490     }
4491
4492     length = j;
4493
4494     if (format) halign = format->align;
4495     else halign = StringAlignmentNear;
4496
4497     while(sum < length){
4498         GetTextExtentExPointW(hdc, stringdup + sum, length - sum,
4499                               nwidth, &fit, NULL, &size);
4500         fitcpy = fit;
4501
4502         if(fit == 0)
4503             break;
4504
4505         for(lret = 0; lret < fit; lret++)
4506             if(*(stringdup + sum + lret) == '\n')
4507                 break;
4508
4509         /* Line break code (may look strange, but it imitates windows). */
4510         if(lret < fit)
4511             lineend = fit = lret;    /* this is not an off-by-one error */
4512         else if(fit < (length - sum)){
4513             if(*(stringdup + sum + fit) == ' ')
4514                 while(*(stringdup + sum + fit) == ' ')
4515                     fit++;
4516             else
4517                 while(*(stringdup + sum + fit - 1) != ' '){
4518                     fit--;
4519
4520                     if(*(stringdup + sum + fit) == '\t')
4521                         break;
4522
4523                     if(fit == 0){
4524                         fit = fitcpy;
4525                         break;
4526                     }
4527                 }
4528             lineend = fit;
4529             while(*(stringdup + sum + lineend - 1) == ' ' ||
4530                   *(stringdup + sum + lineend - 1) == '\t')
4531                 lineend--;
4532         }
4533         else
4534             lineend = fit;
4535
4536         GetTextExtentExPointW(hdc, stringdup + sum, lineend,
4537                               nwidth, &j, NULL, &size);
4538
4539         bounds.Width = size.cx;
4540
4541         if(height + size.cy > nheight)
4542             bounds.Height = nheight - (height + size.cy);
4543         else
4544             bounds.Height = size.cy;
4545
4546         bounds.Y = rect->Y + height;
4547
4548         switch (halign)
4549         {
4550         case StringAlignmentNear:
4551         default:
4552             bounds.X = rect->X;
4553             break;
4554         case StringAlignmentCenter:
4555             bounds.X = rect->X + (rect->Width/2) - (bounds.Width/2);
4556             break;
4557         case StringAlignmentFar:
4558             bounds.X = rect->X + rect->Width - bounds.Width;
4559             break;
4560         }
4561
4562         for (hotkeyprefix_end_pos=hotkeyprefix_pos; hotkeyprefix_end_pos<hotkeyprefix_count; hotkeyprefix_end_pos++)
4563             if (hotkeyprefix_offsets[hotkeyprefix_end_pos] >= sum + lineend)
4564                 break;
4565
4566         stat = callback(hdc, stringdup, sum, lineend,
4567             font, rect, format, lineno, &bounds,
4568             &hotkeyprefix_offsets[hotkeyprefix_pos],
4569             hotkeyprefix_end_pos-hotkeyprefix_pos, user_data);
4570
4571         if (stat != Ok)
4572             break;
4573
4574         sum += fit + (lret < fitcpy ? 1 : 0);
4575         height += size.cy;
4576         lineno++;
4577
4578         hotkeyprefix_pos = hotkeyprefix_end_pos;
4579
4580         if(height > nheight)
4581             break;
4582
4583         /* Stop if this was a linewrap (but not if it was a linebreak). */
4584         if ((lret == fitcpy) && format &&
4585             (format->attr & (StringFormatFlagsNoWrap | StringFormatFlagsLineLimit)))
4586             break;
4587     }
4588
4589     GdipFree(stringdup);
4590     GdipFree(hotkeyprefix_offsets);
4591
4592     return stat;
4593 }
4594
4595 struct measure_ranges_args {
4596     GpRegion **regions;
4597     REAL rel_width, rel_height;
4598 };
4599
4600 static GpStatus measure_ranges_callback(HDC hdc,
4601     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
4602     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4603     INT lineno, const RectF *bounds, INT *underlined_indexes,
4604     INT underlined_index_count, void *user_data)
4605 {
4606     int i;
4607     GpStatus stat = Ok;
4608     struct measure_ranges_args *args = user_data;
4609
4610     for (i=0; i<format->range_count; i++)
4611     {
4612         INT range_start = max(index, format->character_ranges[i].First);
4613         INT range_end = min(index+length, format->character_ranges[i].First+format->character_ranges[i].Length);
4614         if (range_start < range_end)
4615         {
4616             GpRectF range_rect;
4617             SIZE range_size;
4618
4619             range_rect.Y = bounds->Y / args->rel_height;
4620             range_rect.Height = bounds->Height / args->rel_height;
4621
4622             GetTextExtentExPointW(hdc, string + index, range_start - index,
4623                                   INT_MAX, NULL, NULL, &range_size);
4624             range_rect.X = (bounds->X + range_size.cx) / args->rel_width;
4625
4626             GetTextExtentExPointW(hdc, string + index, range_end - index,
4627                                   INT_MAX, NULL, NULL, &range_size);
4628             range_rect.Width = (bounds->X + range_size.cx) / args->rel_width - range_rect.X;
4629
4630             stat = GdipCombineRegionRect(args->regions[i], &range_rect, CombineModeUnion);
4631             if (stat != Ok)
4632                 break;
4633         }
4634     }
4635
4636     return stat;
4637 }
4638
4639 GpStatus WINGDIPAPI GdipMeasureCharacterRanges(GpGraphics* graphics,
4640         GDIPCONST WCHAR* string, INT length, GDIPCONST GpFont* font,
4641         GDIPCONST RectF* layoutRect, GDIPCONST GpStringFormat *stringFormat,
4642         INT regionCount, GpRegion** regions)
4643 {
4644     GpStatus stat;
4645     int i;
4646     HFONT gdifont, oldfont;
4647     struct measure_ranges_args args;
4648     HDC hdc, temp_hdc=NULL;
4649     GpPointF pt[3];
4650     RectF scaled_rect;
4651     REAL margin_x;
4652
4653     TRACE("(%p %s %d %p %s %p %d %p)\n", graphics, debugstr_w(string),
4654             length, font, debugstr_rectf(layoutRect), stringFormat, regionCount, regions);
4655
4656     if (!(graphics && string && font && layoutRect && stringFormat && regions))
4657         return InvalidParameter;
4658
4659     if (regionCount < stringFormat->range_count)
4660         return InvalidParameter;
4661
4662     if(!graphics->hdc)
4663     {
4664         hdc = temp_hdc = CreateCompatibleDC(0);
4665         if (!temp_hdc) return OutOfMemory;
4666     }
4667     else
4668         hdc = graphics->hdc;
4669
4670     if (stringFormat->attr)
4671         TRACE("may be ignoring some format flags: attr %x\n", stringFormat->attr);
4672
4673     pt[0].X = 0.0;
4674     pt[0].Y = 0.0;
4675     pt[1].X = 1.0;
4676     pt[1].Y = 0.0;
4677     pt[2].X = 0.0;
4678     pt[2].Y = 1.0;
4679     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
4680     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
4681                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
4682     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
4683                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
4684
4685     margin_x = stringFormat->generic_typographic ? 0.0 : font->emSize / 6.0;
4686     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
4687
4688     scaled_rect.X = (layoutRect->X + margin_x) * args.rel_width;
4689     scaled_rect.Y = layoutRect->Y * args.rel_height;
4690     scaled_rect.Width = layoutRect->Width * args.rel_width;
4691     scaled_rect.Height = layoutRect->Height * args.rel_height;
4692
4693     get_font_hfont(graphics, font, stringFormat, &gdifont, NULL);
4694     oldfont = SelectObject(hdc, gdifont);
4695
4696     for (i=0; i<stringFormat->range_count; i++)
4697     {
4698         stat = GdipSetEmpty(regions[i]);
4699         if (stat != Ok)
4700             return stat;
4701     }
4702
4703     args.regions = regions;
4704
4705     stat = gdip_format_string(hdc, string, length, font, &scaled_rect, stringFormat,
4706         (stringFormat->attr & StringFormatFlagsNoClip) != 0, measure_ranges_callback, &args);
4707
4708     SelectObject(hdc, oldfont);
4709     DeleteObject(gdifont);
4710
4711     if (temp_hdc)
4712         DeleteDC(temp_hdc);
4713
4714     return stat;
4715 }
4716
4717 struct measure_string_args {
4718     RectF *bounds;
4719     INT *codepointsfitted;
4720     INT *linesfilled;
4721     REAL rel_width, rel_height;
4722 };
4723
4724 static GpStatus measure_string_callback(HDC hdc,
4725     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
4726     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4727     INT lineno, const RectF *bounds, INT *underlined_indexes,
4728     INT underlined_index_count, void *user_data)
4729 {
4730     struct measure_string_args *args = user_data;
4731     REAL new_width, new_height;
4732
4733     new_width = bounds->Width / args->rel_width;
4734     new_height = (bounds->Height + bounds->Y) / args->rel_height - args->bounds->Y;
4735
4736     if (new_width > args->bounds->Width)
4737         args->bounds->Width = new_width;
4738
4739     if (new_height > args->bounds->Height)
4740         args->bounds->Height = new_height;
4741
4742     if (args->codepointsfitted)
4743         *args->codepointsfitted = index + length;
4744
4745     if (args->linesfilled)
4746         (*args->linesfilled)++;
4747
4748     return Ok;
4749 }
4750
4751 /* Find the smallest rectangle that bounds the text when it is printed in rect
4752  * according to the format options listed in format. If rect has 0 width and
4753  * height, then just find the smallest rectangle that bounds the text when it's
4754  * printed at location (rect->X, rect-Y). */
4755 GpStatus WINGDIPAPI GdipMeasureString(GpGraphics *graphics,
4756     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
4757     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format, RectF *bounds,
4758     INT *codepointsfitted, INT *linesfilled)
4759 {
4760     HFONT oldfont, gdifont;
4761     struct measure_string_args args;
4762     HDC temp_hdc=NULL, hdc;
4763     GpPointF pt[3];
4764     RectF scaled_rect;
4765     REAL margin_x;
4766     INT lines, glyphs;
4767
4768     TRACE("(%p, %s, %i, %p, %s, %p, %p, %p, %p)\n", graphics,
4769         debugstr_wn(string, length), length, font, debugstr_rectf(rect), format,
4770         bounds, codepointsfitted, linesfilled);
4771
4772     if(!graphics || !string || !font || !rect || !bounds)
4773         return InvalidParameter;
4774
4775     if(!graphics->hdc)
4776     {
4777         hdc = temp_hdc = CreateCompatibleDC(0);
4778         if (!temp_hdc) return OutOfMemory;
4779     }
4780     else
4781         hdc = graphics->hdc;
4782
4783     if(linesfilled) *linesfilled = 0;
4784     if(codepointsfitted) *codepointsfitted = 0;
4785
4786     if(format)
4787         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
4788
4789     pt[0].X = 0.0;
4790     pt[0].Y = 0.0;
4791     pt[1].X = 1.0;
4792     pt[1].Y = 0.0;
4793     pt[2].X = 0.0;
4794     pt[2].Y = 1.0;
4795     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
4796     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
4797                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
4798     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
4799                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
4800
4801     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
4802     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
4803
4804     scaled_rect.X = (rect->X + margin_x) * args.rel_width;
4805     scaled_rect.Y = rect->Y * args.rel_height;
4806     scaled_rect.Width = rect->Width * args.rel_width;
4807     scaled_rect.Height = rect->Height * args.rel_height;
4808     if (scaled_rect.Width >= 0.5)
4809     {
4810         scaled_rect.Width -= margin_x * 2.0 * args.rel_width;
4811         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
4812     }
4813
4814     if (scaled_rect.Width >= 1 << 23) scaled_rect.Width = 1 << 23;
4815     if (scaled_rect.Height >= 1 << 23) scaled_rect.Height = 1 << 23;
4816
4817     get_font_hfont(graphics, font, format, &gdifont, NULL);
4818     oldfont = SelectObject(hdc, gdifont);
4819
4820     bounds->X = rect->X;
4821     bounds->Y = rect->Y;
4822     bounds->Width = 0.0;
4823     bounds->Height = 0.0;
4824
4825     args.bounds = bounds;
4826     args.codepointsfitted = &glyphs;
4827     args.linesfilled = &lines;
4828     lines = glyphs = 0;
4829
4830     gdip_format_string(hdc, string, length, font, &scaled_rect, format, TRUE,
4831         measure_string_callback, &args);
4832
4833     if (linesfilled) *linesfilled = lines;
4834     if (codepointsfitted) *codepointsfitted = glyphs;
4835
4836     if (lines)
4837         bounds->Width += margin_x * 2.0;
4838
4839     SelectObject(hdc, oldfont);
4840     DeleteObject(gdifont);
4841
4842     if (temp_hdc)
4843         DeleteDC(temp_hdc);
4844
4845     return Ok;
4846 }
4847
4848 struct draw_string_args {
4849     GpGraphics *graphics;
4850     GDIPCONST GpBrush *brush;
4851     REAL x, y, rel_width, rel_height, ascent;
4852 };
4853
4854 static GpStatus draw_string_callback(HDC hdc,
4855     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
4856     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4857     INT lineno, const RectF *bounds, INT *underlined_indexes,
4858     INT underlined_index_count, void *user_data)
4859 {
4860     struct draw_string_args *args = user_data;
4861     PointF position;
4862     GpStatus stat;
4863
4864     position.X = args->x + bounds->X / args->rel_width;
4865     position.Y = args->y + bounds->Y / args->rel_height + args->ascent;
4866
4867     stat = draw_driver_string(args->graphics, &string[index], length, font, format,
4868         args->brush, &position,
4869         DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance, NULL);
4870
4871     if (stat == Ok && underlined_index_count)
4872     {
4873         OUTLINETEXTMETRICW otm;
4874         REAL underline_y, underline_height;
4875         int i;
4876
4877         GetOutlineTextMetricsW(hdc, sizeof(otm), &otm);
4878
4879         underline_height = otm.otmsUnderscoreSize / args->rel_height;
4880         underline_y = position.Y - otm.otmsUnderscorePosition / args->rel_height - underline_height / 2;
4881
4882         for (i=0; i<underlined_index_count; i++)
4883         {
4884             REAL start_x, end_x;
4885             SIZE text_size;
4886             INT ofs = underlined_indexes[i] - index;
4887
4888             GetTextExtentExPointW(hdc, string + index, ofs, INT_MAX, NULL, NULL, &text_size);
4889             start_x = text_size.cx / args->rel_width;
4890
4891             GetTextExtentExPointW(hdc, string + index, ofs+1, INT_MAX, NULL, NULL, &text_size);
4892             end_x = text_size.cx / args->rel_width;
4893
4894             GdipFillRectangle(args->graphics, (GpBrush*)args->brush, position.X+start_x, underline_y, end_x-start_x, underline_height);
4895         }
4896     }
4897
4898     return stat;
4899 }
4900
4901 GpStatus WINGDIPAPI GdipDrawString(GpGraphics *graphics, GDIPCONST WCHAR *string,
4902     INT length, GDIPCONST GpFont *font, GDIPCONST RectF *rect,
4903     GDIPCONST GpStringFormat *format, GDIPCONST GpBrush *brush)
4904 {
4905     HRGN rgn = NULL;
4906     HFONT gdifont;
4907     GpPointF pt[3], rectcpy[4];
4908     POINT corners[4];
4909     REAL rel_width, rel_height, margin_x;
4910     INT save_state, format_flags = 0;
4911     REAL offsety = 0.0;
4912     struct draw_string_args args;
4913     RectF scaled_rect;
4914     HDC hdc, temp_hdc=NULL;
4915     TEXTMETRICW textmetric;
4916
4917     TRACE("(%p, %s, %i, %p, %s, %p, %p)\n", graphics, debugstr_wn(string, length),
4918         length, font, debugstr_rectf(rect), format, brush);
4919
4920     if(!graphics || !string || !font || !brush || !rect)
4921         return InvalidParameter;
4922
4923     if(graphics->hdc)
4924     {
4925         hdc = graphics->hdc;
4926     }
4927     else
4928     {
4929         hdc = temp_hdc = CreateCompatibleDC(0);
4930     }
4931
4932     if(format){
4933         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
4934
4935         format_flags = format->attr;
4936
4937         /* Should be no need to explicitly test for StringAlignmentNear as
4938          * that is default behavior if no alignment is passed. */
4939         if(format->vertalign != StringAlignmentNear){
4940             RectF bounds, in_rect = *rect;
4941             in_rect.Height = 0.0; /* avoid height clipping */
4942             GdipMeasureString(graphics, string, length, font, &in_rect, format, &bounds, 0, 0);
4943
4944             TRACE("bounds %s\n", debugstr_rectf(&bounds));
4945
4946             if(format->vertalign == StringAlignmentCenter)
4947                 offsety = (rect->Height - bounds.Height) / 2;
4948             else if(format->vertalign == StringAlignmentFar)
4949                 offsety = (rect->Height - bounds.Height);
4950         }
4951         TRACE("vertical align %d, offsety %f\n", format->vertalign, offsety);
4952     }
4953
4954     save_state = SaveDC(hdc);
4955
4956     pt[0].X = 0.0;
4957     pt[0].Y = 0.0;
4958     pt[1].X = 1.0;
4959     pt[1].Y = 0.0;
4960     pt[2].X = 0.0;
4961     pt[2].Y = 1.0;
4962     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
4963     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
4964                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
4965     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
4966                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
4967
4968     rectcpy[3].X = rectcpy[0].X = rect->X;
4969     rectcpy[1].Y = rectcpy[0].Y = rect->Y;
4970     rectcpy[2].X = rectcpy[1].X = rect->X + rect->Width;
4971     rectcpy[3].Y = rectcpy[2].Y = rect->Y + rect->Height;
4972     transform_and_round_points(graphics, corners, rectcpy, 4);
4973
4974     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
4975     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
4976
4977     scaled_rect.X = margin_x * rel_width;
4978     scaled_rect.Y = 0.0;
4979     scaled_rect.Width = rel_width * rect->Width;
4980     scaled_rect.Height = rel_height * rect->Height;
4981     if (scaled_rect.Width >= 0.5)
4982     {
4983         scaled_rect.Width -= margin_x * 2.0 * rel_width;
4984         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
4985     }
4986
4987     if (scaled_rect.Width >= 1 << 23) scaled_rect.Width = 1 << 23;
4988     if (scaled_rect.Height >= 1 << 23) scaled_rect.Height = 1 << 23;
4989
4990     if (!(format_flags & StringFormatFlagsNoClip) &&
4991         scaled_rect.Width != 1 << 23 && scaled_rect.Height != 1 << 23)
4992     {
4993         /* FIXME: If only the width or only the height is 0, we should probably still clip */
4994         rgn = CreatePolygonRgn(corners, 4, ALTERNATE);
4995         SelectClipRgn(hdc, rgn);
4996     }
4997
4998     get_font_hfont(graphics, font, format, &gdifont, NULL);
4999     SelectObject(hdc, gdifont);
5000
5001     args.graphics = graphics;
5002     args.brush = brush;
5003
5004     args.x = rect->X;
5005     args.y = rect->Y + offsety;
5006
5007     args.rel_width = rel_width;
5008     args.rel_height = rel_height;
5009
5010     GetTextMetricsW(hdc, &textmetric);
5011     args.ascent = textmetric.tmAscent / rel_height;
5012
5013     gdip_format_string(hdc, string, length, font, &scaled_rect, format, TRUE,
5014         draw_string_callback, &args);
5015
5016     DeleteObject(rgn);
5017     DeleteObject(gdifont);
5018
5019     RestoreDC(hdc, save_state);
5020
5021     DeleteDC(temp_hdc);
5022
5023     return Ok;
5024 }
5025
5026 GpStatus WINGDIPAPI GdipResetClip(GpGraphics *graphics)
5027 {
5028     TRACE("(%p)\n", graphics);
5029
5030     if(!graphics)
5031         return InvalidParameter;
5032
5033     if(graphics->busy)
5034         return ObjectBusy;
5035
5036     return GdipSetInfinite(graphics->clip);
5037 }
5038
5039 GpStatus WINGDIPAPI GdipResetWorldTransform(GpGraphics *graphics)
5040 {
5041     TRACE("(%p)\n", graphics);
5042
5043     if(!graphics)
5044         return InvalidParameter;
5045
5046     if(graphics->busy)
5047         return ObjectBusy;
5048
5049     return GdipSetMatrixElements(&graphics->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
5050 }
5051
5052 GpStatus WINGDIPAPI GdipRestoreGraphics(GpGraphics *graphics, GraphicsState state)
5053 {
5054     return GdipEndContainer(graphics, state);
5055 }
5056
5057 GpStatus WINGDIPAPI GdipRotateWorldTransform(GpGraphics *graphics, REAL angle,
5058     GpMatrixOrder order)
5059 {
5060     TRACE("(%p, %.2f, %d)\n", graphics, angle, order);
5061
5062     if(!graphics)
5063         return InvalidParameter;
5064
5065     if(graphics->busy)
5066         return ObjectBusy;
5067
5068     return GdipRotateMatrix(&graphics->worldtrans, angle, order);
5069 }
5070
5071 GpStatus WINGDIPAPI GdipSaveGraphics(GpGraphics *graphics, GraphicsState *state)
5072 {
5073     return GdipBeginContainer2(graphics, state);
5074 }
5075
5076 GpStatus WINGDIPAPI GdipBeginContainer2(GpGraphics *graphics,
5077         GraphicsContainer *state)
5078 {
5079     GraphicsContainerItem *container;
5080     GpStatus sts;
5081
5082     TRACE("(%p, %p)\n", graphics, state);
5083
5084     if(!graphics || !state)
5085         return InvalidParameter;
5086
5087     sts = init_container(&container, graphics);
5088     if(sts != Ok)
5089         return sts;
5090
5091     list_add_head(&graphics->containers, &container->entry);
5092     *state = graphics->contid = container->contid;
5093
5094     return Ok;
5095 }
5096
5097 GpStatus WINGDIPAPI GdipBeginContainer(GpGraphics *graphics, GDIPCONST GpRectF *dstrect, GDIPCONST GpRectF *srcrect, GpUnit unit, GraphicsContainer *state)
5098 {
5099     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5100     return NotImplemented;
5101 }
5102
5103 GpStatus WINGDIPAPI GdipBeginContainerI(GpGraphics *graphics, GDIPCONST GpRect *dstrect, GDIPCONST GpRect *srcrect, GpUnit unit, GraphicsContainer *state)
5104 {
5105     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5106     return NotImplemented;
5107 }
5108
5109 GpStatus WINGDIPAPI GdipComment(GpGraphics *graphics, UINT sizeData, GDIPCONST BYTE *data)
5110 {
5111     FIXME("(%p, %d, %p): stub\n", graphics, sizeData, data);
5112     return NotImplemented;
5113 }
5114
5115 GpStatus WINGDIPAPI GdipEndContainer(GpGraphics *graphics, GraphicsContainer state)
5116 {
5117     GpStatus sts;
5118     GraphicsContainerItem *container, *container2;
5119
5120     TRACE("(%p, %x)\n", graphics, state);
5121
5122     if(!graphics)
5123         return InvalidParameter;
5124
5125     LIST_FOR_EACH_ENTRY(container, &graphics->containers, GraphicsContainerItem, entry){
5126         if(container->contid == state)
5127             break;
5128     }
5129
5130     /* did not find a matching container */
5131     if(&container->entry == &graphics->containers)
5132         return Ok;
5133
5134     sts = restore_container(graphics, container);
5135     if(sts != Ok)
5136         return sts;
5137
5138     /* remove all of the containers on top of the found container */
5139     LIST_FOR_EACH_ENTRY_SAFE(container, container2, &graphics->containers, GraphicsContainerItem, entry){
5140         if(container->contid == state)
5141             break;
5142         list_remove(&container->entry);
5143         delete_container(container);
5144     }
5145
5146     list_remove(&container->entry);
5147     delete_container(container);
5148
5149     return Ok;
5150 }
5151
5152 GpStatus WINGDIPAPI GdipScaleWorldTransform(GpGraphics *graphics, REAL sx,
5153     REAL sy, GpMatrixOrder order)
5154 {
5155     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, sx, sy, order);
5156
5157     if(!graphics)
5158         return InvalidParameter;
5159
5160     if(graphics->busy)
5161         return ObjectBusy;
5162
5163     return GdipScaleMatrix(&graphics->worldtrans, sx, sy, order);
5164 }
5165
5166 GpStatus WINGDIPAPI GdipSetClipGraphics(GpGraphics *graphics, GpGraphics *srcgraphics,
5167     CombineMode mode)
5168 {
5169     TRACE("(%p, %p, %d)\n", graphics, srcgraphics, mode);
5170
5171     if(!graphics || !srcgraphics)
5172         return InvalidParameter;
5173
5174     return GdipCombineRegionRegion(graphics->clip, srcgraphics->clip, mode);
5175 }
5176
5177 GpStatus WINGDIPAPI GdipSetCompositingMode(GpGraphics *graphics,
5178     CompositingMode mode)
5179 {
5180     TRACE("(%p, %d)\n", graphics, mode);
5181
5182     if(!graphics)
5183         return InvalidParameter;
5184
5185     if(graphics->busy)
5186         return ObjectBusy;
5187
5188     graphics->compmode = mode;
5189
5190     return Ok;
5191 }
5192
5193 GpStatus WINGDIPAPI GdipSetCompositingQuality(GpGraphics *graphics,
5194     CompositingQuality quality)
5195 {
5196     TRACE("(%p, %d)\n", graphics, quality);
5197
5198     if(!graphics)
5199         return InvalidParameter;
5200
5201     if(graphics->busy)
5202         return ObjectBusy;
5203
5204     graphics->compqual = quality;
5205
5206     return Ok;
5207 }
5208
5209 GpStatus WINGDIPAPI GdipSetInterpolationMode(GpGraphics *graphics,
5210     InterpolationMode mode)
5211 {
5212     TRACE("(%p, %d)\n", graphics, mode);
5213
5214     if(!graphics || mode == InterpolationModeInvalid || mode > InterpolationModeHighQualityBicubic)
5215         return InvalidParameter;
5216
5217     if(graphics->busy)
5218         return ObjectBusy;
5219
5220     if (mode == InterpolationModeDefault || mode == InterpolationModeLowQuality)
5221         mode = InterpolationModeBilinear;
5222
5223     if (mode == InterpolationModeHighQuality)
5224         mode = InterpolationModeHighQualityBicubic;
5225
5226     graphics->interpolation = mode;
5227
5228     return Ok;
5229 }
5230
5231 GpStatus WINGDIPAPI GdipSetPageScale(GpGraphics *graphics, REAL scale)
5232 {
5233     TRACE("(%p, %.2f)\n", graphics, scale);
5234
5235     if(!graphics || (scale <= 0.0))
5236         return InvalidParameter;
5237
5238     if(graphics->busy)
5239         return ObjectBusy;
5240
5241     graphics->scale = scale;
5242
5243     return Ok;
5244 }
5245
5246 GpStatus WINGDIPAPI GdipSetPageUnit(GpGraphics *graphics, GpUnit unit)
5247 {
5248     TRACE("(%p, %d)\n", graphics, unit);
5249
5250     if(!graphics)
5251         return InvalidParameter;
5252
5253     if(graphics->busy)
5254         return ObjectBusy;
5255
5256     if(unit == UnitWorld)
5257         return InvalidParameter;
5258
5259     graphics->unit = unit;
5260
5261     return Ok;
5262 }
5263
5264 GpStatus WINGDIPAPI GdipSetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
5265     mode)
5266 {
5267     TRACE("(%p, %d)\n", graphics, mode);
5268
5269     if(!graphics)
5270         return InvalidParameter;
5271
5272     if(graphics->busy)
5273         return ObjectBusy;
5274
5275     graphics->pixeloffset = mode;
5276
5277     return Ok;
5278 }
5279
5280 GpStatus WINGDIPAPI GdipSetRenderingOrigin(GpGraphics *graphics, INT x, INT y)
5281 {
5282     static int calls;
5283
5284     TRACE("(%p,%i,%i)\n", graphics, x, y);
5285
5286     if (!(calls++))
5287         FIXME("value is unused in rendering\n");
5288
5289     if (!graphics)
5290         return InvalidParameter;
5291
5292     graphics->origin_x = x;
5293     graphics->origin_y = y;
5294
5295     return Ok;
5296 }
5297
5298 GpStatus WINGDIPAPI GdipGetRenderingOrigin(GpGraphics *graphics, INT *x, INT *y)
5299 {
5300     TRACE("(%p,%p,%p)\n", graphics, x, y);
5301
5302     if (!graphics || !x || !y)
5303         return InvalidParameter;
5304
5305     *x = graphics->origin_x;
5306     *y = graphics->origin_y;
5307
5308     return Ok;
5309 }
5310
5311 GpStatus WINGDIPAPI GdipSetSmoothingMode(GpGraphics *graphics, SmoothingMode mode)
5312 {
5313     TRACE("(%p, %d)\n", graphics, mode);
5314
5315     if(!graphics)
5316         return InvalidParameter;
5317
5318     if(graphics->busy)
5319         return ObjectBusy;
5320
5321     graphics->smoothing = mode;
5322
5323     return Ok;
5324 }
5325
5326 GpStatus WINGDIPAPI GdipSetTextContrast(GpGraphics *graphics, UINT contrast)
5327 {
5328     TRACE("(%p, %d)\n", graphics, contrast);
5329
5330     if(!graphics)
5331         return InvalidParameter;
5332
5333     graphics->textcontrast = contrast;
5334
5335     return Ok;
5336 }
5337
5338 GpStatus WINGDIPAPI GdipSetTextRenderingHint(GpGraphics *graphics,
5339     TextRenderingHint hint)
5340 {
5341     TRACE("(%p, %d)\n", graphics, hint);
5342
5343     if(!graphics || hint > TextRenderingHintClearTypeGridFit)
5344         return InvalidParameter;
5345
5346     if(graphics->busy)
5347         return ObjectBusy;
5348
5349     graphics->texthint = hint;
5350
5351     return Ok;
5352 }
5353
5354 GpStatus WINGDIPAPI GdipSetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
5355 {
5356     TRACE("(%p, %p)\n", graphics, matrix);
5357
5358     if(!graphics || !matrix)
5359         return InvalidParameter;
5360
5361     if(graphics->busy)
5362         return ObjectBusy;
5363
5364     TRACE("%f,%f,%f,%f,%f,%f\n",
5365           matrix->matrix[0], matrix->matrix[1], matrix->matrix[2],
5366           matrix->matrix[3], matrix->matrix[4], matrix->matrix[5]);
5367
5368     graphics->worldtrans = *matrix;
5369
5370     return Ok;
5371 }
5372
5373 GpStatus WINGDIPAPI GdipTranslateWorldTransform(GpGraphics *graphics, REAL dx,
5374     REAL dy, GpMatrixOrder order)
5375 {
5376     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, dx, dy, order);
5377
5378     if(!graphics)
5379         return InvalidParameter;
5380
5381     if(graphics->busy)
5382         return ObjectBusy;
5383
5384     return GdipTranslateMatrix(&graphics->worldtrans, dx, dy, order);
5385 }
5386
5387 /*****************************************************************************
5388  * GdipSetClipHrgn [GDIPLUS.@]
5389  */
5390 GpStatus WINGDIPAPI GdipSetClipHrgn(GpGraphics *graphics, HRGN hrgn, CombineMode mode)
5391 {
5392     GpRegion *region;
5393     GpStatus status;
5394
5395     TRACE("(%p, %p, %d)\n", graphics, hrgn, mode);
5396
5397     if(!graphics)
5398         return InvalidParameter;
5399
5400     status = GdipCreateRegionHrgn(hrgn, &region);
5401     if(status != Ok)
5402         return status;
5403
5404     status = GdipSetClipRegion(graphics, region, mode);
5405
5406     GdipDeleteRegion(region);
5407     return status;
5408 }
5409
5410 GpStatus WINGDIPAPI GdipSetClipPath(GpGraphics *graphics, GpPath *path, CombineMode mode)
5411 {
5412     TRACE("(%p, %p, %d)\n", graphics, path, mode);
5413
5414     if(!graphics)
5415         return InvalidParameter;
5416
5417     if(graphics->busy)
5418         return ObjectBusy;
5419
5420     return GdipCombineRegionPath(graphics->clip, path, mode);
5421 }
5422
5423 GpStatus WINGDIPAPI GdipSetClipRect(GpGraphics *graphics, REAL x, REAL y,
5424                                     REAL width, REAL height,
5425                                     CombineMode mode)
5426 {
5427     GpRectF rect;
5428
5429     TRACE("(%p, %.2f, %.2f, %.2f, %.2f, %d)\n", graphics, x, y, width, height, mode);
5430
5431     if(!graphics)
5432         return InvalidParameter;
5433
5434     if(graphics->busy)
5435         return ObjectBusy;
5436
5437     rect.X = x;
5438     rect.Y = y;
5439     rect.Width  = width;
5440     rect.Height = height;
5441
5442     return GdipCombineRegionRect(graphics->clip, &rect, mode);
5443 }
5444
5445 GpStatus WINGDIPAPI GdipSetClipRectI(GpGraphics *graphics, INT x, INT y,
5446                                      INT width, INT height,
5447                                      CombineMode mode)
5448 {
5449     TRACE("(%p, %d, %d, %d, %d, %d)\n", graphics, x, y, width, height, mode);
5450
5451     if(!graphics)
5452         return InvalidParameter;
5453
5454     if(graphics->busy)
5455         return ObjectBusy;
5456
5457     return GdipSetClipRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, mode);
5458 }
5459
5460 GpStatus WINGDIPAPI GdipSetClipRegion(GpGraphics *graphics, GpRegion *region,
5461                                       CombineMode mode)
5462 {
5463     TRACE("(%p, %p, %d)\n", graphics, region, mode);
5464
5465     if(!graphics || !region)
5466         return InvalidParameter;
5467
5468     if(graphics->busy)
5469         return ObjectBusy;
5470
5471     return GdipCombineRegionRegion(graphics->clip, region, mode);
5472 }
5473
5474 GpStatus WINGDIPAPI GdipSetMetafileDownLevelRasterizationLimit(GpMetafile *metafile,
5475     UINT limitDpi)
5476 {
5477     static int calls;
5478
5479     TRACE("(%p,%u)\n", metafile, limitDpi);
5480
5481     if(!(calls++))
5482         FIXME("not implemented\n");
5483
5484     return NotImplemented;
5485 }
5486
5487 GpStatus WINGDIPAPI GdipDrawPolygon(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPointF *points,
5488     INT count)
5489 {
5490     INT save_state;
5491     POINT *pti;
5492
5493     TRACE("(%p, %p, %d)\n", graphics, points, count);
5494
5495     if(!graphics || !pen || count<=0)
5496         return InvalidParameter;
5497
5498     if(graphics->busy)
5499         return ObjectBusy;
5500
5501     if (!graphics->hdc)
5502     {
5503         FIXME("graphics object has no HDC\n");
5504         return Ok;
5505     }
5506
5507     pti = GdipAlloc(sizeof(POINT) * count);
5508
5509     save_state = prepare_dc(graphics, pen);
5510     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
5511
5512     transform_and_round_points(graphics, pti, (GpPointF*)points, count);
5513     Polygon(graphics->hdc, pti, count);
5514
5515     restore_dc(graphics, save_state);
5516     GdipFree(pti);
5517
5518     return Ok;
5519 }
5520
5521 GpStatus WINGDIPAPI GdipDrawPolygonI(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPoint *points,
5522     INT count)
5523 {
5524     GpStatus ret;
5525     GpPointF *ptf;
5526     INT i;
5527
5528     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
5529
5530     if(count<=0)    return InvalidParameter;
5531     ptf = GdipAlloc(sizeof(GpPointF) * count);
5532
5533     for(i = 0;i < count; i++){
5534         ptf[i].X = (REAL)points[i].X;
5535         ptf[i].Y = (REAL)points[i].Y;
5536     }
5537
5538     ret = GdipDrawPolygon(graphics,pen,ptf,count);
5539     GdipFree(ptf);
5540
5541     return ret;
5542 }
5543
5544 GpStatus WINGDIPAPI GdipGetDpiX(GpGraphics *graphics, REAL* dpi)
5545 {
5546     TRACE("(%p, %p)\n", graphics, dpi);
5547
5548     if(!graphics || !dpi)
5549         return InvalidParameter;
5550
5551     if(graphics->busy)
5552         return ObjectBusy;
5553
5554     *dpi = graphics->xres;
5555     return Ok;
5556 }
5557
5558 GpStatus WINGDIPAPI GdipGetDpiY(GpGraphics *graphics, REAL* dpi)
5559 {
5560     TRACE("(%p, %p)\n", graphics, dpi);
5561
5562     if(!graphics || !dpi)
5563         return InvalidParameter;
5564
5565     if(graphics->busy)
5566         return ObjectBusy;
5567
5568     *dpi = graphics->yres;
5569     return Ok;
5570 }
5571
5572 GpStatus WINGDIPAPI GdipMultiplyWorldTransform(GpGraphics *graphics, GDIPCONST GpMatrix *matrix,
5573     GpMatrixOrder order)
5574 {
5575     GpMatrix m;
5576     GpStatus ret;
5577
5578     TRACE("(%p, %p, %d)\n", graphics, matrix, order);
5579
5580     if(!graphics || !matrix)
5581         return InvalidParameter;
5582
5583     if(graphics->busy)
5584         return ObjectBusy;
5585
5586     m = graphics->worldtrans;
5587
5588     ret = GdipMultiplyMatrix(&m, matrix, order);
5589     if(ret == Ok)
5590         graphics->worldtrans = m;
5591
5592     return ret;
5593 }
5594
5595 /* Color used to fill bitmaps so we can tell which parts have been drawn over by gdi32. */
5596 static const COLORREF DC_BACKGROUND_KEY = 0x0c0b0d;
5597
5598 GpStatus WINGDIPAPI GdipGetDC(GpGraphics *graphics, HDC *hdc)
5599 {
5600     GpStatus stat=Ok;
5601
5602     TRACE("(%p, %p)\n", graphics, hdc);
5603
5604     if(!graphics || !hdc)
5605         return InvalidParameter;
5606
5607     if(graphics->busy)
5608         return ObjectBusy;
5609
5610     if (graphics->image && graphics->image->type == ImageTypeMetafile)
5611     {
5612         stat = METAFILE_GetDC((GpMetafile*)graphics->image, hdc);
5613     }
5614     else if (!graphics->hdc || graphics->alpha_hdc ||
5615         (graphics->image && graphics->image->type == ImageTypeBitmap && ((GpBitmap*)graphics->image)->format & PixelFormatAlpha))
5616     {
5617         /* Create a fake HDC and fill it with a constant color. */
5618         HDC temp_hdc;
5619         HBITMAP hbitmap;
5620         GpRectF bounds;
5621         BITMAPINFOHEADER bmih;
5622         int i;
5623
5624         stat = get_graphics_bounds(graphics, &bounds);
5625         if (stat != Ok)
5626             return stat;
5627
5628         graphics->temp_hbitmap_width = bounds.Width;
5629         graphics->temp_hbitmap_height = bounds.Height;
5630
5631         bmih.biSize = sizeof(bmih);
5632         bmih.biWidth = graphics->temp_hbitmap_width;
5633         bmih.biHeight = -graphics->temp_hbitmap_height;
5634         bmih.biPlanes = 1;
5635         bmih.biBitCount = 32;
5636         bmih.biCompression = BI_RGB;
5637         bmih.biSizeImage = 0;
5638         bmih.biXPelsPerMeter = 0;
5639         bmih.biYPelsPerMeter = 0;
5640         bmih.biClrUsed = 0;
5641         bmih.biClrImportant = 0;
5642
5643         hbitmap = CreateDIBSection(NULL, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
5644             (void**)&graphics->temp_bits, NULL, 0);
5645         if (!hbitmap)
5646             return GenericError;
5647
5648         temp_hdc = CreateCompatibleDC(0);
5649         if (!temp_hdc)
5650         {
5651             DeleteObject(hbitmap);
5652             return GenericError;
5653         }
5654
5655         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
5656             ((DWORD*)graphics->temp_bits)[i] = DC_BACKGROUND_KEY;
5657
5658         SelectObject(temp_hdc, hbitmap);
5659
5660         graphics->temp_hbitmap = hbitmap;
5661         *hdc = graphics->temp_hdc = temp_hdc;
5662     }
5663     else
5664     {
5665         *hdc = graphics->hdc;
5666     }
5667
5668     if (stat == Ok)
5669         graphics->busy = TRUE;
5670
5671     return stat;
5672 }
5673
5674 GpStatus WINGDIPAPI GdipReleaseDC(GpGraphics *graphics, HDC hdc)
5675 {
5676     GpStatus stat=Ok;
5677
5678     TRACE("(%p, %p)\n", graphics, hdc);
5679
5680     if(!graphics || !hdc || !graphics->busy)
5681         return InvalidParameter;
5682
5683     if (graphics->image && graphics->image->type == ImageTypeMetafile)
5684     {
5685         stat = METAFILE_ReleaseDC((GpMetafile*)graphics->image, hdc);
5686     }
5687     else if (graphics->temp_hdc == hdc)
5688     {
5689         DWORD* pos;
5690         int i;
5691
5692         /* Find the pixels that have changed, and mark them as opaque. */
5693         pos = (DWORD*)graphics->temp_bits;
5694         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
5695         {
5696             if (*pos != DC_BACKGROUND_KEY)
5697             {
5698                 *pos |= 0xff000000;
5699             }
5700             pos++;
5701         }
5702
5703         /* Write the changed pixels to the real target. */
5704         alpha_blend_pixels(graphics, 0, 0, graphics->temp_bits,
5705             graphics->temp_hbitmap_width, graphics->temp_hbitmap_height,
5706             graphics->temp_hbitmap_width * 4);
5707
5708         /* Clean up. */
5709         DeleteDC(graphics->temp_hdc);
5710         DeleteObject(graphics->temp_hbitmap);
5711         graphics->temp_hdc = NULL;
5712         graphics->temp_hbitmap = NULL;
5713     }
5714     else if (hdc != graphics->hdc)
5715     {
5716         stat = InvalidParameter;
5717     }
5718
5719     if (stat == Ok)
5720         graphics->busy = FALSE;
5721
5722     return stat;
5723 }
5724
5725 GpStatus WINGDIPAPI GdipGetClip(GpGraphics *graphics, GpRegion *region)
5726 {
5727     GpRegion *clip;
5728     GpStatus status;
5729
5730     TRACE("(%p, %p)\n", graphics, region);
5731
5732     if(!graphics || !region)
5733         return InvalidParameter;
5734
5735     if(graphics->busy)
5736         return ObjectBusy;
5737
5738     if((status = GdipCloneRegion(graphics->clip, &clip)) != Ok)
5739         return status;
5740
5741     /* free everything except root node and header */
5742     delete_element(&region->node);
5743     memcpy(region, clip, sizeof(GpRegion));
5744     GdipFree(clip);
5745
5746     return Ok;
5747 }
5748
5749 static GpStatus get_graphics_transform(GpGraphics *graphics, GpCoordinateSpace dst_space,
5750         GpCoordinateSpace src_space, GpMatrix *matrix)
5751 {
5752     GpStatus stat = Ok;
5753     REAL scale_x, scale_y;
5754
5755     GdipSetMatrixElements(matrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
5756
5757     if (dst_space != src_space)
5758     {
5759         scale_x = units_to_pixels(1.0, graphics->unit, graphics->xres);
5760         scale_y = units_to_pixels(1.0, graphics->unit, graphics->yres);
5761
5762         if(graphics->unit != UnitDisplay)
5763         {
5764             scale_x *= graphics->scale;
5765             scale_y *= graphics->scale;
5766         }
5767
5768         /* transform from src_space to CoordinateSpacePage */
5769         switch (src_space)
5770         {
5771         case CoordinateSpaceWorld:
5772             GdipMultiplyMatrix(matrix, &graphics->worldtrans, MatrixOrderAppend);
5773             break;
5774         case CoordinateSpacePage:
5775             break;
5776         case CoordinateSpaceDevice:
5777             GdipScaleMatrix(matrix, 1.0/scale_x, 1.0/scale_y, MatrixOrderAppend);
5778             break;
5779         }
5780
5781         /* transform from CoordinateSpacePage to dst_space */
5782         switch (dst_space)
5783         {
5784         case CoordinateSpaceWorld:
5785             {
5786                 GpMatrix inverted_transform = graphics->worldtrans;
5787                 stat = GdipInvertMatrix(&inverted_transform);
5788                 if (stat == Ok)
5789                     GdipMultiplyMatrix(matrix, &inverted_transform, MatrixOrderAppend);
5790                 break;
5791             }
5792         case CoordinateSpacePage:
5793             break;
5794         case CoordinateSpaceDevice:
5795             GdipScaleMatrix(matrix, scale_x, scale_y, MatrixOrderAppend);
5796             break;
5797         }
5798     }
5799     return stat;
5800 }
5801
5802 GpStatus WINGDIPAPI GdipTransformPoints(GpGraphics *graphics, GpCoordinateSpace dst_space,
5803                                         GpCoordinateSpace src_space, GpPointF *points, INT count)
5804 {
5805     GpMatrix matrix;
5806     GpStatus stat;
5807
5808     if(!graphics || !points || count <= 0)
5809         return InvalidParameter;
5810
5811     if(graphics->busy)
5812         return ObjectBusy;
5813
5814     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
5815
5816     if (src_space == dst_space) return Ok;
5817
5818     stat = get_graphics_transform(graphics, dst_space, src_space, &matrix);
5819     if (stat != Ok) return stat;
5820
5821     return GdipTransformMatrixPoints(&matrix, points, count);
5822 }
5823
5824 GpStatus WINGDIPAPI GdipTransformPointsI(GpGraphics *graphics, GpCoordinateSpace dst_space,
5825                                          GpCoordinateSpace src_space, GpPoint *points, INT count)
5826 {
5827     GpPointF *pointsF;
5828     GpStatus ret;
5829     INT i;
5830
5831     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
5832
5833     if(count <= 0)
5834         return InvalidParameter;
5835
5836     pointsF = GdipAlloc(sizeof(GpPointF) * count);
5837     if(!pointsF)
5838         return OutOfMemory;
5839
5840     for(i = 0; i < count; i++){
5841         pointsF[i].X = (REAL)points[i].X;
5842         pointsF[i].Y = (REAL)points[i].Y;
5843     }
5844
5845     ret = GdipTransformPoints(graphics, dst_space, src_space, pointsF, count);
5846
5847     if(ret == Ok)
5848         for(i = 0; i < count; i++){
5849             points[i].X = gdip_round(pointsF[i].X);
5850             points[i].Y = gdip_round(pointsF[i].Y);
5851         }
5852     GdipFree(pointsF);
5853
5854     return ret;
5855 }
5856
5857 HPALETTE WINGDIPAPI GdipCreateHalftonePalette(void)
5858 {
5859     static int calls;
5860
5861     TRACE("\n");
5862
5863     if (!calls++)
5864       FIXME("stub\n");
5865
5866     return NULL;
5867 }
5868
5869 /*****************************************************************************
5870  * GdipTranslateClip [GDIPLUS.@]
5871  */
5872 GpStatus WINGDIPAPI GdipTranslateClip(GpGraphics *graphics, REAL dx, REAL dy)
5873 {
5874     TRACE("(%p, %.2f, %.2f)\n", graphics, dx, dy);
5875
5876     if(!graphics)
5877         return InvalidParameter;
5878
5879     if(graphics->busy)
5880         return ObjectBusy;
5881
5882     return GdipTranslateRegion(graphics->clip, dx, dy);
5883 }
5884
5885 /*****************************************************************************
5886  * GdipTranslateClipI [GDIPLUS.@]
5887  */
5888 GpStatus WINGDIPAPI GdipTranslateClipI(GpGraphics *graphics, INT dx, INT dy)
5889 {
5890     TRACE("(%p, %d, %d)\n", graphics, dx, dy);
5891
5892     if(!graphics)
5893         return InvalidParameter;
5894
5895     if(graphics->busy)
5896         return ObjectBusy;
5897
5898     return GdipTranslateRegion(graphics->clip, (REAL)dx, (REAL)dy);
5899 }
5900
5901
5902 /*****************************************************************************
5903  * GdipMeasureDriverString [GDIPLUS.@]
5904  */
5905 GpStatus WINGDIPAPI GdipMeasureDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
5906                                             GDIPCONST GpFont *font, GDIPCONST PointF *positions,
5907                                             INT flags, GDIPCONST GpMatrix *matrix, RectF *boundingBox)
5908 {
5909     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
5910     HFONT hfont;
5911     HDC hdc;
5912     REAL min_x, min_y, max_x, max_y, x, y;
5913     int i;
5914     TEXTMETRICW textmetric;
5915     const WORD *glyph_indices;
5916     WORD *dynamic_glyph_indices=NULL;
5917     REAL rel_width, rel_height, ascent, descent;
5918     GpPointF pt[3];
5919
5920     TRACE("(%p %p %d %p %p %d %p %p)\n", graphics, text, length, font, positions, flags, matrix, boundingBox);
5921
5922     if (!graphics || !text || !font || !positions || !boundingBox)
5923         return InvalidParameter;
5924
5925     if (length == -1)
5926         length = strlenW(text);
5927
5928     if (length == 0)
5929     {
5930         boundingBox->X = 0.0;
5931         boundingBox->Y = 0.0;
5932         boundingBox->Width = 0.0;
5933         boundingBox->Height = 0.0;
5934     }
5935
5936     if (flags & unsupported_flags)
5937         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
5938
5939     get_font_hfont(graphics, font, NULL, &hfont, matrix);
5940
5941     hdc = CreateCompatibleDC(0);
5942     SelectObject(hdc, hfont);
5943
5944     GetTextMetricsW(hdc, &textmetric);
5945
5946     pt[0].X = 0.0;
5947     pt[0].Y = 0.0;
5948     pt[1].X = 1.0;
5949     pt[1].Y = 0.0;
5950     pt[2].X = 0.0;
5951     pt[2].Y = 1.0;
5952     if (matrix)
5953     {
5954         GpMatrix xform = *matrix;
5955         GdipTransformMatrixPoints(&xform, pt, 3);
5956     }
5957     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5958     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5959                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5960     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5961                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5962
5963     if (flags & DriverStringOptionsCmapLookup)
5964     {
5965         glyph_indices = dynamic_glyph_indices = GdipAlloc(sizeof(WORD) * length);
5966         if (!glyph_indices)
5967         {
5968             DeleteDC(hdc);
5969             DeleteObject(hfont);
5970             return OutOfMemory;
5971         }
5972
5973         GetGlyphIndicesW(hdc, text, length, dynamic_glyph_indices, 0);
5974     }
5975     else
5976         glyph_indices = text;
5977
5978     min_x = max_x = x = positions[0].X;
5979     min_y = max_y = y = positions[0].Y;
5980
5981     ascent = textmetric.tmAscent / rel_height;
5982     descent = textmetric.tmDescent / rel_height;
5983
5984     for (i=0; i<length; i++)
5985     {
5986         int char_width;
5987         ABC abc;
5988
5989         if (!(flags & DriverStringOptionsRealizedAdvance))
5990         {
5991             x = positions[i].X;
5992             y = positions[i].Y;
5993         }
5994
5995         GetCharABCWidthsW(hdc, glyph_indices[i], glyph_indices[i], &abc);
5996         char_width = abc.abcA + abc.abcB + abc.abcC;
5997
5998         if (min_y > y - ascent) min_y = y - ascent;
5999         if (max_y < y + descent) max_y = y + descent;
6000         if (min_x > x) min_x = x;
6001
6002         x += char_width / rel_width;
6003
6004         if (max_x < x) max_x = x;
6005     }
6006
6007     GdipFree(dynamic_glyph_indices);
6008     DeleteDC(hdc);
6009     DeleteObject(hfont);
6010
6011     boundingBox->X = min_x;
6012     boundingBox->Y = min_y;
6013     boundingBox->Width = max_x - min_x;
6014     boundingBox->Height = max_y - min_y;
6015
6016     return Ok;
6017 }
6018
6019 static GpStatus GDI32_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6020                                            GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6021                                            GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6022                                            INT flags, GDIPCONST GpMatrix *matrix)
6023 {
6024     static const INT unsupported_flags = ~(DriverStringOptionsRealizedAdvance|DriverStringOptionsCmapLookup);
6025     INT save_state;
6026     GpPointF pt;
6027     HFONT hfont;
6028     UINT eto_flags=0;
6029
6030     if (flags & unsupported_flags)
6031         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6032
6033     if (!(flags & DriverStringOptionsCmapLookup))
6034         eto_flags |= ETO_GLYPH_INDEX;
6035
6036     save_state = SaveDC(graphics->hdc);
6037     SetBkMode(graphics->hdc, TRANSPARENT);
6038     SetTextColor(graphics->hdc, get_gdi_brush_color(brush));
6039
6040     pt = positions[0];
6041     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, &pt, 1);
6042
6043     get_font_hfont(graphics, font, format, &hfont, matrix);
6044     SelectObject(graphics->hdc, hfont);
6045
6046     SetTextAlign(graphics->hdc, TA_BASELINE|TA_LEFT);
6047
6048     ExtTextOutW(graphics->hdc, gdip_round(pt.X), gdip_round(pt.Y), eto_flags, NULL, text, length, NULL);
6049
6050     RestoreDC(graphics->hdc, save_state);
6051
6052     DeleteObject(hfont);
6053
6054     return Ok;
6055 }
6056
6057 static GpStatus SOFTWARE_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6058                                         GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6059                                         GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6060                                         INT flags, GDIPCONST GpMatrix *matrix)
6061 {
6062     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
6063     GpStatus stat;
6064     PointF *real_positions, real_position;
6065     POINT *pti;
6066     HFONT hfont;
6067     HDC hdc;
6068     int min_x=INT_MAX, min_y=INT_MAX, max_x=INT_MIN, max_y=INT_MIN, i, x, y;
6069     DWORD max_glyphsize=0;
6070     GLYPHMETRICS glyphmetrics;
6071     static const MAT2 identity = {{0,1}, {0,0}, {0,0}, {0,1}};
6072     BYTE *glyph_mask;
6073     BYTE *text_mask;
6074     int text_mask_stride;
6075     BYTE *pixel_data;
6076     int pixel_data_stride;
6077     GpRect pixel_area;
6078     UINT ggo_flags = GGO_GRAY8_BITMAP;
6079
6080     if (length <= 0)
6081         return Ok;
6082
6083     if (!(flags & DriverStringOptionsCmapLookup))
6084         ggo_flags |= GGO_GLYPH_INDEX;
6085
6086     if (flags & unsupported_flags)
6087         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6088
6089     pti = GdipAlloc(sizeof(POINT) * length);
6090     if (!pti)
6091         return OutOfMemory;
6092
6093     if (flags & DriverStringOptionsRealizedAdvance)
6094     {
6095         real_position = positions[0];
6096
6097         transform_and_round_points(graphics, pti, &real_position, 1);
6098     }
6099     else
6100     {
6101         real_positions = GdipAlloc(sizeof(PointF) * length);
6102         if (!real_positions)
6103         {
6104             GdipFree(pti);
6105             return OutOfMemory;
6106         }
6107
6108         memcpy(real_positions, positions, sizeof(PointF) * length);
6109
6110         transform_and_round_points(graphics, pti, real_positions, length);
6111
6112         GdipFree(real_positions);
6113     }
6114
6115     get_font_hfont(graphics, font, format, &hfont, matrix);
6116
6117     hdc = CreateCompatibleDC(0);
6118     SelectObject(hdc, hfont);
6119
6120     /* Get the boundaries of the text to be drawn */
6121     for (i=0; i<length; i++)
6122     {
6123         DWORD glyphsize;
6124         int left, top, right, bottom;
6125
6126         glyphsize = GetGlyphOutlineW(hdc, text[i], ggo_flags,
6127             &glyphmetrics, 0, NULL, &identity);
6128
6129         if (glyphsize == GDI_ERROR)
6130         {
6131             ERR("GetGlyphOutlineW failed\n");
6132             GdipFree(pti);
6133             DeleteDC(hdc);
6134             DeleteObject(hfont);
6135             return GenericError;
6136         }
6137
6138         if (glyphsize > max_glyphsize)
6139             max_glyphsize = glyphsize;
6140
6141         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6142         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6143         right = pti[i].x + glyphmetrics.gmptGlyphOrigin.x + glyphmetrics.gmBlackBoxX;
6144         bottom = pti[i].y - glyphmetrics.gmptGlyphOrigin.y + glyphmetrics.gmBlackBoxY;
6145
6146         if (left < min_x) min_x = left;
6147         if (top < min_y) min_y = top;
6148         if (right > max_x) max_x = right;
6149         if (bottom > max_y) max_y = bottom;
6150
6151         if (i+1 < length && (flags & DriverStringOptionsRealizedAdvance) == DriverStringOptionsRealizedAdvance)
6152         {
6153             pti[i+1].x = pti[i].x + glyphmetrics.gmCellIncX;
6154             pti[i+1].y = pti[i].y + glyphmetrics.gmCellIncY;
6155         }
6156     }
6157
6158     glyph_mask = GdipAlloc(max_glyphsize);
6159     text_mask = GdipAlloc((max_x - min_x) * (max_y - min_y));
6160     text_mask_stride = max_x - min_x;
6161
6162     if (!(glyph_mask && text_mask))
6163     {
6164         GdipFree(glyph_mask);
6165         GdipFree(text_mask);
6166         GdipFree(pti);
6167         DeleteDC(hdc);
6168         DeleteObject(hfont);
6169         return OutOfMemory;
6170     }
6171
6172     /* Generate a mask for the text */
6173     for (i=0; i<length; i++)
6174     {
6175         int left, top, stride;
6176
6177         GetGlyphOutlineW(hdc, text[i], ggo_flags,
6178             &glyphmetrics, max_glyphsize, glyph_mask, &identity);
6179
6180         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6181         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6182         stride = (glyphmetrics.gmBlackBoxX + 3) & (~3);
6183
6184         for (y=0; y<glyphmetrics.gmBlackBoxY; y++)
6185         {
6186             BYTE *glyph_val = glyph_mask + y * stride;
6187             BYTE *text_val = text_mask + (left - min_x) + (top - min_y + y) * text_mask_stride;
6188             for (x=0; x<glyphmetrics.gmBlackBoxX; x++)
6189             {
6190                 *text_val = min(64, *text_val + *glyph_val);
6191                 glyph_val++;
6192                 text_val++;
6193             }
6194         }
6195     }
6196
6197     GdipFree(pti);
6198     DeleteDC(hdc);
6199     DeleteObject(hfont);
6200     GdipFree(glyph_mask);
6201
6202     /* get the brush data */
6203     pixel_data = GdipAlloc(4 * (max_x - min_x) * (max_y - min_y));
6204     if (!pixel_data)
6205     {
6206         GdipFree(text_mask);
6207         return OutOfMemory;
6208     }
6209
6210     pixel_area.X = min_x;
6211     pixel_area.Y = min_y;
6212     pixel_area.Width = max_x - min_x;
6213     pixel_area.Height = max_y - min_y;
6214     pixel_data_stride = pixel_area.Width * 4;
6215
6216     stat = brush_fill_pixels(graphics, (GpBrush*)brush, (DWORD*)pixel_data, &pixel_area, pixel_area.Width);
6217     if (stat != Ok)
6218     {
6219         GdipFree(text_mask);
6220         GdipFree(pixel_data);
6221         return stat;
6222     }
6223
6224     /* multiply the brush data by the mask */
6225     for (y=0; y<pixel_area.Height; y++)
6226     {
6227         BYTE *text_val = text_mask + text_mask_stride * y;
6228         BYTE *pixel_val = pixel_data + pixel_data_stride * y + 3;
6229         for (x=0; x<pixel_area.Width; x++)
6230         {
6231             *pixel_val = (*pixel_val) * (*text_val) / 64;
6232             text_val++;
6233             pixel_val+=4;
6234         }
6235     }
6236
6237     GdipFree(text_mask);
6238
6239     /* draw the result */
6240     stat = alpha_blend_pixels(graphics, min_x, min_y, pixel_data, pixel_area.Width,
6241         pixel_area.Height, pixel_data_stride);
6242
6243     GdipFree(pixel_data);
6244
6245     return stat;
6246 }
6247
6248 static GpStatus draw_driver_string(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6249                                    GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6250                                    GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6251                                    INT flags, GDIPCONST GpMatrix *matrix)
6252 {
6253     GpStatus stat = NotImplemented;
6254
6255     if (length == -1)
6256         length = strlenW(text);
6257
6258     if (graphics->hdc && !graphics->alpha_hdc &&
6259         ((flags & DriverStringOptionsRealizedAdvance) || length <= 1) &&
6260         brush->bt == BrushTypeSolidColor &&
6261         (((GpSolidFill*)brush)->color & 0xff000000) == 0xff000000)
6262         stat = GDI32_GdipDrawDriverString(graphics, text, length, font, format,
6263                                           brush, positions, flags, matrix);
6264     if (stat == NotImplemented)
6265         stat = SOFTWARE_GdipDrawDriverString(graphics, text, length, font, format,
6266                                              brush, positions, flags, matrix);
6267     return stat;
6268 }
6269
6270 /*****************************************************************************
6271  * GdipDrawDriverString [GDIPLUS.@]
6272  */
6273 GpStatus WINGDIPAPI GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6274                                          GDIPCONST GpFont *font, GDIPCONST GpBrush *brush,
6275                                          GDIPCONST PointF *positions, INT flags,
6276                                          GDIPCONST GpMatrix *matrix )
6277 {
6278     TRACE("(%p %s %p %p %p %d %p)\n", graphics, debugstr_wn(text, length), font, brush, positions, flags, matrix);
6279
6280     if (!graphics || !text || !font || !brush || !positions)
6281         return InvalidParameter;
6282
6283     return draw_driver_string(graphics, text, length, font, NULL,
6284                               brush, positions, flags, matrix);
6285 }
6286
6287 GpStatus WINGDIPAPI GdipRecordMetafileStream(IStream *stream, HDC hdc, EmfType type, GDIPCONST GpRect *frameRect,
6288                                         MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc, GpMetafile **metafile)
6289 {
6290     FIXME("(%p %p %d %p %d %p %p): stub\n", stream, hdc, type, frameRect, frameUnit, desc, metafile);
6291     return NotImplemented;
6292 }
6293
6294 /*****************************************************************************
6295  * GdipIsVisibleClipEmpty [GDIPLUS.@]
6296  */
6297 GpStatus WINGDIPAPI GdipIsVisibleClipEmpty(GpGraphics *graphics, BOOL *res)
6298 {
6299     GpStatus stat;
6300     GpRegion* rgn;
6301
6302     TRACE("(%p, %p)\n", graphics, res);
6303
6304     if((stat = GdipCreateRegion(&rgn)) != Ok)
6305         return stat;
6306
6307     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
6308         goto cleanup;
6309
6310     stat = GdipIsEmptyRegion(rgn, graphics, res);
6311
6312 cleanup:
6313     GdipDeleteRegion(rgn);
6314     return stat;
6315 }
6316
6317 GpStatus WINGDIPAPI GdipResetPageTransform(GpGraphics *graphics)
6318 {
6319     static int calls;
6320
6321     TRACE("(%p) stub\n", graphics);
6322
6323     if(!(calls++))
6324         FIXME("not implemented\n");
6325
6326     return NotImplemented;
6327 }