d3d10core: Implement d3d10_device_VSSetSamplers().
[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{
2117         rect->X = 0;
2118         rect->Y = 0;
2119         rect->Width = GetDeviceCaps(graphics->hdc, HORZRES);
2120         rect->Height = GetDeviceCaps(graphics->hdc, VERTRES);
2121     }
2122
2123     return stat;
2124 }
2125
2126 /* on success, rgn will contain the region of the graphics object which
2127  * is visible after clipping has been applied */
2128 static GpStatus get_visible_clip_region(GpGraphics *graphics, GpRegion *rgn)
2129 {
2130     GpStatus stat;
2131     GpRectF rectf;
2132     GpRegion* tmp;
2133
2134     if((stat = get_graphics_bounds(graphics, &rectf)) != Ok)
2135         return stat;
2136
2137     if((stat = GdipCreateRegion(&tmp)) != Ok)
2138         return stat;
2139
2140     if((stat = GdipCombineRegionRect(tmp, &rectf, CombineModeReplace)) != Ok)
2141         goto end;
2142
2143     if((stat = GdipCombineRegionRegion(tmp, graphics->clip, CombineModeIntersect)) != Ok)
2144         goto end;
2145
2146     stat = GdipCombineRegionRegion(rgn, tmp, CombineModeReplace);
2147
2148 end:
2149     GdipDeleteRegion(tmp);
2150     return stat;
2151 }
2152
2153 void get_log_fontW(const GpFont *font, GpGraphics *graphics, LOGFONTW *lf)
2154 {
2155     REAL height;
2156
2157     if (font->unit == UnitPixel)
2158     {
2159         height = units_to_pixels(font->emSize, graphics->unit, graphics->yres);
2160     }
2161     else
2162     {
2163         if (graphics->unit == UnitDisplay || graphics->unit == UnitPixel)
2164             height = units_to_pixels(font->emSize, font->unit, graphics->xres);
2165         else
2166             height = units_to_pixels(font->emSize, font->unit, graphics->yres);
2167     }
2168
2169     lf->lfHeight = -(height + 0.5);
2170     lf->lfWidth = 0;
2171     lf->lfEscapement = 0;
2172     lf->lfOrientation = 0;
2173     lf->lfWeight = font->otm.otmTextMetrics.tmWeight;
2174     lf->lfItalic = font->otm.otmTextMetrics.tmItalic ? 1 : 0;
2175     lf->lfUnderline = font->otm.otmTextMetrics.tmUnderlined ? 1 : 0;
2176     lf->lfStrikeOut = font->otm.otmTextMetrics.tmStruckOut ? 1 : 0;
2177     lf->lfCharSet = font->otm.otmTextMetrics.tmCharSet;
2178     lf->lfOutPrecision = OUT_DEFAULT_PRECIS;
2179     lf->lfClipPrecision = CLIP_DEFAULT_PRECIS;
2180     lf->lfQuality = DEFAULT_QUALITY;
2181     lf->lfPitchAndFamily = 0;
2182     strcpyW(lf->lfFaceName, font->family->FamilyName);
2183 }
2184
2185 static void get_font_hfont(GpGraphics *graphics, GDIPCONST GpFont *font,
2186                            GDIPCONST GpStringFormat *format, HFONT *hfont,
2187                            GDIPCONST GpMatrix *matrix)
2188 {
2189     HDC hdc = CreateCompatibleDC(0);
2190     GpPointF pt[3];
2191     REAL angle, rel_width, rel_height, font_height;
2192     LOGFONTW lfw;
2193     HFONT unscaled_font;
2194     TEXTMETRICW textmet;
2195
2196     if (font->unit == UnitPixel)
2197         font_height = font->emSize;
2198     else
2199     {
2200         REAL unit_scale, res;
2201
2202         res = (graphics->unit == UnitDisplay || graphics->unit == UnitPixel) ? graphics->xres : graphics->yres;
2203         unit_scale = units_scale(font->unit, graphics->unit, res);
2204
2205         font_height = font->emSize * unit_scale;
2206     }
2207
2208     pt[0].X = 0.0;
2209     pt[0].Y = 0.0;
2210     pt[1].X = 1.0;
2211     pt[1].Y = 0.0;
2212     pt[2].X = 0.0;
2213     pt[2].Y = 1.0;
2214     if (matrix)
2215     {
2216         GpMatrix xform = *matrix;
2217         GdipTransformMatrixPoints(&xform, pt, 3);
2218     }
2219     if (graphics)
2220         GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
2221     angle = -gdiplus_atan2((pt[1].Y - pt[0].Y), (pt[1].X - pt[0].X));
2222     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
2223                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
2224     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
2225                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
2226
2227     get_log_fontW(font, graphics, &lfw);
2228     lfw.lfHeight = gdip_round(font_height * rel_height);
2229     unscaled_font = CreateFontIndirectW(&lfw);
2230
2231     SelectObject(hdc, unscaled_font);
2232     GetTextMetricsW(hdc, &textmet);
2233
2234     lfw.lfWidth = gdip_round(textmet.tmAveCharWidth * rel_width / rel_height);
2235     lfw.lfEscapement = lfw.lfOrientation = gdip_round((angle / M_PI) * 1800.0);
2236
2237     *hfont = CreateFontIndirectW(&lfw);
2238
2239     DeleteDC(hdc);
2240     DeleteObject(unscaled_font);
2241 }
2242
2243 GpStatus WINGDIPAPI GdipCreateFromHDC(HDC hdc, GpGraphics **graphics)
2244 {
2245     TRACE("(%p, %p)\n", hdc, graphics);
2246
2247     return GdipCreateFromHDC2(hdc, NULL, graphics);
2248 }
2249
2250 GpStatus WINGDIPAPI GdipCreateFromHDC2(HDC hdc, HANDLE hDevice, GpGraphics **graphics)
2251 {
2252     GpStatus retval;
2253
2254     TRACE("(%p, %p, %p)\n", hdc, hDevice, graphics);
2255
2256     if(hDevice != NULL) {
2257         FIXME("Don't know how to handle parameter hDevice\n");
2258         return NotImplemented;
2259     }
2260
2261     if(hdc == NULL)
2262         return OutOfMemory;
2263
2264     if(graphics == NULL)
2265         return InvalidParameter;
2266
2267     *graphics = GdipAlloc(sizeof(GpGraphics));
2268     if(!*graphics)  return OutOfMemory;
2269
2270     GdipSetMatrixElements(&(*graphics)->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
2271
2272     if((retval = GdipCreateRegion(&(*graphics)->clip)) != Ok){
2273         GdipFree(*graphics);
2274         return retval;
2275     }
2276
2277     (*graphics)->hdc = hdc;
2278     (*graphics)->hwnd = WindowFromDC(hdc);
2279     (*graphics)->owndc = FALSE;
2280     (*graphics)->smoothing = SmoothingModeDefault;
2281     (*graphics)->compqual = CompositingQualityDefault;
2282     (*graphics)->interpolation = InterpolationModeBilinear;
2283     (*graphics)->pixeloffset = PixelOffsetModeDefault;
2284     (*graphics)->compmode = CompositingModeSourceOver;
2285     (*graphics)->unit = UnitDisplay;
2286     (*graphics)->scale = 1.0;
2287     (*graphics)->xres = GetDeviceCaps(hdc, LOGPIXELSX);
2288     (*graphics)->yres = GetDeviceCaps(hdc, LOGPIXELSY);
2289     (*graphics)->busy = FALSE;
2290     (*graphics)->textcontrast = 4;
2291     list_init(&(*graphics)->containers);
2292     (*graphics)->contid = 0;
2293
2294     TRACE("<-- %p\n", *graphics);
2295
2296     return Ok;
2297 }
2298
2299 GpStatus graphics_from_image(GpImage *image, GpGraphics **graphics)
2300 {
2301     GpStatus retval;
2302
2303     *graphics = GdipAlloc(sizeof(GpGraphics));
2304     if(!*graphics)  return OutOfMemory;
2305
2306     GdipSetMatrixElements(&(*graphics)->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
2307
2308     if((retval = GdipCreateRegion(&(*graphics)->clip)) != Ok){
2309         GdipFree(*graphics);
2310         return retval;
2311     }
2312
2313     (*graphics)->hdc = NULL;
2314     (*graphics)->hwnd = NULL;
2315     (*graphics)->owndc = FALSE;
2316     (*graphics)->image = image;
2317     (*graphics)->smoothing = SmoothingModeDefault;
2318     (*graphics)->compqual = CompositingQualityDefault;
2319     (*graphics)->interpolation = InterpolationModeBilinear;
2320     (*graphics)->pixeloffset = PixelOffsetModeDefault;
2321     (*graphics)->compmode = CompositingModeSourceOver;
2322     (*graphics)->unit = UnitDisplay;
2323     (*graphics)->scale = 1.0;
2324     (*graphics)->xres = image->xres;
2325     (*graphics)->yres = image->yres;
2326     (*graphics)->busy = FALSE;
2327     (*graphics)->textcontrast = 4;
2328     list_init(&(*graphics)->containers);
2329     (*graphics)->contid = 0;
2330
2331     TRACE("<-- %p\n", *graphics);
2332
2333     return Ok;
2334 }
2335
2336 GpStatus WINGDIPAPI GdipCreateFromHWND(HWND hwnd, GpGraphics **graphics)
2337 {
2338     GpStatus ret;
2339     HDC hdc;
2340
2341     TRACE("(%p, %p)\n", hwnd, graphics);
2342
2343     hdc = GetDC(hwnd);
2344
2345     if((ret = GdipCreateFromHDC(hdc, graphics)) != Ok)
2346     {
2347         ReleaseDC(hwnd, hdc);
2348         return ret;
2349     }
2350
2351     (*graphics)->hwnd = hwnd;
2352     (*graphics)->owndc = TRUE;
2353
2354     return Ok;
2355 }
2356
2357 /* FIXME: no icm handling */
2358 GpStatus WINGDIPAPI GdipCreateFromHWNDICM(HWND hwnd, GpGraphics **graphics)
2359 {
2360     TRACE("(%p, %p)\n", hwnd, graphics);
2361
2362     return GdipCreateFromHWND(hwnd, graphics);
2363 }
2364
2365 GpStatus WINGDIPAPI GdipCreateMetafileFromEmf(HENHMETAFILE hemf, BOOL delete,
2366     GpMetafile **metafile)
2367 {
2368     ENHMETAHEADER header;
2369     MetafileType metafile_type;
2370
2371     TRACE("(%p,%i,%p)\n", hemf, delete, metafile);
2372
2373     if(!hemf || !metafile)
2374         return InvalidParameter;
2375
2376     if (GetEnhMetaFileHeader(hemf, sizeof(header), &header) == 0)
2377         return GenericError;
2378
2379     metafile_type = METAFILE_GetEmfType(hemf);
2380
2381     if (metafile_type == MetafileTypeInvalid)
2382         return GenericError;
2383
2384     *metafile = GdipAlloc(sizeof(GpMetafile));
2385     if (!*metafile)
2386         return OutOfMemory;
2387
2388     (*metafile)->image.type = ImageTypeMetafile;
2389     (*metafile)->image.format = ImageFormatEMF;
2390     (*metafile)->image.frame_count = 1;
2391     (*metafile)->image.xres = (REAL)header.szlDevice.cx;
2392     (*metafile)->image.yres = (REAL)header.szlDevice.cy;
2393     (*metafile)->bounds.X = (REAL)header.rclBounds.left;
2394     (*metafile)->bounds.Y = (REAL)header.rclBounds.top;
2395     (*metafile)->bounds.Width = (REAL)(header.rclBounds.right - header.rclBounds.left);
2396     (*metafile)->bounds.Height = (REAL)(header.rclBounds.bottom - header.rclBounds.top);
2397     (*metafile)->unit = UnitPixel;
2398     (*metafile)->metafile_type = metafile_type;
2399     (*metafile)->hemf = hemf;
2400     (*metafile)->preserve_hemf = !delete;
2401
2402     TRACE("<-- %p\n", *metafile);
2403
2404     return Ok;
2405 }
2406
2407 GpStatus WINGDIPAPI GdipCreateMetafileFromWmf(HMETAFILE hwmf, BOOL delete,
2408     GDIPCONST WmfPlaceableFileHeader * placeable, GpMetafile **metafile)
2409 {
2410     UINT read;
2411     BYTE *copy;
2412     HENHMETAFILE hemf;
2413     GpStatus retval = Ok;
2414
2415     TRACE("(%p, %d, %p, %p)\n", hwmf, delete, placeable, metafile);
2416
2417     if(!hwmf || !metafile || !placeable)
2418         return InvalidParameter;
2419
2420     *metafile = NULL;
2421     read = GetMetaFileBitsEx(hwmf, 0, NULL);
2422     if(!read)
2423         return GenericError;
2424     copy = GdipAlloc(read);
2425     GetMetaFileBitsEx(hwmf, read, copy);
2426
2427     hemf = SetWinMetaFileBits(read, copy, NULL, NULL);
2428     GdipFree(copy);
2429
2430     /* FIXME: We should store and use hwmf instead of converting to hemf */
2431     retval = GdipCreateMetafileFromEmf(hemf, TRUE, metafile);
2432
2433     if (retval == Ok)
2434     {
2435         (*metafile)->image.xres = (REAL)placeable->Inch;
2436         (*metafile)->image.yres = (REAL)placeable->Inch;
2437         (*metafile)->bounds.X = ((REAL)placeable->BoundingBox.Left) / ((REAL)placeable->Inch);
2438         (*metafile)->bounds.Y = ((REAL)placeable->BoundingBox.Top) / ((REAL)placeable->Inch);
2439         (*metafile)->bounds.Width = (REAL)(placeable->BoundingBox.Right -
2440                                            placeable->BoundingBox.Left);
2441         (*metafile)->bounds.Height = (REAL)(placeable->BoundingBox.Bottom -
2442                                             placeable->BoundingBox.Top);
2443         (*metafile)->metafile_type = MetafileTypeWmfPlaceable;
2444         (*metafile)->image.format = ImageFormatWMF;
2445
2446         if (delete) DeleteMetaFile(hwmf);
2447     }
2448     else
2449         DeleteEnhMetaFile(hemf);
2450     return retval;
2451 }
2452
2453 GpStatus WINGDIPAPI GdipCreateMetafileFromWmfFile(GDIPCONST WCHAR *file,
2454     GDIPCONST WmfPlaceableFileHeader * placeable, GpMetafile **metafile)
2455 {
2456     HMETAFILE hmf = GetMetaFileW(file);
2457
2458     TRACE("(%s, %p, %p)\n", debugstr_w(file), placeable, metafile);
2459
2460     if(!hmf) return InvalidParameter;
2461
2462     return GdipCreateMetafileFromWmf(hmf, TRUE, placeable, metafile);
2463 }
2464
2465 GpStatus WINGDIPAPI GdipCreateMetafileFromFile(GDIPCONST WCHAR *file,
2466     GpMetafile **metafile)
2467 {
2468     FIXME("(%p, %p): stub\n", file, metafile);
2469     return NotImplemented;
2470 }
2471
2472 GpStatus WINGDIPAPI GdipCreateMetafileFromStream(IStream *stream,
2473     GpMetafile **metafile)
2474 {
2475     FIXME("(%p, %p): stub\n", stream, metafile);
2476     return NotImplemented;
2477 }
2478
2479 GpStatus WINGDIPAPI GdipCreateStreamOnFile(GDIPCONST WCHAR * filename,
2480     UINT access, IStream **stream)
2481 {
2482     DWORD dwMode;
2483     HRESULT ret;
2484
2485     TRACE("(%s, %u, %p)\n", debugstr_w(filename), access, stream);
2486
2487     if(!stream || !filename)
2488         return InvalidParameter;
2489
2490     if(access & GENERIC_WRITE)
2491         dwMode = STGM_SHARE_DENY_WRITE | STGM_WRITE | STGM_CREATE;
2492     else if(access & GENERIC_READ)
2493         dwMode = STGM_SHARE_DENY_WRITE | STGM_READ | STGM_FAILIFTHERE;
2494     else
2495         return InvalidParameter;
2496
2497     ret = SHCreateStreamOnFileW(filename, dwMode, stream);
2498
2499     return hresult_to_status(ret);
2500 }
2501
2502 GpStatus WINGDIPAPI GdipDeleteGraphics(GpGraphics *graphics)
2503 {
2504     GraphicsContainerItem *cont, *next;
2505     GpStatus stat;
2506     TRACE("(%p)\n", graphics);
2507
2508     if(!graphics) return InvalidParameter;
2509     if(graphics->busy) return ObjectBusy;
2510
2511     if (graphics->image && graphics->image->type == ImageTypeMetafile)
2512     {
2513         stat = METAFILE_GraphicsDeleted((GpMetafile*)graphics->image);
2514         if (stat != Ok)
2515             return stat;
2516     }
2517
2518     if(graphics->owndc)
2519         ReleaseDC(graphics->hwnd, graphics->hdc);
2520
2521     LIST_FOR_EACH_ENTRY_SAFE(cont, next, &graphics->containers, GraphicsContainerItem, entry){
2522         list_remove(&cont->entry);
2523         delete_container(cont);
2524     }
2525
2526     GdipDeleteRegion(graphics->clip);
2527     GdipFree(graphics);
2528
2529     return Ok;
2530 }
2531
2532 GpStatus WINGDIPAPI GdipDrawArc(GpGraphics *graphics, GpPen *pen, REAL x,
2533     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
2534 {
2535     INT save_state, num_pts;
2536     GpPointF points[MAX_ARC_PTS];
2537     GpStatus retval;
2538
2539     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y,
2540           width, height, startAngle, sweepAngle);
2541
2542     if(!graphics || !pen || width <= 0 || height <= 0)
2543         return InvalidParameter;
2544
2545     if(graphics->busy)
2546         return ObjectBusy;
2547
2548     if (!graphics->hdc)
2549     {
2550         FIXME("graphics object has no HDC\n");
2551         return Ok;
2552     }
2553
2554     num_pts = arc2polybezier(points, x, y, width, height, startAngle, sweepAngle);
2555
2556     save_state = prepare_dc(graphics, pen);
2557
2558     retval = draw_polybezier(graphics, pen, points, num_pts, TRUE);
2559
2560     restore_dc(graphics, save_state);
2561
2562     return retval;
2563 }
2564
2565 GpStatus WINGDIPAPI GdipDrawArcI(GpGraphics *graphics, GpPen *pen, INT x,
2566     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
2567 {
2568     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n", graphics, pen, x, y,
2569           width, height, startAngle, sweepAngle);
2570
2571     return GdipDrawArc(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
2572 }
2573
2574 GpStatus WINGDIPAPI GdipDrawBezier(GpGraphics *graphics, GpPen *pen, REAL x1,
2575     REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)
2576 {
2577     INT save_state;
2578     GpPointF pt[4];
2579     GpStatus retval;
2580
2581     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x1, y1,
2582           x2, y2, x3, y3, x4, y4);
2583
2584     if(!graphics || !pen)
2585         return InvalidParameter;
2586
2587     if(graphics->busy)
2588         return ObjectBusy;
2589
2590     if (!graphics->hdc)
2591     {
2592         FIXME("graphics object has no HDC\n");
2593         return Ok;
2594     }
2595
2596     pt[0].X = x1;
2597     pt[0].Y = y1;
2598     pt[1].X = x2;
2599     pt[1].Y = y2;
2600     pt[2].X = x3;
2601     pt[2].Y = y3;
2602     pt[3].X = x4;
2603     pt[3].Y = y4;
2604
2605     save_state = prepare_dc(graphics, pen);
2606
2607     retval = draw_polybezier(graphics, pen, pt, 4, TRUE);
2608
2609     restore_dc(graphics, save_state);
2610
2611     return retval;
2612 }
2613
2614 GpStatus WINGDIPAPI GdipDrawBezierI(GpGraphics *graphics, GpPen *pen, INT x1,
2615     INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
2616 {
2617     INT save_state;
2618     GpPointF pt[4];
2619     GpStatus retval;
2620
2621     TRACE("(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d)\n", graphics, pen, x1, y1,
2622           x2, y2, x3, y3, x4, y4);
2623
2624     if(!graphics || !pen)
2625         return InvalidParameter;
2626
2627     if(graphics->busy)
2628         return ObjectBusy;
2629
2630     if (!graphics->hdc)
2631     {
2632         FIXME("graphics object has no HDC\n");
2633         return Ok;
2634     }
2635
2636     pt[0].X = x1;
2637     pt[0].Y = y1;
2638     pt[1].X = x2;
2639     pt[1].Y = y2;
2640     pt[2].X = x3;
2641     pt[2].Y = y3;
2642     pt[3].X = x4;
2643     pt[3].Y = y4;
2644
2645     save_state = prepare_dc(graphics, pen);
2646
2647     retval = draw_polybezier(graphics, pen, pt, 4, TRUE);
2648
2649     restore_dc(graphics, save_state);
2650
2651     return retval;
2652 }
2653
2654 GpStatus WINGDIPAPI GdipDrawBeziers(GpGraphics *graphics, GpPen *pen,
2655     GDIPCONST GpPointF *points, INT count)
2656 {
2657     INT i;
2658     GpStatus ret;
2659
2660     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2661
2662     if(!graphics || !pen || !points || (count <= 0))
2663         return InvalidParameter;
2664
2665     if(graphics->busy)
2666         return ObjectBusy;
2667
2668     for(i = 0; i < floor(count / 4); i++){
2669         ret = GdipDrawBezier(graphics, pen,
2670                              points[4*i].X, points[4*i].Y,
2671                              points[4*i + 1].X, points[4*i + 1].Y,
2672                              points[4*i + 2].X, points[4*i + 2].Y,
2673                              points[4*i + 3].X, points[4*i + 3].Y);
2674         if(ret != Ok)
2675             return ret;
2676     }
2677
2678     return Ok;
2679 }
2680
2681 GpStatus WINGDIPAPI GdipDrawBeziersI(GpGraphics *graphics, GpPen *pen,
2682     GDIPCONST GpPoint *points, INT count)
2683 {
2684     GpPointF *pts;
2685     GpStatus ret;
2686     INT i;
2687
2688     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2689
2690     if(!graphics || !pen || !points || (count <= 0))
2691         return InvalidParameter;
2692
2693     if(graphics->busy)
2694         return ObjectBusy;
2695
2696     pts = GdipAlloc(sizeof(GpPointF) * count);
2697     if(!pts)
2698         return OutOfMemory;
2699
2700     for(i = 0; i < count; i++){
2701         pts[i].X = (REAL)points[i].X;
2702         pts[i].Y = (REAL)points[i].Y;
2703     }
2704
2705     ret = GdipDrawBeziers(graphics,pen,pts,count);
2706
2707     GdipFree(pts);
2708
2709     return ret;
2710 }
2711
2712 GpStatus WINGDIPAPI GdipDrawClosedCurve(GpGraphics *graphics, GpPen *pen,
2713     GDIPCONST GpPointF *points, INT count)
2714 {
2715     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2716
2717     return GdipDrawClosedCurve2(graphics, pen, points, count, 1.0);
2718 }
2719
2720 GpStatus WINGDIPAPI GdipDrawClosedCurveI(GpGraphics *graphics, GpPen *pen,
2721     GDIPCONST GpPoint *points, INT count)
2722 {
2723     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2724
2725     return GdipDrawClosedCurve2I(graphics, pen, points, count, 1.0);
2726 }
2727
2728 GpStatus WINGDIPAPI GdipDrawClosedCurve2(GpGraphics *graphics, GpPen *pen,
2729     GDIPCONST GpPointF *points, INT count, REAL tension)
2730 {
2731     GpPath *path;
2732     GpStatus stat;
2733
2734     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2735
2736     if(!graphics || !pen || !points || count <= 0)
2737         return InvalidParameter;
2738
2739     if(graphics->busy)
2740         return ObjectBusy;
2741
2742     if((stat = GdipCreatePath(FillModeAlternate, &path)) != Ok)
2743         return stat;
2744
2745     stat = GdipAddPathClosedCurve2(path, points, count, tension);
2746     if(stat != Ok){
2747         GdipDeletePath(path);
2748         return stat;
2749     }
2750
2751     stat = GdipDrawPath(graphics, pen, path);
2752
2753     GdipDeletePath(path);
2754
2755     return stat;
2756 }
2757
2758 GpStatus WINGDIPAPI GdipDrawClosedCurve2I(GpGraphics *graphics, GpPen *pen,
2759     GDIPCONST GpPoint *points, INT count, REAL tension)
2760 {
2761     GpPointF *ptf;
2762     GpStatus stat;
2763     INT i;
2764
2765     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2766
2767     if(!points || count <= 0)
2768         return InvalidParameter;
2769
2770     ptf = GdipAlloc(sizeof(GpPointF)*count);
2771     if(!ptf)
2772         return OutOfMemory;
2773
2774     for(i = 0; i < count; i++){
2775         ptf[i].X = (REAL)points[i].X;
2776         ptf[i].Y = (REAL)points[i].Y;
2777     }
2778
2779     stat = GdipDrawClosedCurve2(graphics, pen, ptf, count, tension);
2780
2781     GdipFree(ptf);
2782
2783     return stat;
2784 }
2785
2786 GpStatus WINGDIPAPI GdipDrawCurve(GpGraphics *graphics, GpPen *pen,
2787     GDIPCONST GpPointF *points, INT count)
2788 {
2789     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2790
2791     return GdipDrawCurve2(graphics,pen,points,count,1.0);
2792 }
2793
2794 GpStatus WINGDIPAPI GdipDrawCurveI(GpGraphics *graphics, GpPen *pen,
2795     GDIPCONST GpPoint *points, INT count)
2796 {
2797     GpPointF *pointsF;
2798     GpStatus ret;
2799     INT i;
2800
2801     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
2802
2803     if(!points)
2804         return InvalidParameter;
2805
2806     pointsF = GdipAlloc(sizeof(GpPointF)*count);
2807     if(!pointsF)
2808         return OutOfMemory;
2809
2810     for(i = 0; i < count; i++){
2811         pointsF[i].X = (REAL)points[i].X;
2812         pointsF[i].Y = (REAL)points[i].Y;
2813     }
2814
2815     ret = GdipDrawCurve(graphics,pen,pointsF,count);
2816     GdipFree(pointsF);
2817
2818     return ret;
2819 }
2820
2821 /* Approximates cardinal spline with Bezier curves. */
2822 GpStatus WINGDIPAPI GdipDrawCurve2(GpGraphics *graphics, GpPen *pen,
2823     GDIPCONST GpPointF *points, INT count, REAL tension)
2824 {
2825     /* PolyBezier expects count*3-2 points. */
2826     INT i, len_pt = count*3-2, save_state;
2827     GpPointF *pt;
2828     REAL x1, x2, y1, y2;
2829     GpStatus retval;
2830
2831     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2832
2833     if(!graphics || !pen)
2834         return InvalidParameter;
2835
2836     if(graphics->busy)
2837         return ObjectBusy;
2838
2839     if(count < 2)
2840         return InvalidParameter;
2841
2842     if (!graphics->hdc)
2843     {
2844         FIXME("graphics object has no HDC\n");
2845         return Ok;
2846     }
2847
2848     pt = GdipAlloc(len_pt * sizeof(GpPointF));
2849     if(!pt)
2850         return OutOfMemory;
2851
2852     tension = tension * TENSION_CONST;
2853
2854     calc_curve_bezier_endp(points[0].X, points[0].Y, points[1].X, points[1].Y,
2855         tension, &x1, &y1);
2856
2857     pt[0].X = points[0].X;
2858     pt[0].Y = points[0].Y;
2859     pt[1].X = x1;
2860     pt[1].Y = y1;
2861
2862     for(i = 0; i < count-2; i++){
2863         calc_curve_bezier(&(points[i]), tension, &x1, &y1, &x2, &y2);
2864
2865         pt[3*i+2].X = x1;
2866         pt[3*i+2].Y = y1;
2867         pt[3*i+3].X = points[i+1].X;
2868         pt[3*i+3].Y = points[i+1].Y;
2869         pt[3*i+4].X = x2;
2870         pt[3*i+4].Y = y2;
2871     }
2872
2873     calc_curve_bezier_endp(points[count-1].X, points[count-1].Y,
2874         points[count-2].X, points[count-2].Y, tension, &x1, &y1);
2875
2876     pt[len_pt-2].X = x1;
2877     pt[len_pt-2].Y = y1;
2878     pt[len_pt-1].X = points[count-1].X;
2879     pt[len_pt-1].Y = points[count-1].Y;
2880
2881     save_state = prepare_dc(graphics, pen);
2882
2883     retval = draw_polybezier(graphics, pen, pt, len_pt, TRUE);
2884
2885     GdipFree(pt);
2886     restore_dc(graphics, save_state);
2887
2888     return retval;
2889 }
2890
2891 GpStatus WINGDIPAPI GdipDrawCurve2I(GpGraphics *graphics, GpPen *pen,
2892     GDIPCONST GpPoint *points, INT count, REAL tension)
2893 {
2894     GpPointF *pointsF;
2895     GpStatus ret;
2896     INT i;
2897
2898     TRACE("(%p, %p, %p, %d, %.2f)\n", graphics, pen, points, count, tension);
2899
2900     if(!points)
2901         return InvalidParameter;
2902
2903     pointsF = GdipAlloc(sizeof(GpPointF)*count);
2904     if(!pointsF)
2905         return OutOfMemory;
2906
2907     for(i = 0; i < count; i++){
2908         pointsF[i].X = (REAL)points[i].X;
2909         pointsF[i].Y = (REAL)points[i].Y;
2910     }
2911
2912     ret = GdipDrawCurve2(graphics,pen,pointsF,count,tension);
2913     GdipFree(pointsF);
2914
2915     return ret;
2916 }
2917
2918 GpStatus WINGDIPAPI GdipDrawCurve3(GpGraphics *graphics, GpPen *pen,
2919     GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments,
2920     REAL tension)
2921 {
2922     TRACE("(%p, %p, %p, %d, %d, %d, %.2f)\n", graphics, pen, points, count, offset, numberOfSegments, tension);
2923
2924     if(offset >= count || numberOfSegments > count - offset - 1 || numberOfSegments <= 0){
2925         return InvalidParameter;
2926     }
2927
2928     return GdipDrawCurve2(graphics, pen, points + offset, numberOfSegments + 1, tension);
2929 }
2930
2931 GpStatus WINGDIPAPI GdipDrawCurve3I(GpGraphics *graphics, GpPen *pen,
2932     GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments,
2933     REAL tension)
2934 {
2935     TRACE("(%p, %p, %p, %d, %d, %d, %.2f)\n", graphics, pen, points, count, offset, numberOfSegments, tension);
2936
2937     if(count < 0){
2938         return OutOfMemory;
2939     }
2940
2941     if(offset >= count || numberOfSegments > count - offset - 1 || numberOfSegments <= 0){
2942         return InvalidParameter;
2943     }
2944
2945     return GdipDrawCurve2I(graphics, pen, points + offset, numberOfSegments + 1, tension);
2946 }
2947
2948 GpStatus WINGDIPAPI GdipDrawEllipse(GpGraphics *graphics, GpPen *pen, REAL x,
2949     REAL y, REAL width, REAL height)
2950 {
2951     INT save_state;
2952     GpPointF ptf[2];
2953     POINT pti[2];
2954
2955     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y, width, height);
2956
2957     if(!graphics || !pen)
2958         return InvalidParameter;
2959
2960     if(graphics->busy)
2961         return ObjectBusy;
2962
2963     if (!graphics->hdc)
2964     {
2965         FIXME("graphics object has no HDC\n");
2966         return Ok;
2967     }
2968
2969     ptf[0].X = x;
2970     ptf[0].Y = y;
2971     ptf[1].X = x + width;
2972     ptf[1].Y = y + height;
2973
2974     save_state = prepare_dc(graphics, pen);
2975     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
2976
2977     transform_and_round_points(graphics, pti, ptf, 2);
2978
2979     Ellipse(graphics->hdc, pti[0].x, pti[0].y, pti[1].x, pti[1].y);
2980
2981     restore_dc(graphics, save_state);
2982
2983     return Ok;
2984 }
2985
2986 GpStatus WINGDIPAPI GdipDrawEllipseI(GpGraphics *graphics, GpPen *pen, INT x,
2987     INT y, INT width, INT height)
2988 {
2989     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x, y, width, height);
2990
2991     return GdipDrawEllipse(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
2992 }
2993
2994
2995 GpStatus WINGDIPAPI GdipDrawImage(GpGraphics *graphics, GpImage *image, REAL x, REAL y)
2996 {
2997     UINT width, height;
2998
2999     TRACE("(%p, %p, %.2f, %.2f)\n", graphics, image, x, y);
3000
3001     if(!graphics || !image)
3002         return InvalidParameter;
3003
3004     GdipGetImageWidth(image, &width);
3005     GdipGetImageHeight(image, &height);
3006
3007     return GdipDrawImagePointRect(graphics, image, x, y,
3008                                   0.0, 0.0, (REAL)width, (REAL)height, UnitPixel);
3009 }
3010
3011 GpStatus WINGDIPAPI GdipDrawImageI(GpGraphics *graphics, GpImage *image, INT x,
3012     INT y)
3013 {
3014     TRACE("(%p, %p, %d, %d)\n", graphics, image, x, y);
3015
3016     return GdipDrawImage(graphics, image, (REAL)x, (REAL)y);
3017 }
3018
3019 GpStatus WINGDIPAPI GdipDrawImagePointRect(GpGraphics *graphics, GpImage *image,
3020     REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight,
3021     GpUnit srcUnit)
3022 {
3023     GpPointF points[3];
3024     REAL scale_x, scale_y, width, height;
3025
3026     TRACE("(%p, %p, %f, %f, %f, %f, %f, %f, %d)\n", graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
3027
3028     scale_x = units_scale(srcUnit, graphics->unit, graphics->xres);
3029     scale_x *= graphics->xres / image->xres;
3030     scale_y = units_scale(srcUnit, graphics->unit, graphics->yres);
3031     scale_y *= graphics->yres / image->yres;
3032     width = srcwidth * scale_x;
3033     height = srcheight * scale_y;
3034
3035     points[0].X = points[2].X = x;
3036     points[0].Y = points[1].Y = y;
3037     points[1].X = x + width;
3038     points[2].Y = y + height;
3039
3040     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3041         srcwidth, srcheight, srcUnit, NULL, NULL, NULL);
3042 }
3043
3044 GpStatus WINGDIPAPI GdipDrawImagePointRectI(GpGraphics *graphics, GpImage *image,
3045     INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight,
3046     GpUnit srcUnit)
3047 {
3048     return GdipDrawImagePointRect(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
3049 }
3050
3051 GpStatus WINGDIPAPI GdipDrawImagePoints(GpGraphics *graphics, GpImage *image,
3052     GDIPCONST GpPointF *dstpoints, INT count)
3053 {
3054     UINT width, height;
3055
3056     TRACE("(%p, %p, %p, %d)\n", graphics, image, dstpoints, count);
3057
3058     if(!image)
3059         return InvalidParameter;
3060
3061     GdipGetImageWidth(image, &width);
3062     GdipGetImageHeight(image, &height);
3063
3064     return GdipDrawImagePointsRect(graphics, image, dstpoints, count, 0, 0,
3065         width, height, UnitPixel, NULL, NULL, NULL);
3066 }
3067
3068 GpStatus WINGDIPAPI GdipDrawImagePointsI(GpGraphics *graphics, GpImage *image,
3069     GDIPCONST GpPoint *dstpoints, INT count)
3070 {
3071     GpPointF ptf[3];
3072
3073     TRACE("(%p, %p, %p, %d)\n", graphics, image, dstpoints, count);
3074
3075     if (count != 3 || !dstpoints)
3076         return InvalidParameter;
3077
3078     ptf[0].X = (REAL)dstpoints[0].X;
3079     ptf[0].Y = (REAL)dstpoints[0].Y;
3080     ptf[1].X = (REAL)dstpoints[1].X;
3081     ptf[1].Y = (REAL)dstpoints[1].Y;
3082     ptf[2].X = (REAL)dstpoints[2].X;
3083     ptf[2].Y = (REAL)dstpoints[2].Y;
3084
3085     return GdipDrawImagePoints(graphics, image, ptf, count);
3086 }
3087
3088 static BOOL CALLBACK play_metafile_proc(EmfPlusRecordType record_type, unsigned int flags,
3089     unsigned int dataSize, const unsigned char *pStr, void *userdata)
3090 {
3091     GdipPlayMetafileRecord(userdata, record_type, flags, dataSize, pStr);
3092     return TRUE;
3093 }
3094
3095 GpStatus WINGDIPAPI GdipDrawImagePointsRect(GpGraphics *graphics, GpImage *image,
3096      GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth,
3097      REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes,
3098      DrawImageAbort callback, VOID * callbackData)
3099 {
3100     GpPointF ptf[4];
3101     POINT pti[4];
3102     GpStatus stat;
3103
3104     TRACE("(%p, %p, %p, %d, %f, %f, %f, %f, %d, %p, %p, %p)\n", graphics, image, points,
3105           count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback,
3106           callbackData);
3107
3108     if (count > 3)
3109         return NotImplemented;
3110
3111     if(!graphics || !image || !points || count != 3)
3112          return InvalidParameter;
3113
3114     TRACE("%s %s %s\n", debugstr_pointf(&points[0]), debugstr_pointf(&points[1]),
3115         debugstr_pointf(&points[2]));
3116
3117     memcpy(ptf, points, 3 * sizeof(GpPointF));
3118     ptf[3].X = ptf[2].X + ptf[1].X - ptf[0].X;
3119     ptf[3].Y = ptf[2].Y + ptf[1].Y - ptf[0].Y;
3120     if (!srcwidth || !srcheight || ptf[3].X == ptf[0].X || ptf[3].Y == ptf[0].Y)
3121         return Ok;
3122     transform_and_round_points(graphics, pti, ptf, 4);
3123
3124     TRACE("%s %s %s %s\n", wine_dbgstr_point(&pti[0]), wine_dbgstr_point(&pti[1]),
3125         wine_dbgstr_point(&pti[2]), wine_dbgstr_point(&pti[3]));
3126
3127     srcx = units_to_pixels(srcx, srcUnit, image->xres);
3128     srcy = units_to_pixels(srcy, srcUnit, image->yres);
3129     srcwidth = units_to_pixels(srcwidth, srcUnit, image->xres);
3130     srcheight = units_to_pixels(srcheight, srcUnit, image->yres);
3131     TRACE("src pixels: %f,%f %fx%f\n", srcx, srcy, srcwidth, srcheight);
3132
3133     if (image->picture)
3134     {
3135         if (!graphics->hdc)
3136         {
3137             FIXME("graphics object has no HDC\n");
3138         }
3139
3140         if(IPicture_Render(image->picture, graphics->hdc,
3141             pti[0].x, pti[0].y, pti[1].x - pti[0].x, pti[2].y - pti[0].y,
3142             srcx, srcy, srcwidth, srcheight, NULL) != S_OK)
3143         {
3144             if(callback)
3145                 callback(callbackData);
3146             return GenericError;
3147         }
3148     }
3149     else if (image->type == ImageTypeBitmap)
3150     {
3151         GpBitmap* bitmap = (GpBitmap*)image;
3152         int use_software=0;
3153
3154         TRACE("graphics: %.2fx%.2f dpi, fmt %#x, scale %f, image: %.2fx%.2f dpi, fmt %#x, color %08x\n",
3155             graphics->xres, graphics->yres,
3156             graphics->image && graphics->image->type == ImageTypeBitmap ? ((GpBitmap *)graphics->image)->format : 0,
3157             graphics->scale, image->xres, image->yres, bitmap->format,
3158             imageAttributes ? imageAttributes->outside_color : 0);
3159
3160         if (imageAttributes ||
3161             (graphics->image && graphics->image->type == ImageTypeBitmap) ||
3162             ptf[1].Y != ptf[0].Y || ptf[2].X != ptf[0].X ||
3163             ptf[1].X - ptf[0].X != srcwidth || ptf[2].Y - ptf[0].Y != srcheight ||
3164             srcx < 0 || srcy < 0 ||
3165             srcx + srcwidth > bitmap->width || srcy + srcheight > bitmap->height)
3166             use_software = 1;
3167
3168         if (use_software)
3169         {
3170             RECT dst_area;
3171             GpRect src_area;
3172             int i, x, y, src_stride, dst_stride;
3173             GpMatrix dst_to_src;
3174             REAL m11, m12, m21, m22, mdx, mdy;
3175             LPBYTE src_data, dst_data;
3176             BitmapData lockeddata;
3177             InterpolationMode interpolation = graphics->interpolation;
3178             PixelOffsetMode offset_mode = graphics->pixeloffset;
3179             GpPointF dst_to_src_points[3] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}};
3180             REAL x_dx, x_dy, y_dx, y_dy;
3181             static const GpImageAttributes defaultImageAttributes = {WrapModeClamp, 0, FALSE};
3182
3183             if (!imageAttributes)
3184                 imageAttributes = &defaultImageAttributes;
3185
3186             dst_area.left = dst_area.right = pti[0].x;
3187             dst_area.top = dst_area.bottom = pti[0].y;
3188             for (i=1; i<4; i++)
3189             {
3190                 if (dst_area.left > pti[i].x) dst_area.left = pti[i].x;
3191                 if (dst_area.right < pti[i].x) dst_area.right = pti[i].x;
3192                 if (dst_area.top > pti[i].y) dst_area.top = pti[i].y;
3193                 if (dst_area.bottom < pti[i].y) dst_area.bottom = pti[i].y;
3194             }
3195
3196             TRACE("dst_area: %s\n", wine_dbgstr_rect(&dst_area));
3197
3198             m11 = (ptf[1].X - ptf[0].X) / srcwidth;
3199             m21 = (ptf[2].X - ptf[0].X) / srcheight;
3200             mdx = ptf[0].X - m11 * srcx - m21 * srcy;
3201             m12 = (ptf[1].Y - ptf[0].Y) / srcwidth;
3202             m22 = (ptf[2].Y - ptf[0].Y) / srcheight;
3203             mdy = ptf[0].Y - m12 * srcx - m22 * srcy;
3204
3205             GdipSetMatrixElements(&dst_to_src, m11, m12, m21, m22, mdx, mdy);
3206
3207             stat = GdipInvertMatrix(&dst_to_src);
3208             if (stat != Ok) return stat;
3209
3210             dst_data = GdipAlloc(sizeof(ARGB) * (dst_area.right - dst_area.left) * (dst_area.bottom - dst_area.top));
3211             if (!dst_data) return OutOfMemory;
3212
3213             dst_stride = sizeof(ARGB) * (dst_area.right - dst_area.left);
3214
3215             get_bitmap_sample_size(interpolation, imageAttributes->wrap,
3216                 bitmap, srcx, srcy, srcwidth, srcheight, &src_area);
3217
3218             TRACE("src_area: %d x %d\n", src_area.Width, src_area.Height);
3219
3220             src_data = GdipAlloc(sizeof(ARGB) * src_area.Width * src_area.Height);
3221             if (!src_data)
3222             {
3223                 GdipFree(dst_data);
3224                 return OutOfMemory;
3225             }
3226             src_stride = sizeof(ARGB) * src_area.Width;
3227
3228             /* Read the bits we need from the source bitmap into an ARGB buffer. */
3229             lockeddata.Width = src_area.Width;
3230             lockeddata.Height = src_area.Height;
3231             lockeddata.Stride = src_stride;
3232             lockeddata.PixelFormat = PixelFormat32bppARGB;
3233             lockeddata.Scan0 = src_data;
3234
3235             stat = GdipBitmapLockBits(bitmap, &src_area, ImageLockModeRead|ImageLockModeUserInputBuf,
3236                 PixelFormat32bppARGB, &lockeddata);
3237
3238             if (stat == Ok)
3239                 stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
3240
3241             if (stat != Ok)
3242             {
3243                 if (src_data != dst_data)
3244                     GdipFree(src_data);
3245                 GdipFree(dst_data);
3246                 return stat;
3247             }
3248
3249             apply_image_attributes(imageAttributes, src_data,
3250                 src_area.Width, src_area.Height,
3251                 src_stride, ColorAdjustTypeBitmap);
3252
3253             /* Transform the bits as needed to the destination. */
3254             GdipTransformMatrixPoints(&dst_to_src, dst_to_src_points, 3);
3255
3256             x_dx = dst_to_src_points[1].X - dst_to_src_points[0].X;
3257             x_dy = dst_to_src_points[1].Y - dst_to_src_points[0].Y;
3258             y_dx = dst_to_src_points[2].X - dst_to_src_points[0].X;
3259             y_dy = dst_to_src_points[2].Y - dst_to_src_points[0].Y;
3260
3261             for (x=dst_area.left; x<dst_area.right; x++)
3262             {
3263                 for (y=dst_area.top; y<dst_area.bottom; y++)
3264                 {
3265                     GpPointF src_pointf;
3266                     ARGB *dst_color;
3267
3268                     src_pointf.X = dst_to_src_points[0].X + x * x_dx + y * y_dx;
3269                     src_pointf.Y = dst_to_src_points[0].Y + x * x_dy + y * y_dy;
3270
3271                     dst_color = (ARGB*)(dst_data + dst_stride * (y - dst_area.top) + sizeof(ARGB) * (x - dst_area.left));
3272
3273                     if (src_pointf.X >= srcx && src_pointf.X < srcx + srcwidth && src_pointf.Y >= srcy && src_pointf.Y < srcy+srcheight)
3274                         *dst_color = resample_bitmap_pixel(&src_area, src_data, bitmap->width, bitmap->height, &src_pointf,
3275                                                            imageAttributes, interpolation, offset_mode);
3276                     else
3277                         *dst_color = 0;
3278                 }
3279             }
3280
3281             GdipFree(src_data);
3282
3283             stat = alpha_blend_pixels(graphics, dst_area.left, dst_area.top,
3284                 dst_data, dst_area.right - dst_area.left, dst_area.bottom - dst_area.top, dst_stride);
3285
3286             GdipFree(dst_data);
3287
3288             return stat;
3289         }
3290         else
3291         {
3292             HDC hdc;
3293             int temp_hdc=0, temp_bitmap=0;
3294             HBITMAP hbitmap, old_hbm=NULL;
3295
3296             if (!(bitmap->format == PixelFormat16bppRGB555 ||
3297                   bitmap->format == PixelFormat24bppRGB ||
3298                   bitmap->format == PixelFormat32bppRGB ||
3299                   bitmap->format == PixelFormat32bppPARGB))
3300             {
3301                 BITMAPINFOHEADER bih;
3302                 BYTE *temp_bits;
3303                 PixelFormat dst_format;
3304
3305                 /* we can't draw a bitmap of this format directly */
3306                 hdc = CreateCompatibleDC(0);
3307                 temp_hdc = 1;
3308                 temp_bitmap = 1;
3309
3310                 bih.biSize = sizeof(BITMAPINFOHEADER);
3311                 bih.biWidth = bitmap->width;
3312                 bih.biHeight = -bitmap->height;
3313                 bih.biPlanes = 1;
3314                 bih.biBitCount = 32;
3315                 bih.biCompression = BI_RGB;
3316                 bih.biSizeImage = 0;
3317                 bih.biXPelsPerMeter = 0;
3318                 bih.biYPelsPerMeter = 0;
3319                 bih.biClrUsed = 0;
3320                 bih.biClrImportant = 0;
3321
3322                 hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bih, DIB_RGB_COLORS,
3323                     (void**)&temp_bits, NULL, 0);
3324
3325                 if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3326                     dst_format = PixelFormat32bppPARGB;
3327                 else
3328                     dst_format = PixelFormat32bppRGB;
3329
3330                 convert_pixels(bitmap->width, bitmap->height,
3331                     bitmap->width*4, temp_bits, dst_format,
3332                     bitmap->stride, bitmap->bits, bitmap->format,
3333                     bitmap->image.palette);
3334             }
3335             else
3336             {
3337                 if (bitmap->hbitmap)
3338                     hbitmap = bitmap->hbitmap;
3339                 else
3340                 {
3341                     GdipCreateHBITMAPFromBitmap(bitmap, &hbitmap, 0);
3342                     temp_bitmap = 1;
3343                 }
3344
3345                 hdc = bitmap->hdc;
3346                 temp_hdc = (hdc == 0);
3347             }
3348
3349             if (temp_hdc)
3350             {
3351                 if (!hdc) hdc = CreateCompatibleDC(0);
3352                 old_hbm = SelectObject(hdc, hbitmap);
3353             }
3354
3355             if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3356             {
3357                 gdi_alpha_blend(graphics, pti[0].x, pti[0].y, pti[1].x - pti[0].x, pti[2].y - pti[0].y,
3358                                 hdc, srcx, srcy, srcwidth, srcheight);
3359             }
3360             else
3361             {
3362                 StretchBlt(graphics->hdc, pti[0].x, pti[0].y, pti[1].x-pti[0].x, pti[2].y-pti[0].y,
3363                     hdc, srcx, srcy, srcwidth, srcheight, SRCCOPY);
3364             }
3365
3366             if (temp_hdc)
3367             {
3368                 SelectObject(hdc, old_hbm);
3369                 DeleteDC(hdc);
3370             }
3371
3372             if (temp_bitmap)
3373                 DeleteObject(hbitmap);
3374         }
3375     }
3376     else if (image->type == ImageTypeMetafile && ((GpMetafile*)image)->hemf)
3377     {
3378         GpRectF rc;
3379
3380         rc.X = srcx;
3381         rc.Y = srcy;
3382         rc.Width = srcwidth;
3383         rc.Height = srcheight;
3384
3385         return GdipEnumerateMetafileSrcRectDestPoints(graphics, (GpMetafile*)image,
3386             points, count, &rc, srcUnit, play_metafile_proc, image, imageAttributes);
3387     }
3388     else
3389     {
3390         WARN("GpImage with nothing we can draw (metafile in wrong state?)\n");
3391         return InvalidParameter;
3392     }
3393
3394     return Ok;
3395 }
3396
3397 GpStatus WINGDIPAPI GdipDrawImagePointsRectI(GpGraphics *graphics, GpImage *image,
3398      GDIPCONST GpPoint *points, INT count, INT srcx, INT srcy, INT srcwidth,
3399      INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes,
3400      DrawImageAbort callback, VOID * callbackData)
3401 {
3402     GpPointF pointsF[3];
3403     INT i;
3404
3405     TRACE("(%p, %p, %p, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n", graphics, image, points, count,
3406           srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback,
3407           callbackData);
3408
3409     if(!points || count!=3)
3410         return InvalidParameter;
3411
3412     for(i = 0; i < count; i++){
3413         pointsF[i].X = (REAL)points[i].X;
3414         pointsF[i].Y = (REAL)points[i].Y;
3415     }
3416
3417     return GdipDrawImagePointsRect(graphics, image, pointsF, count, (REAL)srcx, (REAL)srcy,
3418                                    (REAL)srcwidth, (REAL)srcheight, srcUnit, imageAttributes,
3419                                    callback, callbackData);
3420 }
3421
3422 GpStatus WINGDIPAPI GdipDrawImageRectRect(GpGraphics *graphics, GpImage *image,
3423     REAL dstx, REAL dsty, REAL dstwidth, REAL dstheight, REAL srcx, REAL srcy,
3424     REAL srcwidth, REAL srcheight, GpUnit srcUnit,
3425     GDIPCONST GpImageAttributes* imageattr, DrawImageAbort callback,
3426     VOID * callbackData)
3427 {
3428     GpPointF points[3];
3429
3430     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %d, %p, %p, %p)\n",
3431           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3432           srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3433
3434     points[0].X = dstx;
3435     points[0].Y = dsty;
3436     points[1].X = dstx + dstwidth;
3437     points[1].Y = dsty;
3438     points[2].X = dstx;
3439     points[2].Y = dsty + dstheight;
3440
3441     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3442                srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3443 }
3444
3445 GpStatus WINGDIPAPI GdipDrawImageRectRectI(GpGraphics *graphics, GpImage *image,
3446         INT dstx, INT dsty, INT dstwidth, INT dstheight, INT srcx, INT srcy,
3447         INT srcwidth, INT srcheight, GpUnit srcUnit,
3448         GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback,
3449         VOID * callbackData)
3450 {
3451     GpPointF points[3];
3452
3453     TRACE("(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n",
3454           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3455           srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3456
3457     points[0].X = dstx;
3458     points[0].Y = dsty;
3459     points[1].X = dstx + dstwidth;
3460     points[1].Y = dsty;
3461     points[2].X = dstx;
3462     points[2].Y = dsty + dstheight;
3463
3464     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3465                srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3466 }
3467
3468 GpStatus WINGDIPAPI GdipDrawImageRect(GpGraphics *graphics, GpImage *image,
3469     REAL x, REAL y, REAL width, REAL height)
3470 {
3471     RectF bounds;
3472     GpUnit unit;
3473     GpStatus ret;
3474
3475     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, image, x, y, width, height);
3476
3477     if(!graphics || !image)
3478         return InvalidParameter;
3479
3480     ret = GdipGetImageBounds(image, &bounds, &unit);
3481     if(ret != Ok)
3482         return ret;
3483
3484     return GdipDrawImageRectRect(graphics, image, x, y, width, height,
3485                                  bounds.X, bounds.Y, bounds.Width, bounds.Height,
3486                                  unit, NULL, NULL, NULL);
3487 }
3488
3489 GpStatus WINGDIPAPI GdipDrawImageRectI(GpGraphics *graphics, GpImage *image,
3490     INT x, INT y, INT width, INT height)
3491 {
3492     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, image, x, y, width, height);
3493
3494     return GdipDrawImageRect(graphics, image, (REAL)x, (REAL)y, (REAL)width, (REAL)height);
3495 }
3496
3497 GpStatus WINGDIPAPI GdipDrawLine(GpGraphics *graphics, GpPen *pen, REAL x1,
3498     REAL y1, REAL x2, REAL y2)
3499 {
3500     INT save_state;
3501     GpPointF pt[2];
3502     GpStatus retval;
3503
3504     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x1, y1, x2, y2);
3505
3506     if(!pen || !graphics)
3507         return InvalidParameter;
3508
3509     if(graphics->busy)
3510         return ObjectBusy;
3511
3512     if (!graphics->hdc)
3513     {
3514         FIXME("graphics object has no HDC\n");
3515         return Ok;
3516     }
3517
3518     pt[0].X = x1;
3519     pt[0].Y = y1;
3520     pt[1].X = x2;
3521     pt[1].Y = y2;
3522
3523     save_state = prepare_dc(graphics, pen);
3524
3525     retval = draw_polyline(graphics, pen, pt, 2, TRUE);
3526
3527     restore_dc(graphics, save_state);
3528
3529     return retval;
3530 }
3531
3532 GpStatus WINGDIPAPI GdipDrawLineI(GpGraphics *graphics, GpPen *pen, INT x1,
3533     INT y1, INT x2, INT y2)
3534 {
3535     INT save_state;
3536     GpPointF pt[2];
3537     GpStatus retval;
3538
3539     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x1, y1, x2, y2);
3540
3541     if(!pen || !graphics)
3542         return InvalidParameter;
3543
3544     if(graphics->busy)
3545         return ObjectBusy;
3546
3547     if (!graphics->hdc)
3548     {
3549         FIXME("graphics object has no HDC\n");
3550         return Ok;
3551     }
3552
3553     pt[0].X = (REAL)x1;
3554     pt[0].Y = (REAL)y1;
3555     pt[1].X = (REAL)x2;
3556     pt[1].Y = (REAL)y2;
3557
3558     save_state = prepare_dc(graphics, pen);
3559
3560     retval = draw_polyline(graphics, pen, pt, 2, TRUE);
3561
3562     restore_dc(graphics, save_state);
3563
3564     return retval;
3565 }
3566
3567 GpStatus WINGDIPAPI GdipDrawLines(GpGraphics *graphics, GpPen *pen, GDIPCONST
3568     GpPointF *points, INT count)
3569 {
3570     INT save_state;
3571     GpStatus retval;
3572
3573     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3574
3575     if(!pen || !graphics || (count < 2))
3576         return InvalidParameter;
3577
3578     if(graphics->busy)
3579         return ObjectBusy;
3580
3581     if (!graphics->hdc)
3582     {
3583         FIXME("graphics object has no HDC\n");
3584         return Ok;
3585     }
3586
3587     save_state = prepare_dc(graphics, pen);
3588
3589     retval = draw_polyline(graphics, pen, points, count, TRUE);
3590
3591     restore_dc(graphics, save_state);
3592
3593     return retval;
3594 }
3595
3596 GpStatus WINGDIPAPI GdipDrawLinesI(GpGraphics *graphics, GpPen *pen, GDIPCONST
3597     GpPoint *points, INT count)
3598 {
3599     INT save_state;
3600     GpStatus retval;
3601     GpPointF *ptf = NULL;
3602     int i;
3603
3604     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3605
3606     if(!pen || !graphics || (count < 2))
3607         return InvalidParameter;
3608
3609     if(graphics->busy)
3610         return ObjectBusy;
3611
3612     if (!graphics->hdc)
3613     {
3614         FIXME("graphics object has no HDC\n");
3615         return Ok;
3616     }
3617
3618     ptf = GdipAlloc(count * sizeof(GpPointF));
3619     if(!ptf) return OutOfMemory;
3620
3621     for(i = 0; i < count; i ++){
3622         ptf[i].X = (REAL) points[i].X;
3623         ptf[i].Y = (REAL) points[i].Y;
3624     }
3625
3626     save_state = prepare_dc(graphics, pen);
3627
3628     retval = draw_polyline(graphics, pen, ptf, count, TRUE);
3629
3630     restore_dc(graphics, save_state);
3631
3632     GdipFree(ptf);
3633     return retval;
3634 }
3635
3636 GpStatus WINGDIPAPI GdipDrawPath(GpGraphics *graphics, GpPen *pen, GpPath *path)
3637 {
3638     INT save_state;
3639     GpStatus retval;
3640
3641     TRACE("(%p, %p, %p)\n", graphics, pen, path);
3642
3643     if(!pen || !graphics)
3644         return InvalidParameter;
3645
3646     if(graphics->busy)
3647         return ObjectBusy;
3648
3649     if (!graphics->hdc)
3650     {
3651         FIXME("graphics object has no HDC\n");
3652         return Ok;
3653     }
3654
3655     save_state = prepare_dc(graphics, pen);
3656
3657     retval = draw_poly(graphics, pen, path->pathdata.Points,
3658                        path->pathdata.Types, path->pathdata.Count, TRUE);
3659
3660     restore_dc(graphics, save_state);
3661
3662     return retval;
3663 }
3664
3665 GpStatus WINGDIPAPI GdipDrawPie(GpGraphics *graphics, GpPen *pen, REAL x,
3666     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
3667 {
3668     INT save_state;
3669
3670     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y,
3671             width, height, startAngle, sweepAngle);
3672
3673     if(!graphics || !pen)
3674         return InvalidParameter;
3675
3676     if(graphics->busy)
3677         return ObjectBusy;
3678
3679     if (!graphics->hdc)
3680     {
3681         FIXME("graphics object has no HDC\n");
3682         return Ok;
3683     }
3684
3685     save_state = prepare_dc(graphics, pen);
3686     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3687
3688     draw_pie(graphics, x, y, width, height, startAngle, sweepAngle);
3689
3690     restore_dc(graphics, save_state);
3691
3692     return Ok;
3693 }
3694
3695 GpStatus WINGDIPAPI GdipDrawPieI(GpGraphics *graphics, GpPen *pen, INT x,
3696     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
3697 {
3698     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n", graphics, pen, x, y,
3699             width, height, startAngle, sweepAngle);
3700
3701     return GdipDrawPie(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
3702 }
3703
3704 GpStatus WINGDIPAPI GdipDrawRectangle(GpGraphics *graphics, GpPen *pen, REAL x,
3705     REAL y, REAL width, REAL height)
3706 {
3707     INT save_state;
3708     GpPointF ptf[4];
3709     POINT pti[4];
3710
3711     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y, width, height);
3712
3713     if(!pen || !graphics)
3714         return InvalidParameter;
3715
3716     if(graphics->busy)
3717         return ObjectBusy;
3718
3719     if (!graphics->hdc)
3720     {
3721         FIXME("graphics object has no HDC\n");
3722         return Ok;
3723     }
3724
3725     ptf[0].X = x;
3726     ptf[0].Y = y;
3727     ptf[1].X = x + width;
3728     ptf[1].Y = y;
3729     ptf[2].X = x + width;
3730     ptf[2].Y = y + height;
3731     ptf[3].X = x;
3732     ptf[3].Y = y + height;
3733
3734     save_state = prepare_dc(graphics, pen);
3735     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3736
3737     transform_and_round_points(graphics, pti, ptf, 4);
3738     Polygon(graphics->hdc, pti, 4);
3739
3740     restore_dc(graphics, save_state);
3741
3742     return Ok;
3743 }
3744
3745 GpStatus WINGDIPAPI GdipDrawRectangleI(GpGraphics *graphics, GpPen *pen, INT x,
3746     INT y, INT width, INT height)
3747 {
3748     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x, y, width, height);
3749
3750     return GdipDrawRectangle(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3751 }
3752
3753 GpStatus WINGDIPAPI GdipDrawRectangles(GpGraphics *graphics, GpPen *pen,
3754     GDIPCONST GpRectF* rects, INT count)
3755 {
3756     GpPointF *ptf;
3757     POINT *pti;
3758     INT save_state, i;
3759
3760     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3761
3762     if(!graphics || !pen || !rects || count < 1)
3763         return InvalidParameter;
3764
3765     if(graphics->busy)
3766         return ObjectBusy;
3767
3768     if (!graphics->hdc)
3769     {
3770         FIXME("graphics object has no HDC\n");
3771         return Ok;
3772     }
3773
3774     ptf = GdipAlloc(4 * count * sizeof(GpPointF));
3775     pti = GdipAlloc(4 * count * sizeof(POINT));
3776
3777     if(!ptf || !pti){
3778         GdipFree(ptf);
3779         GdipFree(pti);
3780         return OutOfMemory;
3781     }
3782
3783     for(i = 0; i < count; i++){
3784         ptf[4 * i + 3].X = ptf[4 * i].X = rects[i].X;
3785         ptf[4 * i + 1].Y = ptf[4 * i].Y = rects[i].Y;
3786         ptf[4 * i + 2].X = ptf[4 * i + 1].X = rects[i].X + rects[i].Width;
3787         ptf[4 * i + 3].Y = ptf[4 * i + 2].Y = rects[i].Y + rects[i].Height;
3788     }
3789
3790     save_state = prepare_dc(graphics, pen);
3791     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3792
3793     transform_and_round_points(graphics, pti, ptf, 4 * count);
3794
3795     for(i = 0; i < count; i++)
3796         Polygon(graphics->hdc, &pti[4 * i], 4);
3797
3798     restore_dc(graphics, save_state);
3799
3800     GdipFree(ptf);
3801     GdipFree(pti);
3802
3803     return Ok;
3804 }
3805
3806 GpStatus WINGDIPAPI GdipDrawRectanglesI(GpGraphics *graphics, GpPen *pen,
3807     GDIPCONST GpRect* rects, INT count)
3808 {
3809     GpRectF *rectsF;
3810     GpStatus ret;
3811     INT i;
3812
3813     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3814
3815     if(!rects || count<=0)
3816         return InvalidParameter;
3817
3818     rectsF = GdipAlloc(sizeof(GpRectF) * count);
3819     if(!rectsF)
3820         return OutOfMemory;
3821
3822     for(i = 0;i < count;i++){
3823         rectsF[i].X      = (REAL)rects[i].X;
3824         rectsF[i].Y      = (REAL)rects[i].Y;
3825         rectsF[i].Width  = (REAL)rects[i].Width;
3826         rectsF[i].Height = (REAL)rects[i].Height;
3827     }
3828
3829     ret = GdipDrawRectangles(graphics, pen, rectsF, count);
3830     GdipFree(rectsF);
3831
3832     return ret;
3833 }
3834
3835 GpStatus WINGDIPAPI GdipFillClosedCurve2(GpGraphics *graphics, GpBrush *brush,
3836     GDIPCONST GpPointF *points, INT count, REAL tension, GpFillMode fill)
3837 {
3838     GpPath *path;
3839     GpStatus stat;
3840
3841     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3842             count, tension, fill);
3843
3844     if(!graphics || !brush || !points)
3845         return InvalidParameter;
3846
3847     if(graphics->busy)
3848         return ObjectBusy;
3849
3850     if(count == 1)    /* Do nothing */
3851         return Ok;
3852
3853     stat = GdipCreatePath(fill, &path);
3854     if(stat != Ok)
3855         return stat;
3856
3857     stat = GdipAddPathClosedCurve2(path, points, count, tension);
3858     if(stat != Ok){
3859         GdipDeletePath(path);
3860         return stat;
3861     }
3862
3863     stat = GdipFillPath(graphics, brush, path);
3864     if(stat != Ok){
3865         GdipDeletePath(path);
3866         return stat;
3867     }
3868
3869     GdipDeletePath(path);
3870
3871     return Ok;
3872 }
3873
3874 GpStatus WINGDIPAPI GdipFillClosedCurve2I(GpGraphics *graphics, GpBrush *brush,
3875     GDIPCONST GpPoint *points, INT count, REAL tension, GpFillMode fill)
3876 {
3877     GpPointF *ptf;
3878     GpStatus stat;
3879     INT i;
3880
3881     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3882             count, tension, fill);
3883
3884     if(!points || count == 0)
3885         return InvalidParameter;
3886
3887     if(count == 1)    /* Do nothing */
3888         return Ok;
3889
3890     ptf = GdipAlloc(sizeof(GpPointF)*count);
3891     if(!ptf)
3892         return OutOfMemory;
3893
3894     for(i = 0;i < count;i++){
3895         ptf[i].X = (REAL)points[i].X;
3896         ptf[i].Y = (REAL)points[i].Y;
3897     }
3898
3899     stat = GdipFillClosedCurve2(graphics, brush, ptf, count, tension, fill);
3900
3901     GdipFree(ptf);
3902
3903     return stat;
3904 }
3905
3906 GpStatus WINGDIPAPI GdipFillClosedCurve(GpGraphics *graphics, GpBrush *brush,
3907     GDIPCONST GpPointF *points, INT count)
3908 {
3909     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3910     return GdipFillClosedCurve2(graphics, brush, points, count,
3911                0.5f, FillModeAlternate);
3912 }
3913
3914 GpStatus WINGDIPAPI GdipFillClosedCurveI(GpGraphics *graphics, GpBrush *brush,
3915     GDIPCONST GpPoint *points, INT count)
3916 {
3917     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3918     return GdipFillClosedCurve2I(graphics, brush, points, count,
3919                0.5f, FillModeAlternate);
3920 }
3921
3922 GpStatus WINGDIPAPI GdipFillEllipse(GpGraphics *graphics, GpBrush *brush, REAL x,
3923     REAL y, REAL width, REAL height)
3924 {
3925     GpStatus stat;
3926     GpPath *path;
3927
3928     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
3929
3930     if(!graphics || !brush)
3931         return InvalidParameter;
3932
3933     if(graphics->busy)
3934         return ObjectBusy;
3935
3936     stat = GdipCreatePath(FillModeAlternate, &path);
3937
3938     if (stat == Ok)
3939     {
3940         stat = GdipAddPathEllipse(path, x, y, width, height);
3941
3942         if (stat == Ok)
3943             stat = GdipFillPath(graphics, brush, path);
3944
3945         GdipDeletePath(path);
3946     }
3947
3948     return stat;
3949 }
3950
3951 GpStatus WINGDIPAPI GdipFillEllipseI(GpGraphics *graphics, GpBrush *brush, INT x,
3952     INT y, INT width, INT height)
3953 {
3954     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
3955
3956     return GdipFillEllipse(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3957 }
3958
3959 static GpStatus GDI32_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3960 {
3961     INT save_state;
3962     GpStatus retval;
3963
3964     if(!graphics->hdc || !brush_can_fill_path(brush))
3965         return NotImplemented;
3966
3967     save_state = SaveDC(graphics->hdc);
3968     EndPath(graphics->hdc);
3969     SetPolyFillMode(graphics->hdc, (path->fill == FillModeAlternate ? ALTERNATE
3970                                                                     : WINDING));
3971
3972     BeginPath(graphics->hdc);
3973     retval = draw_poly(graphics, NULL, path->pathdata.Points,
3974                        path->pathdata.Types, path->pathdata.Count, FALSE);
3975
3976     if(retval != Ok)
3977         goto end;
3978
3979     EndPath(graphics->hdc);
3980     brush_fill_path(graphics, brush);
3981
3982     retval = Ok;
3983
3984 end:
3985     RestoreDC(graphics->hdc, save_state);
3986
3987     return retval;
3988 }
3989
3990 static GpStatus SOFTWARE_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3991 {
3992     GpStatus stat;
3993     GpRegion *rgn;
3994
3995     if (!brush_can_fill_pixels(brush))
3996         return NotImplemented;
3997
3998     /* FIXME: This could probably be done more efficiently without regions. */
3999
4000     stat = GdipCreateRegionPath(path, &rgn);
4001
4002     if (stat == Ok)
4003     {
4004         stat = GdipFillRegion(graphics, brush, rgn);
4005
4006         GdipDeleteRegion(rgn);
4007     }
4008
4009     return stat;
4010 }
4011
4012 GpStatus WINGDIPAPI GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
4013 {
4014     GpStatus stat = NotImplemented;
4015
4016     TRACE("(%p, %p, %p)\n", graphics, brush, path);
4017
4018     if(!brush || !graphics || !path)
4019         return InvalidParameter;
4020
4021     if(graphics->busy)
4022         return ObjectBusy;
4023
4024     if (!graphics->image)
4025         stat = GDI32_GdipFillPath(graphics, brush, path);
4026
4027     if (stat == NotImplemented)
4028         stat = SOFTWARE_GdipFillPath(graphics, brush, path);
4029
4030     if (stat == NotImplemented)
4031     {
4032         FIXME("Not implemented for brushtype %i\n", brush->bt);
4033         stat = Ok;
4034     }
4035
4036     return stat;
4037 }
4038
4039 GpStatus WINGDIPAPI GdipFillPie(GpGraphics *graphics, GpBrush *brush, REAL x,
4040     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
4041 {
4042     GpStatus stat;
4043     GpPath *path;
4044
4045     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n",
4046             graphics, brush, x, y, width, height, startAngle, sweepAngle);
4047
4048     if(!graphics || !brush)
4049         return InvalidParameter;
4050
4051     if(graphics->busy)
4052         return ObjectBusy;
4053
4054     stat = GdipCreatePath(FillModeAlternate, &path);
4055
4056     if (stat == Ok)
4057     {
4058         stat = GdipAddPathPie(path, x, y, width, height, startAngle, sweepAngle);
4059
4060         if (stat == Ok)
4061             stat = GdipFillPath(graphics, brush, path);
4062
4063         GdipDeletePath(path);
4064     }
4065
4066     return stat;
4067 }
4068
4069 GpStatus WINGDIPAPI GdipFillPieI(GpGraphics *graphics, GpBrush *brush, INT x,
4070     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
4071 {
4072     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n",
4073             graphics, brush, x, y, width, height, startAngle, sweepAngle);
4074
4075     return GdipFillPie(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
4076 }
4077
4078 GpStatus WINGDIPAPI GdipFillPolygon(GpGraphics *graphics, GpBrush *brush,
4079     GDIPCONST GpPointF *points, INT count, GpFillMode fillMode)
4080 {
4081     GpStatus stat;
4082     GpPath *path;
4083
4084     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
4085
4086     if(!graphics || !brush || !points || !count)
4087         return InvalidParameter;
4088
4089     if(graphics->busy)
4090         return ObjectBusy;
4091
4092     stat = GdipCreatePath(fillMode, &path);
4093
4094     if (stat == Ok)
4095     {
4096         stat = GdipAddPathPolygon(path, points, count);
4097
4098         if (stat == Ok)
4099             stat = GdipFillPath(graphics, brush, path);
4100
4101         GdipDeletePath(path);
4102     }
4103
4104     return stat;
4105 }
4106
4107 GpStatus WINGDIPAPI GdipFillPolygonI(GpGraphics *graphics, GpBrush *brush,
4108     GDIPCONST GpPoint *points, INT count, GpFillMode fillMode)
4109 {
4110     GpStatus stat;
4111     GpPath *path;
4112
4113     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
4114
4115     if(!graphics || !brush || !points || !count)
4116         return InvalidParameter;
4117
4118     if(graphics->busy)
4119         return ObjectBusy;
4120
4121     stat = GdipCreatePath(fillMode, &path);
4122
4123     if (stat == Ok)
4124     {
4125         stat = GdipAddPathPolygonI(path, points, count);
4126
4127         if (stat == Ok)
4128             stat = GdipFillPath(graphics, brush, path);
4129
4130         GdipDeletePath(path);
4131     }
4132
4133     return stat;
4134 }
4135
4136 GpStatus WINGDIPAPI GdipFillPolygon2(GpGraphics *graphics, GpBrush *brush,
4137     GDIPCONST GpPointF *points, INT count)
4138 {
4139     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
4140
4141     return GdipFillPolygon(graphics, brush, points, count, FillModeAlternate);
4142 }
4143
4144 GpStatus WINGDIPAPI GdipFillPolygon2I(GpGraphics *graphics, GpBrush *brush,
4145     GDIPCONST GpPoint *points, INT count)
4146 {
4147     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
4148
4149     return GdipFillPolygonI(graphics, brush, points, count, FillModeAlternate);
4150 }
4151
4152 GpStatus WINGDIPAPI GdipFillRectangle(GpGraphics *graphics, GpBrush *brush,
4153     REAL x, REAL y, REAL width, REAL height)
4154 {
4155     GpStatus stat;
4156     GpPath *path;
4157
4158     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
4159
4160     if(!graphics || !brush)
4161         return InvalidParameter;
4162
4163     if(graphics->busy)
4164         return ObjectBusy;
4165
4166     stat = GdipCreatePath(FillModeAlternate, &path);
4167
4168     if (stat == Ok)
4169     {
4170         stat = GdipAddPathRectangle(path, x, y, width, height);
4171
4172         if (stat == Ok)
4173             stat = GdipFillPath(graphics, brush, path);
4174
4175         GdipDeletePath(path);
4176     }
4177
4178     return stat;
4179 }
4180
4181 GpStatus WINGDIPAPI GdipFillRectangleI(GpGraphics *graphics, GpBrush *brush,
4182     INT x, INT y, INT width, INT height)
4183 {
4184     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
4185
4186     return GdipFillRectangle(graphics, brush, x, y, width, height);
4187 }
4188
4189 GpStatus WINGDIPAPI GdipFillRectangles(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRectF *rects,
4190     INT count)
4191 {
4192     GpStatus ret;
4193     INT i;
4194
4195     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
4196
4197     if(!rects)
4198         return InvalidParameter;
4199
4200     for(i = 0; i < count; i++){
4201         ret = GdipFillRectangle(graphics, brush, rects[i].X, rects[i].Y, rects[i].Width, rects[i].Height);
4202         if(ret != Ok)   return ret;
4203     }
4204
4205     return Ok;
4206 }
4207
4208 GpStatus WINGDIPAPI GdipFillRectanglesI(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRect *rects,
4209     INT count)
4210 {
4211     GpRectF *rectsF;
4212     GpStatus ret;
4213     INT i;
4214
4215     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
4216
4217     if(!rects || count <= 0)
4218         return InvalidParameter;
4219
4220     rectsF = GdipAlloc(sizeof(GpRectF)*count);
4221     if(!rectsF)
4222         return OutOfMemory;
4223
4224     for(i = 0; i < count; i++){
4225         rectsF[i].X      = (REAL)rects[i].X;
4226         rectsF[i].Y      = (REAL)rects[i].Y;
4227         rectsF[i].X      = (REAL)rects[i].Width;
4228         rectsF[i].Height = (REAL)rects[i].Height;
4229     }
4230
4231     ret = GdipFillRectangles(graphics,brush,rectsF,count);
4232     GdipFree(rectsF);
4233
4234     return ret;
4235 }
4236
4237 static GpStatus GDI32_GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
4238     GpRegion* region)
4239 {
4240     INT save_state;
4241     GpStatus status;
4242     HRGN hrgn;
4243     RECT rc;
4244
4245     if(!graphics->hdc || !brush_can_fill_path(brush))
4246         return NotImplemented;
4247
4248     status = GdipGetRegionHRgn(region, graphics, &hrgn);
4249     if(status != Ok)
4250         return status;
4251
4252     save_state = SaveDC(graphics->hdc);
4253     EndPath(graphics->hdc);
4254
4255     ExtSelectClipRgn(graphics->hdc, hrgn, RGN_AND);
4256
4257     if (GetClipBox(graphics->hdc, &rc) != NULLREGION)
4258     {
4259         BeginPath(graphics->hdc);
4260         Rectangle(graphics->hdc, rc.left, rc.top, rc.right, rc.bottom);
4261         EndPath(graphics->hdc);
4262
4263         brush_fill_path(graphics, brush);
4264     }
4265
4266     RestoreDC(graphics->hdc, save_state);
4267
4268     DeleteObject(hrgn);
4269
4270     return Ok;
4271 }
4272
4273 static GpStatus SOFTWARE_GdipFillRegion(GpGraphics *graphics, GpBrush *brush,
4274     GpRegion* region)
4275 {
4276     GpStatus stat;
4277     GpRegion *temp_region;
4278     GpMatrix world_to_device;
4279     GpRectF graphics_bounds;
4280     DWORD *pixel_data;
4281     HRGN hregion;
4282     RECT bound_rect;
4283     GpRect gp_bound_rect;
4284
4285     if (!brush_can_fill_pixels(brush))
4286         return NotImplemented;
4287
4288     stat = get_graphics_bounds(graphics, &graphics_bounds);
4289
4290     if (stat == Ok)
4291         stat = GdipCloneRegion(region, &temp_region);
4292
4293     if (stat == Ok)
4294     {
4295         stat = get_graphics_transform(graphics, CoordinateSpaceDevice,
4296             CoordinateSpaceWorld, &world_to_device);
4297
4298         if (stat == Ok)
4299             stat = GdipTransformRegion(temp_region, &world_to_device);
4300
4301         if (stat == Ok)
4302             stat = GdipCombineRegionRect(temp_region, &graphics_bounds, CombineModeIntersect);
4303
4304         if (stat == Ok)
4305             stat = GdipGetRegionHRgn(temp_region, NULL, &hregion);
4306
4307         GdipDeleteRegion(temp_region);
4308     }
4309
4310     if (stat == Ok && GetRgnBox(hregion, &bound_rect) == NULLREGION)
4311     {
4312         DeleteObject(hregion);
4313         return Ok;
4314     }
4315
4316     if (stat == Ok)
4317     {
4318         gp_bound_rect.X = bound_rect.left;
4319         gp_bound_rect.Y = bound_rect.top;
4320         gp_bound_rect.Width = bound_rect.right - bound_rect.left;
4321         gp_bound_rect.Height = bound_rect.bottom - bound_rect.top;
4322
4323         pixel_data = GdipAlloc(sizeof(*pixel_data) * gp_bound_rect.Width * gp_bound_rect.Height);
4324         if (!pixel_data)
4325             stat = OutOfMemory;
4326
4327         if (stat == Ok)
4328         {
4329             stat = brush_fill_pixels(graphics, brush, pixel_data,
4330                 &gp_bound_rect, gp_bound_rect.Width);
4331
4332             if (stat == Ok)
4333                 stat = alpha_blend_pixels_hrgn(graphics, gp_bound_rect.X,
4334                     gp_bound_rect.Y, (BYTE*)pixel_data, gp_bound_rect.Width,
4335                     gp_bound_rect.Height, gp_bound_rect.Width * 4, hregion);
4336
4337             GdipFree(pixel_data);
4338         }
4339
4340         DeleteObject(hregion);
4341     }
4342
4343     return stat;
4344 }
4345
4346 /*****************************************************************************
4347  * GdipFillRegion [GDIPLUS.@]
4348  */
4349 GpStatus WINGDIPAPI GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
4350         GpRegion* region)
4351 {
4352     GpStatus stat = NotImplemented;
4353
4354     TRACE("(%p, %p, %p)\n", graphics, brush, region);
4355
4356     if (!(graphics && brush && region))
4357         return InvalidParameter;
4358
4359     if(graphics->busy)
4360         return ObjectBusy;
4361
4362     if (!graphics->image)
4363         stat = GDI32_GdipFillRegion(graphics, brush, region);
4364
4365     if (stat == NotImplemented)
4366         stat = SOFTWARE_GdipFillRegion(graphics, brush, region);
4367
4368     if (stat == NotImplemented)
4369     {
4370         FIXME("not implemented for brushtype %i\n", brush->bt);
4371         stat = Ok;
4372     }
4373
4374     return stat;
4375 }
4376
4377 GpStatus WINGDIPAPI GdipFlush(GpGraphics *graphics, GpFlushIntention intention)
4378 {
4379     TRACE("(%p,%u)\n", graphics, intention);
4380
4381     if(!graphics)
4382         return InvalidParameter;
4383
4384     if(graphics->busy)
4385         return ObjectBusy;
4386
4387     /* We have no internal operation queue, so there's no need to clear it. */
4388
4389     if (graphics->hdc)
4390         GdiFlush();
4391
4392     return Ok;
4393 }
4394
4395 /*****************************************************************************
4396  * GdipGetClipBounds [GDIPLUS.@]
4397  */
4398 GpStatus WINGDIPAPI GdipGetClipBounds(GpGraphics *graphics, GpRectF *rect)
4399 {
4400     TRACE("(%p, %p)\n", graphics, rect);
4401
4402     if(!graphics)
4403         return InvalidParameter;
4404
4405     if(graphics->busy)
4406         return ObjectBusy;
4407
4408     return GdipGetRegionBounds(graphics->clip, graphics, rect);
4409 }
4410
4411 /*****************************************************************************
4412  * GdipGetClipBoundsI [GDIPLUS.@]
4413  */
4414 GpStatus WINGDIPAPI GdipGetClipBoundsI(GpGraphics *graphics, GpRect *rect)
4415 {
4416     TRACE("(%p, %p)\n", graphics, rect);
4417
4418     if(!graphics)
4419         return InvalidParameter;
4420
4421     if(graphics->busy)
4422         return ObjectBusy;
4423
4424     return GdipGetRegionBoundsI(graphics->clip, graphics, rect);
4425 }
4426
4427 /* FIXME: Compositing mode is not used anywhere except the getter/setter. */
4428 GpStatus WINGDIPAPI GdipGetCompositingMode(GpGraphics *graphics,
4429     CompositingMode *mode)
4430 {
4431     TRACE("(%p, %p)\n", graphics, mode);
4432
4433     if(!graphics || !mode)
4434         return InvalidParameter;
4435
4436     if(graphics->busy)
4437         return ObjectBusy;
4438
4439     *mode = graphics->compmode;
4440
4441     return Ok;
4442 }
4443
4444 /* FIXME: Compositing quality is not used anywhere except the getter/setter. */
4445 GpStatus WINGDIPAPI GdipGetCompositingQuality(GpGraphics *graphics,
4446     CompositingQuality *quality)
4447 {
4448     TRACE("(%p, %p)\n", graphics, quality);
4449
4450     if(!graphics || !quality)
4451         return InvalidParameter;
4452
4453     if(graphics->busy)
4454         return ObjectBusy;
4455
4456     *quality = graphics->compqual;
4457
4458     return Ok;
4459 }
4460
4461 /* FIXME: Interpolation mode is not used anywhere except the getter/setter. */
4462 GpStatus WINGDIPAPI GdipGetInterpolationMode(GpGraphics *graphics,
4463     InterpolationMode *mode)
4464 {
4465     TRACE("(%p, %p)\n", graphics, mode);
4466
4467     if(!graphics || !mode)
4468         return InvalidParameter;
4469
4470     if(graphics->busy)
4471         return ObjectBusy;
4472
4473     *mode = graphics->interpolation;
4474
4475     return Ok;
4476 }
4477
4478 /* FIXME: Need to handle color depths less than 24bpp */
4479 GpStatus WINGDIPAPI GdipGetNearestColor(GpGraphics *graphics, ARGB* argb)
4480 {
4481     FIXME("(%p, %p): Passing color unmodified\n", graphics, argb);
4482
4483     if(!graphics || !argb)
4484         return InvalidParameter;
4485
4486     if(graphics->busy)
4487         return ObjectBusy;
4488
4489     return Ok;
4490 }
4491
4492 GpStatus WINGDIPAPI GdipGetPageScale(GpGraphics *graphics, REAL *scale)
4493 {
4494     TRACE("(%p, %p)\n", graphics, scale);
4495
4496     if(!graphics || !scale)
4497         return InvalidParameter;
4498
4499     if(graphics->busy)
4500         return ObjectBusy;
4501
4502     *scale = graphics->scale;
4503
4504     return Ok;
4505 }
4506
4507 GpStatus WINGDIPAPI GdipGetPageUnit(GpGraphics *graphics, GpUnit *unit)
4508 {
4509     TRACE("(%p, %p)\n", graphics, unit);
4510
4511     if(!graphics || !unit)
4512         return InvalidParameter;
4513
4514     if(graphics->busy)
4515         return ObjectBusy;
4516
4517     *unit = graphics->unit;
4518
4519     return Ok;
4520 }
4521
4522 /* FIXME: Pixel offset mode is not used anywhere except the getter/setter. */
4523 GpStatus WINGDIPAPI GdipGetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
4524     *mode)
4525 {
4526     TRACE("(%p, %p)\n", graphics, mode);
4527
4528     if(!graphics || !mode)
4529         return InvalidParameter;
4530
4531     if(graphics->busy)
4532         return ObjectBusy;
4533
4534     *mode = graphics->pixeloffset;
4535
4536     return Ok;
4537 }
4538
4539 /* FIXME: Smoothing mode is not used anywhere except the getter/setter. */
4540 GpStatus WINGDIPAPI GdipGetSmoothingMode(GpGraphics *graphics, SmoothingMode *mode)
4541 {
4542     TRACE("(%p, %p)\n", graphics, mode);
4543
4544     if(!graphics || !mode)
4545         return InvalidParameter;
4546
4547     if(graphics->busy)
4548         return ObjectBusy;
4549
4550     *mode = graphics->smoothing;
4551
4552     return Ok;
4553 }
4554
4555 GpStatus WINGDIPAPI GdipGetTextContrast(GpGraphics *graphics, UINT *contrast)
4556 {
4557     TRACE("(%p, %p)\n", graphics, contrast);
4558
4559     if(!graphics || !contrast)
4560         return InvalidParameter;
4561
4562     *contrast = graphics->textcontrast;
4563
4564     return Ok;
4565 }
4566
4567 /* FIXME: Text rendering hint is not used anywhere except the getter/setter. */
4568 GpStatus WINGDIPAPI GdipGetTextRenderingHint(GpGraphics *graphics,
4569     TextRenderingHint *hint)
4570 {
4571     TRACE("(%p, %p)\n", graphics, hint);
4572
4573     if(!graphics || !hint)
4574         return InvalidParameter;
4575
4576     if(graphics->busy)
4577         return ObjectBusy;
4578
4579     *hint = graphics->texthint;
4580
4581     return Ok;
4582 }
4583
4584 GpStatus WINGDIPAPI GdipGetVisibleClipBounds(GpGraphics *graphics, GpRectF *rect)
4585 {
4586     GpRegion *clip_rgn;
4587     GpStatus stat;
4588
4589     TRACE("(%p, %p)\n", graphics, rect);
4590
4591     if(!graphics || !rect)
4592         return InvalidParameter;
4593
4594     if(graphics->busy)
4595         return ObjectBusy;
4596
4597     /* intersect window and graphics clipping regions */
4598     if((stat = GdipCreateRegion(&clip_rgn)) != Ok)
4599         return stat;
4600
4601     if((stat = get_visible_clip_region(graphics, clip_rgn)) != Ok)
4602         goto cleanup;
4603
4604     /* get bounds of the region */
4605     stat = GdipGetRegionBounds(clip_rgn, graphics, rect);
4606
4607 cleanup:
4608     GdipDeleteRegion(clip_rgn);
4609
4610     return stat;
4611 }
4612
4613 GpStatus WINGDIPAPI GdipGetVisibleClipBoundsI(GpGraphics *graphics, GpRect *rect)
4614 {
4615     GpRectF rectf;
4616     GpStatus stat;
4617
4618     TRACE("(%p, %p)\n", graphics, rect);
4619
4620     if(!graphics || !rect)
4621         return InvalidParameter;
4622
4623     if((stat = GdipGetVisibleClipBounds(graphics, &rectf)) == Ok)
4624     {
4625         rect->X = gdip_round(rectf.X);
4626         rect->Y = gdip_round(rectf.Y);
4627         rect->Width  = gdip_round(rectf.Width);
4628         rect->Height = gdip_round(rectf.Height);
4629     }
4630
4631     return stat;
4632 }
4633
4634 GpStatus WINGDIPAPI GdipGetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
4635 {
4636     TRACE("(%p, %p)\n", graphics, matrix);
4637
4638     if(!graphics || !matrix)
4639         return InvalidParameter;
4640
4641     if(graphics->busy)
4642         return ObjectBusy;
4643
4644     *matrix = graphics->worldtrans;
4645     return Ok;
4646 }
4647
4648 GpStatus WINGDIPAPI GdipGraphicsClear(GpGraphics *graphics, ARGB color)
4649 {
4650     GpSolidFill *brush;
4651     GpStatus stat;
4652     GpRectF wnd_rect;
4653
4654     TRACE("(%p, %x)\n", graphics, color);
4655
4656     if(!graphics)
4657         return InvalidParameter;
4658
4659     if(graphics->busy)
4660         return ObjectBusy;
4661
4662     if((stat = GdipCreateSolidFill(color, &brush)) != Ok)
4663         return stat;
4664
4665     if((stat = get_graphics_bounds(graphics, &wnd_rect)) != Ok){
4666         GdipDeleteBrush((GpBrush*)brush);
4667         return stat;
4668     }
4669
4670     GdipFillRectangle(graphics, (GpBrush*)brush, wnd_rect.X, wnd_rect.Y,
4671                                                  wnd_rect.Width, wnd_rect.Height);
4672
4673     GdipDeleteBrush((GpBrush*)brush);
4674
4675     return Ok;
4676 }
4677
4678 GpStatus WINGDIPAPI GdipIsClipEmpty(GpGraphics *graphics, BOOL *res)
4679 {
4680     TRACE("(%p, %p)\n", graphics, res);
4681
4682     if(!graphics || !res)
4683         return InvalidParameter;
4684
4685     return GdipIsEmptyRegion(graphics->clip, graphics, res);
4686 }
4687
4688 GpStatus WINGDIPAPI GdipIsVisiblePoint(GpGraphics *graphics, REAL x, REAL y, BOOL *result)
4689 {
4690     GpStatus stat;
4691     GpRegion* rgn;
4692     GpPointF pt;
4693
4694     TRACE("(%p, %.2f, %.2f, %p)\n", graphics, x, y, result);
4695
4696     if(!graphics || !result)
4697         return InvalidParameter;
4698
4699     if(graphics->busy)
4700         return ObjectBusy;
4701
4702     pt.X = x;
4703     pt.Y = y;
4704     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4705                    CoordinateSpaceWorld, &pt, 1)) != Ok)
4706         return stat;
4707
4708     if((stat = GdipCreateRegion(&rgn)) != Ok)
4709         return stat;
4710
4711     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4712         goto cleanup;
4713
4714     stat = GdipIsVisibleRegionPoint(rgn, pt.X, pt.Y, graphics, result);
4715
4716 cleanup:
4717     GdipDeleteRegion(rgn);
4718     return stat;
4719 }
4720
4721 GpStatus WINGDIPAPI GdipIsVisiblePointI(GpGraphics *graphics, INT x, INT y, BOOL *result)
4722 {
4723     return GdipIsVisiblePoint(graphics, (REAL)x, (REAL)y, result);
4724 }
4725
4726 GpStatus WINGDIPAPI GdipIsVisibleRect(GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, BOOL *result)
4727 {
4728     GpStatus stat;
4729     GpRegion* rgn;
4730     GpPointF pts[2];
4731
4732     TRACE("(%p %.2f %.2f %.2f %.2f %p)\n", graphics, x, y, width, height, result);
4733
4734     if(!graphics || !result)
4735         return InvalidParameter;
4736
4737     if(graphics->busy)
4738         return ObjectBusy;
4739
4740     pts[0].X = x;
4741     pts[0].Y = y;
4742     pts[1].X = x + width;
4743     pts[1].Y = y + height;
4744
4745     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4746                     CoordinateSpaceWorld, pts, 2)) != Ok)
4747         return stat;
4748
4749     pts[1].X -= pts[0].X;
4750     pts[1].Y -= pts[0].Y;
4751
4752     if((stat = GdipCreateRegion(&rgn)) != Ok)
4753         return stat;
4754
4755     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4756         goto cleanup;
4757
4758     stat = GdipIsVisibleRegionRect(rgn, pts[0].X, pts[0].Y, pts[1].X, pts[1].Y, graphics, result);
4759
4760 cleanup:
4761     GdipDeleteRegion(rgn);
4762     return stat;
4763 }
4764
4765 GpStatus WINGDIPAPI GdipIsVisibleRectI(GpGraphics *graphics, INT x, INT y, INT width, INT height, BOOL *result)
4766 {
4767     return GdipIsVisibleRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, result);
4768 }
4769
4770 GpStatus gdip_format_string(HDC hdc,
4771     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
4772     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4773     gdip_format_string_callback callback, void *user_data)
4774 {
4775     WCHAR* stringdup;
4776     int sum = 0, height = 0, fit, fitcpy, i, j, lret, nwidth,
4777         nheight, lineend, lineno = 0;
4778     RectF bounds;
4779     StringAlignment halign;
4780     GpStatus stat = Ok;
4781     SIZE size;
4782     HotkeyPrefix hkprefix;
4783     INT *hotkeyprefix_offsets=NULL;
4784     INT hotkeyprefix_count=0;
4785     INT hotkeyprefix_pos=0, hotkeyprefix_end_pos=0;
4786     int seen_prefix=0;
4787
4788     if(length == -1) length = lstrlenW(string);
4789
4790     stringdup = GdipAlloc((length + 1) * sizeof(WCHAR));
4791     if(!stringdup) return OutOfMemory;
4792
4793     nwidth = rect->Width;
4794     nheight = rect->Height;
4795
4796     if (format)
4797         hkprefix = format->hkprefix;
4798     else
4799         hkprefix = HotkeyPrefixNone;
4800
4801     if (hkprefix == HotkeyPrefixShow)
4802     {
4803         for (i=0; i<length; i++)
4804         {
4805             if (string[i] == '&')
4806                 hotkeyprefix_count++;
4807         }
4808     }
4809
4810     if (hotkeyprefix_count)
4811         hotkeyprefix_offsets = GdipAlloc(sizeof(INT) * hotkeyprefix_count);
4812
4813     hotkeyprefix_count = 0;
4814
4815     for(i = 0, j = 0; i < length; i++){
4816         /* FIXME: This makes the indexes passed to callback inaccurate. */
4817         if(!isprintW(string[i]) && (string[i] != '\n'))
4818             continue;
4819
4820         /* FIXME: tabs should be handled using tabstops from stringformat */
4821         if (string[i] == '\t')
4822             continue;
4823
4824         if (seen_prefix && hkprefix == HotkeyPrefixShow && string[i] != '&')
4825             hotkeyprefix_offsets[hotkeyprefix_count++] = j;
4826         else if (!seen_prefix && hkprefix != HotkeyPrefixNone && string[i] == '&')
4827         {
4828             seen_prefix = 1;
4829             continue;
4830         }
4831
4832         seen_prefix = 0;
4833
4834         stringdup[j] = string[i];
4835         j++;
4836     }
4837
4838     length = j;
4839
4840     if (format) halign = format->align;
4841     else halign = StringAlignmentNear;
4842
4843     while(sum < length){
4844         GetTextExtentExPointW(hdc, stringdup + sum, length - sum,
4845                               nwidth, &fit, NULL, &size);
4846         fitcpy = fit;
4847
4848         if(fit == 0)
4849             break;
4850
4851         for(lret = 0; lret < fit; lret++)
4852             if(*(stringdup + sum + lret) == '\n')
4853                 break;
4854
4855         /* Line break code (may look strange, but it imitates windows). */
4856         if(lret < fit)
4857             lineend = fit = lret;    /* this is not an off-by-one error */
4858         else if(fit < (length - sum)){
4859             if(*(stringdup + sum + fit) == ' ')
4860                 while(*(stringdup + sum + fit) == ' ')
4861                     fit++;
4862             else
4863                 while(*(stringdup + sum + fit - 1) != ' '){
4864                     fit--;
4865
4866                     if(*(stringdup + sum + fit) == '\t')
4867                         break;
4868
4869                     if(fit == 0){
4870                         fit = fitcpy;
4871                         break;
4872                     }
4873                 }
4874             lineend = fit;
4875             while(*(stringdup + sum + lineend - 1) == ' ' ||
4876                   *(stringdup + sum + lineend - 1) == '\t')
4877                 lineend--;
4878         }
4879         else
4880             lineend = fit;
4881
4882         GetTextExtentExPointW(hdc, stringdup + sum, lineend,
4883                               nwidth, &j, NULL, &size);
4884
4885         bounds.Width = size.cx;
4886
4887         if(height + size.cy > nheight)
4888             bounds.Height = nheight - (height + size.cy);
4889         else
4890             bounds.Height = size.cy;
4891
4892         bounds.Y = rect->Y + height;
4893
4894         switch (halign)
4895         {
4896         case StringAlignmentNear:
4897         default:
4898             bounds.X = rect->X;
4899             break;
4900         case StringAlignmentCenter:
4901             bounds.X = rect->X + (rect->Width/2) - (bounds.Width/2);
4902             break;
4903         case StringAlignmentFar:
4904             bounds.X = rect->X + rect->Width - bounds.Width;
4905             break;
4906         }
4907
4908         for (hotkeyprefix_end_pos=hotkeyprefix_pos; hotkeyprefix_end_pos<hotkeyprefix_count; hotkeyprefix_end_pos++)
4909             if (hotkeyprefix_offsets[hotkeyprefix_end_pos] >= sum + lineend)
4910                 break;
4911
4912         stat = callback(hdc, stringdup, sum, lineend,
4913             font, rect, format, lineno, &bounds,
4914             &hotkeyprefix_offsets[hotkeyprefix_pos],
4915             hotkeyprefix_end_pos-hotkeyprefix_pos, user_data);
4916
4917         if (stat != Ok)
4918             break;
4919
4920         sum += fit + (lret < fitcpy ? 1 : 0);
4921         height += size.cy;
4922         lineno++;
4923
4924         hotkeyprefix_pos = hotkeyprefix_end_pos;
4925
4926         if(height > nheight)
4927             break;
4928
4929         /* Stop if this was a linewrap (but not if it was a linebreak). */
4930         if ((lret == fitcpy) && format &&
4931             (format->attr & (StringFormatFlagsNoWrap | StringFormatFlagsLineLimit)))
4932             break;
4933     }
4934
4935     GdipFree(stringdup);
4936     GdipFree(hotkeyprefix_offsets);
4937
4938     return stat;
4939 }
4940
4941 struct measure_ranges_args {
4942     GpRegion **regions;
4943     REAL rel_width, rel_height;
4944 };
4945
4946 static GpStatus measure_ranges_callback(HDC hdc,
4947     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
4948     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4949     INT lineno, const RectF *bounds, INT *underlined_indexes,
4950     INT underlined_index_count, void *user_data)
4951 {
4952     int i;
4953     GpStatus stat = Ok;
4954     struct measure_ranges_args *args = user_data;
4955
4956     for (i=0; i<format->range_count; i++)
4957     {
4958         INT range_start = max(index, format->character_ranges[i].First);
4959         INT range_end = min(index+length, format->character_ranges[i].First+format->character_ranges[i].Length);
4960         if (range_start < range_end)
4961         {
4962             GpRectF range_rect;
4963             SIZE range_size;
4964
4965             range_rect.Y = bounds->Y / args->rel_height;
4966             range_rect.Height = bounds->Height / args->rel_height;
4967
4968             GetTextExtentExPointW(hdc, string + index, range_start - index,
4969                                   INT_MAX, NULL, NULL, &range_size);
4970             range_rect.X = (bounds->X + range_size.cx) / args->rel_width;
4971
4972             GetTextExtentExPointW(hdc, string + index, range_end - index,
4973                                   INT_MAX, NULL, NULL, &range_size);
4974             range_rect.Width = (bounds->X + range_size.cx) / args->rel_width - range_rect.X;
4975
4976             stat = GdipCombineRegionRect(args->regions[i], &range_rect, CombineModeUnion);
4977             if (stat != Ok)
4978                 break;
4979         }
4980     }
4981
4982     return stat;
4983 }
4984
4985 GpStatus WINGDIPAPI GdipMeasureCharacterRanges(GpGraphics* graphics,
4986         GDIPCONST WCHAR* string, INT length, GDIPCONST GpFont* font,
4987         GDIPCONST RectF* layoutRect, GDIPCONST GpStringFormat *stringFormat,
4988         INT regionCount, GpRegion** regions)
4989 {
4990     GpStatus stat;
4991     int i;
4992     HFONT gdifont, oldfont;
4993     struct measure_ranges_args args;
4994     HDC hdc, temp_hdc=NULL;
4995     GpPointF pt[3];
4996     RectF scaled_rect;
4997     REAL margin_x;
4998
4999     TRACE("(%p %s %d %p %s %p %d %p)\n", graphics, debugstr_w(string),
5000             length, font, debugstr_rectf(layoutRect), stringFormat, regionCount, regions);
5001
5002     if (!(graphics && string && font && layoutRect && stringFormat && regions))
5003         return InvalidParameter;
5004
5005     if (regionCount < stringFormat->range_count)
5006         return InvalidParameter;
5007
5008     if(!graphics->hdc)
5009     {
5010         hdc = temp_hdc = CreateCompatibleDC(0);
5011         if (!temp_hdc) return OutOfMemory;
5012     }
5013     else
5014         hdc = graphics->hdc;
5015
5016     if (stringFormat->attr)
5017         TRACE("may be ignoring some format flags: attr %x\n", stringFormat->attr);
5018
5019     pt[0].X = 0.0;
5020     pt[0].Y = 0.0;
5021     pt[1].X = 1.0;
5022     pt[1].Y = 0.0;
5023     pt[2].X = 0.0;
5024     pt[2].Y = 1.0;
5025     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5026     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5027                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5028     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5029                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5030
5031     margin_x = stringFormat->generic_typographic ? 0.0 : font->emSize / 6.0;
5032     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5033
5034     scaled_rect.X = (layoutRect->X + margin_x) * args.rel_width;
5035     scaled_rect.Y = layoutRect->Y * args.rel_height;
5036     if (stringFormat->attr & StringFormatFlagsNoClip)
5037     {
5038         scaled_rect.Width = (REAL)(1 << 23);
5039         scaled_rect.Height = (REAL)(1 << 23);
5040     }
5041     else
5042     {
5043         scaled_rect.Width = layoutRect->Width * args.rel_width;
5044         scaled_rect.Height = layoutRect->Height * args.rel_height;
5045     }
5046     if (scaled_rect.Width >= 0.5)
5047     {
5048         scaled_rect.Width -= margin_x * 2.0 * args.rel_width;
5049         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5050     }
5051
5052     get_font_hfont(graphics, font, stringFormat, &gdifont, NULL);
5053     oldfont = SelectObject(hdc, gdifont);
5054
5055     for (i=0; i<stringFormat->range_count; i++)
5056     {
5057         stat = GdipSetEmpty(regions[i]);
5058         if (stat != Ok)
5059             return stat;
5060     }
5061
5062     args.regions = regions;
5063
5064     stat = gdip_format_string(hdc, string, length, font, &scaled_rect, stringFormat,
5065         measure_ranges_callback, &args);
5066
5067     SelectObject(hdc, oldfont);
5068     DeleteObject(gdifont);
5069
5070     if (temp_hdc)
5071         DeleteDC(temp_hdc);
5072
5073     return stat;
5074 }
5075
5076 struct measure_string_args {
5077     RectF *bounds;
5078     INT *codepointsfitted;
5079     INT *linesfilled;
5080     REAL rel_width, rel_height;
5081 };
5082
5083 static GpStatus measure_string_callback(HDC hdc,
5084     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
5085     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
5086     INT lineno, const RectF *bounds, INT *underlined_indexes,
5087     INT underlined_index_count, void *user_data)
5088 {
5089     struct measure_string_args *args = user_data;
5090     REAL new_width, new_height;
5091
5092     new_width = bounds->Width / args->rel_width;
5093     new_height = (bounds->Height + bounds->Y) / args->rel_height - args->bounds->Y;
5094
5095     if (new_width > args->bounds->Width)
5096         args->bounds->Width = new_width;
5097
5098     if (new_height > args->bounds->Height)
5099         args->bounds->Height = new_height;
5100
5101     if (args->codepointsfitted)
5102         *args->codepointsfitted = index + length;
5103
5104     if (args->linesfilled)
5105         (*args->linesfilled)++;
5106
5107     return Ok;
5108 }
5109
5110 /* Find the smallest rectangle that bounds the text when it is printed in rect
5111  * according to the format options listed in format. If rect has 0 width and
5112  * height, then just find the smallest rectangle that bounds the text when it's
5113  * printed at location (rect->X, rect-Y). */
5114 GpStatus WINGDIPAPI GdipMeasureString(GpGraphics *graphics,
5115     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
5116     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format, RectF *bounds,
5117     INT *codepointsfitted, INT *linesfilled)
5118 {
5119     HFONT oldfont, gdifont;
5120     struct measure_string_args args;
5121     HDC temp_hdc=NULL, hdc;
5122     GpPointF pt[3];
5123     RectF scaled_rect;
5124     REAL margin_x;
5125     INT lines, glyphs, format_flags = format ? format->attr : 0;
5126
5127     TRACE("(%p, %s, %i, %p, %s, %p, %p, %p, %p)\n", graphics,
5128         debugstr_wn(string, length), length, font, debugstr_rectf(rect), format,
5129         bounds, codepointsfitted, linesfilled);
5130
5131     if(!graphics || !string || !font || !rect || !bounds)
5132         return InvalidParameter;
5133
5134     if(!graphics->hdc)
5135     {
5136         hdc = temp_hdc = CreateCompatibleDC(0);
5137         if (!temp_hdc) return OutOfMemory;
5138     }
5139     else
5140         hdc = graphics->hdc;
5141
5142     if(linesfilled) *linesfilled = 0;
5143     if(codepointsfitted) *codepointsfitted = 0;
5144
5145     if(format)
5146         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
5147
5148     pt[0].X = 0.0;
5149     pt[0].Y = 0.0;
5150     pt[1].X = 1.0;
5151     pt[1].Y = 0.0;
5152     pt[2].X = 0.0;
5153     pt[2].Y = 1.0;
5154     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5155     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5156                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5157     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5158                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5159
5160     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
5161     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5162
5163     scaled_rect.X = (rect->X + margin_x) * args.rel_width;
5164     scaled_rect.Y = rect->Y * args.rel_height;
5165     scaled_rect.Width = rect->Width * args.rel_width;
5166     scaled_rect.Height = rect->Height * args.rel_height;
5167
5168     if ((format_flags & StringFormatFlagsNoClip) ||
5169         scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5170     if ((format_flags & StringFormatFlagsNoClip) ||
5171         scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5172
5173     if (scaled_rect.Width >= 0.5)
5174     {
5175         scaled_rect.Width -= margin_x * 2.0 * args.rel_width;
5176         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5177     }
5178
5179     if (scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5180     if (scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5181
5182     get_font_hfont(graphics, font, format, &gdifont, NULL);
5183     oldfont = SelectObject(hdc, gdifont);
5184
5185     bounds->X = rect->X;
5186     bounds->Y = rect->Y;
5187     bounds->Width = 0.0;
5188     bounds->Height = 0.0;
5189
5190     args.bounds = bounds;
5191     args.codepointsfitted = &glyphs;
5192     args.linesfilled = &lines;
5193     lines = glyphs = 0;
5194
5195     gdip_format_string(hdc, string, length, font, &scaled_rect, format,
5196         measure_string_callback, &args);
5197
5198     if (linesfilled) *linesfilled = lines;
5199     if (codepointsfitted) *codepointsfitted = glyphs;
5200
5201     if (lines)
5202         bounds->Width += margin_x * 2.0;
5203
5204     SelectObject(hdc, oldfont);
5205     DeleteObject(gdifont);
5206
5207     if (temp_hdc)
5208         DeleteDC(temp_hdc);
5209
5210     return Ok;
5211 }
5212
5213 struct draw_string_args {
5214     GpGraphics *graphics;
5215     GDIPCONST GpBrush *brush;
5216     REAL x, y, rel_width, rel_height, ascent;
5217 };
5218
5219 static GpStatus draw_string_callback(HDC hdc,
5220     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
5221     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
5222     INT lineno, const RectF *bounds, INT *underlined_indexes,
5223     INT underlined_index_count, void *user_data)
5224 {
5225     struct draw_string_args *args = user_data;
5226     PointF position;
5227     GpStatus stat;
5228
5229     position.X = args->x + bounds->X / args->rel_width;
5230     position.Y = args->y + bounds->Y / args->rel_height + args->ascent;
5231
5232     stat = draw_driver_string(args->graphics, &string[index], length, font, format,
5233         args->brush, &position,
5234         DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance, NULL);
5235
5236     if (stat == Ok && underlined_index_count)
5237     {
5238         OUTLINETEXTMETRICW otm;
5239         REAL underline_y, underline_height;
5240         int i;
5241
5242         GetOutlineTextMetricsW(hdc, sizeof(otm), &otm);
5243
5244         underline_height = otm.otmsUnderscoreSize / args->rel_height;
5245         underline_y = position.Y - otm.otmsUnderscorePosition / args->rel_height - underline_height / 2;
5246
5247         for (i=0; i<underlined_index_count; i++)
5248         {
5249             REAL start_x, end_x;
5250             SIZE text_size;
5251             INT ofs = underlined_indexes[i] - index;
5252
5253             GetTextExtentExPointW(hdc, string + index, ofs, INT_MAX, NULL, NULL, &text_size);
5254             start_x = text_size.cx / args->rel_width;
5255
5256             GetTextExtentExPointW(hdc, string + index, ofs+1, INT_MAX, NULL, NULL, &text_size);
5257             end_x = text_size.cx / args->rel_width;
5258
5259             GdipFillRectangle(args->graphics, (GpBrush*)args->brush, position.X+start_x, underline_y, end_x-start_x, underline_height);
5260         }
5261     }
5262
5263     return stat;
5264 }
5265
5266 GpStatus WINGDIPAPI GdipDrawString(GpGraphics *graphics, GDIPCONST WCHAR *string,
5267     INT length, GDIPCONST GpFont *font, GDIPCONST RectF *rect,
5268     GDIPCONST GpStringFormat *format, GDIPCONST GpBrush *brush)
5269 {
5270     HRGN rgn = NULL;
5271     HFONT gdifont;
5272     GpPointF pt[3], rectcpy[4];
5273     POINT corners[4];
5274     REAL rel_width, rel_height, margin_x;
5275     INT save_state, format_flags = 0;
5276     REAL offsety = 0.0;
5277     struct draw_string_args args;
5278     RectF scaled_rect;
5279     HDC hdc, temp_hdc=NULL;
5280     TEXTMETRICW textmetric;
5281
5282     TRACE("(%p, %s, %i, %p, %s, %p, %p)\n", graphics, debugstr_wn(string, length),
5283         length, font, debugstr_rectf(rect), format, brush);
5284
5285     if(!graphics || !string || !font || !brush || !rect)
5286         return InvalidParameter;
5287
5288     if(graphics->hdc)
5289     {
5290         hdc = graphics->hdc;
5291     }
5292     else
5293     {
5294         hdc = temp_hdc = CreateCompatibleDC(0);
5295     }
5296
5297     if(format){
5298         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
5299
5300         format_flags = format->attr;
5301
5302         /* Should be no need to explicitly test for StringAlignmentNear as
5303          * that is default behavior if no alignment is passed. */
5304         if(format->vertalign != StringAlignmentNear){
5305             RectF bounds, in_rect = *rect;
5306             in_rect.Height = 0.0; /* avoid height clipping */
5307             GdipMeasureString(graphics, string, length, font, &in_rect, format, &bounds, 0, 0);
5308
5309             TRACE("bounds %s\n", debugstr_rectf(&bounds));
5310
5311             if(format->vertalign == StringAlignmentCenter)
5312                 offsety = (rect->Height - bounds.Height) / 2;
5313             else if(format->vertalign == StringAlignmentFar)
5314                 offsety = (rect->Height - bounds.Height);
5315         }
5316         TRACE("vertical align %d, offsety %f\n", format->vertalign, offsety);
5317     }
5318
5319     save_state = SaveDC(hdc);
5320
5321     pt[0].X = 0.0;
5322     pt[0].Y = 0.0;
5323     pt[1].X = 1.0;
5324     pt[1].Y = 0.0;
5325     pt[2].X = 0.0;
5326     pt[2].Y = 1.0;
5327     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5328     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5329                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5330     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5331                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5332
5333     rectcpy[3].X = rectcpy[0].X = rect->X;
5334     rectcpy[1].Y = rectcpy[0].Y = rect->Y;
5335     rectcpy[2].X = rectcpy[1].X = rect->X + rect->Width;
5336     rectcpy[3].Y = rectcpy[2].Y = rect->Y + rect->Height;
5337     transform_and_round_points(graphics, corners, rectcpy, 4);
5338
5339     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
5340     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5341
5342     scaled_rect.X = margin_x * rel_width;
5343     scaled_rect.Y = 0.0;
5344     scaled_rect.Width = rel_width * rect->Width;
5345     scaled_rect.Height = rel_height * rect->Height;
5346
5347     if ((format_flags & StringFormatFlagsNoClip) ||
5348         scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5349     if ((format_flags & StringFormatFlagsNoClip) ||
5350         scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5351
5352     if (scaled_rect.Width >= 0.5)
5353     {
5354         scaled_rect.Width -= margin_x * 2.0 * rel_width;
5355         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5356     }
5357
5358     if (scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5359     if (scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5360
5361     if (!(format_flags & StringFormatFlagsNoClip) &&
5362         scaled_rect.Width != 1 << 23 && scaled_rect.Height != 1 << 23)
5363     {
5364         /* FIXME: If only the width or only the height is 0, we should probably still clip */
5365         rgn = CreatePolygonRgn(corners, 4, ALTERNATE);
5366         SelectClipRgn(hdc, rgn);
5367     }
5368
5369     get_font_hfont(graphics, font, format, &gdifont, NULL);
5370     SelectObject(hdc, gdifont);
5371
5372     args.graphics = graphics;
5373     args.brush = brush;
5374
5375     args.x = rect->X;
5376     args.y = rect->Y + offsety;
5377
5378     args.rel_width = rel_width;
5379     args.rel_height = rel_height;
5380
5381     GetTextMetricsW(hdc, &textmetric);
5382     args.ascent = textmetric.tmAscent / rel_height;
5383
5384     gdip_format_string(hdc, string, length, font, &scaled_rect, format,
5385         draw_string_callback, &args);
5386
5387     DeleteObject(rgn);
5388     DeleteObject(gdifont);
5389
5390     RestoreDC(hdc, save_state);
5391
5392     DeleteDC(temp_hdc);
5393
5394     return Ok;
5395 }
5396
5397 GpStatus WINGDIPAPI GdipResetClip(GpGraphics *graphics)
5398 {
5399     TRACE("(%p)\n", graphics);
5400
5401     if(!graphics)
5402         return InvalidParameter;
5403
5404     if(graphics->busy)
5405         return ObjectBusy;
5406
5407     return GdipSetInfinite(graphics->clip);
5408 }
5409
5410 GpStatus WINGDIPAPI GdipResetWorldTransform(GpGraphics *graphics)
5411 {
5412     TRACE("(%p)\n", graphics);
5413
5414     if(!graphics)
5415         return InvalidParameter;
5416
5417     if(graphics->busy)
5418         return ObjectBusy;
5419
5420     return GdipSetMatrixElements(&graphics->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
5421 }
5422
5423 GpStatus WINGDIPAPI GdipRestoreGraphics(GpGraphics *graphics, GraphicsState state)
5424 {
5425     return GdipEndContainer(graphics, state);
5426 }
5427
5428 GpStatus WINGDIPAPI GdipRotateWorldTransform(GpGraphics *graphics, REAL angle,
5429     GpMatrixOrder order)
5430 {
5431     TRACE("(%p, %.2f, %d)\n", graphics, angle, order);
5432
5433     if(!graphics)
5434         return InvalidParameter;
5435
5436     if(graphics->busy)
5437         return ObjectBusy;
5438
5439     return GdipRotateMatrix(&graphics->worldtrans, angle, order);
5440 }
5441
5442 GpStatus WINGDIPAPI GdipSaveGraphics(GpGraphics *graphics, GraphicsState *state)
5443 {
5444     return GdipBeginContainer2(graphics, state);
5445 }
5446
5447 GpStatus WINGDIPAPI GdipBeginContainer2(GpGraphics *graphics,
5448         GraphicsContainer *state)
5449 {
5450     GraphicsContainerItem *container;
5451     GpStatus sts;
5452
5453     TRACE("(%p, %p)\n", graphics, state);
5454
5455     if(!graphics || !state)
5456         return InvalidParameter;
5457
5458     sts = init_container(&container, graphics);
5459     if(sts != Ok)
5460         return sts;
5461
5462     list_add_head(&graphics->containers, &container->entry);
5463     *state = graphics->contid = container->contid;
5464
5465     return Ok;
5466 }
5467
5468 GpStatus WINGDIPAPI GdipBeginContainer(GpGraphics *graphics, GDIPCONST GpRectF *dstrect, GDIPCONST GpRectF *srcrect, GpUnit unit, GraphicsContainer *state)
5469 {
5470     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5471     return NotImplemented;
5472 }
5473
5474 GpStatus WINGDIPAPI GdipBeginContainerI(GpGraphics *graphics, GDIPCONST GpRect *dstrect, GDIPCONST GpRect *srcrect, GpUnit unit, GraphicsContainer *state)
5475 {
5476     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5477     return NotImplemented;
5478 }
5479
5480 GpStatus WINGDIPAPI GdipComment(GpGraphics *graphics, UINT sizeData, GDIPCONST BYTE *data)
5481 {
5482     FIXME("(%p, %d, %p): stub\n", graphics, sizeData, data);
5483     return NotImplemented;
5484 }
5485
5486 GpStatus WINGDIPAPI GdipEndContainer(GpGraphics *graphics, GraphicsContainer state)
5487 {
5488     GpStatus sts;
5489     GraphicsContainerItem *container, *container2;
5490
5491     TRACE("(%p, %x)\n", graphics, state);
5492
5493     if(!graphics)
5494         return InvalidParameter;
5495
5496     LIST_FOR_EACH_ENTRY(container, &graphics->containers, GraphicsContainerItem, entry){
5497         if(container->contid == state)
5498             break;
5499     }
5500
5501     /* did not find a matching container */
5502     if(&container->entry == &graphics->containers)
5503         return Ok;
5504
5505     sts = restore_container(graphics, container);
5506     if(sts != Ok)
5507         return sts;
5508
5509     /* remove all of the containers on top of the found container */
5510     LIST_FOR_EACH_ENTRY_SAFE(container, container2, &graphics->containers, GraphicsContainerItem, entry){
5511         if(container->contid == state)
5512             break;
5513         list_remove(&container->entry);
5514         delete_container(container);
5515     }
5516
5517     list_remove(&container->entry);
5518     delete_container(container);
5519
5520     return Ok;
5521 }
5522
5523 GpStatus WINGDIPAPI GdipScaleWorldTransform(GpGraphics *graphics, REAL sx,
5524     REAL sy, GpMatrixOrder order)
5525 {
5526     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, sx, sy, order);
5527
5528     if(!graphics)
5529         return InvalidParameter;
5530
5531     if(graphics->busy)
5532         return ObjectBusy;
5533
5534     return GdipScaleMatrix(&graphics->worldtrans, sx, sy, order);
5535 }
5536
5537 GpStatus WINGDIPAPI GdipSetClipGraphics(GpGraphics *graphics, GpGraphics *srcgraphics,
5538     CombineMode mode)
5539 {
5540     TRACE("(%p, %p, %d)\n", graphics, srcgraphics, mode);
5541
5542     if(!graphics || !srcgraphics)
5543         return InvalidParameter;
5544
5545     return GdipCombineRegionRegion(graphics->clip, srcgraphics->clip, mode);
5546 }
5547
5548 GpStatus WINGDIPAPI GdipSetCompositingMode(GpGraphics *graphics,
5549     CompositingMode mode)
5550 {
5551     TRACE("(%p, %d)\n", graphics, mode);
5552
5553     if(!graphics)
5554         return InvalidParameter;
5555
5556     if(graphics->busy)
5557         return ObjectBusy;
5558
5559     graphics->compmode = mode;
5560
5561     return Ok;
5562 }
5563
5564 GpStatus WINGDIPAPI GdipSetCompositingQuality(GpGraphics *graphics,
5565     CompositingQuality quality)
5566 {
5567     TRACE("(%p, %d)\n", graphics, quality);
5568
5569     if(!graphics)
5570         return InvalidParameter;
5571
5572     if(graphics->busy)
5573         return ObjectBusy;
5574
5575     graphics->compqual = quality;
5576
5577     return Ok;
5578 }
5579
5580 GpStatus WINGDIPAPI GdipSetInterpolationMode(GpGraphics *graphics,
5581     InterpolationMode mode)
5582 {
5583     TRACE("(%p, %d)\n", graphics, mode);
5584
5585     if(!graphics || mode == InterpolationModeInvalid || mode > InterpolationModeHighQualityBicubic)
5586         return InvalidParameter;
5587
5588     if(graphics->busy)
5589         return ObjectBusy;
5590
5591     if (mode == InterpolationModeDefault || mode == InterpolationModeLowQuality)
5592         mode = InterpolationModeBilinear;
5593
5594     if (mode == InterpolationModeHighQuality)
5595         mode = InterpolationModeHighQualityBicubic;
5596
5597     graphics->interpolation = mode;
5598
5599     return Ok;
5600 }
5601
5602 GpStatus WINGDIPAPI GdipSetPageScale(GpGraphics *graphics, REAL scale)
5603 {
5604     TRACE("(%p, %.2f)\n", graphics, scale);
5605
5606     if(!graphics || (scale <= 0.0))
5607         return InvalidParameter;
5608
5609     if(graphics->busy)
5610         return ObjectBusy;
5611
5612     graphics->scale = scale;
5613
5614     return Ok;
5615 }
5616
5617 GpStatus WINGDIPAPI GdipSetPageUnit(GpGraphics *graphics, GpUnit unit)
5618 {
5619     TRACE("(%p, %d)\n", graphics, unit);
5620
5621     if(!graphics)
5622         return InvalidParameter;
5623
5624     if(graphics->busy)
5625         return ObjectBusy;
5626
5627     if(unit == UnitWorld)
5628         return InvalidParameter;
5629
5630     graphics->unit = unit;
5631
5632     return Ok;
5633 }
5634
5635 GpStatus WINGDIPAPI GdipSetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
5636     mode)
5637 {
5638     TRACE("(%p, %d)\n", graphics, mode);
5639
5640     if(!graphics)
5641         return InvalidParameter;
5642
5643     if(graphics->busy)
5644         return ObjectBusy;
5645
5646     graphics->pixeloffset = mode;
5647
5648     return Ok;
5649 }
5650
5651 GpStatus WINGDIPAPI GdipSetRenderingOrigin(GpGraphics *graphics, INT x, INT y)
5652 {
5653     static int calls;
5654
5655     TRACE("(%p,%i,%i)\n", graphics, x, y);
5656
5657     if (!(calls++))
5658         FIXME("value is unused in rendering\n");
5659
5660     if (!graphics)
5661         return InvalidParameter;
5662
5663     graphics->origin_x = x;
5664     graphics->origin_y = y;
5665
5666     return Ok;
5667 }
5668
5669 GpStatus WINGDIPAPI GdipGetRenderingOrigin(GpGraphics *graphics, INT *x, INT *y)
5670 {
5671     TRACE("(%p,%p,%p)\n", graphics, x, y);
5672
5673     if (!graphics || !x || !y)
5674         return InvalidParameter;
5675
5676     *x = graphics->origin_x;
5677     *y = graphics->origin_y;
5678
5679     return Ok;
5680 }
5681
5682 GpStatus WINGDIPAPI GdipSetSmoothingMode(GpGraphics *graphics, SmoothingMode mode)
5683 {
5684     TRACE("(%p, %d)\n", graphics, mode);
5685
5686     if(!graphics)
5687         return InvalidParameter;
5688
5689     if(graphics->busy)
5690         return ObjectBusy;
5691
5692     graphics->smoothing = mode;
5693
5694     return Ok;
5695 }
5696
5697 GpStatus WINGDIPAPI GdipSetTextContrast(GpGraphics *graphics, UINT contrast)
5698 {
5699     TRACE("(%p, %d)\n", graphics, contrast);
5700
5701     if(!graphics)
5702         return InvalidParameter;
5703
5704     graphics->textcontrast = contrast;
5705
5706     return Ok;
5707 }
5708
5709 GpStatus WINGDIPAPI GdipSetTextRenderingHint(GpGraphics *graphics,
5710     TextRenderingHint hint)
5711 {
5712     TRACE("(%p, %d)\n", graphics, hint);
5713
5714     if(!graphics || hint > TextRenderingHintClearTypeGridFit)
5715         return InvalidParameter;
5716
5717     if(graphics->busy)
5718         return ObjectBusy;
5719
5720     graphics->texthint = hint;
5721
5722     return Ok;
5723 }
5724
5725 GpStatus WINGDIPAPI GdipSetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
5726 {
5727     TRACE("(%p, %p)\n", graphics, matrix);
5728
5729     if(!graphics || !matrix)
5730         return InvalidParameter;
5731
5732     if(graphics->busy)
5733         return ObjectBusy;
5734
5735     TRACE("%f,%f,%f,%f,%f,%f\n",
5736           matrix->matrix[0], matrix->matrix[1], matrix->matrix[2],
5737           matrix->matrix[3], matrix->matrix[4], matrix->matrix[5]);
5738
5739     graphics->worldtrans = *matrix;
5740
5741     return Ok;
5742 }
5743
5744 GpStatus WINGDIPAPI GdipTranslateWorldTransform(GpGraphics *graphics, REAL dx,
5745     REAL dy, GpMatrixOrder order)
5746 {
5747     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, dx, dy, order);
5748
5749     if(!graphics)
5750         return InvalidParameter;
5751
5752     if(graphics->busy)
5753         return ObjectBusy;
5754
5755     return GdipTranslateMatrix(&graphics->worldtrans, dx, dy, order);
5756 }
5757
5758 /*****************************************************************************
5759  * GdipSetClipHrgn [GDIPLUS.@]
5760  */
5761 GpStatus WINGDIPAPI GdipSetClipHrgn(GpGraphics *graphics, HRGN hrgn, CombineMode mode)
5762 {
5763     GpRegion *region;
5764     GpStatus status;
5765
5766     TRACE("(%p, %p, %d)\n", graphics, hrgn, mode);
5767
5768     if(!graphics)
5769         return InvalidParameter;
5770
5771     status = GdipCreateRegionHrgn(hrgn, &region);
5772     if(status != Ok)
5773         return status;
5774
5775     status = GdipSetClipRegion(graphics, region, mode);
5776
5777     GdipDeleteRegion(region);
5778     return status;
5779 }
5780
5781 GpStatus WINGDIPAPI GdipSetClipPath(GpGraphics *graphics, GpPath *path, CombineMode mode)
5782 {
5783     TRACE("(%p, %p, %d)\n", graphics, path, mode);
5784
5785     if(!graphics)
5786         return InvalidParameter;
5787
5788     if(graphics->busy)
5789         return ObjectBusy;
5790
5791     return GdipCombineRegionPath(graphics->clip, path, mode);
5792 }
5793
5794 GpStatus WINGDIPAPI GdipSetClipRect(GpGraphics *graphics, REAL x, REAL y,
5795                                     REAL width, REAL height,
5796                                     CombineMode mode)
5797 {
5798     GpRectF rect;
5799
5800     TRACE("(%p, %.2f, %.2f, %.2f, %.2f, %d)\n", graphics, x, y, width, height, mode);
5801
5802     if(!graphics)
5803         return InvalidParameter;
5804
5805     if(graphics->busy)
5806         return ObjectBusy;
5807
5808     rect.X = x;
5809     rect.Y = y;
5810     rect.Width  = width;
5811     rect.Height = height;
5812
5813     return GdipCombineRegionRect(graphics->clip, &rect, mode);
5814 }
5815
5816 GpStatus WINGDIPAPI GdipSetClipRectI(GpGraphics *graphics, INT x, INT y,
5817                                      INT width, INT height,
5818                                      CombineMode mode)
5819 {
5820     TRACE("(%p, %d, %d, %d, %d, %d)\n", graphics, x, y, width, height, mode);
5821
5822     if(!graphics)
5823         return InvalidParameter;
5824
5825     if(graphics->busy)
5826         return ObjectBusy;
5827
5828     return GdipSetClipRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, mode);
5829 }
5830
5831 GpStatus WINGDIPAPI GdipSetClipRegion(GpGraphics *graphics, GpRegion *region,
5832                                       CombineMode mode)
5833 {
5834     TRACE("(%p, %p, %d)\n", graphics, region, mode);
5835
5836     if(!graphics || !region)
5837         return InvalidParameter;
5838
5839     if(graphics->busy)
5840         return ObjectBusy;
5841
5842     return GdipCombineRegionRegion(graphics->clip, region, mode);
5843 }
5844
5845 GpStatus WINGDIPAPI GdipSetMetafileDownLevelRasterizationLimit(GpMetafile *metafile,
5846     UINT limitDpi)
5847 {
5848     static int calls;
5849
5850     TRACE("(%p,%u)\n", metafile, limitDpi);
5851
5852     if(!(calls++))
5853         FIXME("not implemented\n");
5854
5855     return NotImplemented;
5856 }
5857
5858 GpStatus WINGDIPAPI GdipDrawPolygon(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPointF *points,
5859     INT count)
5860 {
5861     INT save_state;
5862     POINT *pti;
5863
5864     TRACE("(%p, %p, %d)\n", graphics, points, count);
5865
5866     if(!graphics || !pen || count<=0)
5867         return InvalidParameter;
5868
5869     if(graphics->busy)
5870         return ObjectBusy;
5871
5872     if (!graphics->hdc)
5873     {
5874         FIXME("graphics object has no HDC\n");
5875         return Ok;
5876     }
5877
5878     pti = GdipAlloc(sizeof(POINT) * count);
5879
5880     save_state = prepare_dc(graphics, pen);
5881     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
5882
5883     transform_and_round_points(graphics, pti, (GpPointF*)points, count);
5884     Polygon(graphics->hdc, pti, count);
5885
5886     restore_dc(graphics, save_state);
5887     GdipFree(pti);
5888
5889     return Ok;
5890 }
5891
5892 GpStatus WINGDIPAPI GdipDrawPolygonI(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPoint *points,
5893     INT count)
5894 {
5895     GpStatus ret;
5896     GpPointF *ptf;
5897     INT i;
5898
5899     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
5900
5901     if(count<=0)    return InvalidParameter;
5902     ptf = GdipAlloc(sizeof(GpPointF) * count);
5903
5904     for(i = 0;i < count; i++){
5905         ptf[i].X = (REAL)points[i].X;
5906         ptf[i].Y = (REAL)points[i].Y;
5907     }
5908
5909     ret = GdipDrawPolygon(graphics,pen,ptf,count);
5910     GdipFree(ptf);
5911
5912     return ret;
5913 }
5914
5915 GpStatus WINGDIPAPI GdipGetDpiX(GpGraphics *graphics, REAL* dpi)
5916 {
5917     TRACE("(%p, %p)\n", graphics, dpi);
5918
5919     if(!graphics || !dpi)
5920         return InvalidParameter;
5921
5922     if(graphics->busy)
5923         return ObjectBusy;
5924
5925     *dpi = graphics->xres;
5926     return Ok;
5927 }
5928
5929 GpStatus WINGDIPAPI GdipGetDpiY(GpGraphics *graphics, REAL* dpi)
5930 {
5931     TRACE("(%p, %p)\n", graphics, dpi);
5932
5933     if(!graphics || !dpi)
5934         return InvalidParameter;
5935
5936     if(graphics->busy)
5937         return ObjectBusy;
5938
5939     *dpi = graphics->yres;
5940     return Ok;
5941 }
5942
5943 GpStatus WINGDIPAPI GdipMultiplyWorldTransform(GpGraphics *graphics, GDIPCONST GpMatrix *matrix,
5944     GpMatrixOrder order)
5945 {
5946     GpMatrix m;
5947     GpStatus ret;
5948
5949     TRACE("(%p, %p, %d)\n", graphics, matrix, order);
5950
5951     if(!graphics || !matrix)
5952         return InvalidParameter;
5953
5954     if(graphics->busy)
5955         return ObjectBusy;
5956
5957     m = graphics->worldtrans;
5958
5959     ret = GdipMultiplyMatrix(&m, matrix, order);
5960     if(ret == Ok)
5961         graphics->worldtrans = m;
5962
5963     return ret;
5964 }
5965
5966 /* Color used to fill bitmaps so we can tell which parts have been drawn over by gdi32. */
5967 static const COLORREF DC_BACKGROUND_KEY = 0x0c0b0d;
5968
5969 GpStatus WINGDIPAPI GdipGetDC(GpGraphics *graphics, HDC *hdc)
5970 {
5971     GpStatus stat=Ok;
5972
5973     TRACE("(%p, %p)\n", graphics, hdc);
5974
5975     if(!graphics || !hdc)
5976         return InvalidParameter;
5977
5978     if(graphics->busy)
5979         return ObjectBusy;
5980
5981     if (graphics->image && graphics->image->type == ImageTypeMetafile)
5982     {
5983         stat = METAFILE_GetDC((GpMetafile*)graphics->image, hdc);
5984     }
5985     else if (!graphics->hdc ||
5986         (graphics->image && graphics->image->type == ImageTypeBitmap && ((GpBitmap*)graphics->image)->format & PixelFormatAlpha))
5987     {
5988         /* Create a fake HDC and fill it with a constant color. */
5989         HDC temp_hdc;
5990         HBITMAP hbitmap;
5991         GpRectF bounds;
5992         BITMAPINFOHEADER bmih;
5993         int i;
5994
5995         stat = get_graphics_bounds(graphics, &bounds);
5996         if (stat != Ok)
5997             return stat;
5998
5999         graphics->temp_hbitmap_width = bounds.Width;
6000         graphics->temp_hbitmap_height = bounds.Height;
6001
6002         bmih.biSize = sizeof(bmih);
6003         bmih.biWidth = graphics->temp_hbitmap_width;
6004         bmih.biHeight = -graphics->temp_hbitmap_height;
6005         bmih.biPlanes = 1;
6006         bmih.biBitCount = 32;
6007         bmih.biCompression = BI_RGB;
6008         bmih.biSizeImage = 0;
6009         bmih.biXPelsPerMeter = 0;
6010         bmih.biYPelsPerMeter = 0;
6011         bmih.biClrUsed = 0;
6012         bmih.biClrImportant = 0;
6013
6014         hbitmap = CreateDIBSection(NULL, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
6015             (void**)&graphics->temp_bits, NULL, 0);
6016         if (!hbitmap)
6017             return GenericError;
6018
6019         temp_hdc = CreateCompatibleDC(0);
6020         if (!temp_hdc)
6021         {
6022             DeleteObject(hbitmap);
6023             return GenericError;
6024         }
6025
6026         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
6027             ((DWORD*)graphics->temp_bits)[i] = DC_BACKGROUND_KEY;
6028
6029         SelectObject(temp_hdc, hbitmap);
6030
6031         graphics->temp_hbitmap = hbitmap;
6032         *hdc = graphics->temp_hdc = temp_hdc;
6033     }
6034     else
6035     {
6036         *hdc = graphics->hdc;
6037     }
6038
6039     if (stat == Ok)
6040         graphics->busy = TRUE;
6041
6042     return stat;
6043 }
6044
6045 GpStatus WINGDIPAPI GdipReleaseDC(GpGraphics *graphics, HDC hdc)
6046 {
6047     GpStatus stat=Ok;
6048
6049     TRACE("(%p, %p)\n", graphics, hdc);
6050
6051     if(!graphics || !hdc || !graphics->busy)
6052         return InvalidParameter;
6053
6054     if (graphics->image && graphics->image->type == ImageTypeMetafile)
6055     {
6056         stat = METAFILE_ReleaseDC((GpMetafile*)graphics->image, hdc);
6057     }
6058     else if (graphics->temp_hdc == hdc)
6059     {
6060         DWORD* pos;
6061         int i;
6062
6063         /* Find the pixels that have changed, and mark them as opaque. */
6064         pos = (DWORD*)graphics->temp_bits;
6065         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
6066         {
6067             if (*pos != DC_BACKGROUND_KEY)
6068             {
6069                 *pos |= 0xff000000;
6070             }
6071             pos++;
6072         }
6073
6074         /* Write the changed pixels to the real target. */
6075         alpha_blend_pixels(graphics, 0, 0, graphics->temp_bits,
6076             graphics->temp_hbitmap_width, graphics->temp_hbitmap_height,
6077             graphics->temp_hbitmap_width * 4);
6078
6079         /* Clean up. */
6080         DeleteDC(graphics->temp_hdc);
6081         DeleteObject(graphics->temp_hbitmap);
6082         graphics->temp_hdc = NULL;
6083         graphics->temp_hbitmap = NULL;
6084     }
6085     else if (hdc != graphics->hdc)
6086     {
6087         stat = InvalidParameter;
6088     }
6089
6090     if (stat == Ok)
6091         graphics->busy = FALSE;
6092
6093     return stat;
6094 }
6095
6096 GpStatus WINGDIPAPI GdipGetClip(GpGraphics *graphics, GpRegion *region)
6097 {
6098     GpRegion *clip;
6099     GpStatus status;
6100
6101     TRACE("(%p, %p)\n", graphics, region);
6102
6103     if(!graphics || !region)
6104         return InvalidParameter;
6105
6106     if(graphics->busy)
6107         return ObjectBusy;
6108
6109     if((status = GdipCloneRegion(graphics->clip, &clip)) != Ok)
6110         return status;
6111
6112     /* free everything except root node and header */
6113     delete_element(&region->node);
6114     memcpy(region, clip, sizeof(GpRegion));
6115     GdipFree(clip);
6116
6117     return Ok;
6118 }
6119
6120 static GpStatus get_graphics_transform(GpGraphics *graphics, GpCoordinateSpace dst_space,
6121         GpCoordinateSpace src_space, GpMatrix *matrix)
6122 {
6123     GpStatus stat = Ok;
6124     REAL scale_x, scale_y;
6125
6126     GdipSetMatrixElements(matrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
6127
6128     if (dst_space != src_space)
6129     {
6130         scale_x = units_to_pixels(1.0, graphics->unit, graphics->xres);
6131         scale_y = units_to_pixels(1.0, graphics->unit, graphics->yres);
6132
6133         if(graphics->unit != UnitDisplay)
6134         {
6135             scale_x *= graphics->scale;
6136             scale_y *= graphics->scale;
6137         }
6138
6139         /* transform from src_space to CoordinateSpacePage */
6140         switch (src_space)
6141         {
6142         case CoordinateSpaceWorld:
6143             GdipMultiplyMatrix(matrix, &graphics->worldtrans, MatrixOrderAppend);
6144             break;
6145         case CoordinateSpacePage:
6146             break;
6147         case CoordinateSpaceDevice:
6148             GdipScaleMatrix(matrix, 1.0/scale_x, 1.0/scale_y, MatrixOrderAppend);
6149             break;
6150         }
6151
6152         /* transform from CoordinateSpacePage to dst_space */
6153         switch (dst_space)
6154         {
6155         case CoordinateSpaceWorld:
6156             {
6157                 GpMatrix inverted_transform = graphics->worldtrans;
6158                 stat = GdipInvertMatrix(&inverted_transform);
6159                 if (stat == Ok)
6160                     GdipMultiplyMatrix(matrix, &inverted_transform, MatrixOrderAppend);
6161                 break;
6162             }
6163         case CoordinateSpacePage:
6164             break;
6165         case CoordinateSpaceDevice:
6166             GdipScaleMatrix(matrix, scale_x, scale_y, MatrixOrderAppend);
6167             break;
6168         }
6169     }
6170     return stat;
6171 }
6172
6173 GpStatus WINGDIPAPI GdipTransformPoints(GpGraphics *graphics, GpCoordinateSpace dst_space,
6174                                         GpCoordinateSpace src_space, GpPointF *points, INT count)
6175 {
6176     GpMatrix matrix;
6177     GpStatus stat;
6178
6179     if(!graphics || !points || count <= 0)
6180         return InvalidParameter;
6181
6182     if(graphics->busy)
6183         return ObjectBusy;
6184
6185     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
6186
6187     if (src_space == dst_space) return Ok;
6188
6189     stat = get_graphics_transform(graphics, dst_space, src_space, &matrix);
6190     if (stat != Ok) return stat;
6191
6192     return GdipTransformMatrixPoints(&matrix, points, count);
6193 }
6194
6195 GpStatus WINGDIPAPI GdipTransformPointsI(GpGraphics *graphics, GpCoordinateSpace dst_space,
6196                                          GpCoordinateSpace src_space, GpPoint *points, INT count)
6197 {
6198     GpPointF *pointsF;
6199     GpStatus ret;
6200     INT i;
6201
6202     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
6203
6204     if(count <= 0)
6205         return InvalidParameter;
6206
6207     pointsF = GdipAlloc(sizeof(GpPointF) * count);
6208     if(!pointsF)
6209         return OutOfMemory;
6210
6211     for(i = 0; i < count; i++){
6212         pointsF[i].X = (REAL)points[i].X;
6213         pointsF[i].Y = (REAL)points[i].Y;
6214     }
6215
6216     ret = GdipTransformPoints(graphics, dst_space, src_space, pointsF, count);
6217
6218     if(ret == Ok)
6219         for(i = 0; i < count; i++){
6220             points[i].X = gdip_round(pointsF[i].X);
6221             points[i].Y = gdip_round(pointsF[i].Y);
6222         }
6223     GdipFree(pointsF);
6224
6225     return ret;
6226 }
6227
6228 HPALETTE WINGDIPAPI GdipCreateHalftonePalette(void)
6229 {
6230     static int calls;
6231
6232     TRACE("\n");
6233
6234     if (!calls++)
6235       FIXME("stub\n");
6236
6237     return NULL;
6238 }
6239
6240 /*****************************************************************************
6241  * GdipTranslateClip [GDIPLUS.@]
6242  */
6243 GpStatus WINGDIPAPI GdipTranslateClip(GpGraphics *graphics, REAL dx, REAL dy)
6244 {
6245     TRACE("(%p, %.2f, %.2f)\n", graphics, dx, dy);
6246
6247     if(!graphics)
6248         return InvalidParameter;
6249
6250     if(graphics->busy)
6251         return ObjectBusy;
6252
6253     return GdipTranslateRegion(graphics->clip, dx, dy);
6254 }
6255
6256 /*****************************************************************************
6257  * GdipTranslateClipI [GDIPLUS.@]
6258  */
6259 GpStatus WINGDIPAPI GdipTranslateClipI(GpGraphics *graphics, INT dx, INT dy)
6260 {
6261     TRACE("(%p, %d, %d)\n", graphics, dx, dy);
6262
6263     if(!graphics)
6264         return InvalidParameter;
6265
6266     if(graphics->busy)
6267         return ObjectBusy;
6268
6269     return GdipTranslateRegion(graphics->clip, (REAL)dx, (REAL)dy);
6270 }
6271
6272
6273 /*****************************************************************************
6274  * GdipMeasureDriverString [GDIPLUS.@]
6275  */
6276 GpStatus WINGDIPAPI GdipMeasureDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6277                                             GDIPCONST GpFont *font, GDIPCONST PointF *positions,
6278                                             INT flags, GDIPCONST GpMatrix *matrix, RectF *boundingBox)
6279 {
6280     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
6281     HFONT hfont;
6282     HDC hdc;
6283     REAL min_x, min_y, max_x, max_y, x, y;
6284     int i;
6285     TEXTMETRICW textmetric;
6286     const WORD *glyph_indices;
6287     WORD *dynamic_glyph_indices=NULL;
6288     REAL rel_width, rel_height, ascent, descent;
6289     GpPointF pt[3];
6290
6291     TRACE("(%p %p %d %p %p %d %p %p)\n", graphics, text, length, font, positions, flags, matrix, boundingBox);
6292
6293     if (!graphics || !text || !font || !positions || !boundingBox)
6294         return InvalidParameter;
6295
6296     if (length == -1)
6297         length = strlenW(text);
6298
6299     if (length == 0)
6300     {
6301         boundingBox->X = 0.0;
6302         boundingBox->Y = 0.0;
6303         boundingBox->Width = 0.0;
6304         boundingBox->Height = 0.0;
6305     }
6306
6307     if (flags & unsupported_flags)
6308         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6309
6310     get_font_hfont(graphics, font, NULL, &hfont, matrix);
6311
6312     hdc = CreateCompatibleDC(0);
6313     SelectObject(hdc, hfont);
6314
6315     GetTextMetricsW(hdc, &textmetric);
6316
6317     pt[0].X = 0.0;
6318     pt[0].Y = 0.0;
6319     pt[1].X = 1.0;
6320     pt[1].Y = 0.0;
6321     pt[2].X = 0.0;
6322     pt[2].Y = 1.0;
6323     if (matrix)
6324     {
6325         GpMatrix xform = *matrix;
6326         GdipTransformMatrixPoints(&xform, pt, 3);
6327     }
6328     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
6329     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
6330                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
6331     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
6332                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
6333
6334     if (flags & DriverStringOptionsCmapLookup)
6335     {
6336         glyph_indices = dynamic_glyph_indices = GdipAlloc(sizeof(WORD) * length);
6337         if (!glyph_indices)
6338         {
6339             DeleteDC(hdc);
6340             DeleteObject(hfont);
6341             return OutOfMemory;
6342         }
6343
6344         GetGlyphIndicesW(hdc, text, length, dynamic_glyph_indices, 0);
6345     }
6346     else
6347         glyph_indices = text;
6348
6349     min_x = max_x = x = positions[0].X;
6350     min_y = max_y = y = positions[0].Y;
6351
6352     ascent = textmetric.tmAscent / rel_height;
6353     descent = textmetric.tmDescent / rel_height;
6354
6355     for (i=0; i<length; i++)
6356     {
6357         int char_width;
6358         ABC abc;
6359
6360         if (!(flags & DriverStringOptionsRealizedAdvance))
6361         {
6362             x = positions[i].X;
6363             y = positions[i].Y;
6364         }
6365
6366         GetCharABCWidthsW(hdc, glyph_indices[i], glyph_indices[i], &abc);
6367         char_width = abc.abcA + abc.abcB + abc.abcC;
6368
6369         if (min_y > y - ascent) min_y = y - ascent;
6370         if (max_y < y + descent) max_y = y + descent;
6371         if (min_x > x) min_x = x;
6372
6373         x += char_width / rel_width;
6374
6375         if (max_x < x) max_x = x;
6376     }
6377
6378     GdipFree(dynamic_glyph_indices);
6379     DeleteDC(hdc);
6380     DeleteObject(hfont);
6381
6382     boundingBox->X = min_x;
6383     boundingBox->Y = min_y;
6384     boundingBox->Width = max_x - min_x;
6385     boundingBox->Height = max_y - min_y;
6386
6387     return Ok;
6388 }
6389
6390 static GpStatus GDI32_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6391                                            GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6392                                            GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6393                                            INT flags, GDIPCONST GpMatrix *matrix)
6394 {
6395     static const INT unsupported_flags = ~(DriverStringOptionsRealizedAdvance|DriverStringOptionsCmapLookup);
6396     INT save_state;
6397     GpPointF pt;
6398     HFONT hfont;
6399     UINT eto_flags=0;
6400
6401     if (flags & unsupported_flags)
6402         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6403
6404     if (!(flags & DriverStringOptionsCmapLookup))
6405         eto_flags |= ETO_GLYPH_INDEX;
6406
6407     save_state = SaveDC(graphics->hdc);
6408     SetBkMode(graphics->hdc, TRANSPARENT);
6409     SetTextColor(graphics->hdc, get_gdi_brush_color(brush));
6410
6411     pt = positions[0];
6412     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, &pt, 1);
6413
6414     get_font_hfont(graphics, font, format, &hfont, matrix);
6415     SelectObject(graphics->hdc, hfont);
6416
6417     SetTextAlign(graphics->hdc, TA_BASELINE|TA_LEFT);
6418
6419     ExtTextOutW(graphics->hdc, gdip_round(pt.X), gdip_round(pt.Y), eto_flags, NULL, text, length, NULL);
6420
6421     RestoreDC(graphics->hdc, save_state);
6422
6423     DeleteObject(hfont);
6424
6425     return Ok;
6426 }
6427
6428 static GpStatus SOFTWARE_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6429                                         GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6430                                         GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6431                                         INT flags, GDIPCONST GpMatrix *matrix)
6432 {
6433     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
6434     GpStatus stat;
6435     PointF *real_positions, real_position;
6436     POINT *pti;
6437     HFONT hfont;
6438     HDC hdc;
6439     int min_x=INT_MAX, min_y=INT_MAX, max_x=INT_MIN, max_y=INT_MIN, i, x, y;
6440     DWORD max_glyphsize=0;
6441     GLYPHMETRICS glyphmetrics;
6442     static const MAT2 identity = {{0,1}, {0,0}, {0,0}, {0,1}};
6443     BYTE *glyph_mask;
6444     BYTE *text_mask;
6445     int text_mask_stride;
6446     BYTE *pixel_data;
6447     int pixel_data_stride;
6448     GpRect pixel_area;
6449     UINT ggo_flags = GGO_GRAY8_BITMAP;
6450
6451     if (length <= 0)
6452         return Ok;
6453
6454     if (!(flags & DriverStringOptionsCmapLookup))
6455         ggo_flags |= GGO_GLYPH_INDEX;
6456
6457     if (flags & unsupported_flags)
6458         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6459
6460     pti = GdipAlloc(sizeof(POINT) * length);
6461     if (!pti)
6462         return OutOfMemory;
6463
6464     if (flags & DriverStringOptionsRealizedAdvance)
6465     {
6466         real_position = positions[0];
6467
6468         transform_and_round_points(graphics, pti, &real_position, 1);
6469     }
6470     else
6471     {
6472         real_positions = GdipAlloc(sizeof(PointF) * length);
6473         if (!real_positions)
6474         {
6475             GdipFree(pti);
6476             return OutOfMemory;
6477         }
6478
6479         memcpy(real_positions, positions, sizeof(PointF) * length);
6480
6481         transform_and_round_points(graphics, pti, real_positions, length);
6482
6483         GdipFree(real_positions);
6484     }
6485
6486     get_font_hfont(graphics, font, format, &hfont, matrix);
6487
6488     hdc = CreateCompatibleDC(0);
6489     SelectObject(hdc, hfont);
6490
6491     /* Get the boundaries of the text to be drawn */
6492     for (i=0; i<length; i++)
6493     {
6494         DWORD glyphsize;
6495         int left, top, right, bottom;
6496
6497         glyphsize = GetGlyphOutlineW(hdc, text[i], ggo_flags,
6498             &glyphmetrics, 0, NULL, &identity);
6499
6500         if (glyphsize == GDI_ERROR)
6501         {
6502             ERR("GetGlyphOutlineW failed\n");
6503             GdipFree(pti);
6504             DeleteDC(hdc);
6505             DeleteObject(hfont);
6506             return GenericError;
6507         }
6508
6509         if (glyphsize > max_glyphsize)
6510             max_glyphsize = glyphsize;
6511
6512         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6513         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6514         right = pti[i].x + glyphmetrics.gmptGlyphOrigin.x + glyphmetrics.gmBlackBoxX;
6515         bottom = pti[i].y - glyphmetrics.gmptGlyphOrigin.y + glyphmetrics.gmBlackBoxY;
6516
6517         if (left < min_x) min_x = left;
6518         if (top < min_y) min_y = top;
6519         if (right > max_x) max_x = right;
6520         if (bottom > max_y) max_y = bottom;
6521
6522         if (i+1 < length && (flags & DriverStringOptionsRealizedAdvance) == DriverStringOptionsRealizedAdvance)
6523         {
6524             pti[i+1].x = pti[i].x + glyphmetrics.gmCellIncX;
6525             pti[i+1].y = pti[i].y + glyphmetrics.gmCellIncY;
6526         }
6527     }
6528
6529     glyph_mask = GdipAlloc(max_glyphsize);
6530     text_mask = GdipAlloc((max_x - min_x) * (max_y - min_y));
6531     text_mask_stride = max_x - min_x;
6532
6533     if (!(glyph_mask && text_mask))
6534     {
6535         GdipFree(glyph_mask);
6536         GdipFree(text_mask);
6537         GdipFree(pti);
6538         DeleteDC(hdc);
6539         DeleteObject(hfont);
6540         return OutOfMemory;
6541     }
6542
6543     /* Generate a mask for the text */
6544     for (i=0; i<length; i++)
6545     {
6546         int left, top, stride;
6547
6548         GetGlyphOutlineW(hdc, text[i], ggo_flags,
6549             &glyphmetrics, max_glyphsize, glyph_mask, &identity);
6550
6551         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6552         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6553         stride = (glyphmetrics.gmBlackBoxX + 3) & (~3);
6554
6555         for (y=0; y<glyphmetrics.gmBlackBoxY; y++)
6556         {
6557             BYTE *glyph_val = glyph_mask + y * stride;
6558             BYTE *text_val = text_mask + (left - min_x) + (top - min_y + y) * text_mask_stride;
6559             for (x=0; x<glyphmetrics.gmBlackBoxX; x++)
6560             {
6561                 *text_val = min(64, *text_val + *glyph_val);
6562                 glyph_val++;
6563                 text_val++;
6564             }
6565         }
6566     }
6567
6568     GdipFree(pti);
6569     DeleteDC(hdc);
6570     DeleteObject(hfont);
6571     GdipFree(glyph_mask);
6572
6573     /* get the brush data */
6574     pixel_data = GdipAlloc(4 * (max_x - min_x) * (max_y - min_y));
6575     if (!pixel_data)
6576     {
6577         GdipFree(text_mask);
6578         return OutOfMemory;
6579     }
6580
6581     pixel_area.X = min_x;
6582     pixel_area.Y = min_y;
6583     pixel_area.Width = max_x - min_x;
6584     pixel_area.Height = max_y - min_y;
6585     pixel_data_stride = pixel_area.Width * 4;
6586
6587     stat = brush_fill_pixels(graphics, (GpBrush*)brush, (DWORD*)pixel_data, &pixel_area, pixel_area.Width);
6588     if (stat != Ok)
6589     {
6590         GdipFree(text_mask);
6591         GdipFree(pixel_data);
6592         return stat;
6593     }
6594
6595     /* multiply the brush data by the mask */
6596     for (y=0; y<pixel_area.Height; y++)
6597     {
6598         BYTE *text_val = text_mask + text_mask_stride * y;
6599         BYTE *pixel_val = pixel_data + pixel_data_stride * y + 3;
6600         for (x=0; x<pixel_area.Width; x++)
6601         {
6602             *pixel_val = (*pixel_val) * (*text_val) / 64;
6603             text_val++;
6604             pixel_val+=4;
6605         }
6606     }
6607
6608     GdipFree(text_mask);
6609
6610     /* draw the result */
6611     stat = alpha_blend_pixels(graphics, min_x, min_y, pixel_data, pixel_area.Width,
6612         pixel_area.Height, pixel_data_stride);
6613
6614     GdipFree(pixel_data);
6615
6616     return stat;
6617 }
6618
6619 static GpStatus draw_driver_string(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6620                                    GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6621                                    GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6622                                    INT flags, GDIPCONST GpMatrix *matrix)
6623 {
6624     GpStatus stat = NotImplemented;
6625
6626     if (length == -1)
6627         length = strlenW(text);
6628
6629     if (graphics->hdc &&
6630         ((flags & DriverStringOptionsRealizedAdvance) || length <= 1) &&
6631         brush->bt == BrushTypeSolidColor &&
6632         (((GpSolidFill*)brush)->color & 0xff000000) == 0xff000000)
6633         stat = GDI32_GdipDrawDriverString(graphics, text, length, font, format,
6634                                           brush, positions, flags, matrix);
6635     if (stat == NotImplemented)
6636         stat = SOFTWARE_GdipDrawDriverString(graphics, text, length, font, format,
6637                                              brush, positions, flags, matrix);
6638     return stat;
6639 }
6640
6641 /*****************************************************************************
6642  * GdipDrawDriverString [GDIPLUS.@]
6643  */
6644 GpStatus WINGDIPAPI GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6645                                          GDIPCONST GpFont *font, GDIPCONST GpBrush *brush,
6646                                          GDIPCONST PointF *positions, INT flags,
6647                                          GDIPCONST GpMatrix *matrix )
6648 {
6649     TRACE("(%p %s %p %p %p %d %p)\n", graphics, debugstr_wn(text, length), font, brush, positions, flags, matrix);
6650
6651     if (!graphics || !text || !font || !brush || !positions)
6652         return InvalidParameter;
6653
6654     return draw_driver_string(graphics, text, length, font, NULL,
6655                               brush, positions, flags, matrix);
6656 }
6657
6658 GpStatus WINGDIPAPI GdipRecordMetafileStream(IStream *stream, HDC hdc, EmfType type, GDIPCONST GpRect *frameRect,
6659                                         MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc, GpMetafile **metafile)
6660 {
6661     FIXME("(%p %p %d %p %d %p %p): stub\n", stream, hdc, type, frameRect, frameUnit, desc, metafile);
6662     return NotImplemented;
6663 }
6664
6665 /*****************************************************************************
6666  * GdipIsVisibleClipEmpty [GDIPLUS.@]
6667  */
6668 GpStatus WINGDIPAPI GdipIsVisibleClipEmpty(GpGraphics *graphics, BOOL *res)
6669 {
6670     GpStatus stat;
6671     GpRegion* rgn;
6672
6673     TRACE("(%p, %p)\n", graphics, res);
6674
6675     if((stat = GdipCreateRegion(&rgn)) != Ok)
6676         return stat;
6677
6678     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
6679         goto cleanup;
6680
6681     stat = GdipIsEmptyRegion(rgn, graphics, res);
6682
6683 cleanup:
6684     GdipDeleteRegion(rgn);
6685     return stat;
6686 }
6687
6688 GpStatus WINGDIPAPI GdipResetPageTransform(GpGraphics *graphics)
6689 {
6690     static int calls;
6691
6692     TRACE("(%p) stub\n", graphics);
6693
6694     if(!(calls++))
6695         FIXME("not implemented\n");
6696
6697     return NotImplemented;
6698 }