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