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