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