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