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