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