mshtml: Properly report history update for location.replace call.
[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 = NULL;
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 || (GdipCreateMatrix(&matrix) != Ok))
1588                 goto custend;
1589
1590             memcpy(custptf, custom->pathdata.Points, count * sizeof(PointF));
1591
1592             GdipScaleMatrix(matrix, size, size, MatrixOrderAppend);
1593             GdipRotateMatrix(matrix, (180.0 / M_PI) * (theta - M_PI_2),
1594                              MatrixOrderAppend);
1595             GdipTranslateMatrix(matrix, x2, y2, MatrixOrderAppend);
1596             GdipTransformMatrixPoints(matrix, custptf, count);
1597
1598             transform_and_round_points(graphics, custpt, custptf, count);
1599
1600             for(i = 0; i < count; i++)
1601                 tp[i] = convert_path_point_type(custom->pathdata.Types[i]);
1602
1603             if(custom->fill){
1604                 BeginPath(graphics->hdc);
1605                 PolyDraw(graphics->hdc, custpt, tp, count);
1606                 EndPath(graphics->hdc);
1607                 StrokeAndFillPath(graphics->hdc);
1608             }
1609             else
1610                 PolyDraw(graphics->hdc, custpt, tp, count);
1611
1612 custend:
1613             GdipFree(custptf);
1614             GdipFree(custpt);
1615             GdipFree(tp);
1616             GdipDeleteMatrix(matrix);
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             stat = GdipCreateMatrix2(m11, m12, m21, m22, mdx, mdy, &dst_to_src);
3163             if (stat != Ok) return stat;
3164
3165             stat = GdipInvertMatrix(dst_to_src);
3166             if (stat != Ok)
3167             {
3168                 GdipDeleteMatrix(dst_to_src);
3169                 return stat;
3170             }
3171
3172             dst_data = GdipAlloc(sizeof(ARGB) * (dst_area.right - dst_area.left) * (dst_area.bottom - dst_area.top));
3173             if (!dst_data)
3174             {
3175                 GdipDeleteMatrix(dst_to_src);
3176                 return OutOfMemory;
3177             }
3178
3179             dst_stride = sizeof(ARGB) * (dst_area.right - dst_area.left);
3180
3181             get_bitmap_sample_size(interpolation, imageAttributes->wrap,
3182                 bitmap, srcx, srcy, srcwidth, srcheight, &src_area);
3183
3184             TRACE("src_area: %d x %d\n", src_area.Width, src_area.Height);
3185
3186             src_data = GdipAlloc(sizeof(ARGB) * src_area.Width * src_area.Height);
3187             if (!src_data)
3188             {
3189                 GdipFree(dst_data);
3190                 GdipDeleteMatrix(dst_to_src);
3191                 return OutOfMemory;
3192             }
3193             src_stride = sizeof(ARGB) * src_area.Width;
3194
3195             /* Read the bits we need from the source bitmap into an ARGB buffer. */
3196             lockeddata.Width = src_area.Width;
3197             lockeddata.Height = src_area.Height;
3198             lockeddata.Stride = src_stride;
3199             lockeddata.PixelFormat = PixelFormat32bppARGB;
3200             lockeddata.Scan0 = src_data;
3201
3202             stat = GdipBitmapLockBits(bitmap, &src_area, ImageLockModeRead|ImageLockModeUserInputBuf,
3203                 PixelFormat32bppARGB, &lockeddata);
3204
3205             if (stat == Ok)
3206                 stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
3207
3208             if (stat != Ok)
3209             {
3210                 if (src_data != dst_data)
3211                     GdipFree(src_data);
3212                 GdipFree(dst_data);
3213                 GdipDeleteMatrix(dst_to_src);
3214                 return stat;
3215             }
3216
3217             apply_image_attributes(imageAttributes, src_data,
3218                 src_area.Width, src_area.Height,
3219                 src_stride, ColorAdjustTypeBitmap);
3220
3221             /* Transform the bits as needed to the destination. */
3222             GdipTransformMatrixPoints(dst_to_src, dst_to_src_points, 3);
3223
3224             x_dx = dst_to_src_points[1].X - dst_to_src_points[0].X;
3225             x_dy = dst_to_src_points[1].Y - dst_to_src_points[0].Y;
3226             y_dx = dst_to_src_points[2].X - dst_to_src_points[0].X;
3227             y_dy = dst_to_src_points[2].Y - dst_to_src_points[0].Y;
3228
3229             for (x=dst_area.left; x<dst_area.right; x++)
3230             {
3231                 for (y=dst_area.top; y<dst_area.bottom; y++)
3232                 {
3233                     GpPointF src_pointf;
3234                     ARGB *dst_color;
3235
3236                     src_pointf.X = dst_to_src_points[0].X + x * x_dx + y * y_dx;
3237                     src_pointf.Y = dst_to_src_points[0].Y + x * x_dy + y * y_dy;
3238
3239                     dst_color = (ARGB*)(dst_data + dst_stride * (y - dst_area.top) + sizeof(ARGB) * (x - dst_area.left));
3240
3241                     if (src_pointf.X >= srcx && src_pointf.X < srcx + srcwidth && src_pointf.Y >= srcy && src_pointf.Y < srcy+srcheight)
3242                         *dst_color = resample_bitmap_pixel(&src_area, src_data, bitmap->width, bitmap->height, &src_pointf,
3243                                                            imageAttributes, interpolation, offset_mode);
3244                     else
3245                         *dst_color = 0;
3246                 }
3247             }
3248
3249             GdipDeleteMatrix(dst_to_src);
3250
3251             GdipFree(src_data);
3252
3253             stat = alpha_blend_pixels(graphics, dst_area.left, dst_area.top,
3254                 dst_data, dst_area.right - dst_area.left, dst_area.bottom - dst_area.top, dst_stride);
3255
3256             GdipFree(dst_data);
3257
3258             return stat;
3259         }
3260         else
3261         {
3262             HDC hdc;
3263             int temp_hdc=0, temp_bitmap=0;
3264             HBITMAP hbitmap, old_hbm=NULL;
3265
3266             if (!(bitmap->format == PixelFormat16bppRGB555 ||
3267                   bitmap->format == PixelFormat24bppRGB ||
3268                   bitmap->format == PixelFormat32bppRGB ||
3269                   bitmap->format == PixelFormat32bppPARGB))
3270             {
3271                 BITMAPINFOHEADER bih;
3272                 BYTE *temp_bits;
3273                 PixelFormat dst_format;
3274
3275                 /* we can't draw a bitmap of this format directly */
3276                 hdc = CreateCompatibleDC(0);
3277                 temp_hdc = 1;
3278                 temp_bitmap = 1;
3279
3280                 bih.biSize = sizeof(BITMAPINFOHEADER);
3281                 bih.biWidth = bitmap->width;
3282                 bih.biHeight = -bitmap->height;
3283                 bih.biPlanes = 1;
3284                 bih.biBitCount = 32;
3285                 bih.biCompression = BI_RGB;
3286                 bih.biSizeImage = 0;
3287                 bih.biXPelsPerMeter = 0;
3288                 bih.biYPelsPerMeter = 0;
3289                 bih.biClrUsed = 0;
3290                 bih.biClrImportant = 0;
3291
3292                 hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bih, DIB_RGB_COLORS,
3293                     (void**)&temp_bits, NULL, 0);
3294
3295                 if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3296                     dst_format = PixelFormat32bppPARGB;
3297                 else
3298                     dst_format = PixelFormat32bppRGB;
3299
3300                 convert_pixels(bitmap->width, bitmap->height,
3301                     bitmap->width*4, temp_bits, dst_format,
3302                     bitmap->stride, bitmap->bits, bitmap->format,
3303                     bitmap->image.palette);
3304             }
3305             else
3306             {
3307                 if (bitmap->hbitmap)
3308                     hbitmap = bitmap->hbitmap;
3309                 else
3310                 {
3311                     GdipCreateHBITMAPFromBitmap(bitmap, &hbitmap, 0);
3312                     temp_bitmap = 1;
3313                 }
3314
3315                 hdc = bitmap->hdc;
3316                 temp_hdc = (hdc == 0);
3317             }
3318
3319             if (temp_hdc)
3320             {
3321                 if (!hdc) hdc = CreateCompatibleDC(0);
3322                 old_hbm = SelectObject(hdc, hbitmap);
3323             }
3324
3325             if (bitmap->format & (PixelFormatAlpha|PixelFormatPAlpha))
3326             {
3327                 gdi_alpha_blend(graphics, pti[0].x, pti[0].y, pti[1].x - pti[0].x, pti[2].y - pti[0].y,
3328                                 hdc, srcx, srcy, srcwidth, srcheight);
3329             }
3330             else
3331             {
3332                 StretchBlt(graphics->hdc, pti[0].x, pti[0].y, pti[1].x-pti[0].x, pti[2].y-pti[0].y,
3333                     hdc, srcx, srcy, srcwidth, srcheight, SRCCOPY);
3334             }
3335
3336             if (temp_hdc)
3337             {
3338                 SelectObject(hdc, old_hbm);
3339                 DeleteDC(hdc);
3340             }
3341
3342             if (temp_bitmap)
3343                 DeleteObject(hbitmap);
3344         }
3345     }
3346     else if (image->type == ImageTypeMetafile && ((GpMetafile*)image)->hemf)
3347     {
3348         GpRectF rc;
3349
3350         rc.X = srcx;
3351         rc.Y = srcy;
3352         rc.Width = srcwidth;
3353         rc.Height = srcheight;
3354
3355         return GdipEnumerateMetafileSrcRectDestPoints(graphics, (GpMetafile*)image,
3356             points, count, &rc, srcUnit, play_metafile_proc, image, imageAttributes);
3357     }
3358     else
3359     {
3360         WARN("GpImage with nothing we can draw (metafile in wrong state?)\n");
3361         return InvalidParameter;
3362     }
3363
3364     return Ok;
3365 }
3366
3367 GpStatus WINGDIPAPI GdipDrawImagePointsRectI(GpGraphics *graphics, GpImage *image,
3368      GDIPCONST GpPoint *points, INT count, INT srcx, INT srcy, INT srcwidth,
3369      INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes,
3370      DrawImageAbort callback, VOID * callbackData)
3371 {
3372     GpPointF pointsF[3];
3373     INT i;
3374
3375     TRACE("(%p, %p, %p, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n", graphics, image, points, count,
3376           srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback,
3377           callbackData);
3378
3379     if(!points || count!=3)
3380         return InvalidParameter;
3381
3382     for(i = 0; i < count; i++){
3383         pointsF[i].X = (REAL)points[i].X;
3384         pointsF[i].Y = (REAL)points[i].Y;
3385     }
3386
3387     return GdipDrawImagePointsRect(graphics, image, pointsF, count, (REAL)srcx, (REAL)srcy,
3388                                    (REAL)srcwidth, (REAL)srcheight, srcUnit, imageAttributes,
3389                                    callback, callbackData);
3390 }
3391
3392 GpStatus WINGDIPAPI GdipDrawImageRectRect(GpGraphics *graphics, GpImage *image,
3393     REAL dstx, REAL dsty, REAL dstwidth, REAL dstheight, REAL srcx, REAL srcy,
3394     REAL srcwidth, REAL srcheight, GpUnit srcUnit,
3395     GDIPCONST GpImageAttributes* imageattr, DrawImageAbort callback,
3396     VOID * callbackData)
3397 {
3398     GpPointF points[3];
3399
3400     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %d, %p, %p, %p)\n",
3401           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3402           srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3403
3404     points[0].X = dstx;
3405     points[0].Y = dsty;
3406     points[1].X = dstx + dstwidth;
3407     points[1].Y = dsty;
3408     points[2].X = dstx;
3409     points[2].Y = dsty + dstheight;
3410
3411     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3412                srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
3413 }
3414
3415 GpStatus WINGDIPAPI GdipDrawImageRectRectI(GpGraphics *graphics, GpImage *image,
3416         INT dstx, INT dsty, INT dstwidth, INT dstheight, INT srcx, INT srcy,
3417         INT srcwidth, INT srcheight, GpUnit srcUnit,
3418         GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback,
3419         VOID * callbackData)
3420 {
3421     GpPointF points[3];
3422
3423     TRACE("(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d, %d, %p, %p, %p)\n",
3424           graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy,
3425           srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3426
3427     points[0].X = dstx;
3428     points[0].Y = dsty;
3429     points[1].X = dstx + dstwidth;
3430     points[1].Y = dsty;
3431     points[2].X = dstx;
3432     points[2].Y = dsty + dstheight;
3433
3434     return GdipDrawImagePointsRect(graphics, image, points, 3, srcx, srcy,
3435                srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData);
3436 }
3437
3438 GpStatus WINGDIPAPI GdipDrawImageRect(GpGraphics *graphics, GpImage *image,
3439     REAL x, REAL y, REAL width, REAL height)
3440 {
3441     RectF bounds;
3442     GpUnit unit;
3443     GpStatus ret;
3444
3445     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, image, x, y, width, height);
3446
3447     if(!graphics || !image)
3448         return InvalidParameter;
3449
3450     ret = GdipGetImageBounds(image, &bounds, &unit);
3451     if(ret != Ok)
3452         return ret;
3453
3454     return GdipDrawImageRectRect(graphics, image, x, y, width, height,
3455                                  bounds.X, bounds.Y, bounds.Width, bounds.Height,
3456                                  unit, NULL, NULL, NULL);
3457 }
3458
3459 GpStatus WINGDIPAPI GdipDrawImageRectI(GpGraphics *graphics, GpImage *image,
3460     INT x, INT y, INT width, INT height)
3461 {
3462     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, image, x, y, width, height);
3463
3464     return GdipDrawImageRect(graphics, image, (REAL)x, (REAL)y, (REAL)width, (REAL)height);
3465 }
3466
3467 GpStatus WINGDIPAPI GdipDrawLine(GpGraphics *graphics, GpPen *pen, REAL x1,
3468     REAL y1, REAL x2, REAL y2)
3469 {
3470     INT save_state;
3471     GpPointF pt[2];
3472     GpStatus retval;
3473
3474     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x1, y1, x2, y2);
3475
3476     if(!pen || !graphics)
3477         return InvalidParameter;
3478
3479     if(graphics->busy)
3480         return ObjectBusy;
3481
3482     if (!graphics->hdc)
3483     {
3484         FIXME("graphics object has no HDC\n");
3485         return Ok;
3486     }
3487
3488     pt[0].X = x1;
3489     pt[0].Y = y1;
3490     pt[1].X = x2;
3491     pt[1].Y = y2;
3492
3493     save_state = prepare_dc(graphics, pen);
3494
3495     retval = draw_polyline(graphics, pen, pt, 2, TRUE);
3496
3497     restore_dc(graphics, save_state);
3498
3499     return retval;
3500 }
3501
3502 GpStatus WINGDIPAPI GdipDrawLineI(GpGraphics *graphics, GpPen *pen, INT x1,
3503     INT y1, INT x2, INT y2)
3504 {
3505     INT save_state;
3506     GpPointF pt[2];
3507     GpStatus retval;
3508
3509     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x1, y1, x2, y2);
3510
3511     if(!pen || !graphics)
3512         return InvalidParameter;
3513
3514     if(graphics->busy)
3515         return ObjectBusy;
3516
3517     if (!graphics->hdc)
3518     {
3519         FIXME("graphics object has no HDC\n");
3520         return Ok;
3521     }
3522
3523     pt[0].X = (REAL)x1;
3524     pt[0].Y = (REAL)y1;
3525     pt[1].X = (REAL)x2;
3526     pt[1].Y = (REAL)y2;
3527
3528     save_state = prepare_dc(graphics, pen);
3529
3530     retval = draw_polyline(graphics, pen, pt, 2, TRUE);
3531
3532     restore_dc(graphics, save_state);
3533
3534     return retval;
3535 }
3536
3537 GpStatus WINGDIPAPI GdipDrawLines(GpGraphics *graphics, GpPen *pen, GDIPCONST
3538     GpPointF *points, INT count)
3539 {
3540     INT save_state;
3541     GpStatus retval;
3542
3543     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3544
3545     if(!pen || !graphics || (count < 2))
3546         return InvalidParameter;
3547
3548     if(graphics->busy)
3549         return ObjectBusy;
3550
3551     if (!graphics->hdc)
3552     {
3553         FIXME("graphics object has no HDC\n");
3554         return Ok;
3555     }
3556
3557     save_state = prepare_dc(graphics, pen);
3558
3559     retval = draw_polyline(graphics, pen, points, count, TRUE);
3560
3561     restore_dc(graphics, save_state);
3562
3563     return retval;
3564 }
3565
3566 GpStatus WINGDIPAPI GdipDrawLinesI(GpGraphics *graphics, GpPen *pen, GDIPCONST
3567     GpPoint *points, INT count)
3568 {
3569     INT save_state;
3570     GpStatus retval;
3571     GpPointF *ptf = NULL;
3572     int i;
3573
3574     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
3575
3576     if(!pen || !graphics || (count < 2))
3577         return InvalidParameter;
3578
3579     if(graphics->busy)
3580         return ObjectBusy;
3581
3582     if (!graphics->hdc)
3583     {
3584         FIXME("graphics object has no HDC\n");
3585         return Ok;
3586     }
3587
3588     ptf = GdipAlloc(count * sizeof(GpPointF));
3589     if(!ptf) return OutOfMemory;
3590
3591     for(i = 0; i < count; i ++){
3592         ptf[i].X = (REAL) points[i].X;
3593         ptf[i].Y = (REAL) points[i].Y;
3594     }
3595
3596     save_state = prepare_dc(graphics, pen);
3597
3598     retval = draw_polyline(graphics, pen, ptf, count, TRUE);
3599
3600     restore_dc(graphics, save_state);
3601
3602     GdipFree(ptf);
3603     return retval;
3604 }
3605
3606 GpStatus WINGDIPAPI GdipDrawPath(GpGraphics *graphics, GpPen *pen, GpPath *path)
3607 {
3608     INT save_state;
3609     GpStatus retval;
3610
3611     TRACE("(%p, %p, %p)\n", graphics, pen, path);
3612
3613     if(!pen || !graphics)
3614         return InvalidParameter;
3615
3616     if(graphics->busy)
3617         return ObjectBusy;
3618
3619     if (!graphics->hdc)
3620     {
3621         FIXME("graphics object has no HDC\n");
3622         return Ok;
3623     }
3624
3625     save_state = prepare_dc(graphics, pen);
3626
3627     retval = draw_poly(graphics, pen, path->pathdata.Points,
3628                        path->pathdata.Types, path->pathdata.Count, TRUE);
3629
3630     restore_dc(graphics, save_state);
3631
3632     return retval;
3633 }
3634
3635 GpStatus WINGDIPAPI GdipDrawPie(GpGraphics *graphics, GpPen *pen, REAL x,
3636     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
3637 {
3638     INT save_state;
3639
3640     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y,
3641             width, height, startAngle, sweepAngle);
3642
3643     if(!graphics || !pen)
3644         return InvalidParameter;
3645
3646     if(graphics->busy)
3647         return ObjectBusy;
3648
3649     if (!graphics->hdc)
3650     {
3651         FIXME("graphics object has no HDC\n");
3652         return Ok;
3653     }
3654
3655     save_state = prepare_dc(graphics, pen);
3656     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3657
3658     draw_pie(graphics, x, y, width, height, startAngle, sweepAngle);
3659
3660     restore_dc(graphics, save_state);
3661
3662     return Ok;
3663 }
3664
3665 GpStatus WINGDIPAPI GdipDrawPieI(GpGraphics *graphics, GpPen *pen, INT x,
3666     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
3667 {
3668     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n", graphics, pen, x, y,
3669             width, height, startAngle, sweepAngle);
3670
3671     return GdipDrawPie(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
3672 }
3673
3674 GpStatus WINGDIPAPI GdipDrawRectangle(GpGraphics *graphics, GpPen *pen, REAL x,
3675     REAL y, REAL width, REAL height)
3676 {
3677     INT save_state;
3678     GpPointF ptf[4];
3679     POINT pti[4];
3680
3681     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, pen, x, y, width, height);
3682
3683     if(!pen || !graphics)
3684         return InvalidParameter;
3685
3686     if(graphics->busy)
3687         return ObjectBusy;
3688
3689     if (!graphics->hdc)
3690     {
3691         FIXME("graphics object has no HDC\n");
3692         return Ok;
3693     }
3694
3695     ptf[0].X = x;
3696     ptf[0].Y = y;
3697     ptf[1].X = x + width;
3698     ptf[1].Y = y;
3699     ptf[2].X = x + width;
3700     ptf[2].Y = y + height;
3701     ptf[3].X = x;
3702     ptf[3].Y = y + height;
3703
3704     save_state = prepare_dc(graphics, pen);
3705     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3706
3707     transform_and_round_points(graphics, pti, ptf, 4);
3708     Polygon(graphics->hdc, pti, 4);
3709
3710     restore_dc(graphics, save_state);
3711
3712     return Ok;
3713 }
3714
3715 GpStatus WINGDIPAPI GdipDrawRectangleI(GpGraphics *graphics, GpPen *pen, INT x,
3716     INT y, INT width, INT height)
3717 {
3718     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, pen, x, y, width, height);
3719
3720     return GdipDrawRectangle(graphics,pen,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3721 }
3722
3723 GpStatus WINGDIPAPI GdipDrawRectangles(GpGraphics *graphics, GpPen *pen,
3724     GDIPCONST GpRectF* rects, INT count)
3725 {
3726     GpPointF *ptf;
3727     POINT *pti;
3728     INT save_state, i;
3729
3730     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3731
3732     if(!graphics || !pen || !rects || count < 1)
3733         return InvalidParameter;
3734
3735     if(graphics->busy)
3736         return ObjectBusy;
3737
3738     if (!graphics->hdc)
3739     {
3740         FIXME("graphics object has no HDC\n");
3741         return Ok;
3742     }
3743
3744     ptf = GdipAlloc(4 * count * sizeof(GpPointF));
3745     pti = GdipAlloc(4 * count * sizeof(POINT));
3746
3747     if(!ptf || !pti){
3748         GdipFree(ptf);
3749         GdipFree(pti);
3750         return OutOfMemory;
3751     }
3752
3753     for(i = 0; i < count; i++){
3754         ptf[4 * i + 3].X = ptf[4 * i].X = rects[i].X;
3755         ptf[4 * i + 1].Y = ptf[4 * i].Y = rects[i].Y;
3756         ptf[4 * i + 2].X = ptf[4 * i + 1].X = rects[i].X + rects[i].Width;
3757         ptf[4 * i + 3].Y = ptf[4 * i + 2].Y = rects[i].Y + rects[i].Height;
3758     }
3759
3760     save_state = prepare_dc(graphics, pen);
3761     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
3762
3763     transform_and_round_points(graphics, pti, ptf, 4 * count);
3764
3765     for(i = 0; i < count; i++)
3766         Polygon(graphics->hdc, &pti[4 * i], 4);
3767
3768     restore_dc(graphics, save_state);
3769
3770     GdipFree(ptf);
3771     GdipFree(pti);
3772
3773     return Ok;
3774 }
3775
3776 GpStatus WINGDIPAPI GdipDrawRectanglesI(GpGraphics *graphics, GpPen *pen,
3777     GDIPCONST GpRect* rects, INT count)
3778 {
3779     GpRectF *rectsF;
3780     GpStatus ret;
3781     INT i;
3782
3783     TRACE("(%p, %p, %p, %d)\n", graphics, pen, rects, count);
3784
3785     if(!rects || count<=0)
3786         return InvalidParameter;
3787
3788     rectsF = GdipAlloc(sizeof(GpRectF) * count);
3789     if(!rectsF)
3790         return OutOfMemory;
3791
3792     for(i = 0;i < count;i++){
3793         rectsF[i].X      = (REAL)rects[i].X;
3794         rectsF[i].Y      = (REAL)rects[i].Y;
3795         rectsF[i].Width  = (REAL)rects[i].Width;
3796         rectsF[i].Height = (REAL)rects[i].Height;
3797     }
3798
3799     ret = GdipDrawRectangles(graphics, pen, rectsF, count);
3800     GdipFree(rectsF);
3801
3802     return ret;
3803 }
3804
3805 GpStatus WINGDIPAPI GdipFillClosedCurve2(GpGraphics *graphics, GpBrush *brush,
3806     GDIPCONST GpPointF *points, INT count, REAL tension, GpFillMode fill)
3807 {
3808     GpPath *path;
3809     GpStatus stat;
3810
3811     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3812             count, tension, fill);
3813
3814     if(!graphics || !brush || !points)
3815         return InvalidParameter;
3816
3817     if(graphics->busy)
3818         return ObjectBusy;
3819
3820     if(count == 1)    /* Do nothing */
3821         return Ok;
3822
3823     stat = GdipCreatePath(fill, &path);
3824     if(stat != Ok)
3825         return stat;
3826
3827     stat = GdipAddPathClosedCurve2(path, points, count, tension);
3828     if(stat != Ok){
3829         GdipDeletePath(path);
3830         return stat;
3831     }
3832
3833     stat = GdipFillPath(graphics, brush, path);
3834     if(stat != Ok){
3835         GdipDeletePath(path);
3836         return stat;
3837     }
3838
3839     GdipDeletePath(path);
3840
3841     return Ok;
3842 }
3843
3844 GpStatus WINGDIPAPI GdipFillClosedCurve2I(GpGraphics *graphics, GpBrush *brush,
3845     GDIPCONST GpPoint *points, INT count, REAL tension, GpFillMode fill)
3846 {
3847     GpPointF *ptf;
3848     GpStatus stat;
3849     INT i;
3850
3851     TRACE("(%p, %p, %p, %d, %.2f, %d)\n", graphics, brush, points,
3852             count, tension, fill);
3853
3854     if(!points || count == 0)
3855         return InvalidParameter;
3856
3857     if(count == 1)    /* Do nothing */
3858         return Ok;
3859
3860     ptf = GdipAlloc(sizeof(GpPointF)*count);
3861     if(!ptf)
3862         return OutOfMemory;
3863
3864     for(i = 0;i < count;i++){
3865         ptf[i].X = (REAL)points[i].X;
3866         ptf[i].Y = (REAL)points[i].Y;
3867     }
3868
3869     stat = GdipFillClosedCurve2(graphics, brush, ptf, count, tension, fill);
3870
3871     GdipFree(ptf);
3872
3873     return stat;
3874 }
3875
3876 GpStatus WINGDIPAPI GdipFillClosedCurve(GpGraphics *graphics, GpBrush *brush,
3877     GDIPCONST GpPointF *points, INT count)
3878 {
3879     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3880     return GdipFillClosedCurve2(graphics, brush, points, count,
3881                0.5f, FillModeAlternate);
3882 }
3883
3884 GpStatus WINGDIPAPI GdipFillClosedCurveI(GpGraphics *graphics, GpBrush *brush,
3885     GDIPCONST GpPoint *points, INT count)
3886 {
3887     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
3888     return GdipFillClosedCurve2I(graphics, brush, points, count,
3889                0.5f, FillModeAlternate);
3890 }
3891
3892 GpStatus WINGDIPAPI GdipFillEllipse(GpGraphics *graphics, GpBrush *brush, REAL x,
3893     REAL y, REAL width, REAL height)
3894 {
3895     GpStatus stat;
3896     GpPath *path;
3897
3898     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
3899
3900     if(!graphics || !brush)
3901         return InvalidParameter;
3902
3903     if(graphics->busy)
3904         return ObjectBusy;
3905
3906     stat = GdipCreatePath(FillModeAlternate, &path);
3907
3908     if (stat == Ok)
3909     {
3910         stat = GdipAddPathEllipse(path, x, y, width, height);
3911
3912         if (stat == Ok)
3913             stat = GdipFillPath(graphics, brush, path);
3914
3915         GdipDeletePath(path);
3916     }
3917
3918     return stat;
3919 }
3920
3921 GpStatus WINGDIPAPI GdipFillEllipseI(GpGraphics *graphics, GpBrush *brush, INT x,
3922     INT y, INT width, INT height)
3923 {
3924     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
3925
3926     return GdipFillEllipse(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height);
3927 }
3928
3929 static GpStatus GDI32_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3930 {
3931     INT save_state;
3932     GpStatus retval;
3933
3934     if(!graphics->hdc || !brush_can_fill_path(brush))
3935         return NotImplemented;
3936
3937     save_state = SaveDC(graphics->hdc);
3938     EndPath(graphics->hdc);
3939     SetPolyFillMode(graphics->hdc, (path->fill == FillModeAlternate ? ALTERNATE
3940                                                                     : WINDING));
3941
3942     BeginPath(graphics->hdc);
3943     retval = draw_poly(graphics, NULL, path->pathdata.Points,
3944                        path->pathdata.Types, path->pathdata.Count, FALSE);
3945
3946     if(retval != Ok)
3947         goto end;
3948
3949     EndPath(graphics->hdc);
3950     brush_fill_path(graphics, brush);
3951
3952     retval = Ok;
3953
3954 end:
3955     RestoreDC(graphics->hdc, save_state);
3956
3957     return retval;
3958 }
3959
3960 static GpStatus SOFTWARE_GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3961 {
3962     GpStatus stat;
3963     GpRegion *rgn;
3964
3965     if (!brush_can_fill_pixels(brush))
3966         return NotImplemented;
3967
3968     /* FIXME: This could probably be done more efficiently without regions. */
3969
3970     stat = GdipCreateRegionPath(path, &rgn);
3971
3972     if (stat == Ok)
3973     {
3974         stat = GdipFillRegion(graphics, brush, rgn);
3975
3976         GdipDeleteRegion(rgn);
3977     }
3978
3979     return stat;
3980 }
3981
3982 GpStatus WINGDIPAPI GdipFillPath(GpGraphics *graphics, GpBrush *brush, GpPath *path)
3983 {
3984     GpStatus stat = NotImplemented;
3985
3986     TRACE("(%p, %p, %p)\n", graphics, brush, path);
3987
3988     if(!brush || !graphics || !path)
3989         return InvalidParameter;
3990
3991     if(graphics->busy)
3992         return ObjectBusy;
3993
3994     if (!graphics->image)
3995         stat = GDI32_GdipFillPath(graphics, brush, path);
3996
3997     if (stat == NotImplemented)
3998         stat = SOFTWARE_GdipFillPath(graphics, brush, path);
3999
4000     if (stat == NotImplemented)
4001     {
4002         FIXME("Not implemented for brushtype %i\n", brush->bt);
4003         stat = Ok;
4004     }
4005
4006     return stat;
4007 }
4008
4009 GpStatus WINGDIPAPI GdipFillPie(GpGraphics *graphics, GpBrush *brush, REAL x,
4010     REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
4011 {
4012     GpStatus stat;
4013     GpPath *path;
4014
4015     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f)\n",
4016             graphics, brush, x, y, width, height, startAngle, sweepAngle);
4017
4018     if(!graphics || !brush)
4019         return InvalidParameter;
4020
4021     if(graphics->busy)
4022         return ObjectBusy;
4023
4024     stat = GdipCreatePath(FillModeAlternate, &path);
4025
4026     if (stat == Ok)
4027     {
4028         stat = GdipAddPathPie(path, x, y, width, height, startAngle, sweepAngle);
4029
4030         if (stat == Ok)
4031             stat = GdipFillPath(graphics, brush, path);
4032
4033         GdipDeletePath(path);
4034     }
4035
4036     return stat;
4037 }
4038
4039 GpStatus WINGDIPAPI GdipFillPieI(GpGraphics *graphics, GpBrush *brush, INT x,
4040     INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
4041 {
4042     TRACE("(%p, %p, %d, %d, %d, %d, %.2f, %.2f)\n",
4043             graphics, brush, x, y, width, height, startAngle, sweepAngle);
4044
4045     return GdipFillPie(graphics,brush,(REAL)x,(REAL)y,(REAL)width,(REAL)height,startAngle,sweepAngle);
4046 }
4047
4048 GpStatus WINGDIPAPI GdipFillPolygon(GpGraphics *graphics, GpBrush *brush,
4049     GDIPCONST GpPointF *points, INT count, GpFillMode fillMode)
4050 {
4051     GpStatus stat;
4052     GpPath *path;
4053
4054     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
4055
4056     if(!graphics || !brush || !points || !count)
4057         return InvalidParameter;
4058
4059     if(graphics->busy)
4060         return ObjectBusy;
4061
4062     stat = GdipCreatePath(fillMode, &path);
4063
4064     if (stat == Ok)
4065     {
4066         stat = GdipAddPathPolygon(path, points, count);
4067
4068         if (stat == Ok)
4069             stat = GdipFillPath(graphics, brush, path);
4070
4071         GdipDeletePath(path);
4072     }
4073
4074     return stat;
4075 }
4076
4077 GpStatus WINGDIPAPI GdipFillPolygonI(GpGraphics *graphics, GpBrush *brush,
4078     GDIPCONST GpPoint *points, INT count, GpFillMode fillMode)
4079 {
4080     GpStatus stat;
4081     GpPath *path;
4082
4083     TRACE("(%p, %p, %p, %d, %d)\n", graphics, brush, points, count, fillMode);
4084
4085     if(!graphics || !brush || !points || !count)
4086         return InvalidParameter;
4087
4088     if(graphics->busy)
4089         return ObjectBusy;
4090
4091     stat = GdipCreatePath(fillMode, &path);
4092
4093     if (stat == Ok)
4094     {
4095         stat = GdipAddPathPolygonI(path, points, count);
4096
4097         if (stat == Ok)
4098             stat = GdipFillPath(graphics, brush, path);
4099
4100         GdipDeletePath(path);
4101     }
4102
4103     return stat;
4104 }
4105
4106 GpStatus WINGDIPAPI GdipFillPolygon2(GpGraphics *graphics, GpBrush *brush,
4107     GDIPCONST GpPointF *points, INT count)
4108 {
4109     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
4110
4111     return GdipFillPolygon(graphics, brush, points, count, FillModeAlternate);
4112 }
4113
4114 GpStatus WINGDIPAPI GdipFillPolygon2I(GpGraphics *graphics, GpBrush *brush,
4115     GDIPCONST GpPoint *points, INT count)
4116 {
4117     TRACE("(%p, %p, %p, %d)\n", graphics, brush, points, count);
4118
4119     return GdipFillPolygonI(graphics, brush, points, count, FillModeAlternate);
4120 }
4121
4122 GpStatus WINGDIPAPI GdipFillRectangle(GpGraphics *graphics, GpBrush *brush,
4123     REAL x, REAL y, REAL width, REAL height)
4124 {
4125     GpStatus stat;
4126     GpPath *path;
4127
4128     TRACE("(%p, %p, %.2f, %.2f, %.2f, %.2f)\n", graphics, brush, x, y, width, height);
4129
4130     if(!graphics || !brush)
4131         return InvalidParameter;
4132
4133     if(graphics->busy)
4134         return ObjectBusy;
4135
4136     stat = GdipCreatePath(FillModeAlternate, &path);
4137
4138     if (stat == Ok)
4139     {
4140         stat = GdipAddPathRectangle(path, x, y, width, height);
4141
4142         if (stat == Ok)
4143             stat = GdipFillPath(graphics, brush, path);
4144
4145         GdipDeletePath(path);
4146     }
4147
4148     return stat;
4149 }
4150
4151 GpStatus WINGDIPAPI GdipFillRectangleI(GpGraphics *graphics, GpBrush *brush,
4152     INT x, INT y, INT width, INT height)
4153 {
4154     TRACE("(%p, %p, %d, %d, %d, %d)\n", graphics, brush, x, y, width, height);
4155
4156     return GdipFillRectangle(graphics, brush, x, y, width, height);
4157 }
4158
4159 GpStatus WINGDIPAPI GdipFillRectangles(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRectF *rects,
4160     INT count)
4161 {
4162     GpStatus ret;
4163     INT i;
4164
4165     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
4166
4167     if(!rects)
4168         return InvalidParameter;
4169
4170     for(i = 0; i < count; i++){
4171         ret = GdipFillRectangle(graphics, brush, rects[i].X, rects[i].Y, rects[i].Width, rects[i].Height);
4172         if(ret != Ok)   return ret;
4173     }
4174
4175     return Ok;
4176 }
4177
4178 GpStatus WINGDIPAPI GdipFillRectanglesI(GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRect *rects,
4179     INT count)
4180 {
4181     GpRectF *rectsF;
4182     GpStatus ret;
4183     INT i;
4184
4185     TRACE("(%p, %p, %p, %d)\n", graphics, brush, rects, count);
4186
4187     if(!rects || count <= 0)
4188         return InvalidParameter;
4189
4190     rectsF = GdipAlloc(sizeof(GpRectF)*count);
4191     if(!rectsF)
4192         return OutOfMemory;
4193
4194     for(i = 0; i < count; i++){
4195         rectsF[i].X      = (REAL)rects[i].X;
4196         rectsF[i].Y      = (REAL)rects[i].Y;
4197         rectsF[i].X      = (REAL)rects[i].Width;
4198         rectsF[i].Height = (REAL)rects[i].Height;
4199     }
4200
4201     ret = GdipFillRectangles(graphics,brush,rectsF,count);
4202     GdipFree(rectsF);
4203
4204     return ret;
4205 }
4206
4207 static GpStatus GDI32_GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
4208     GpRegion* region)
4209 {
4210     INT save_state;
4211     GpStatus status;
4212     HRGN hrgn;
4213     RECT rc;
4214
4215     if(!graphics->hdc || !brush_can_fill_path(brush))
4216         return NotImplemented;
4217
4218     status = GdipGetRegionHRgn(region, graphics, &hrgn);
4219     if(status != Ok)
4220         return status;
4221
4222     save_state = SaveDC(graphics->hdc);
4223     EndPath(graphics->hdc);
4224
4225     ExtSelectClipRgn(graphics->hdc, hrgn, RGN_AND);
4226
4227     if (GetClipBox(graphics->hdc, &rc) != NULLREGION)
4228     {
4229         BeginPath(graphics->hdc);
4230         Rectangle(graphics->hdc, rc.left, rc.top, rc.right, rc.bottom);
4231         EndPath(graphics->hdc);
4232
4233         brush_fill_path(graphics, brush);
4234     }
4235
4236     RestoreDC(graphics->hdc, save_state);
4237
4238     DeleteObject(hrgn);
4239
4240     return Ok;
4241 }
4242
4243 static GpStatus SOFTWARE_GdipFillRegion(GpGraphics *graphics, GpBrush *brush,
4244     GpRegion* region)
4245 {
4246     GpStatus stat;
4247     GpRegion *temp_region;
4248     GpMatrix world_to_device;
4249     GpRectF graphics_bounds;
4250     DWORD *pixel_data;
4251     HRGN hregion;
4252     RECT bound_rect;
4253     GpRect gp_bound_rect;
4254
4255     if (!brush_can_fill_pixels(brush))
4256         return NotImplemented;
4257
4258     stat = get_graphics_bounds(graphics, &graphics_bounds);
4259
4260     if (stat == Ok)
4261         stat = GdipCloneRegion(region, &temp_region);
4262
4263     if (stat == Ok)
4264     {
4265         stat = get_graphics_transform(graphics, CoordinateSpaceDevice,
4266             CoordinateSpaceWorld, &world_to_device);
4267
4268         if (stat == Ok)
4269             stat = GdipTransformRegion(temp_region, &world_to_device);
4270
4271         if (stat == Ok)
4272             stat = GdipCombineRegionRect(temp_region, &graphics_bounds, CombineModeIntersect);
4273
4274         if (stat == Ok)
4275             stat = GdipGetRegionHRgn(temp_region, NULL, &hregion);
4276
4277         GdipDeleteRegion(temp_region);
4278     }
4279
4280     if (stat == Ok && GetRgnBox(hregion, &bound_rect) == NULLREGION)
4281     {
4282         DeleteObject(hregion);
4283         return Ok;
4284     }
4285
4286     if (stat == Ok)
4287     {
4288         gp_bound_rect.X = bound_rect.left;
4289         gp_bound_rect.Y = bound_rect.top;
4290         gp_bound_rect.Width = bound_rect.right - bound_rect.left;
4291         gp_bound_rect.Height = bound_rect.bottom - bound_rect.top;
4292
4293         pixel_data = GdipAlloc(sizeof(*pixel_data) * gp_bound_rect.Width * gp_bound_rect.Height);
4294         if (!pixel_data)
4295             stat = OutOfMemory;
4296
4297         if (stat == Ok)
4298         {
4299             stat = brush_fill_pixels(graphics, brush, pixel_data,
4300                 &gp_bound_rect, gp_bound_rect.Width);
4301
4302             if (stat == Ok)
4303                 stat = alpha_blend_pixels_hrgn(graphics, gp_bound_rect.X,
4304                     gp_bound_rect.Y, (BYTE*)pixel_data, gp_bound_rect.Width,
4305                     gp_bound_rect.Height, gp_bound_rect.Width * 4, hregion);
4306
4307             GdipFree(pixel_data);
4308         }
4309
4310         DeleteObject(hregion);
4311     }
4312
4313     return stat;
4314 }
4315
4316 /*****************************************************************************
4317  * GdipFillRegion [GDIPLUS.@]
4318  */
4319 GpStatus WINGDIPAPI GdipFillRegion(GpGraphics* graphics, GpBrush* brush,
4320         GpRegion* region)
4321 {
4322     GpStatus stat = NotImplemented;
4323
4324     TRACE("(%p, %p, %p)\n", graphics, brush, region);
4325
4326     if (!(graphics && brush && region))
4327         return InvalidParameter;
4328
4329     if(graphics->busy)
4330         return ObjectBusy;
4331
4332     if (!graphics->image)
4333         stat = GDI32_GdipFillRegion(graphics, brush, region);
4334
4335     if (stat == NotImplemented)
4336         stat = SOFTWARE_GdipFillRegion(graphics, brush, region);
4337
4338     if (stat == NotImplemented)
4339     {
4340         FIXME("not implemented for brushtype %i\n", brush->bt);
4341         stat = Ok;
4342     }
4343
4344     return stat;
4345 }
4346
4347 GpStatus WINGDIPAPI GdipFlush(GpGraphics *graphics, GpFlushIntention intention)
4348 {
4349     TRACE("(%p,%u)\n", graphics, intention);
4350
4351     if(!graphics)
4352         return InvalidParameter;
4353
4354     if(graphics->busy)
4355         return ObjectBusy;
4356
4357     /* We have no internal operation queue, so there's no need to clear it. */
4358
4359     if (graphics->hdc)
4360         GdiFlush();
4361
4362     return Ok;
4363 }
4364
4365 /*****************************************************************************
4366  * GdipGetClipBounds [GDIPLUS.@]
4367  */
4368 GpStatus WINGDIPAPI GdipGetClipBounds(GpGraphics *graphics, GpRectF *rect)
4369 {
4370     TRACE("(%p, %p)\n", graphics, rect);
4371
4372     if(!graphics)
4373         return InvalidParameter;
4374
4375     if(graphics->busy)
4376         return ObjectBusy;
4377
4378     return GdipGetRegionBounds(graphics->clip, graphics, rect);
4379 }
4380
4381 /*****************************************************************************
4382  * GdipGetClipBoundsI [GDIPLUS.@]
4383  */
4384 GpStatus WINGDIPAPI GdipGetClipBoundsI(GpGraphics *graphics, GpRect *rect)
4385 {
4386     TRACE("(%p, %p)\n", graphics, rect);
4387
4388     if(!graphics)
4389         return InvalidParameter;
4390
4391     if(graphics->busy)
4392         return ObjectBusy;
4393
4394     return GdipGetRegionBoundsI(graphics->clip, graphics, rect);
4395 }
4396
4397 /* FIXME: Compositing mode is not used anywhere except the getter/setter. */
4398 GpStatus WINGDIPAPI GdipGetCompositingMode(GpGraphics *graphics,
4399     CompositingMode *mode)
4400 {
4401     TRACE("(%p, %p)\n", graphics, mode);
4402
4403     if(!graphics || !mode)
4404         return InvalidParameter;
4405
4406     if(graphics->busy)
4407         return ObjectBusy;
4408
4409     *mode = graphics->compmode;
4410
4411     return Ok;
4412 }
4413
4414 /* FIXME: Compositing quality is not used anywhere except the getter/setter. */
4415 GpStatus WINGDIPAPI GdipGetCompositingQuality(GpGraphics *graphics,
4416     CompositingQuality *quality)
4417 {
4418     TRACE("(%p, %p)\n", graphics, quality);
4419
4420     if(!graphics || !quality)
4421         return InvalidParameter;
4422
4423     if(graphics->busy)
4424         return ObjectBusy;
4425
4426     *quality = graphics->compqual;
4427
4428     return Ok;
4429 }
4430
4431 /* FIXME: Interpolation mode is not used anywhere except the getter/setter. */
4432 GpStatus WINGDIPAPI GdipGetInterpolationMode(GpGraphics *graphics,
4433     InterpolationMode *mode)
4434 {
4435     TRACE("(%p, %p)\n", graphics, mode);
4436
4437     if(!graphics || !mode)
4438         return InvalidParameter;
4439
4440     if(graphics->busy)
4441         return ObjectBusy;
4442
4443     *mode = graphics->interpolation;
4444
4445     return Ok;
4446 }
4447
4448 /* FIXME: Need to handle color depths less than 24bpp */
4449 GpStatus WINGDIPAPI GdipGetNearestColor(GpGraphics *graphics, ARGB* argb)
4450 {
4451     FIXME("(%p, %p): Passing color unmodified\n", graphics, argb);
4452
4453     if(!graphics || !argb)
4454         return InvalidParameter;
4455
4456     if(graphics->busy)
4457         return ObjectBusy;
4458
4459     return Ok;
4460 }
4461
4462 GpStatus WINGDIPAPI GdipGetPageScale(GpGraphics *graphics, REAL *scale)
4463 {
4464     TRACE("(%p, %p)\n", graphics, scale);
4465
4466     if(!graphics || !scale)
4467         return InvalidParameter;
4468
4469     if(graphics->busy)
4470         return ObjectBusy;
4471
4472     *scale = graphics->scale;
4473
4474     return Ok;
4475 }
4476
4477 GpStatus WINGDIPAPI GdipGetPageUnit(GpGraphics *graphics, GpUnit *unit)
4478 {
4479     TRACE("(%p, %p)\n", graphics, unit);
4480
4481     if(!graphics || !unit)
4482         return InvalidParameter;
4483
4484     if(graphics->busy)
4485         return ObjectBusy;
4486
4487     *unit = graphics->unit;
4488
4489     return Ok;
4490 }
4491
4492 /* FIXME: Pixel offset mode is not used anywhere except the getter/setter. */
4493 GpStatus WINGDIPAPI GdipGetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
4494     *mode)
4495 {
4496     TRACE("(%p, %p)\n", graphics, mode);
4497
4498     if(!graphics || !mode)
4499         return InvalidParameter;
4500
4501     if(graphics->busy)
4502         return ObjectBusy;
4503
4504     *mode = graphics->pixeloffset;
4505
4506     return Ok;
4507 }
4508
4509 /* FIXME: Smoothing mode is not used anywhere except the getter/setter. */
4510 GpStatus WINGDIPAPI GdipGetSmoothingMode(GpGraphics *graphics, SmoothingMode *mode)
4511 {
4512     TRACE("(%p, %p)\n", graphics, mode);
4513
4514     if(!graphics || !mode)
4515         return InvalidParameter;
4516
4517     if(graphics->busy)
4518         return ObjectBusy;
4519
4520     *mode = graphics->smoothing;
4521
4522     return Ok;
4523 }
4524
4525 GpStatus WINGDIPAPI GdipGetTextContrast(GpGraphics *graphics, UINT *contrast)
4526 {
4527     TRACE("(%p, %p)\n", graphics, contrast);
4528
4529     if(!graphics || !contrast)
4530         return InvalidParameter;
4531
4532     *contrast = graphics->textcontrast;
4533
4534     return Ok;
4535 }
4536
4537 /* FIXME: Text rendering hint is not used anywhere except the getter/setter. */
4538 GpStatus WINGDIPAPI GdipGetTextRenderingHint(GpGraphics *graphics,
4539     TextRenderingHint *hint)
4540 {
4541     TRACE("(%p, %p)\n", graphics, hint);
4542
4543     if(!graphics || !hint)
4544         return InvalidParameter;
4545
4546     if(graphics->busy)
4547         return ObjectBusy;
4548
4549     *hint = graphics->texthint;
4550
4551     return Ok;
4552 }
4553
4554 GpStatus WINGDIPAPI GdipGetVisibleClipBounds(GpGraphics *graphics, GpRectF *rect)
4555 {
4556     GpRegion *clip_rgn;
4557     GpStatus stat;
4558
4559     TRACE("(%p, %p)\n", graphics, rect);
4560
4561     if(!graphics || !rect)
4562         return InvalidParameter;
4563
4564     if(graphics->busy)
4565         return ObjectBusy;
4566
4567     /* intersect window and graphics clipping regions */
4568     if((stat = GdipCreateRegion(&clip_rgn)) != Ok)
4569         return stat;
4570
4571     if((stat = get_visible_clip_region(graphics, clip_rgn)) != Ok)
4572         goto cleanup;
4573
4574     /* get bounds of the region */
4575     stat = GdipGetRegionBounds(clip_rgn, graphics, rect);
4576
4577 cleanup:
4578     GdipDeleteRegion(clip_rgn);
4579
4580     return stat;
4581 }
4582
4583 GpStatus WINGDIPAPI GdipGetVisibleClipBoundsI(GpGraphics *graphics, GpRect *rect)
4584 {
4585     GpRectF rectf;
4586     GpStatus stat;
4587
4588     TRACE("(%p, %p)\n", graphics, rect);
4589
4590     if(!graphics || !rect)
4591         return InvalidParameter;
4592
4593     if((stat = GdipGetVisibleClipBounds(graphics, &rectf)) == Ok)
4594     {
4595         rect->X = gdip_round(rectf.X);
4596         rect->Y = gdip_round(rectf.Y);
4597         rect->Width  = gdip_round(rectf.Width);
4598         rect->Height = gdip_round(rectf.Height);
4599     }
4600
4601     return stat;
4602 }
4603
4604 GpStatus WINGDIPAPI GdipGetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
4605 {
4606     TRACE("(%p, %p)\n", graphics, matrix);
4607
4608     if(!graphics || !matrix)
4609         return InvalidParameter;
4610
4611     if(graphics->busy)
4612         return ObjectBusy;
4613
4614     *matrix = graphics->worldtrans;
4615     return Ok;
4616 }
4617
4618 GpStatus WINGDIPAPI GdipGraphicsClear(GpGraphics *graphics, ARGB color)
4619 {
4620     GpSolidFill *brush;
4621     GpStatus stat;
4622     GpRectF wnd_rect;
4623
4624     TRACE("(%p, %x)\n", graphics, color);
4625
4626     if(!graphics)
4627         return InvalidParameter;
4628
4629     if(graphics->busy)
4630         return ObjectBusy;
4631
4632     if((stat = GdipCreateSolidFill(color, &brush)) != Ok)
4633         return stat;
4634
4635     if((stat = get_graphics_bounds(graphics, &wnd_rect)) != Ok){
4636         GdipDeleteBrush((GpBrush*)brush);
4637         return stat;
4638     }
4639
4640     GdipFillRectangle(graphics, (GpBrush*)brush, wnd_rect.X, wnd_rect.Y,
4641                                                  wnd_rect.Width, wnd_rect.Height);
4642
4643     GdipDeleteBrush((GpBrush*)brush);
4644
4645     return Ok;
4646 }
4647
4648 GpStatus WINGDIPAPI GdipIsClipEmpty(GpGraphics *graphics, BOOL *res)
4649 {
4650     TRACE("(%p, %p)\n", graphics, res);
4651
4652     if(!graphics || !res)
4653         return InvalidParameter;
4654
4655     return GdipIsEmptyRegion(graphics->clip, graphics, res);
4656 }
4657
4658 GpStatus WINGDIPAPI GdipIsVisiblePoint(GpGraphics *graphics, REAL x, REAL y, BOOL *result)
4659 {
4660     GpStatus stat;
4661     GpRegion* rgn;
4662     GpPointF pt;
4663
4664     TRACE("(%p, %.2f, %.2f, %p)\n", graphics, x, y, result);
4665
4666     if(!graphics || !result)
4667         return InvalidParameter;
4668
4669     if(graphics->busy)
4670         return ObjectBusy;
4671
4672     pt.X = x;
4673     pt.Y = y;
4674     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4675                    CoordinateSpaceWorld, &pt, 1)) != Ok)
4676         return stat;
4677
4678     if((stat = GdipCreateRegion(&rgn)) != Ok)
4679         return stat;
4680
4681     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4682         goto cleanup;
4683
4684     stat = GdipIsVisibleRegionPoint(rgn, pt.X, pt.Y, graphics, result);
4685
4686 cleanup:
4687     GdipDeleteRegion(rgn);
4688     return stat;
4689 }
4690
4691 GpStatus WINGDIPAPI GdipIsVisiblePointI(GpGraphics *graphics, INT x, INT y, BOOL *result)
4692 {
4693     return GdipIsVisiblePoint(graphics, (REAL)x, (REAL)y, result);
4694 }
4695
4696 GpStatus WINGDIPAPI GdipIsVisibleRect(GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, BOOL *result)
4697 {
4698     GpStatus stat;
4699     GpRegion* rgn;
4700     GpPointF pts[2];
4701
4702     TRACE("(%p %.2f %.2f %.2f %.2f %p)\n", graphics, x, y, width, height, result);
4703
4704     if(!graphics || !result)
4705         return InvalidParameter;
4706
4707     if(graphics->busy)
4708         return ObjectBusy;
4709
4710     pts[0].X = x;
4711     pts[0].Y = y;
4712     pts[1].X = x + width;
4713     pts[1].Y = y + height;
4714
4715     if((stat = GdipTransformPoints(graphics, CoordinateSpaceDevice,
4716                     CoordinateSpaceWorld, pts, 2)) != Ok)
4717         return stat;
4718
4719     pts[1].X -= pts[0].X;
4720     pts[1].Y -= pts[0].Y;
4721
4722     if((stat = GdipCreateRegion(&rgn)) != Ok)
4723         return stat;
4724
4725     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
4726         goto cleanup;
4727
4728     stat = GdipIsVisibleRegionRect(rgn, pts[0].X, pts[0].Y, pts[1].X, pts[1].Y, graphics, result);
4729
4730 cleanup:
4731     GdipDeleteRegion(rgn);
4732     return stat;
4733 }
4734
4735 GpStatus WINGDIPAPI GdipIsVisibleRectI(GpGraphics *graphics, INT x, INT y, INT width, INT height, BOOL *result)
4736 {
4737     return GdipIsVisibleRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, result);
4738 }
4739
4740 GpStatus gdip_format_string(HDC hdc,
4741     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
4742     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4743     gdip_format_string_callback callback, void *user_data)
4744 {
4745     WCHAR* stringdup;
4746     int sum = 0, height = 0, fit, fitcpy, i, j, lret, nwidth,
4747         nheight, lineend, lineno = 0;
4748     RectF bounds;
4749     StringAlignment halign;
4750     GpStatus stat = Ok;
4751     SIZE size;
4752     HotkeyPrefix hkprefix;
4753     INT *hotkeyprefix_offsets=NULL;
4754     INT hotkeyprefix_count=0;
4755     INT hotkeyprefix_pos=0, hotkeyprefix_end_pos=0;
4756     int seen_prefix=0;
4757
4758     if(length == -1) length = lstrlenW(string);
4759
4760     stringdup = GdipAlloc((length + 1) * sizeof(WCHAR));
4761     if(!stringdup) return OutOfMemory;
4762
4763     nwidth = rect->Width;
4764     nheight = rect->Height;
4765
4766     if (format)
4767         hkprefix = format->hkprefix;
4768     else
4769         hkprefix = HotkeyPrefixNone;
4770
4771     if (hkprefix == HotkeyPrefixShow)
4772     {
4773         for (i=0; i<length; i++)
4774         {
4775             if (string[i] == '&')
4776                 hotkeyprefix_count++;
4777         }
4778     }
4779
4780     if (hotkeyprefix_count)
4781         hotkeyprefix_offsets = GdipAlloc(sizeof(INT) * hotkeyprefix_count);
4782
4783     hotkeyprefix_count = 0;
4784
4785     for(i = 0, j = 0; i < length; i++){
4786         /* FIXME: This makes the indexes passed to callback inaccurate. */
4787         if(!isprintW(string[i]) && (string[i] != '\n'))
4788             continue;
4789
4790         /* FIXME: tabs should be handled using tabstops from stringformat */
4791         if (string[i] == '\t')
4792             continue;
4793
4794         if (seen_prefix && hkprefix == HotkeyPrefixShow && string[i] != '&')
4795             hotkeyprefix_offsets[hotkeyprefix_count++] = j;
4796         else if (!seen_prefix && hkprefix != HotkeyPrefixNone && string[i] == '&')
4797         {
4798             seen_prefix = 1;
4799             continue;
4800         }
4801
4802         seen_prefix = 0;
4803
4804         stringdup[j] = string[i];
4805         j++;
4806     }
4807
4808     length = j;
4809
4810     if (format) halign = format->align;
4811     else halign = StringAlignmentNear;
4812
4813     while(sum < length){
4814         GetTextExtentExPointW(hdc, stringdup + sum, length - sum,
4815                               nwidth, &fit, NULL, &size);
4816         fitcpy = fit;
4817
4818         if(fit == 0)
4819             break;
4820
4821         for(lret = 0; lret < fit; lret++)
4822             if(*(stringdup + sum + lret) == '\n')
4823                 break;
4824
4825         /* Line break code (may look strange, but it imitates windows). */
4826         if(lret < fit)
4827             lineend = fit = lret;    /* this is not an off-by-one error */
4828         else if(fit < (length - sum)){
4829             if(*(stringdup + sum + fit) == ' ')
4830                 while(*(stringdup + sum + fit) == ' ')
4831                     fit++;
4832             else
4833                 while(*(stringdup + sum + fit - 1) != ' '){
4834                     fit--;
4835
4836                     if(*(stringdup + sum + fit) == '\t')
4837                         break;
4838
4839                     if(fit == 0){
4840                         fit = fitcpy;
4841                         break;
4842                     }
4843                 }
4844             lineend = fit;
4845             while(*(stringdup + sum + lineend - 1) == ' ' ||
4846                   *(stringdup + sum + lineend - 1) == '\t')
4847                 lineend--;
4848         }
4849         else
4850             lineend = fit;
4851
4852         GetTextExtentExPointW(hdc, stringdup + sum, lineend,
4853                               nwidth, &j, NULL, &size);
4854
4855         bounds.Width = size.cx;
4856
4857         if(height + size.cy > nheight)
4858             bounds.Height = nheight - (height + size.cy);
4859         else
4860             bounds.Height = size.cy;
4861
4862         bounds.Y = rect->Y + height;
4863
4864         switch (halign)
4865         {
4866         case StringAlignmentNear:
4867         default:
4868             bounds.X = rect->X;
4869             break;
4870         case StringAlignmentCenter:
4871             bounds.X = rect->X + (rect->Width/2) - (bounds.Width/2);
4872             break;
4873         case StringAlignmentFar:
4874             bounds.X = rect->X + rect->Width - bounds.Width;
4875             break;
4876         }
4877
4878         for (hotkeyprefix_end_pos=hotkeyprefix_pos; hotkeyprefix_end_pos<hotkeyprefix_count; hotkeyprefix_end_pos++)
4879             if (hotkeyprefix_offsets[hotkeyprefix_end_pos] >= sum + lineend)
4880                 break;
4881
4882         stat = callback(hdc, stringdup, sum, lineend,
4883             font, rect, format, lineno, &bounds,
4884             &hotkeyprefix_offsets[hotkeyprefix_pos],
4885             hotkeyprefix_end_pos-hotkeyprefix_pos, user_data);
4886
4887         if (stat != Ok)
4888             break;
4889
4890         sum += fit + (lret < fitcpy ? 1 : 0);
4891         height += size.cy;
4892         lineno++;
4893
4894         hotkeyprefix_pos = hotkeyprefix_end_pos;
4895
4896         if(height > nheight)
4897             break;
4898
4899         /* Stop if this was a linewrap (but not if it was a linebreak). */
4900         if ((lret == fitcpy) && format &&
4901             (format->attr & (StringFormatFlagsNoWrap | StringFormatFlagsLineLimit)))
4902             break;
4903     }
4904
4905     GdipFree(stringdup);
4906     GdipFree(hotkeyprefix_offsets);
4907
4908     return stat;
4909 }
4910
4911 struct measure_ranges_args {
4912     GpRegion **regions;
4913     REAL rel_width, rel_height;
4914 };
4915
4916 static GpStatus measure_ranges_callback(HDC hdc,
4917     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
4918     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
4919     INT lineno, const RectF *bounds, INT *underlined_indexes,
4920     INT underlined_index_count, void *user_data)
4921 {
4922     int i;
4923     GpStatus stat = Ok;
4924     struct measure_ranges_args *args = user_data;
4925
4926     for (i=0; i<format->range_count; i++)
4927     {
4928         INT range_start = max(index, format->character_ranges[i].First);
4929         INT range_end = min(index+length, format->character_ranges[i].First+format->character_ranges[i].Length);
4930         if (range_start < range_end)
4931         {
4932             GpRectF range_rect;
4933             SIZE range_size;
4934
4935             range_rect.Y = bounds->Y / args->rel_height;
4936             range_rect.Height = bounds->Height / args->rel_height;
4937
4938             GetTextExtentExPointW(hdc, string + index, range_start - index,
4939                                   INT_MAX, NULL, NULL, &range_size);
4940             range_rect.X = (bounds->X + range_size.cx) / args->rel_width;
4941
4942             GetTextExtentExPointW(hdc, string + index, range_end - index,
4943                                   INT_MAX, NULL, NULL, &range_size);
4944             range_rect.Width = (bounds->X + range_size.cx) / args->rel_width - range_rect.X;
4945
4946             stat = GdipCombineRegionRect(args->regions[i], &range_rect, CombineModeUnion);
4947             if (stat != Ok)
4948                 break;
4949         }
4950     }
4951
4952     return stat;
4953 }
4954
4955 GpStatus WINGDIPAPI GdipMeasureCharacterRanges(GpGraphics* graphics,
4956         GDIPCONST WCHAR* string, INT length, GDIPCONST GpFont* font,
4957         GDIPCONST RectF* layoutRect, GDIPCONST GpStringFormat *stringFormat,
4958         INT regionCount, GpRegion** regions)
4959 {
4960     GpStatus stat;
4961     int i;
4962     HFONT gdifont, oldfont;
4963     struct measure_ranges_args args;
4964     HDC hdc, temp_hdc=NULL;
4965     GpPointF pt[3];
4966     RectF scaled_rect;
4967     REAL margin_x;
4968
4969     TRACE("(%p %s %d %p %s %p %d %p)\n", graphics, debugstr_w(string),
4970             length, font, debugstr_rectf(layoutRect), stringFormat, regionCount, regions);
4971
4972     if (!(graphics && string && font && layoutRect && stringFormat && regions))
4973         return InvalidParameter;
4974
4975     if (regionCount < stringFormat->range_count)
4976         return InvalidParameter;
4977
4978     if(!graphics->hdc)
4979     {
4980         hdc = temp_hdc = CreateCompatibleDC(0);
4981         if (!temp_hdc) return OutOfMemory;
4982     }
4983     else
4984         hdc = graphics->hdc;
4985
4986     if (stringFormat->attr)
4987         TRACE("may be ignoring some format flags: attr %x\n", stringFormat->attr);
4988
4989     pt[0].X = 0.0;
4990     pt[0].Y = 0.0;
4991     pt[1].X = 1.0;
4992     pt[1].Y = 0.0;
4993     pt[2].X = 0.0;
4994     pt[2].Y = 1.0;
4995     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
4996     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
4997                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
4998     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
4999                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5000
5001     margin_x = stringFormat->generic_typographic ? 0.0 : font->emSize / 6.0;
5002     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5003
5004     scaled_rect.X = (layoutRect->X + margin_x) * args.rel_width;
5005     scaled_rect.Y = layoutRect->Y * args.rel_height;
5006     if (stringFormat->attr & StringFormatFlagsNoClip)
5007     {
5008         scaled_rect.Width = (REAL)(1 << 23);
5009         scaled_rect.Height = (REAL)(1 << 23);
5010     }
5011     else
5012     {
5013         scaled_rect.Width = layoutRect->Width * args.rel_width;
5014         scaled_rect.Height = layoutRect->Height * args.rel_height;
5015     }
5016     if (scaled_rect.Width >= 0.5)
5017     {
5018         scaled_rect.Width -= margin_x * 2.0 * args.rel_width;
5019         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5020     }
5021
5022     get_font_hfont(graphics, font, stringFormat, &gdifont, NULL);
5023     oldfont = SelectObject(hdc, gdifont);
5024
5025     for (i=0; i<stringFormat->range_count; i++)
5026     {
5027         stat = GdipSetEmpty(regions[i]);
5028         if (stat != Ok)
5029             return stat;
5030     }
5031
5032     args.regions = regions;
5033
5034     stat = gdip_format_string(hdc, string, length, font, &scaled_rect, stringFormat,
5035         measure_ranges_callback, &args);
5036
5037     SelectObject(hdc, oldfont);
5038     DeleteObject(gdifont);
5039
5040     if (temp_hdc)
5041         DeleteDC(temp_hdc);
5042
5043     return stat;
5044 }
5045
5046 struct measure_string_args {
5047     RectF *bounds;
5048     INT *codepointsfitted;
5049     INT *linesfilled;
5050     REAL rel_width, rel_height;
5051 };
5052
5053 static GpStatus measure_string_callback(HDC hdc,
5054     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
5055     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
5056     INT lineno, const RectF *bounds, INT *underlined_indexes,
5057     INT underlined_index_count, void *user_data)
5058 {
5059     struct measure_string_args *args = user_data;
5060     REAL new_width, new_height;
5061
5062     new_width = bounds->Width / args->rel_width;
5063     new_height = (bounds->Height + bounds->Y) / args->rel_height - args->bounds->Y;
5064
5065     if (new_width > args->bounds->Width)
5066         args->bounds->Width = new_width;
5067
5068     if (new_height > args->bounds->Height)
5069         args->bounds->Height = new_height;
5070
5071     if (args->codepointsfitted)
5072         *args->codepointsfitted = index + length;
5073
5074     if (args->linesfilled)
5075         (*args->linesfilled)++;
5076
5077     return Ok;
5078 }
5079
5080 /* Find the smallest rectangle that bounds the text when it is printed in rect
5081  * according to the format options listed in format. If rect has 0 width and
5082  * height, then just find the smallest rectangle that bounds the text when it's
5083  * printed at location (rect->X, rect-Y). */
5084 GpStatus WINGDIPAPI GdipMeasureString(GpGraphics *graphics,
5085     GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font,
5086     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format, RectF *bounds,
5087     INT *codepointsfitted, INT *linesfilled)
5088 {
5089     HFONT oldfont, gdifont;
5090     struct measure_string_args args;
5091     HDC temp_hdc=NULL, hdc;
5092     GpPointF pt[3];
5093     RectF scaled_rect;
5094     REAL margin_x;
5095     INT lines, glyphs, format_flags = format ? format->attr : 0;
5096
5097     TRACE("(%p, %s, %i, %p, %s, %p, %p, %p, %p)\n", graphics,
5098         debugstr_wn(string, length), length, font, debugstr_rectf(rect), format,
5099         bounds, codepointsfitted, linesfilled);
5100
5101     if(!graphics || !string || !font || !rect || !bounds)
5102         return InvalidParameter;
5103
5104     if(!graphics->hdc)
5105     {
5106         hdc = temp_hdc = CreateCompatibleDC(0);
5107         if (!temp_hdc) return OutOfMemory;
5108     }
5109     else
5110         hdc = graphics->hdc;
5111
5112     if(linesfilled) *linesfilled = 0;
5113     if(codepointsfitted) *codepointsfitted = 0;
5114
5115     if(format)
5116         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
5117
5118     pt[0].X = 0.0;
5119     pt[0].Y = 0.0;
5120     pt[1].X = 1.0;
5121     pt[1].Y = 0.0;
5122     pt[2].X = 0.0;
5123     pt[2].Y = 1.0;
5124     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5125     args.rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5126                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5127     args.rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5128                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5129
5130     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
5131     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5132
5133     scaled_rect.X = (rect->X + margin_x) * args.rel_width;
5134     scaled_rect.Y = rect->Y * args.rel_height;
5135     scaled_rect.Width = rect->Width * args.rel_width;
5136     scaled_rect.Height = rect->Height * args.rel_height;
5137
5138     if ((format_flags & StringFormatFlagsNoClip) ||
5139         scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5140     if ((format_flags & StringFormatFlagsNoClip) ||
5141         scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5142
5143     if (scaled_rect.Width >= 0.5)
5144     {
5145         scaled_rect.Width -= margin_x * 2.0 * args.rel_width;
5146         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5147     }
5148
5149     if (scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5150     if (scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5151
5152     get_font_hfont(graphics, font, format, &gdifont, NULL);
5153     oldfont = SelectObject(hdc, gdifont);
5154
5155     bounds->X = rect->X;
5156     bounds->Y = rect->Y;
5157     bounds->Width = 0.0;
5158     bounds->Height = 0.0;
5159
5160     args.bounds = bounds;
5161     args.codepointsfitted = &glyphs;
5162     args.linesfilled = &lines;
5163     lines = glyphs = 0;
5164
5165     gdip_format_string(hdc, string, length, font, &scaled_rect, format,
5166         measure_string_callback, &args);
5167
5168     if (linesfilled) *linesfilled = lines;
5169     if (codepointsfitted) *codepointsfitted = glyphs;
5170
5171     if (lines)
5172         bounds->Width += margin_x * 2.0;
5173
5174     SelectObject(hdc, oldfont);
5175     DeleteObject(gdifont);
5176
5177     if (temp_hdc)
5178         DeleteDC(temp_hdc);
5179
5180     return Ok;
5181 }
5182
5183 struct draw_string_args {
5184     GpGraphics *graphics;
5185     GDIPCONST GpBrush *brush;
5186     REAL x, y, rel_width, rel_height, ascent;
5187 };
5188
5189 static GpStatus draw_string_callback(HDC hdc,
5190     GDIPCONST WCHAR *string, INT index, INT length, GDIPCONST GpFont *font,
5191     GDIPCONST RectF *rect, GDIPCONST GpStringFormat *format,
5192     INT lineno, const RectF *bounds, INT *underlined_indexes,
5193     INT underlined_index_count, void *user_data)
5194 {
5195     struct draw_string_args *args = user_data;
5196     PointF position;
5197     GpStatus stat;
5198
5199     position.X = args->x + bounds->X / args->rel_width;
5200     position.Y = args->y + bounds->Y / args->rel_height + args->ascent;
5201
5202     stat = draw_driver_string(args->graphics, &string[index], length, font, format,
5203         args->brush, &position,
5204         DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance, NULL);
5205
5206     if (stat == Ok && underlined_index_count)
5207     {
5208         OUTLINETEXTMETRICW otm;
5209         REAL underline_y, underline_height;
5210         int i;
5211
5212         GetOutlineTextMetricsW(hdc, sizeof(otm), &otm);
5213
5214         underline_height = otm.otmsUnderscoreSize / args->rel_height;
5215         underline_y = position.Y - otm.otmsUnderscorePosition / args->rel_height - underline_height / 2;
5216
5217         for (i=0; i<underlined_index_count; i++)
5218         {
5219             REAL start_x, end_x;
5220             SIZE text_size;
5221             INT ofs = underlined_indexes[i] - index;
5222
5223             GetTextExtentExPointW(hdc, string + index, ofs, INT_MAX, NULL, NULL, &text_size);
5224             start_x = text_size.cx / args->rel_width;
5225
5226             GetTextExtentExPointW(hdc, string + index, ofs+1, INT_MAX, NULL, NULL, &text_size);
5227             end_x = text_size.cx / args->rel_width;
5228
5229             GdipFillRectangle(args->graphics, (GpBrush*)args->brush, position.X+start_x, underline_y, end_x-start_x, underline_height);
5230         }
5231     }
5232
5233     return stat;
5234 }
5235
5236 GpStatus WINGDIPAPI GdipDrawString(GpGraphics *graphics, GDIPCONST WCHAR *string,
5237     INT length, GDIPCONST GpFont *font, GDIPCONST RectF *rect,
5238     GDIPCONST GpStringFormat *format, GDIPCONST GpBrush *brush)
5239 {
5240     HRGN rgn = NULL;
5241     HFONT gdifont;
5242     GpPointF pt[3], rectcpy[4];
5243     POINT corners[4];
5244     REAL rel_width, rel_height, margin_x;
5245     INT save_state, format_flags = 0;
5246     REAL offsety = 0.0;
5247     struct draw_string_args args;
5248     RectF scaled_rect;
5249     HDC hdc, temp_hdc=NULL;
5250     TEXTMETRICW textmetric;
5251
5252     TRACE("(%p, %s, %i, %p, %s, %p, %p)\n", graphics, debugstr_wn(string, length),
5253         length, font, debugstr_rectf(rect), format, brush);
5254
5255     if(!graphics || !string || !font || !brush || !rect)
5256         return InvalidParameter;
5257
5258     if(graphics->hdc)
5259     {
5260         hdc = graphics->hdc;
5261     }
5262     else
5263     {
5264         hdc = temp_hdc = CreateCompatibleDC(0);
5265     }
5266
5267     if(format){
5268         TRACE("may be ignoring some format flags: attr %x\n", format->attr);
5269
5270         format_flags = format->attr;
5271
5272         /* Should be no need to explicitly test for StringAlignmentNear as
5273          * that is default behavior if no alignment is passed. */
5274         if(format->vertalign != StringAlignmentNear){
5275             RectF bounds, in_rect = *rect;
5276             in_rect.Height = 0.0; /* avoid height clipping */
5277             GdipMeasureString(graphics, string, length, font, &in_rect, format, &bounds, 0, 0);
5278
5279             TRACE("bounds %s\n", debugstr_rectf(&bounds));
5280
5281             if(format->vertalign == StringAlignmentCenter)
5282                 offsety = (rect->Height - bounds.Height) / 2;
5283             else if(format->vertalign == StringAlignmentFar)
5284                 offsety = (rect->Height - bounds.Height);
5285         }
5286         TRACE("vertical align %d, offsety %f\n", format->vertalign, offsety);
5287     }
5288
5289     save_state = SaveDC(hdc);
5290
5291     pt[0].X = 0.0;
5292     pt[0].Y = 0.0;
5293     pt[1].X = 1.0;
5294     pt[1].Y = 0.0;
5295     pt[2].X = 0.0;
5296     pt[2].Y = 1.0;
5297     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
5298     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
5299                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
5300     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
5301                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
5302
5303     rectcpy[3].X = rectcpy[0].X = rect->X;
5304     rectcpy[1].Y = rectcpy[0].Y = rect->Y;
5305     rectcpy[2].X = rectcpy[1].X = rect->X + rect->Width;
5306     rectcpy[3].Y = rectcpy[2].Y = rect->Y + rect->Height;
5307     transform_and_round_points(graphics, corners, rectcpy, 4);
5308
5309     margin_x = (format && format->generic_typographic) ? 0.0 : font->emSize / 6.0;
5310     margin_x *= units_scale(font->unit, graphics->unit, graphics->xres);
5311
5312     scaled_rect.X = margin_x * rel_width;
5313     scaled_rect.Y = 0.0;
5314     scaled_rect.Width = rel_width * rect->Width;
5315     scaled_rect.Height = rel_height * rect->Height;
5316
5317     if ((format_flags & StringFormatFlagsNoClip) ||
5318         scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5319     if ((format_flags & StringFormatFlagsNoClip) ||
5320         scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5321
5322     if (scaled_rect.Width >= 0.5)
5323     {
5324         scaled_rect.Width -= margin_x * 2.0 * rel_width;
5325         if (scaled_rect.Width < 0.5) return Ok; /* doesn't fit */
5326     }
5327
5328     if (scaled_rect.Width >= 1 << 23 || scaled_rect.Width < 0.5) scaled_rect.Width = 1 << 23;
5329     if (scaled_rect.Height >= 1 << 23 || scaled_rect.Height < 0.5) scaled_rect.Height = 1 << 23;
5330
5331     if (!(format_flags & StringFormatFlagsNoClip) &&
5332         scaled_rect.Width != 1 << 23 && scaled_rect.Height != 1 << 23)
5333     {
5334         /* FIXME: If only the width or only the height is 0, we should probably still clip */
5335         rgn = CreatePolygonRgn(corners, 4, ALTERNATE);
5336         SelectClipRgn(hdc, rgn);
5337     }
5338
5339     get_font_hfont(graphics, font, format, &gdifont, NULL);
5340     SelectObject(hdc, gdifont);
5341
5342     args.graphics = graphics;
5343     args.brush = brush;
5344
5345     args.x = rect->X;
5346     args.y = rect->Y + offsety;
5347
5348     args.rel_width = rel_width;
5349     args.rel_height = rel_height;
5350
5351     GetTextMetricsW(hdc, &textmetric);
5352     args.ascent = textmetric.tmAscent / rel_height;
5353
5354     gdip_format_string(hdc, string, length, font, &scaled_rect, format,
5355         draw_string_callback, &args);
5356
5357     DeleteObject(rgn);
5358     DeleteObject(gdifont);
5359
5360     RestoreDC(hdc, save_state);
5361
5362     DeleteDC(temp_hdc);
5363
5364     return Ok;
5365 }
5366
5367 GpStatus WINGDIPAPI GdipResetClip(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 GdipSetInfinite(graphics->clip);
5378 }
5379
5380 GpStatus WINGDIPAPI GdipResetWorldTransform(GpGraphics *graphics)
5381 {
5382     TRACE("(%p)\n", graphics);
5383
5384     if(!graphics)
5385         return InvalidParameter;
5386
5387     if(graphics->busy)
5388         return ObjectBusy;
5389
5390     return GdipSetMatrixElements(&graphics->worldtrans, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
5391 }
5392
5393 GpStatus WINGDIPAPI GdipRestoreGraphics(GpGraphics *graphics, GraphicsState state)
5394 {
5395     return GdipEndContainer(graphics, state);
5396 }
5397
5398 GpStatus WINGDIPAPI GdipRotateWorldTransform(GpGraphics *graphics, REAL angle,
5399     GpMatrixOrder order)
5400 {
5401     TRACE("(%p, %.2f, %d)\n", graphics, angle, order);
5402
5403     if(!graphics)
5404         return InvalidParameter;
5405
5406     if(graphics->busy)
5407         return ObjectBusy;
5408
5409     return GdipRotateMatrix(&graphics->worldtrans, angle, order);
5410 }
5411
5412 GpStatus WINGDIPAPI GdipSaveGraphics(GpGraphics *graphics, GraphicsState *state)
5413 {
5414     return GdipBeginContainer2(graphics, state);
5415 }
5416
5417 GpStatus WINGDIPAPI GdipBeginContainer2(GpGraphics *graphics,
5418         GraphicsContainer *state)
5419 {
5420     GraphicsContainerItem *container;
5421     GpStatus sts;
5422
5423     TRACE("(%p, %p)\n", graphics, state);
5424
5425     if(!graphics || !state)
5426         return InvalidParameter;
5427
5428     sts = init_container(&container, graphics);
5429     if(sts != Ok)
5430         return sts;
5431
5432     list_add_head(&graphics->containers, &container->entry);
5433     *state = graphics->contid = container->contid;
5434
5435     return Ok;
5436 }
5437
5438 GpStatus WINGDIPAPI GdipBeginContainer(GpGraphics *graphics, GDIPCONST GpRectF *dstrect, GDIPCONST GpRectF *srcrect, GpUnit unit, GraphicsContainer *state)
5439 {
5440     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5441     return NotImplemented;
5442 }
5443
5444 GpStatus WINGDIPAPI GdipBeginContainerI(GpGraphics *graphics, GDIPCONST GpRect *dstrect, GDIPCONST GpRect *srcrect, GpUnit unit, GraphicsContainer *state)
5445 {
5446     FIXME("(%p, %p, %p, %d, %p): stub\n", graphics, dstrect, srcrect, unit, state);
5447     return NotImplemented;
5448 }
5449
5450 GpStatus WINGDIPAPI GdipComment(GpGraphics *graphics, UINT sizeData, GDIPCONST BYTE *data)
5451 {
5452     FIXME("(%p, %d, %p): stub\n", graphics, sizeData, data);
5453     return NotImplemented;
5454 }
5455
5456 GpStatus WINGDIPAPI GdipEndContainer(GpGraphics *graphics, GraphicsContainer state)
5457 {
5458     GpStatus sts;
5459     GraphicsContainerItem *container, *container2;
5460
5461     TRACE("(%p, %x)\n", graphics, state);
5462
5463     if(!graphics)
5464         return InvalidParameter;
5465
5466     LIST_FOR_EACH_ENTRY(container, &graphics->containers, GraphicsContainerItem, entry){
5467         if(container->contid == state)
5468             break;
5469     }
5470
5471     /* did not find a matching container */
5472     if(&container->entry == &graphics->containers)
5473         return Ok;
5474
5475     sts = restore_container(graphics, container);
5476     if(sts != Ok)
5477         return sts;
5478
5479     /* remove all of the containers on top of the found container */
5480     LIST_FOR_EACH_ENTRY_SAFE(container, container2, &graphics->containers, GraphicsContainerItem, entry){
5481         if(container->contid == state)
5482             break;
5483         list_remove(&container->entry);
5484         delete_container(container);
5485     }
5486
5487     list_remove(&container->entry);
5488     delete_container(container);
5489
5490     return Ok;
5491 }
5492
5493 GpStatus WINGDIPAPI GdipScaleWorldTransform(GpGraphics *graphics, REAL sx,
5494     REAL sy, GpMatrixOrder order)
5495 {
5496     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, sx, sy, order);
5497
5498     if(!graphics)
5499         return InvalidParameter;
5500
5501     if(graphics->busy)
5502         return ObjectBusy;
5503
5504     return GdipScaleMatrix(&graphics->worldtrans, sx, sy, order);
5505 }
5506
5507 GpStatus WINGDIPAPI GdipSetClipGraphics(GpGraphics *graphics, GpGraphics *srcgraphics,
5508     CombineMode mode)
5509 {
5510     TRACE("(%p, %p, %d)\n", graphics, srcgraphics, mode);
5511
5512     if(!graphics || !srcgraphics)
5513         return InvalidParameter;
5514
5515     return GdipCombineRegionRegion(graphics->clip, srcgraphics->clip, mode);
5516 }
5517
5518 GpStatus WINGDIPAPI GdipSetCompositingMode(GpGraphics *graphics,
5519     CompositingMode mode)
5520 {
5521     TRACE("(%p, %d)\n", graphics, mode);
5522
5523     if(!graphics)
5524         return InvalidParameter;
5525
5526     if(graphics->busy)
5527         return ObjectBusy;
5528
5529     graphics->compmode = mode;
5530
5531     return Ok;
5532 }
5533
5534 GpStatus WINGDIPAPI GdipSetCompositingQuality(GpGraphics *graphics,
5535     CompositingQuality quality)
5536 {
5537     TRACE("(%p, %d)\n", graphics, quality);
5538
5539     if(!graphics)
5540         return InvalidParameter;
5541
5542     if(graphics->busy)
5543         return ObjectBusy;
5544
5545     graphics->compqual = quality;
5546
5547     return Ok;
5548 }
5549
5550 GpStatus WINGDIPAPI GdipSetInterpolationMode(GpGraphics *graphics,
5551     InterpolationMode mode)
5552 {
5553     TRACE("(%p, %d)\n", graphics, mode);
5554
5555     if(!graphics || mode == InterpolationModeInvalid || mode > InterpolationModeHighQualityBicubic)
5556         return InvalidParameter;
5557
5558     if(graphics->busy)
5559         return ObjectBusy;
5560
5561     if (mode == InterpolationModeDefault || mode == InterpolationModeLowQuality)
5562         mode = InterpolationModeBilinear;
5563
5564     if (mode == InterpolationModeHighQuality)
5565         mode = InterpolationModeHighQualityBicubic;
5566
5567     graphics->interpolation = mode;
5568
5569     return Ok;
5570 }
5571
5572 GpStatus WINGDIPAPI GdipSetPageScale(GpGraphics *graphics, REAL scale)
5573 {
5574     TRACE("(%p, %.2f)\n", graphics, scale);
5575
5576     if(!graphics || (scale <= 0.0))
5577         return InvalidParameter;
5578
5579     if(graphics->busy)
5580         return ObjectBusy;
5581
5582     graphics->scale = scale;
5583
5584     return Ok;
5585 }
5586
5587 GpStatus WINGDIPAPI GdipSetPageUnit(GpGraphics *graphics, GpUnit unit)
5588 {
5589     TRACE("(%p, %d)\n", graphics, unit);
5590
5591     if(!graphics)
5592         return InvalidParameter;
5593
5594     if(graphics->busy)
5595         return ObjectBusy;
5596
5597     if(unit == UnitWorld)
5598         return InvalidParameter;
5599
5600     graphics->unit = unit;
5601
5602     return Ok;
5603 }
5604
5605 GpStatus WINGDIPAPI GdipSetPixelOffsetMode(GpGraphics *graphics, PixelOffsetMode
5606     mode)
5607 {
5608     TRACE("(%p, %d)\n", graphics, mode);
5609
5610     if(!graphics)
5611         return InvalidParameter;
5612
5613     if(graphics->busy)
5614         return ObjectBusy;
5615
5616     graphics->pixeloffset = mode;
5617
5618     return Ok;
5619 }
5620
5621 GpStatus WINGDIPAPI GdipSetRenderingOrigin(GpGraphics *graphics, INT x, INT y)
5622 {
5623     static int calls;
5624
5625     TRACE("(%p,%i,%i)\n", graphics, x, y);
5626
5627     if (!(calls++))
5628         FIXME("value is unused in rendering\n");
5629
5630     if (!graphics)
5631         return InvalidParameter;
5632
5633     graphics->origin_x = x;
5634     graphics->origin_y = y;
5635
5636     return Ok;
5637 }
5638
5639 GpStatus WINGDIPAPI GdipGetRenderingOrigin(GpGraphics *graphics, INT *x, INT *y)
5640 {
5641     TRACE("(%p,%p,%p)\n", graphics, x, y);
5642
5643     if (!graphics || !x || !y)
5644         return InvalidParameter;
5645
5646     *x = graphics->origin_x;
5647     *y = graphics->origin_y;
5648
5649     return Ok;
5650 }
5651
5652 GpStatus WINGDIPAPI GdipSetSmoothingMode(GpGraphics *graphics, SmoothingMode mode)
5653 {
5654     TRACE("(%p, %d)\n", graphics, mode);
5655
5656     if(!graphics)
5657         return InvalidParameter;
5658
5659     if(graphics->busy)
5660         return ObjectBusy;
5661
5662     graphics->smoothing = mode;
5663
5664     return Ok;
5665 }
5666
5667 GpStatus WINGDIPAPI GdipSetTextContrast(GpGraphics *graphics, UINT contrast)
5668 {
5669     TRACE("(%p, %d)\n", graphics, contrast);
5670
5671     if(!graphics)
5672         return InvalidParameter;
5673
5674     graphics->textcontrast = contrast;
5675
5676     return Ok;
5677 }
5678
5679 GpStatus WINGDIPAPI GdipSetTextRenderingHint(GpGraphics *graphics,
5680     TextRenderingHint hint)
5681 {
5682     TRACE("(%p, %d)\n", graphics, hint);
5683
5684     if(!graphics || hint > TextRenderingHintClearTypeGridFit)
5685         return InvalidParameter;
5686
5687     if(graphics->busy)
5688         return ObjectBusy;
5689
5690     graphics->texthint = hint;
5691
5692     return Ok;
5693 }
5694
5695 GpStatus WINGDIPAPI GdipSetWorldTransform(GpGraphics *graphics, GpMatrix *matrix)
5696 {
5697     TRACE("(%p, %p)\n", graphics, matrix);
5698
5699     if(!graphics || !matrix)
5700         return InvalidParameter;
5701
5702     if(graphics->busy)
5703         return ObjectBusy;
5704
5705     TRACE("%f,%f,%f,%f,%f,%f\n",
5706           matrix->matrix[0], matrix->matrix[1], matrix->matrix[2],
5707           matrix->matrix[3], matrix->matrix[4], matrix->matrix[5]);
5708
5709     graphics->worldtrans = *matrix;
5710
5711     return Ok;
5712 }
5713
5714 GpStatus WINGDIPAPI GdipTranslateWorldTransform(GpGraphics *graphics, REAL dx,
5715     REAL dy, GpMatrixOrder order)
5716 {
5717     TRACE("(%p, %.2f, %.2f, %d)\n", graphics, dx, dy, order);
5718
5719     if(!graphics)
5720         return InvalidParameter;
5721
5722     if(graphics->busy)
5723         return ObjectBusy;
5724
5725     return GdipTranslateMatrix(&graphics->worldtrans, dx, dy, order);
5726 }
5727
5728 /*****************************************************************************
5729  * GdipSetClipHrgn [GDIPLUS.@]
5730  */
5731 GpStatus WINGDIPAPI GdipSetClipHrgn(GpGraphics *graphics, HRGN hrgn, CombineMode mode)
5732 {
5733     GpRegion *region;
5734     GpStatus status;
5735
5736     TRACE("(%p, %p, %d)\n", graphics, hrgn, mode);
5737
5738     if(!graphics)
5739         return InvalidParameter;
5740
5741     status = GdipCreateRegionHrgn(hrgn, &region);
5742     if(status != Ok)
5743         return status;
5744
5745     status = GdipSetClipRegion(graphics, region, mode);
5746
5747     GdipDeleteRegion(region);
5748     return status;
5749 }
5750
5751 GpStatus WINGDIPAPI GdipSetClipPath(GpGraphics *graphics, GpPath *path, CombineMode mode)
5752 {
5753     TRACE("(%p, %p, %d)\n", graphics, path, mode);
5754
5755     if(!graphics)
5756         return InvalidParameter;
5757
5758     if(graphics->busy)
5759         return ObjectBusy;
5760
5761     return GdipCombineRegionPath(graphics->clip, path, mode);
5762 }
5763
5764 GpStatus WINGDIPAPI GdipSetClipRect(GpGraphics *graphics, REAL x, REAL y,
5765                                     REAL width, REAL height,
5766                                     CombineMode mode)
5767 {
5768     GpRectF rect;
5769
5770     TRACE("(%p, %.2f, %.2f, %.2f, %.2f, %d)\n", graphics, x, y, width, height, mode);
5771
5772     if(!graphics)
5773         return InvalidParameter;
5774
5775     if(graphics->busy)
5776         return ObjectBusy;
5777
5778     rect.X = x;
5779     rect.Y = y;
5780     rect.Width  = width;
5781     rect.Height = height;
5782
5783     return GdipCombineRegionRect(graphics->clip, &rect, mode);
5784 }
5785
5786 GpStatus WINGDIPAPI GdipSetClipRectI(GpGraphics *graphics, INT x, INT y,
5787                                      INT width, INT height,
5788                                      CombineMode mode)
5789 {
5790     TRACE("(%p, %d, %d, %d, %d, %d)\n", graphics, x, y, width, height, mode);
5791
5792     if(!graphics)
5793         return InvalidParameter;
5794
5795     if(graphics->busy)
5796         return ObjectBusy;
5797
5798     return GdipSetClipRect(graphics, (REAL)x, (REAL)y, (REAL)width, (REAL)height, mode);
5799 }
5800
5801 GpStatus WINGDIPAPI GdipSetClipRegion(GpGraphics *graphics, GpRegion *region,
5802                                       CombineMode mode)
5803 {
5804     TRACE("(%p, %p, %d)\n", graphics, region, mode);
5805
5806     if(!graphics || !region)
5807         return InvalidParameter;
5808
5809     if(graphics->busy)
5810         return ObjectBusy;
5811
5812     return GdipCombineRegionRegion(graphics->clip, region, mode);
5813 }
5814
5815 GpStatus WINGDIPAPI GdipSetMetafileDownLevelRasterizationLimit(GpMetafile *metafile,
5816     UINT limitDpi)
5817 {
5818     static int calls;
5819
5820     TRACE("(%p,%u)\n", metafile, limitDpi);
5821
5822     if(!(calls++))
5823         FIXME("not implemented\n");
5824
5825     return NotImplemented;
5826 }
5827
5828 GpStatus WINGDIPAPI GdipDrawPolygon(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPointF *points,
5829     INT count)
5830 {
5831     INT save_state;
5832     POINT *pti;
5833
5834     TRACE("(%p, %p, %d)\n", graphics, points, count);
5835
5836     if(!graphics || !pen || count<=0)
5837         return InvalidParameter;
5838
5839     if(graphics->busy)
5840         return ObjectBusy;
5841
5842     if (!graphics->hdc)
5843     {
5844         FIXME("graphics object has no HDC\n");
5845         return Ok;
5846     }
5847
5848     pti = GdipAlloc(sizeof(POINT) * count);
5849
5850     save_state = prepare_dc(graphics, pen);
5851     SelectObject(graphics->hdc, GetStockObject(NULL_BRUSH));
5852
5853     transform_and_round_points(graphics, pti, (GpPointF*)points, count);
5854     Polygon(graphics->hdc, pti, count);
5855
5856     restore_dc(graphics, save_state);
5857     GdipFree(pti);
5858
5859     return Ok;
5860 }
5861
5862 GpStatus WINGDIPAPI GdipDrawPolygonI(GpGraphics *graphics,GpPen *pen,GDIPCONST GpPoint *points,
5863     INT count)
5864 {
5865     GpStatus ret;
5866     GpPointF *ptf;
5867     INT i;
5868
5869     TRACE("(%p, %p, %p, %d)\n", graphics, pen, points, count);
5870
5871     if(count<=0)    return InvalidParameter;
5872     ptf = GdipAlloc(sizeof(GpPointF) * count);
5873
5874     for(i = 0;i < count; i++){
5875         ptf[i].X = (REAL)points[i].X;
5876         ptf[i].Y = (REAL)points[i].Y;
5877     }
5878
5879     ret = GdipDrawPolygon(graphics,pen,ptf,count);
5880     GdipFree(ptf);
5881
5882     return ret;
5883 }
5884
5885 GpStatus WINGDIPAPI GdipGetDpiX(GpGraphics *graphics, REAL* dpi)
5886 {
5887     TRACE("(%p, %p)\n", graphics, dpi);
5888
5889     if(!graphics || !dpi)
5890         return InvalidParameter;
5891
5892     if(graphics->busy)
5893         return ObjectBusy;
5894
5895     *dpi = graphics->xres;
5896     return Ok;
5897 }
5898
5899 GpStatus WINGDIPAPI GdipGetDpiY(GpGraphics *graphics, REAL* dpi)
5900 {
5901     TRACE("(%p, %p)\n", graphics, dpi);
5902
5903     if(!graphics || !dpi)
5904         return InvalidParameter;
5905
5906     if(graphics->busy)
5907         return ObjectBusy;
5908
5909     *dpi = graphics->yres;
5910     return Ok;
5911 }
5912
5913 GpStatus WINGDIPAPI GdipMultiplyWorldTransform(GpGraphics *graphics, GDIPCONST GpMatrix *matrix,
5914     GpMatrixOrder order)
5915 {
5916     GpMatrix m;
5917     GpStatus ret;
5918
5919     TRACE("(%p, %p, %d)\n", graphics, matrix, order);
5920
5921     if(!graphics || !matrix)
5922         return InvalidParameter;
5923
5924     if(graphics->busy)
5925         return ObjectBusy;
5926
5927     m = graphics->worldtrans;
5928
5929     ret = GdipMultiplyMatrix(&m, matrix, order);
5930     if(ret == Ok)
5931         graphics->worldtrans = m;
5932
5933     return ret;
5934 }
5935
5936 /* Color used to fill bitmaps so we can tell which parts have been drawn over by gdi32. */
5937 static const COLORREF DC_BACKGROUND_KEY = 0x0c0b0d;
5938
5939 GpStatus WINGDIPAPI GdipGetDC(GpGraphics *graphics, HDC *hdc)
5940 {
5941     GpStatus stat=Ok;
5942
5943     TRACE("(%p, %p)\n", graphics, hdc);
5944
5945     if(!graphics || !hdc)
5946         return InvalidParameter;
5947
5948     if(graphics->busy)
5949         return ObjectBusy;
5950
5951     if (graphics->image && graphics->image->type == ImageTypeMetafile)
5952     {
5953         stat = METAFILE_GetDC((GpMetafile*)graphics->image, hdc);
5954     }
5955     else if (!graphics->hdc ||
5956         (graphics->image && graphics->image->type == ImageTypeBitmap && ((GpBitmap*)graphics->image)->format & PixelFormatAlpha))
5957     {
5958         /* Create a fake HDC and fill it with a constant color. */
5959         HDC temp_hdc;
5960         HBITMAP hbitmap;
5961         GpRectF bounds;
5962         BITMAPINFOHEADER bmih;
5963         int i;
5964
5965         stat = get_graphics_bounds(graphics, &bounds);
5966         if (stat != Ok)
5967             return stat;
5968
5969         graphics->temp_hbitmap_width = bounds.Width;
5970         graphics->temp_hbitmap_height = bounds.Height;
5971
5972         bmih.biSize = sizeof(bmih);
5973         bmih.biWidth = graphics->temp_hbitmap_width;
5974         bmih.biHeight = -graphics->temp_hbitmap_height;
5975         bmih.biPlanes = 1;
5976         bmih.biBitCount = 32;
5977         bmih.biCompression = BI_RGB;
5978         bmih.biSizeImage = 0;
5979         bmih.biXPelsPerMeter = 0;
5980         bmih.biYPelsPerMeter = 0;
5981         bmih.biClrUsed = 0;
5982         bmih.biClrImportant = 0;
5983
5984         hbitmap = CreateDIBSection(NULL, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
5985             (void**)&graphics->temp_bits, NULL, 0);
5986         if (!hbitmap)
5987             return GenericError;
5988
5989         temp_hdc = CreateCompatibleDC(0);
5990         if (!temp_hdc)
5991         {
5992             DeleteObject(hbitmap);
5993             return GenericError;
5994         }
5995
5996         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
5997             ((DWORD*)graphics->temp_bits)[i] = DC_BACKGROUND_KEY;
5998
5999         SelectObject(temp_hdc, hbitmap);
6000
6001         graphics->temp_hbitmap = hbitmap;
6002         *hdc = graphics->temp_hdc = temp_hdc;
6003     }
6004     else
6005     {
6006         *hdc = graphics->hdc;
6007     }
6008
6009     if (stat == Ok)
6010         graphics->busy = TRUE;
6011
6012     return stat;
6013 }
6014
6015 GpStatus WINGDIPAPI GdipReleaseDC(GpGraphics *graphics, HDC hdc)
6016 {
6017     GpStatus stat=Ok;
6018
6019     TRACE("(%p, %p)\n", graphics, hdc);
6020
6021     if(!graphics || !hdc || !graphics->busy)
6022         return InvalidParameter;
6023
6024     if (graphics->image && graphics->image->type == ImageTypeMetafile)
6025     {
6026         stat = METAFILE_ReleaseDC((GpMetafile*)graphics->image, hdc);
6027     }
6028     else if (graphics->temp_hdc == hdc)
6029     {
6030         DWORD* pos;
6031         int i;
6032
6033         /* Find the pixels that have changed, and mark them as opaque. */
6034         pos = (DWORD*)graphics->temp_bits;
6035         for (i=0; i<(graphics->temp_hbitmap_width * graphics->temp_hbitmap_height); i++)
6036         {
6037             if (*pos != DC_BACKGROUND_KEY)
6038             {
6039                 *pos |= 0xff000000;
6040             }
6041             pos++;
6042         }
6043
6044         /* Write the changed pixels to the real target. */
6045         alpha_blend_pixels(graphics, 0, 0, graphics->temp_bits,
6046             graphics->temp_hbitmap_width, graphics->temp_hbitmap_height,
6047             graphics->temp_hbitmap_width * 4);
6048
6049         /* Clean up. */
6050         DeleteDC(graphics->temp_hdc);
6051         DeleteObject(graphics->temp_hbitmap);
6052         graphics->temp_hdc = NULL;
6053         graphics->temp_hbitmap = NULL;
6054     }
6055     else if (hdc != graphics->hdc)
6056     {
6057         stat = InvalidParameter;
6058     }
6059
6060     if (stat == Ok)
6061         graphics->busy = FALSE;
6062
6063     return stat;
6064 }
6065
6066 GpStatus WINGDIPAPI GdipGetClip(GpGraphics *graphics, GpRegion *region)
6067 {
6068     GpRegion *clip;
6069     GpStatus status;
6070
6071     TRACE("(%p, %p)\n", graphics, region);
6072
6073     if(!graphics || !region)
6074         return InvalidParameter;
6075
6076     if(graphics->busy)
6077         return ObjectBusy;
6078
6079     if((status = GdipCloneRegion(graphics->clip, &clip)) != Ok)
6080         return status;
6081
6082     /* free everything except root node and header */
6083     delete_element(&region->node);
6084     memcpy(region, clip, sizeof(GpRegion));
6085     GdipFree(clip);
6086
6087     return Ok;
6088 }
6089
6090 static GpStatus get_graphics_transform(GpGraphics *graphics, GpCoordinateSpace dst_space,
6091         GpCoordinateSpace src_space, GpMatrix *matrix)
6092 {
6093     GpStatus stat = Ok;
6094     REAL scale_x, scale_y;
6095
6096     GdipSetMatrixElements(matrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
6097
6098     if (dst_space != src_space)
6099     {
6100         scale_x = units_to_pixels(1.0, graphics->unit, graphics->xres);
6101         scale_y = units_to_pixels(1.0, graphics->unit, graphics->yres);
6102
6103         if(graphics->unit != UnitDisplay)
6104         {
6105             scale_x *= graphics->scale;
6106             scale_y *= graphics->scale;
6107         }
6108
6109         /* transform from src_space to CoordinateSpacePage */
6110         switch (src_space)
6111         {
6112         case CoordinateSpaceWorld:
6113             GdipMultiplyMatrix(matrix, &graphics->worldtrans, MatrixOrderAppend);
6114             break;
6115         case CoordinateSpacePage:
6116             break;
6117         case CoordinateSpaceDevice:
6118             GdipScaleMatrix(matrix, 1.0/scale_x, 1.0/scale_y, MatrixOrderAppend);
6119             break;
6120         }
6121
6122         /* transform from CoordinateSpacePage to dst_space */
6123         switch (dst_space)
6124         {
6125         case CoordinateSpaceWorld:
6126             {
6127                 GpMatrix inverted_transform = graphics->worldtrans;
6128                 stat = GdipInvertMatrix(&inverted_transform);
6129                 if (stat == Ok)
6130                     GdipMultiplyMatrix(matrix, &inverted_transform, MatrixOrderAppend);
6131                 break;
6132             }
6133         case CoordinateSpacePage:
6134             break;
6135         case CoordinateSpaceDevice:
6136             GdipScaleMatrix(matrix, scale_x, scale_y, MatrixOrderAppend);
6137             break;
6138         }
6139     }
6140     return stat;
6141 }
6142
6143 GpStatus WINGDIPAPI GdipTransformPoints(GpGraphics *graphics, GpCoordinateSpace dst_space,
6144                                         GpCoordinateSpace src_space, GpPointF *points, INT count)
6145 {
6146     GpMatrix matrix;
6147     GpStatus stat;
6148
6149     if(!graphics || !points || count <= 0)
6150         return InvalidParameter;
6151
6152     if(graphics->busy)
6153         return ObjectBusy;
6154
6155     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
6156
6157     if (src_space == dst_space) return Ok;
6158
6159     stat = get_graphics_transform(graphics, dst_space, src_space, &matrix);
6160     if (stat != Ok) return stat;
6161
6162     return GdipTransformMatrixPoints(&matrix, points, count);
6163 }
6164
6165 GpStatus WINGDIPAPI GdipTransformPointsI(GpGraphics *graphics, GpCoordinateSpace dst_space,
6166                                          GpCoordinateSpace src_space, GpPoint *points, INT count)
6167 {
6168     GpPointF *pointsF;
6169     GpStatus ret;
6170     INT i;
6171
6172     TRACE("(%p, %d, %d, %p, %d)\n", graphics, dst_space, src_space, points, count);
6173
6174     if(count <= 0)
6175         return InvalidParameter;
6176
6177     pointsF = GdipAlloc(sizeof(GpPointF) * count);
6178     if(!pointsF)
6179         return OutOfMemory;
6180
6181     for(i = 0; i < count; i++){
6182         pointsF[i].X = (REAL)points[i].X;
6183         pointsF[i].Y = (REAL)points[i].Y;
6184     }
6185
6186     ret = GdipTransformPoints(graphics, dst_space, src_space, pointsF, count);
6187
6188     if(ret == Ok)
6189         for(i = 0; i < count; i++){
6190             points[i].X = gdip_round(pointsF[i].X);
6191             points[i].Y = gdip_round(pointsF[i].Y);
6192         }
6193     GdipFree(pointsF);
6194
6195     return ret;
6196 }
6197
6198 HPALETTE WINGDIPAPI GdipCreateHalftonePalette(void)
6199 {
6200     static int calls;
6201
6202     TRACE("\n");
6203
6204     if (!calls++)
6205       FIXME("stub\n");
6206
6207     return NULL;
6208 }
6209
6210 /*****************************************************************************
6211  * GdipTranslateClip [GDIPLUS.@]
6212  */
6213 GpStatus WINGDIPAPI GdipTranslateClip(GpGraphics *graphics, REAL dx, REAL dy)
6214 {
6215     TRACE("(%p, %.2f, %.2f)\n", graphics, dx, dy);
6216
6217     if(!graphics)
6218         return InvalidParameter;
6219
6220     if(graphics->busy)
6221         return ObjectBusy;
6222
6223     return GdipTranslateRegion(graphics->clip, dx, dy);
6224 }
6225
6226 /*****************************************************************************
6227  * GdipTranslateClipI [GDIPLUS.@]
6228  */
6229 GpStatus WINGDIPAPI GdipTranslateClipI(GpGraphics *graphics, INT dx, INT dy)
6230 {
6231     TRACE("(%p, %d, %d)\n", graphics, dx, dy);
6232
6233     if(!graphics)
6234         return InvalidParameter;
6235
6236     if(graphics->busy)
6237         return ObjectBusy;
6238
6239     return GdipTranslateRegion(graphics->clip, (REAL)dx, (REAL)dy);
6240 }
6241
6242
6243 /*****************************************************************************
6244  * GdipMeasureDriverString [GDIPLUS.@]
6245  */
6246 GpStatus WINGDIPAPI GdipMeasureDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6247                                             GDIPCONST GpFont *font, GDIPCONST PointF *positions,
6248                                             INT flags, GDIPCONST GpMatrix *matrix, RectF *boundingBox)
6249 {
6250     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
6251     HFONT hfont;
6252     HDC hdc;
6253     REAL min_x, min_y, max_x, max_y, x, y;
6254     int i;
6255     TEXTMETRICW textmetric;
6256     const WORD *glyph_indices;
6257     WORD *dynamic_glyph_indices=NULL;
6258     REAL rel_width, rel_height, ascent, descent;
6259     GpPointF pt[3];
6260
6261     TRACE("(%p %p %d %p %p %d %p %p)\n", graphics, text, length, font, positions, flags, matrix, boundingBox);
6262
6263     if (!graphics || !text || !font || !positions || !boundingBox)
6264         return InvalidParameter;
6265
6266     if (length == -1)
6267         length = strlenW(text);
6268
6269     if (length == 0)
6270     {
6271         boundingBox->X = 0.0;
6272         boundingBox->Y = 0.0;
6273         boundingBox->Width = 0.0;
6274         boundingBox->Height = 0.0;
6275     }
6276
6277     if (flags & unsupported_flags)
6278         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6279
6280     get_font_hfont(graphics, font, NULL, &hfont, matrix);
6281
6282     hdc = CreateCompatibleDC(0);
6283     SelectObject(hdc, hfont);
6284
6285     GetTextMetricsW(hdc, &textmetric);
6286
6287     pt[0].X = 0.0;
6288     pt[0].Y = 0.0;
6289     pt[1].X = 1.0;
6290     pt[1].Y = 0.0;
6291     pt[2].X = 0.0;
6292     pt[2].Y = 1.0;
6293     if (matrix)
6294     {
6295         GpMatrix xform = *matrix;
6296         GdipTransformMatrixPoints(&xform, pt, 3);
6297     }
6298     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, pt, 3);
6299     rel_width = sqrt((pt[1].Y-pt[0].Y)*(pt[1].Y-pt[0].Y)+
6300                      (pt[1].X-pt[0].X)*(pt[1].X-pt[0].X));
6301     rel_height = sqrt((pt[2].Y-pt[0].Y)*(pt[2].Y-pt[0].Y)+
6302                       (pt[2].X-pt[0].X)*(pt[2].X-pt[0].X));
6303
6304     if (flags & DriverStringOptionsCmapLookup)
6305     {
6306         glyph_indices = dynamic_glyph_indices = GdipAlloc(sizeof(WORD) * length);
6307         if (!glyph_indices)
6308         {
6309             DeleteDC(hdc);
6310             DeleteObject(hfont);
6311             return OutOfMemory;
6312         }
6313
6314         GetGlyphIndicesW(hdc, text, length, dynamic_glyph_indices, 0);
6315     }
6316     else
6317         glyph_indices = text;
6318
6319     min_x = max_x = x = positions[0].X;
6320     min_y = max_y = y = positions[0].Y;
6321
6322     ascent = textmetric.tmAscent / rel_height;
6323     descent = textmetric.tmDescent / rel_height;
6324
6325     for (i=0; i<length; i++)
6326     {
6327         int char_width;
6328         ABC abc;
6329
6330         if (!(flags & DriverStringOptionsRealizedAdvance))
6331         {
6332             x = positions[i].X;
6333             y = positions[i].Y;
6334         }
6335
6336         GetCharABCWidthsW(hdc, glyph_indices[i], glyph_indices[i], &abc);
6337         char_width = abc.abcA + abc.abcB + abc.abcC;
6338
6339         if (min_y > y - ascent) min_y = y - ascent;
6340         if (max_y < y + descent) max_y = y + descent;
6341         if (min_x > x) min_x = x;
6342
6343         x += char_width / rel_width;
6344
6345         if (max_x < x) max_x = x;
6346     }
6347
6348     GdipFree(dynamic_glyph_indices);
6349     DeleteDC(hdc);
6350     DeleteObject(hfont);
6351
6352     boundingBox->X = min_x;
6353     boundingBox->Y = min_y;
6354     boundingBox->Width = max_x - min_x;
6355     boundingBox->Height = max_y - min_y;
6356
6357     return Ok;
6358 }
6359
6360 static GpStatus GDI32_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6361                                            GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6362                                            GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6363                                            INT flags, GDIPCONST GpMatrix *matrix)
6364 {
6365     static const INT unsupported_flags = ~(DriverStringOptionsRealizedAdvance|DriverStringOptionsCmapLookup);
6366     INT save_state;
6367     GpPointF pt;
6368     HFONT hfont;
6369     UINT eto_flags=0;
6370
6371     if (flags & unsupported_flags)
6372         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6373
6374     if (!(flags & DriverStringOptionsCmapLookup))
6375         eto_flags |= ETO_GLYPH_INDEX;
6376
6377     save_state = SaveDC(graphics->hdc);
6378     SetBkMode(graphics->hdc, TRANSPARENT);
6379     SetTextColor(graphics->hdc, get_gdi_brush_color(brush));
6380
6381     pt = positions[0];
6382     GdipTransformPoints(graphics, CoordinateSpaceDevice, CoordinateSpaceWorld, &pt, 1);
6383
6384     get_font_hfont(graphics, font, format, &hfont, matrix);
6385     SelectObject(graphics->hdc, hfont);
6386
6387     SetTextAlign(graphics->hdc, TA_BASELINE|TA_LEFT);
6388
6389     ExtTextOutW(graphics->hdc, gdip_round(pt.X), gdip_round(pt.Y), eto_flags, NULL, text, length, NULL);
6390
6391     RestoreDC(graphics->hdc, save_state);
6392
6393     DeleteObject(hfont);
6394
6395     return Ok;
6396 }
6397
6398 static GpStatus SOFTWARE_GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6399                                         GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6400                                         GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6401                                         INT flags, GDIPCONST GpMatrix *matrix)
6402 {
6403     static const INT unsupported_flags = ~(DriverStringOptionsCmapLookup|DriverStringOptionsRealizedAdvance);
6404     GpStatus stat;
6405     PointF *real_positions, real_position;
6406     POINT *pti;
6407     HFONT hfont;
6408     HDC hdc;
6409     int min_x=INT_MAX, min_y=INT_MAX, max_x=INT_MIN, max_y=INT_MIN, i, x, y;
6410     DWORD max_glyphsize=0;
6411     GLYPHMETRICS glyphmetrics;
6412     static const MAT2 identity = {{0,1}, {0,0}, {0,0}, {0,1}};
6413     BYTE *glyph_mask;
6414     BYTE *text_mask;
6415     int text_mask_stride;
6416     BYTE *pixel_data;
6417     int pixel_data_stride;
6418     GpRect pixel_area;
6419     UINT ggo_flags = GGO_GRAY8_BITMAP;
6420
6421     if (length <= 0)
6422         return Ok;
6423
6424     if (!(flags & DriverStringOptionsCmapLookup))
6425         ggo_flags |= GGO_GLYPH_INDEX;
6426
6427     if (flags & unsupported_flags)
6428         FIXME("Ignoring flags %x\n", flags & unsupported_flags);
6429
6430     pti = GdipAlloc(sizeof(POINT) * length);
6431     if (!pti)
6432         return OutOfMemory;
6433
6434     if (flags & DriverStringOptionsRealizedAdvance)
6435     {
6436         real_position = positions[0];
6437
6438         transform_and_round_points(graphics, pti, &real_position, 1);
6439     }
6440     else
6441     {
6442         real_positions = GdipAlloc(sizeof(PointF) * length);
6443         if (!real_positions)
6444         {
6445             GdipFree(pti);
6446             return OutOfMemory;
6447         }
6448
6449         memcpy(real_positions, positions, sizeof(PointF) * length);
6450
6451         transform_and_round_points(graphics, pti, real_positions, length);
6452
6453         GdipFree(real_positions);
6454     }
6455
6456     get_font_hfont(graphics, font, format, &hfont, matrix);
6457
6458     hdc = CreateCompatibleDC(0);
6459     SelectObject(hdc, hfont);
6460
6461     /* Get the boundaries of the text to be drawn */
6462     for (i=0; i<length; i++)
6463     {
6464         DWORD glyphsize;
6465         int left, top, right, bottom;
6466
6467         glyphsize = GetGlyphOutlineW(hdc, text[i], ggo_flags,
6468             &glyphmetrics, 0, NULL, &identity);
6469
6470         if (glyphsize == GDI_ERROR)
6471         {
6472             ERR("GetGlyphOutlineW failed\n");
6473             GdipFree(pti);
6474             DeleteDC(hdc);
6475             DeleteObject(hfont);
6476             return GenericError;
6477         }
6478
6479         if (glyphsize > max_glyphsize)
6480             max_glyphsize = glyphsize;
6481
6482         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6483         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6484         right = pti[i].x + glyphmetrics.gmptGlyphOrigin.x + glyphmetrics.gmBlackBoxX;
6485         bottom = pti[i].y - glyphmetrics.gmptGlyphOrigin.y + glyphmetrics.gmBlackBoxY;
6486
6487         if (left < min_x) min_x = left;
6488         if (top < min_y) min_y = top;
6489         if (right > max_x) max_x = right;
6490         if (bottom > max_y) max_y = bottom;
6491
6492         if (i+1 < length && (flags & DriverStringOptionsRealizedAdvance) == DriverStringOptionsRealizedAdvance)
6493         {
6494             pti[i+1].x = pti[i].x + glyphmetrics.gmCellIncX;
6495             pti[i+1].y = pti[i].y + glyphmetrics.gmCellIncY;
6496         }
6497     }
6498
6499     glyph_mask = GdipAlloc(max_glyphsize);
6500     text_mask = GdipAlloc((max_x - min_x) * (max_y - min_y));
6501     text_mask_stride = max_x - min_x;
6502
6503     if (!(glyph_mask && text_mask))
6504     {
6505         GdipFree(glyph_mask);
6506         GdipFree(text_mask);
6507         GdipFree(pti);
6508         DeleteDC(hdc);
6509         DeleteObject(hfont);
6510         return OutOfMemory;
6511     }
6512
6513     /* Generate a mask for the text */
6514     for (i=0; i<length; i++)
6515     {
6516         int left, top, stride;
6517
6518         GetGlyphOutlineW(hdc, text[i], ggo_flags,
6519             &glyphmetrics, max_glyphsize, glyph_mask, &identity);
6520
6521         left = pti[i].x + glyphmetrics.gmptGlyphOrigin.x;
6522         top = pti[i].y - glyphmetrics.gmptGlyphOrigin.y;
6523         stride = (glyphmetrics.gmBlackBoxX + 3) & (~3);
6524
6525         for (y=0; y<glyphmetrics.gmBlackBoxY; y++)
6526         {
6527             BYTE *glyph_val = glyph_mask + y * stride;
6528             BYTE *text_val = text_mask + (left - min_x) + (top - min_y + y) * text_mask_stride;
6529             for (x=0; x<glyphmetrics.gmBlackBoxX; x++)
6530             {
6531                 *text_val = min(64, *text_val + *glyph_val);
6532                 glyph_val++;
6533                 text_val++;
6534             }
6535         }
6536     }
6537
6538     GdipFree(pti);
6539     DeleteDC(hdc);
6540     DeleteObject(hfont);
6541     GdipFree(glyph_mask);
6542
6543     /* get the brush data */
6544     pixel_data = GdipAlloc(4 * (max_x - min_x) * (max_y - min_y));
6545     if (!pixel_data)
6546     {
6547         GdipFree(text_mask);
6548         return OutOfMemory;
6549     }
6550
6551     pixel_area.X = min_x;
6552     pixel_area.Y = min_y;
6553     pixel_area.Width = max_x - min_x;
6554     pixel_area.Height = max_y - min_y;
6555     pixel_data_stride = pixel_area.Width * 4;
6556
6557     stat = brush_fill_pixels(graphics, (GpBrush*)brush, (DWORD*)pixel_data, &pixel_area, pixel_area.Width);
6558     if (stat != Ok)
6559     {
6560         GdipFree(text_mask);
6561         GdipFree(pixel_data);
6562         return stat;
6563     }
6564
6565     /* multiply the brush data by the mask */
6566     for (y=0; y<pixel_area.Height; y++)
6567     {
6568         BYTE *text_val = text_mask + text_mask_stride * y;
6569         BYTE *pixel_val = pixel_data + pixel_data_stride * y + 3;
6570         for (x=0; x<pixel_area.Width; x++)
6571         {
6572             *pixel_val = (*pixel_val) * (*text_val) / 64;
6573             text_val++;
6574             pixel_val+=4;
6575         }
6576     }
6577
6578     GdipFree(text_mask);
6579
6580     /* draw the result */
6581     stat = alpha_blend_pixels(graphics, min_x, min_y, pixel_data, pixel_area.Width,
6582         pixel_area.Height, pixel_data_stride);
6583
6584     GdipFree(pixel_data);
6585
6586     return stat;
6587 }
6588
6589 static GpStatus draw_driver_string(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6590                                    GDIPCONST GpFont *font, GDIPCONST GpStringFormat *format,
6591                                    GDIPCONST GpBrush *brush, GDIPCONST PointF *positions,
6592                                    INT flags, GDIPCONST GpMatrix *matrix)
6593 {
6594     GpStatus stat = NotImplemented;
6595
6596     if (length == -1)
6597         length = strlenW(text);
6598
6599     if (graphics->hdc &&
6600         ((flags & DriverStringOptionsRealizedAdvance) || length <= 1) &&
6601         brush->bt == BrushTypeSolidColor &&
6602         (((GpSolidFill*)brush)->color & 0xff000000) == 0xff000000)
6603         stat = GDI32_GdipDrawDriverString(graphics, text, length, font, format,
6604                                           brush, positions, flags, matrix);
6605     if (stat == NotImplemented)
6606         stat = SOFTWARE_GdipDrawDriverString(graphics, text, length, font, format,
6607                                              brush, positions, flags, matrix);
6608     return stat;
6609 }
6610
6611 /*****************************************************************************
6612  * GdipDrawDriverString [GDIPLUS.@]
6613  */
6614 GpStatus WINGDIPAPI GdipDrawDriverString(GpGraphics *graphics, GDIPCONST UINT16 *text, INT length,
6615                                          GDIPCONST GpFont *font, GDIPCONST GpBrush *brush,
6616                                          GDIPCONST PointF *positions, INT flags,
6617                                          GDIPCONST GpMatrix *matrix )
6618 {
6619     TRACE("(%p %s %p %p %p %d %p)\n", graphics, debugstr_wn(text, length), font, brush, positions, flags, matrix);
6620
6621     if (!graphics || !text || !font || !brush || !positions)
6622         return InvalidParameter;
6623
6624     return draw_driver_string(graphics, text, length, font, NULL,
6625                               brush, positions, flags, matrix);
6626 }
6627
6628 GpStatus WINGDIPAPI GdipRecordMetafileStream(IStream *stream, HDC hdc, EmfType type, GDIPCONST GpRect *frameRect,
6629                                         MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc, GpMetafile **metafile)
6630 {
6631     FIXME("(%p %p %d %p %d %p %p): stub\n", stream, hdc, type, frameRect, frameUnit, desc, metafile);
6632     return NotImplemented;
6633 }
6634
6635 /*****************************************************************************
6636  * GdipIsVisibleClipEmpty [GDIPLUS.@]
6637  */
6638 GpStatus WINGDIPAPI GdipIsVisibleClipEmpty(GpGraphics *graphics, BOOL *res)
6639 {
6640     GpStatus stat;
6641     GpRegion* rgn;
6642
6643     TRACE("(%p, %p)\n", graphics, res);
6644
6645     if((stat = GdipCreateRegion(&rgn)) != Ok)
6646         return stat;
6647
6648     if((stat = get_visible_clip_region(graphics, rgn)) != Ok)
6649         goto cleanup;
6650
6651     stat = GdipIsEmptyRegion(rgn, graphics, res);
6652
6653 cleanup:
6654     GdipDeleteRegion(rgn);
6655     return stat;
6656 }
6657
6658 GpStatus WINGDIPAPI GdipResetPageTransform(GpGraphics *graphics)
6659 {
6660     static int calls;
6661
6662     TRACE("(%p) stub\n", graphics);
6663
6664     if(!(calls++))
6665         FIXME("not implemented\n");
6666
6667     return NotImplemented;
6668 }