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