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