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