gdi32: Implement SelectBrush for solid brushes.
[wine] / dlls / gdi32 / path.c
1 /*
2  * Graphics paths (BeginPath, EndPath etc.)
3  *
4  * Copyright 1997, 1998 Martin Boehme
5  *                 1999 Huw D M Davies
6  * Copyright 2005 Dmitry Timoshkov
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <assert.h>
27 #include <math.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #if defined(HAVE_FLOAT_H)
32 #include <float.h>
33 #endif
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wingdi.h"
38 #include "winerror.h"
39
40 #include "gdi_private.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(gdi);
44
45 /* Notes on the implementation
46  *
47  * The implementation is based on dynamically resizable arrays of points and
48  * flags. I dithered for a bit before deciding on this implementation, and
49  * I had even done a bit of work on a linked list version before switching
50  * to arrays. It's a bit of a tradeoff. When you use linked lists, the
51  * implementation of FlattenPath is easier, because you can rip the
52  * PT_BEZIERTO entries out of the middle of the list and link the
53  * corresponding PT_LINETO entries in. However, when you use arrays,
54  * PathToRegion becomes easier, since you can essentially just pass your array
55  * of points to CreatePolyPolygonRgn. Also, if I'd used linked lists, I would
56  * have had the extra effort of creating a chunk-based allocation scheme
57  * in order to use memory effectively. That's why I finally decided to use
58  * arrays. Note by the way that the array based implementation has the same
59  * linear time complexity that linked lists would have since the arrays grow
60  * exponentially.
61  *
62  * The points are stored in the path in device coordinates. This is
63  * consistent with the way Windows does things (for instance, see the Win32
64  * SDK documentation for GetPath).
65  *
66  * The word "stroke" appears in several places (e.g. in the flag
67  * GdiPath.newStroke). A stroke consists of a PT_MOVETO followed by one or
68  * more PT_LINETOs or PT_BEZIERTOs, up to, but not including, the next
69  * PT_MOVETO. Note that this is not the same as the definition of a figure;
70  * a figure can contain several strokes.
71  *
72  * I modified the drawing functions (MoveTo, LineTo etc.) to test whether
73  * the path is open and to call the corresponding function in path.c if this
74  * is the case. A more elegant approach would be to modify the function
75  * pointers in the DC_FUNCTIONS structure; however, this would be a lot more
76  * complex. Also, the performance degradation caused by my approach in the
77  * case where no path is open is so small that it cannot be measured.
78  *
79  * Martin Boehme
80  */
81
82 /* FIXME: A lot of stuff isn't implemented yet. There is much more to come. */
83
84 #define NUM_ENTRIES_INITIAL 16  /* Initial size of points / flags arrays  */
85 #define GROW_FACTOR_NUMER    2  /* Numerator of grow factor for the array */
86 #define GROW_FACTOR_DENOM    1  /* Denominator of grow factor             */
87
88 /* A floating point version of the POINT structure */
89 typedef struct tagFLOAT_POINT
90 {
91    double x, y;
92 } FLOAT_POINT;
93
94
95 static BOOL PATH_AddEntry(GdiPath *pPath, const POINT *pPoint, BYTE flags);
96 static BOOL PATH_PathToRegion(GdiPath *pPath, INT nPolyFillMode,
97    HRGN *pHrgn);
98 static void   PATH_EmptyPath(GdiPath *pPath);
99 static BOOL PATH_ReserveEntries(GdiPath *pPath, INT numEntries);
100 static BOOL PATH_DoArcPart(GdiPath *pPath, FLOAT_POINT corners[],
101    double angleStart, double angleEnd, BYTE startEntryType);
102 static void PATH_ScaleNormalizedPoint(FLOAT_POINT corners[], double x,
103    double y, POINT *pPoint);
104 static void PATH_NormalizePoint(FLOAT_POINT corners[], const FLOAT_POINT
105    *pPoint, double *pX, double *pY);
106 static BOOL PATH_CheckCorners(DC *dc, POINT corners[], INT x1, INT y1, INT x2, INT y2);
107
108 /* Performs a world-to-viewport transformation on the specified point (which
109  * is in floating point format).
110  */
111 static inline void INTERNAL_LPTODP_FLOAT(DC *dc, FLOAT_POINT *point)
112 {
113     double x, y;
114
115     /* Perform the transformation */
116     x = point->x;
117     y = point->y;
118     point->x = x * dc->xformWorld2Vport.eM11 +
119                y * dc->xformWorld2Vport.eM21 +
120                dc->xformWorld2Vport.eDx;
121     point->y = x * dc->xformWorld2Vport.eM12 +
122                y * dc->xformWorld2Vport.eM22 +
123                dc->xformWorld2Vport.eDy;
124 }
125
126
127 /***********************************************************************
128  *           BeginPath    (GDI32.@)
129  */
130 BOOL WINAPI BeginPath(HDC hdc)
131 {
132     BOOL ret = FALSE;
133     DC *dc = get_dc_ptr( hdc );
134
135     if (dc)
136     {
137         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pBeginPath );
138         ret = physdev->funcs->pBeginPath( physdev );
139         release_dc_ptr( dc );
140     }
141     return ret;
142 }
143
144
145 /***********************************************************************
146  *           EndPath    (GDI32.@)
147  */
148 BOOL WINAPI EndPath(HDC hdc)
149 {
150     BOOL ret = FALSE;
151     DC *dc = get_dc_ptr( hdc );
152
153     if (dc)
154     {
155         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pEndPath );
156         ret = physdev->funcs->pEndPath( physdev );
157         release_dc_ptr( dc );
158     }
159     return ret;
160 }
161
162
163 /******************************************************************************
164  * AbortPath [GDI32.@]
165  * Closes and discards paths from device context
166  *
167  * NOTES
168  *    Check that SetLastError is being called correctly
169  *
170  * PARAMS
171  *    hdc [I] Handle to device context
172  *
173  * RETURNS
174  *    Success: TRUE
175  *    Failure: FALSE
176  */
177 BOOL WINAPI AbortPath( HDC hdc )
178 {
179     BOOL ret = FALSE;
180     DC *dc = get_dc_ptr( hdc );
181
182     if (dc)
183     {
184         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pAbortPath );
185         ret = physdev->funcs->pAbortPath( physdev );
186         release_dc_ptr( dc );
187     }
188     return ret;
189 }
190
191
192 /***********************************************************************
193  *           CloseFigure    (GDI32.@)
194  *
195  * FIXME: Check that SetLastError is being called correctly
196  */
197 BOOL WINAPI CloseFigure(HDC hdc)
198 {
199     BOOL ret = FALSE;
200     DC *dc = get_dc_ptr( hdc );
201
202     if (dc)
203     {
204         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pCloseFigure );
205         ret = physdev->funcs->pCloseFigure( physdev );
206         release_dc_ptr( dc );
207     }
208     return ret;
209 }
210
211
212 /***********************************************************************
213  *           GetPath    (GDI32.@)
214  */
215 INT WINAPI GetPath(HDC hdc, LPPOINT pPoints, LPBYTE pTypes,
216    INT nSize)
217 {
218    INT ret = -1;
219    GdiPath *pPath;
220    DC *dc = get_dc_ptr( hdc );
221
222    if(!dc) return -1;
223
224    pPath = &dc->path;
225
226    /* Check that path is closed */
227    if(pPath->state!=PATH_Closed)
228    {
229       SetLastError(ERROR_CAN_NOT_COMPLETE);
230       goto done;
231    }
232
233    if(nSize==0)
234       ret = pPath->numEntriesUsed;
235    else if(nSize<pPath->numEntriesUsed)
236    {
237       SetLastError(ERROR_INVALID_PARAMETER);
238       goto done;
239    }
240    else
241    {
242       memcpy(pPoints, pPath->pPoints, sizeof(POINT)*pPath->numEntriesUsed);
243       memcpy(pTypes, pPath->pFlags, sizeof(BYTE)*pPath->numEntriesUsed);
244
245       /* Convert the points to logical coordinates */
246       if(!DPtoLP(hdc, pPoints, pPath->numEntriesUsed))
247       {
248          /* FIXME: Is this the correct value? */
249          SetLastError(ERROR_CAN_NOT_COMPLETE);
250         goto done;
251       }
252      else ret = pPath->numEntriesUsed;
253    }
254  done:
255    release_dc_ptr( dc );
256    return ret;
257 }
258
259
260 /***********************************************************************
261  *           PathToRegion    (GDI32.@)
262  *
263  * FIXME
264  *   Check that SetLastError is being called correctly
265  *
266  * The documentation does not state this explicitly, but a test under Windows
267  * shows that the region which is returned should be in device coordinates.
268  */
269 HRGN WINAPI PathToRegion(HDC hdc)
270 {
271    GdiPath *pPath;
272    HRGN  hrgnRval = 0;
273    DC *dc = get_dc_ptr( hdc );
274
275    /* Get pointer to path */
276    if(!dc) return 0;
277
278     pPath = &dc->path;
279
280    /* Check that path is closed */
281    if(pPath->state!=PATH_Closed) SetLastError(ERROR_CAN_NOT_COMPLETE);
282    else
283    {
284        /* FIXME: Should we empty the path even if conversion failed? */
285        if(PATH_PathToRegion(pPath, GetPolyFillMode(hdc), &hrgnRval))
286            PATH_EmptyPath(pPath);
287        else
288            hrgnRval=0;
289    }
290    release_dc_ptr( dc );
291    return hrgnRval;
292 }
293
294 static BOOL PATH_FillPath(DC *dc, GdiPath *pPath)
295 {
296    INT   mapMode, graphicsMode;
297    SIZE  ptViewportExt, ptWindowExt;
298    POINT ptViewportOrg, ptWindowOrg;
299    XFORM xform;
300    HRGN  hrgn;
301
302    /* Construct a region from the path and fill it */
303    if(PATH_PathToRegion(pPath, dc->polyFillMode, &hrgn))
304    {
305       /* Since PaintRgn interprets the region as being in logical coordinates
306        * but the points we store for the path are already in device
307        * coordinates, we have to set the mapping mode to MM_TEXT temporarily.
308        * Using SaveDC to save information about the mapping mode / world
309        * transform would be easier but would require more overhead, especially
310        * now that SaveDC saves the current path.
311        */
312
313       /* Save the information about the old mapping mode */
314       mapMode=GetMapMode(dc->hSelf);
315       GetViewportExtEx(dc->hSelf, &ptViewportExt);
316       GetViewportOrgEx(dc->hSelf, &ptViewportOrg);
317       GetWindowExtEx(dc->hSelf, &ptWindowExt);
318       GetWindowOrgEx(dc->hSelf, &ptWindowOrg);
319
320       /* Save world transform
321        * NB: The Windows documentation on world transforms would lead one to
322        * believe that this has to be done only in GM_ADVANCED; however, my
323        * tests show that resetting the graphics mode to GM_COMPATIBLE does
324        * not reset the world transform.
325        */
326       GetWorldTransform(dc->hSelf, &xform);
327
328       /* Set MM_TEXT */
329       SetMapMode(dc->hSelf, MM_TEXT);
330       SetViewportOrgEx(dc->hSelf, 0, 0, NULL);
331       SetWindowOrgEx(dc->hSelf, 0, 0, NULL);
332       graphicsMode=GetGraphicsMode(dc->hSelf);
333       SetGraphicsMode(dc->hSelf, GM_ADVANCED);
334       ModifyWorldTransform(dc->hSelf, &xform, MWT_IDENTITY);
335       SetGraphicsMode(dc->hSelf, graphicsMode);
336
337       /* Paint the region */
338       PaintRgn(dc->hSelf, hrgn);
339       DeleteObject(hrgn);
340       /* Restore the old mapping mode */
341       SetMapMode(dc->hSelf, mapMode);
342       SetViewportExtEx(dc->hSelf, ptViewportExt.cx, ptViewportExt.cy, NULL);
343       SetViewportOrgEx(dc->hSelf, ptViewportOrg.x, ptViewportOrg.y, NULL);
344       SetWindowExtEx(dc->hSelf, ptWindowExt.cx, ptWindowExt.cy, NULL);
345       SetWindowOrgEx(dc->hSelf, ptWindowOrg.x, ptWindowOrg.y, NULL);
346
347       /* Go to GM_ADVANCED temporarily to restore the world transform */
348       graphicsMode=GetGraphicsMode(dc->hSelf);
349       SetGraphicsMode(dc->hSelf, GM_ADVANCED);
350       SetWorldTransform(dc->hSelf, &xform);
351       SetGraphicsMode(dc->hSelf, graphicsMode);
352       return TRUE;
353    }
354    return FALSE;
355 }
356
357
358 /***********************************************************************
359  *           FillPath    (GDI32.@)
360  *
361  * FIXME
362  *    Check that SetLastError is being called correctly
363  */
364 BOOL WINAPI FillPath(HDC hdc)
365 {
366     BOOL ret = FALSE;
367     DC *dc = get_dc_ptr( hdc );
368
369     if (dc)
370     {
371         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pFillPath );
372         ret = physdev->funcs->pFillPath( physdev );
373         release_dc_ptr( dc );
374     }
375     return ret;
376 }
377
378
379 /***********************************************************************
380  *           SelectClipPath    (GDI32.@)
381  * FIXME
382  *  Check that SetLastError is being called correctly
383  */
384 BOOL WINAPI SelectClipPath(HDC hdc, INT iMode)
385 {
386     BOOL ret = FALSE;
387     DC *dc = get_dc_ptr( hdc );
388
389     if (dc)
390     {
391         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pSelectClipPath );
392         ret = physdev->funcs->pSelectClipPath( physdev, iMode );
393         release_dc_ptr( dc );
394     }
395     return ret;
396 }
397
398
399 /***********************************************************************
400  * Exported functions
401  */
402
403 /* PATH_InitGdiPath
404  *
405  * Initializes the GdiPath structure.
406  */
407 void PATH_InitGdiPath(GdiPath *pPath)
408 {
409    assert(pPath!=NULL);
410
411    pPath->state=PATH_Null;
412    pPath->pPoints=NULL;
413    pPath->pFlags=NULL;
414    pPath->numEntriesUsed=0;
415    pPath->numEntriesAllocated=0;
416 }
417
418 /* PATH_DestroyGdiPath
419  *
420  * Destroys a GdiPath structure (frees the memory in the arrays).
421  */
422 void PATH_DestroyGdiPath(GdiPath *pPath)
423 {
424    assert(pPath!=NULL);
425
426    HeapFree( GetProcessHeap(), 0, pPath->pPoints );
427    HeapFree( GetProcessHeap(), 0, pPath->pFlags );
428 }
429
430 /* PATH_AssignGdiPath
431  *
432  * Copies the GdiPath structure "pPathSrc" to "pPathDest". A deep copy is
433  * performed, i.e. the contents of the pPoints and pFlags arrays are copied,
434  * not just the pointers. Since this means that the arrays in pPathDest may
435  * need to be resized, pPathDest should have been initialized using
436  * PATH_InitGdiPath (in C++, this function would be an assignment operator,
437  * not a copy constructor).
438  * Returns TRUE if successful, else FALSE.
439  */
440 BOOL PATH_AssignGdiPath(GdiPath *pPathDest, const GdiPath *pPathSrc)
441 {
442    assert(pPathDest!=NULL && pPathSrc!=NULL);
443
444    /* Make sure destination arrays are big enough */
445    if(!PATH_ReserveEntries(pPathDest, pPathSrc->numEntriesUsed))
446       return FALSE;
447
448    /* Perform the copy operation */
449    memcpy(pPathDest->pPoints, pPathSrc->pPoints,
450       sizeof(POINT)*pPathSrc->numEntriesUsed);
451    memcpy(pPathDest->pFlags, pPathSrc->pFlags,
452       sizeof(BYTE)*pPathSrc->numEntriesUsed);
453
454    pPathDest->state=pPathSrc->state;
455    pPathDest->numEntriesUsed=pPathSrc->numEntriesUsed;
456    pPathDest->newStroke=pPathSrc->newStroke;
457
458    return TRUE;
459 }
460
461 /* PATH_MoveTo
462  *
463  * Should be called when a MoveTo is performed on a DC that has an
464  * open path. This starts a new stroke. Returns TRUE if successful, else
465  * FALSE.
466  */
467 BOOL PATH_MoveTo(DC *dc)
468 {
469    GdiPath *pPath = &dc->path;
470
471    /* Check that path is open */
472    if(pPath->state!=PATH_Open)
473       /* FIXME: Do we have to call SetLastError? */
474       return FALSE;
475
476    /* Start a new stroke */
477    pPath->newStroke=TRUE;
478
479    return TRUE;
480 }
481
482 /* PATH_LineTo
483  *
484  * Should be called when a LineTo is performed on a DC that has an
485  * open path. This adds a PT_LINETO entry to the path (and possibly
486  * a PT_MOVETO entry, if this is the first LineTo in a stroke).
487  * Returns TRUE if successful, else FALSE.
488  */
489 BOOL PATH_LineTo(DC *dc, INT x, INT y)
490 {
491    GdiPath *pPath = &dc->path;
492    POINT point, pointCurPos;
493
494    /* Check that path is open */
495    if(pPath->state!=PATH_Open)
496       return FALSE;
497
498    /* Convert point to device coordinates */
499    point.x=x;
500    point.y=y;
501    if(!LPtoDP(dc->hSelf, &point, 1))
502       return FALSE;
503
504    /* Add a PT_MOVETO if necessary */
505    if(pPath->newStroke)
506    {
507       pPath->newStroke=FALSE;
508       pointCurPos.x = dc->CursPosX;
509       pointCurPos.y = dc->CursPosY;
510       if(!LPtoDP(dc->hSelf, &pointCurPos, 1))
511          return FALSE;
512       if(!PATH_AddEntry(pPath, &pointCurPos, PT_MOVETO))
513          return FALSE;
514    }
515
516    /* Add a PT_LINETO entry */
517    return PATH_AddEntry(pPath, &point, PT_LINETO);
518 }
519
520 /* PATH_RoundRect
521  *
522  * Should be called when a call to RoundRect is performed on a DC that has
523  * an open path. Returns TRUE if successful, else FALSE.
524  *
525  * FIXME: it adds the same entries to the path as windows does, but there
526  * is an error in the bezier drawing code so that there are small pixel-size
527  * gaps when the resulting path is drawn by StrokePath()
528  */
529 BOOL PATH_RoundRect(DC *dc, INT x1, INT y1, INT x2, INT y2, INT ell_width, INT ell_height)
530 {
531    GdiPath *pPath = &dc->path;
532    POINT corners[2], pointTemp;
533    FLOAT_POINT ellCorners[2];
534
535    /* Check that path is open */
536    if(pPath->state!=PATH_Open)
537       return FALSE;
538
539    if(!PATH_CheckCorners(dc,corners,x1,y1,x2,y2))
540       return FALSE;
541
542    /* Add points to the roundrect path */
543    ellCorners[0].x = corners[1].x-ell_width;
544    ellCorners[0].y = corners[0].y;
545    ellCorners[1].x = corners[1].x;
546    ellCorners[1].y = corners[0].y+ell_height;
547    if(!PATH_DoArcPart(pPath, ellCorners, 0, -M_PI_2, PT_MOVETO))
548       return FALSE;
549    pointTemp.x = corners[0].x+ell_width/2;
550    pointTemp.y = corners[0].y;
551    if(!PATH_AddEntry(pPath, &pointTemp, PT_LINETO))
552       return FALSE;
553    ellCorners[0].x = corners[0].x;
554    ellCorners[1].x = corners[0].x+ell_width;
555    if(!PATH_DoArcPart(pPath, ellCorners, -M_PI_2, -M_PI, FALSE))
556       return FALSE;
557    pointTemp.x = corners[0].x;
558    pointTemp.y = corners[1].y-ell_height/2;
559    if(!PATH_AddEntry(pPath, &pointTemp, PT_LINETO))
560       return FALSE;
561    ellCorners[0].y = corners[1].y-ell_height;
562    ellCorners[1].y = corners[1].y;
563    if(!PATH_DoArcPart(pPath, ellCorners, M_PI, M_PI_2, FALSE))
564       return FALSE;
565    pointTemp.x = corners[1].x-ell_width/2;
566    pointTemp.y = corners[1].y;
567    if(!PATH_AddEntry(pPath, &pointTemp, PT_LINETO))
568       return FALSE;
569    ellCorners[0].x = corners[1].x-ell_width;
570    ellCorners[1].x = corners[1].x;
571    if(!PATH_DoArcPart(pPath, ellCorners, M_PI_2, 0, FALSE))
572       return FALSE;
573
574    /* Close the roundrect figure */
575    if(!CloseFigure(dc->hSelf))
576       return FALSE;
577
578    return TRUE;
579 }
580
581 /* PATH_Rectangle
582  *
583  * Should be called when a call to Rectangle is performed on a DC that has
584  * an open path. Returns TRUE if successful, else FALSE.
585  */
586 BOOL PATH_Rectangle(DC *dc, INT x1, INT y1, INT x2, INT y2)
587 {
588    GdiPath *pPath = &dc->path;
589    POINT corners[2], pointTemp;
590
591    /* Check that path is open */
592    if(pPath->state!=PATH_Open)
593       return FALSE;
594
595    if(!PATH_CheckCorners(dc,corners,x1,y1,x2,y2))
596       return FALSE;
597
598    /* Close any previous figure */
599    if(!CloseFigure(dc->hSelf))
600    {
601       /* The CloseFigure call shouldn't have failed */
602       assert(FALSE);
603       return FALSE;
604    }
605
606    /* Add four points to the path */
607    pointTemp.x=corners[1].x;
608    pointTemp.y=corners[0].y;
609    if(!PATH_AddEntry(pPath, &pointTemp, PT_MOVETO))
610       return FALSE;
611    if(!PATH_AddEntry(pPath, corners, PT_LINETO))
612       return FALSE;
613    pointTemp.x=corners[0].x;
614    pointTemp.y=corners[1].y;
615    if(!PATH_AddEntry(pPath, &pointTemp, PT_LINETO))
616       return FALSE;
617    if(!PATH_AddEntry(pPath, corners+1, PT_LINETO))
618       return FALSE;
619
620    /* Close the rectangle figure */
621    if(!CloseFigure(dc->hSelf))
622    {
623       /* The CloseFigure call shouldn't have failed */
624       assert(FALSE);
625       return FALSE;
626    }
627
628    return TRUE;
629 }
630
631 /* PATH_Ellipse
632  *
633  * Should be called when a call to Ellipse is performed on a DC that has
634  * an open path. This adds four Bezier splines representing the ellipse
635  * to the path. Returns TRUE if successful, else FALSE.
636  */
637 BOOL PATH_Ellipse(DC *dc, INT x1, INT y1, INT x2, INT y2)
638 {
639    return( PATH_Arc(dc, x1, y1, x2, y2, x1, (y1+y2)/2, x1, (y1+y2)/2,0) &&
640            CloseFigure(dc->hSelf) );
641 }
642
643 /* PATH_Arc
644  *
645  * Should be called when a call to Arc is performed on a DC that has
646  * an open path. This adds up to five Bezier splines representing the arc
647  * to the path. When 'lines' is 1, we add 1 extra line to get a chord,
648  * when 'lines' is 2, we add 2 extra lines to get a pie, and when 'lines' is
649  * -1 we add 1 extra line from the current DC position to the starting position
650  * of the arc before drawing the arc itself (arcto). Returns TRUE if successful,
651  * else FALSE.
652  */
653 BOOL PATH_Arc(DC *dc, INT x1, INT y1, INT x2, INT y2,
654    INT xStart, INT yStart, INT xEnd, INT yEnd, INT lines)
655 {
656    GdiPath     *pPath = &dc->path;
657    double      angleStart, angleEnd, angleStartQuadrant, angleEndQuadrant=0.0;
658                /* Initialize angleEndQuadrant to silence gcc's warning */
659    double      x, y;
660    FLOAT_POINT corners[2], pointStart, pointEnd;
661    POINT       centre, pointCurPos;
662    BOOL      start, end;
663    INT       temp;
664
665    /* FIXME: This function should check for all possible error returns */
666    /* FIXME: Do we have to respect newStroke? */
667
668    /* Check that path is open */
669    if(pPath->state!=PATH_Open)
670       return FALSE;
671
672    /* Check for zero height / width */
673    /* FIXME: Only in GM_COMPATIBLE? */
674    if(x1==x2 || y1==y2)
675       return TRUE;
676
677    /* Convert points to device coordinates */
678    corners[0].x = x1;
679    corners[0].y = y1;
680    corners[1].x = x2;
681    corners[1].y = y2;
682    pointStart.x = xStart;
683    pointStart.y = yStart;
684    pointEnd.x = xEnd;
685    pointEnd.y = yEnd;
686    INTERNAL_LPTODP_FLOAT(dc, corners);
687    INTERNAL_LPTODP_FLOAT(dc, corners+1);
688    INTERNAL_LPTODP_FLOAT(dc, &pointStart);
689    INTERNAL_LPTODP_FLOAT(dc, &pointEnd);
690
691    /* Make sure first corner is top left and second corner is bottom right */
692    if(corners[0].x>corners[1].x)
693    {
694       temp=corners[0].x;
695       corners[0].x=corners[1].x;
696       corners[1].x=temp;
697    }
698    if(corners[0].y>corners[1].y)
699    {
700       temp=corners[0].y;
701       corners[0].y=corners[1].y;
702       corners[1].y=temp;
703    }
704
705    /* Compute start and end angle */
706    PATH_NormalizePoint(corners, &pointStart, &x, &y);
707    angleStart=atan2(y, x);
708    PATH_NormalizePoint(corners, &pointEnd, &x, &y);
709    angleEnd=atan2(y, x);
710
711    /* Make sure the end angle is "on the right side" of the start angle */
712    if(dc->ArcDirection==AD_CLOCKWISE)
713    {
714       if(angleEnd<=angleStart)
715       {
716          angleEnd+=2*M_PI;
717          assert(angleEnd>=angleStart);
718       }
719    }
720    else
721    {
722       if(angleEnd>=angleStart)
723       {
724          angleEnd-=2*M_PI;
725          assert(angleEnd<=angleStart);
726       }
727    }
728
729    /* In GM_COMPATIBLE, don't include bottom and right edges */
730    if(dc->GraphicsMode==GM_COMPATIBLE)
731    {
732       corners[1].x--;
733       corners[1].y--;
734    }
735
736    /* arcto: Add a PT_MOVETO only if this is the first entry in a stroke */
737    if(lines==-1 && pPath->newStroke)
738    {
739       pPath->newStroke=FALSE;
740       pointCurPos.x = dc->CursPosX;
741       pointCurPos.y = dc->CursPosY;
742       if(!LPtoDP(dc->hSelf, &pointCurPos, 1))
743          return FALSE;
744       if(!PATH_AddEntry(pPath, &pointCurPos, PT_MOVETO))
745          return FALSE;
746    }
747
748    /* Add the arc to the path with one Bezier spline per quadrant that the
749     * arc spans */
750    start=TRUE;
751    end=FALSE;
752    do
753    {
754       /* Determine the start and end angles for this quadrant */
755       if(start)
756       {
757          angleStartQuadrant=angleStart;
758          if(dc->ArcDirection==AD_CLOCKWISE)
759             angleEndQuadrant=(floor(angleStart/M_PI_2)+1.0)*M_PI_2;
760          else
761             angleEndQuadrant=(ceil(angleStart/M_PI_2)-1.0)*M_PI_2;
762       }
763       else
764       {
765          angleStartQuadrant=angleEndQuadrant;
766          if(dc->ArcDirection==AD_CLOCKWISE)
767             angleEndQuadrant+=M_PI_2;
768          else
769             angleEndQuadrant-=M_PI_2;
770       }
771
772       /* Have we reached the last part of the arc? */
773       if((dc->ArcDirection==AD_CLOCKWISE &&
774          angleEnd<angleEndQuadrant) ||
775          (dc->ArcDirection==AD_COUNTERCLOCKWISE &&
776          angleEnd>angleEndQuadrant))
777       {
778          /* Adjust the end angle for this quadrant */
779          angleEndQuadrant=angleEnd;
780          end=TRUE;
781       }
782
783       /* Add the Bezier spline to the path */
784       PATH_DoArcPart(pPath, corners, angleStartQuadrant, angleEndQuadrant,
785          start ? (lines==-1 ? PT_LINETO : PT_MOVETO) : FALSE);
786       start=FALSE;
787    }  while(!end);
788
789    /* chord: close figure. pie: add line and close figure */
790    if(lines==1)
791    {
792       if(!CloseFigure(dc->hSelf))
793          return FALSE;
794    }
795    else if(lines==2)
796    {
797       centre.x = (corners[0].x+corners[1].x)/2;
798       centre.y = (corners[0].y+corners[1].y)/2;
799       if(!PATH_AddEntry(pPath, &centre, PT_LINETO | PT_CLOSEFIGURE))
800          return FALSE;
801    }
802
803    return TRUE;
804 }
805
806 BOOL PATH_PolyBezierTo(DC *dc, const POINT *pts, DWORD cbPoints)
807 {
808    GdiPath     *pPath = &dc->path;
809    POINT       pt;
810    UINT        i;
811
812    /* Check that path is open */
813    if(pPath->state!=PATH_Open)
814       return FALSE;
815
816    /* Add a PT_MOVETO if necessary */
817    if(pPath->newStroke)
818    {
819       pPath->newStroke=FALSE;
820       pt.x = dc->CursPosX;
821       pt.y = dc->CursPosY;
822       if(!LPtoDP(dc->hSelf, &pt, 1))
823          return FALSE;
824       if(!PATH_AddEntry(pPath, &pt, PT_MOVETO))
825          return FALSE;
826    }
827
828    for(i = 0; i < cbPoints; i++) {
829        pt = pts[i];
830        if(!LPtoDP(dc->hSelf, &pt, 1))
831            return FALSE;
832        PATH_AddEntry(pPath, &pt, PT_BEZIERTO);
833    }
834    return TRUE;
835 }
836
837 BOOL PATH_PolyBezier(DC *dc, const POINT *pts, DWORD cbPoints)
838 {
839    GdiPath     *pPath = &dc->path;
840    POINT       pt;
841    UINT        i;
842
843    /* Check that path is open */
844    if(pPath->state!=PATH_Open)
845       return FALSE;
846
847    for(i = 0; i < cbPoints; i++) {
848        pt = pts[i];
849        if(!LPtoDP(dc->hSelf, &pt, 1))
850            return FALSE;
851        PATH_AddEntry(pPath, &pt, (i == 0) ? PT_MOVETO : PT_BEZIERTO);
852    }
853    return TRUE;
854 }
855
856 /* PATH_PolyDraw
857  *
858  * Should be called when a call to PolyDraw is performed on a DC that has
859  * an open path. Returns TRUE if successful, else FALSE.
860  */
861 BOOL PATH_PolyDraw(DC *dc, const POINT *pts, const BYTE *types,
862     DWORD cbPoints)
863 {
864         GdiPath     *pPath = &dc->path;
865         POINT       lastmove, orig_pos;
866         INT         i;
867
868         lastmove.x = orig_pos.x = dc->CursPosX;
869         lastmove.y = orig_pos.y = dc->CursPosY;
870
871         for(i = pPath->numEntriesUsed - 1; i >= 0; i--){
872             if(pPath->pFlags[i] == PT_MOVETO){
873                 lastmove.x = pPath->pPoints[i].x;
874                 lastmove.y = pPath->pPoints[i].y;
875                 if(!DPtoLP(dc->hSelf, &lastmove, 1))
876                     return FALSE;
877                 break;
878             }
879         }
880
881         for(i = 0; i < cbPoints; i++){
882             if(types[i] == PT_MOVETO){
883                 pPath->newStroke = TRUE;
884                 lastmove.x = pts[i].x;
885                 lastmove.y = pts[i].y;
886             }
887             else if((types[i] & ~PT_CLOSEFIGURE) == PT_LINETO){
888                 PATH_LineTo(dc, pts[i].x, pts[i].y);
889             }
890             else if(types[i] == PT_BEZIERTO){
891                 if(!((i + 2 < cbPoints) && (types[i + 1] == PT_BEZIERTO)
892                     && ((types[i + 2] & ~PT_CLOSEFIGURE) == PT_BEZIERTO)))
893                     goto err;
894                 PATH_PolyBezierTo(dc, &(pts[i]), 3);
895                 i += 2;
896             }
897             else
898                 goto err;
899
900             dc->CursPosX = pts[i].x;
901             dc->CursPosY = pts[i].y;
902
903             if(types[i] & PT_CLOSEFIGURE){
904                 pPath->pFlags[pPath->numEntriesUsed-1] |= PT_CLOSEFIGURE;
905                 pPath->newStroke = TRUE;
906                 dc->CursPosX = lastmove.x;
907                 dc->CursPosY = lastmove.y;
908             }
909         }
910
911         return TRUE;
912
913 err:
914         if((dc->CursPosX != orig_pos.x) || (dc->CursPosY != orig_pos.y)){
915             pPath->newStroke = TRUE;
916             dc->CursPosX = orig_pos.x;
917             dc->CursPosY = orig_pos.y;
918         }
919
920         return FALSE;
921 }
922
923 BOOL PATH_Polyline(DC *dc, const POINT *pts, DWORD cbPoints)
924 {
925    GdiPath     *pPath = &dc->path;
926    POINT       pt;
927    UINT        i;
928
929    /* Check that path is open */
930    if(pPath->state!=PATH_Open)
931       return FALSE;
932
933    for(i = 0; i < cbPoints; i++) {
934        pt = pts[i];
935        if(!LPtoDP(dc->hSelf, &pt, 1))
936            return FALSE;
937        PATH_AddEntry(pPath, &pt, (i == 0) ? PT_MOVETO : PT_LINETO);
938    }
939    return TRUE;
940 }
941
942 BOOL PATH_PolylineTo(DC *dc, const POINT *pts, DWORD cbPoints)
943 {
944    GdiPath     *pPath = &dc->path;
945    POINT       pt;
946    UINT        i;
947
948    /* Check that path is open */
949    if(pPath->state!=PATH_Open)
950       return FALSE;
951
952    /* Add a PT_MOVETO if necessary */
953    if(pPath->newStroke)
954    {
955       pPath->newStroke=FALSE;
956       pt.x = dc->CursPosX;
957       pt.y = dc->CursPosY;
958       if(!LPtoDP(dc->hSelf, &pt, 1))
959          return FALSE;
960       if(!PATH_AddEntry(pPath, &pt, PT_MOVETO))
961          return FALSE;
962    }
963
964    for(i = 0; i < cbPoints; i++) {
965        pt = pts[i];
966        if(!LPtoDP(dc->hSelf, &pt, 1))
967            return FALSE;
968        PATH_AddEntry(pPath, &pt, PT_LINETO);
969    }
970
971    return TRUE;
972 }
973
974
975 BOOL PATH_Polygon(DC *dc, const POINT *pts, DWORD cbPoints)
976 {
977    GdiPath     *pPath = &dc->path;
978    POINT       pt;
979    UINT        i;
980
981    /* Check that path is open */
982    if(pPath->state!=PATH_Open)
983       return FALSE;
984
985    for(i = 0; i < cbPoints; i++) {
986        pt = pts[i];
987        if(!LPtoDP(dc->hSelf, &pt, 1))
988            return FALSE;
989        PATH_AddEntry(pPath, &pt, (i == 0) ? PT_MOVETO :
990                      ((i == cbPoints-1) ? PT_LINETO | PT_CLOSEFIGURE :
991                       PT_LINETO));
992    }
993    return TRUE;
994 }
995
996 BOOL PATH_PolyPolygon( DC *dc, const POINT* pts, const INT* counts,
997                        UINT polygons )
998 {
999    GdiPath     *pPath = &dc->path;
1000    POINT       pt, startpt;
1001    UINT        poly, i;
1002    INT         point;
1003
1004    /* Check that path is open */
1005    if(pPath->state!=PATH_Open)
1006       return FALSE;
1007
1008    for(i = 0, poly = 0; poly < polygons; poly++) {
1009        for(point = 0; point < counts[poly]; point++, i++) {
1010            pt = pts[i];
1011            if(!LPtoDP(dc->hSelf, &pt, 1))
1012                return FALSE;
1013            if(point == 0) startpt = pt;
1014            PATH_AddEntry(pPath, &pt, (point == 0) ? PT_MOVETO : PT_LINETO);
1015        }
1016        /* win98 adds an extra line to close the figure for some reason */
1017        PATH_AddEntry(pPath, &startpt, PT_LINETO | PT_CLOSEFIGURE);
1018    }
1019    return TRUE;
1020 }
1021
1022 BOOL PATH_PolyPolyline( DC *dc, const POINT* pts, const DWORD* counts,
1023                         DWORD polylines )
1024 {
1025    GdiPath     *pPath = &dc->path;
1026    POINT       pt;
1027    UINT        poly, point, i;
1028
1029    /* Check that path is open */
1030    if(pPath->state!=PATH_Open)
1031       return FALSE;
1032
1033    for(i = 0, poly = 0; poly < polylines; poly++) {
1034        for(point = 0; point < counts[poly]; point++, i++) {
1035            pt = pts[i];
1036            if(!LPtoDP(dc->hSelf, &pt, 1))
1037                return FALSE;
1038            PATH_AddEntry(pPath, &pt, (point == 0) ? PT_MOVETO : PT_LINETO);
1039        }
1040    }
1041    return TRUE;
1042 }
1043
1044 /***********************************************************************
1045  * Internal functions
1046  */
1047
1048 /* PATH_CheckCorners
1049  *
1050  * Helper function for PATH_RoundRect() and PATH_Rectangle()
1051  */
1052 static BOOL PATH_CheckCorners(DC *dc, POINT corners[], INT x1, INT y1, INT x2, INT y2)
1053 {
1054    INT temp;
1055
1056    /* Convert points to device coordinates */
1057    corners[0].x=x1;
1058    corners[0].y=y1;
1059    corners[1].x=x2;
1060    corners[1].y=y2;
1061    if(!LPtoDP(dc->hSelf, corners, 2))
1062       return FALSE;
1063
1064    /* Make sure first corner is top left and second corner is bottom right */
1065    if(corners[0].x>corners[1].x)
1066    {
1067       temp=corners[0].x;
1068       corners[0].x=corners[1].x;
1069       corners[1].x=temp;
1070    }
1071    if(corners[0].y>corners[1].y)
1072    {
1073       temp=corners[0].y;
1074       corners[0].y=corners[1].y;
1075       corners[1].y=temp;
1076    }
1077
1078    /* In GM_COMPATIBLE, don't include bottom and right edges */
1079    if(dc->GraphicsMode==GM_COMPATIBLE)
1080    {
1081       corners[1].x--;
1082       corners[1].y--;
1083    }
1084
1085    return TRUE;
1086 }
1087
1088 /* PATH_AddFlatBezier
1089  */
1090 static BOOL PATH_AddFlatBezier(GdiPath *pPath, POINT *pt, BOOL closed)
1091 {
1092     POINT *pts;
1093     INT no, i;
1094
1095     pts = GDI_Bezier( pt, 4, &no );
1096     if(!pts) return FALSE;
1097
1098     for(i = 1; i < no; i++)
1099         PATH_AddEntry(pPath, &pts[i],
1100             (i == no-1 && closed) ? PT_LINETO | PT_CLOSEFIGURE : PT_LINETO);
1101     HeapFree( GetProcessHeap(), 0, pts );
1102     return TRUE;
1103 }
1104
1105 /* PATH_FlattenPath
1106  *
1107  * Replaces Beziers with line segments
1108  *
1109  */
1110 static BOOL PATH_FlattenPath(GdiPath *pPath)
1111 {
1112     GdiPath newPath;
1113     INT srcpt;
1114
1115     memset(&newPath, 0, sizeof(newPath));
1116     newPath.state = PATH_Open;
1117     for(srcpt = 0; srcpt < pPath->numEntriesUsed; srcpt++) {
1118         switch(pPath->pFlags[srcpt] & ~PT_CLOSEFIGURE) {
1119         case PT_MOVETO:
1120         case PT_LINETO:
1121             PATH_AddEntry(&newPath, &pPath->pPoints[srcpt],
1122                           pPath->pFlags[srcpt]);
1123             break;
1124         case PT_BEZIERTO:
1125           PATH_AddFlatBezier(&newPath, &pPath->pPoints[srcpt-1],
1126                              pPath->pFlags[srcpt+2] & PT_CLOSEFIGURE);
1127             srcpt += 2;
1128             break;
1129         }
1130     }
1131     newPath.state = PATH_Closed;
1132     PATH_AssignGdiPath(pPath, &newPath);
1133     PATH_DestroyGdiPath(&newPath);
1134     return TRUE;
1135 }
1136
1137 /* PATH_PathToRegion
1138  *
1139  * Creates a region from the specified path using the specified polygon
1140  * filling mode. The path is left unchanged. A handle to the region that
1141  * was created is stored in *pHrgn. If successful, TRUE is returned; if an
1142  * error occurs, SetLastError is called with the appropriate value and
1143  * FALSE is returned.
1144  */
1145 static BOOL PATH_PathToRegion(GdiPath *pPath, INT nPolyFillMode,
1146    HRGN *pHrgn)
1147 {
1148    int    numStrokes, iStroke, i;
1149    INT  *pNumPointsInStroke;
1150    HRGN hrgn;
1151
1152    assert(pPath!=NULL);
1153    assert(pHrgn!=NULL);
1154
1155    PATH_FlattenPath(pPath);
1156
1157    /* FIXME: What happens when number of points is zero? */
1158
1159    /* First pass: Find out how many strokes there are in the path */
1160    /* FIXME: We could eliminate this with some bookkeeping in GdiPath */
1161    numStrokes=0;
1162    for(i=0; i<pPath->numEntriesUsed; i++)
1163       if((pPath->pFlags[i] & ~PT_CLOSEFIGURE) == PT_MOVETO)
1164          numStrokes++;
1165
1166    /* Allocate memory for number-of-points-in-stroke array */
1167    pNumPointsInStroke=HeapAlloc( GetProcessHeap(), 0, sizeof(int) * numStrokes );
1168    if(!pNumPointsInStroke)
1169    {
1170       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1171       return FALSE;
1172    }
1173
1174    /* Second pass: remember number of points in each polygon */
1175    iStroke=-1;  /* Will get incremented to 0 at beginning of first stroke */
1176    for(i=0; i<pPath->numEntriesUsed; i++)
1177    {
1178       /* Is this the beginning of a new stroke? */
1179       if((pPath->pFlags[i] & ~PT_CLOSEFIGURE) == PT_MOVETO)
1180       {
1181          iStroke++;
1182          pNumPointsInStroke[iStroke]=0;
1183       }
1184
1185       pNumPointsInStroke[iStroke]++;
1186    }
1187
1188    /* Create a region from the strokes */
1189    hrgn=CreatePolyPolygonRgn(pPath->pPoints, pNumPointsInStroke,
1190       numStrokes, nPolyFillMode);
1191
1192    /* Free memory for number-of-points-in-stroke array */
1193    HeapFree( GetProcessHeap(), 0, pNumPointsInStroke );
1194
1195    if(hrgn==NULL)
1196    {
1197       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1198       return FALSE;
1199    }
1200
1201    /* Success! */
1202    *pHrgn=hrgn;
1203    return TRUE;
1204 }
1205
1206 static inline INT int_from_fixed(FIXED f)
1207 {
1208     return (f.fract >= 0x8000) ? (f.value + 1) : f.value;
1209 }
1210
1211 /**********************************************************************
1212  *      PATH_BezierTo
1213  *
1214  * internally used by PATH_add_outline
1215  */
1216 static void PATH_BezierTo(GdiPath *pPath, POINT *lppt, INT n)
1217 {
1218     if (n < 2) return;
1219
1220     if (n == 2)
1221     {
1222         PATH_AddEntry(pPath, &lppt[1], PT_LINETO);
1223     }
1224     else if (n == 3)
1225     {
1226         PATH_AddEntry(pPath, &lppt[0], PT_BEZIERTO);
1227         PATH_AddEntry(pPath, &lppt[1], PT_BEZIERTO);
1228         PATH_AddEntry(pPath, &lppt[2], PT_BEZIERTO);
1229     }
1230     else
1231     {
1232         POINT pt[3];
1233         INT i = 0;
1234
1235         pt[2] = lppt[0];
1236         n--;
1237
1238         while (n > 2)
1239         {
1240             pt[0] = pt[2];
1241             pt[1] = lppt[i+1];
1242             pt[2].x = (lppt[i+2].x + lppt[i+1].x) / 2;
1243             pt[2].y = (lppt[i+2].y + lppt[i+1].y) / 2;
1244             PATH_BezierTo(pPath, pt, 3);
1245             n--;
1246             i++;
1247         }
1248
1249         pt[0] = pt[2];
1250         pt[1] = lppt[i+1];
1251         pt[2] = lppt[i+2];
1252         PATH_BezierTo(pPath, pt, 3);
1253     }
1254 }
1255
1256 static BOOL PATH_add_outline(DC *dc, INT x, INT y, TTPOLYGONHEADER *header, DWORD size)
1257 {
1258     GdiPath *pPath = &dc->path;
1259     TTPOLYGONHEADER *start;
1260     POINT pt;
1261
1262     start = header;
1263
1264     while ((char *)header < (char *)start + size)
1265     {
1266         TTPOLYCURVE *curve;
1267
1268         if (header->dwType != TT_POLYGON_TYPE)
1269         {
1270             FIXME("Unknown header type %d\n", header->dwType);
1271             return FALSE;
1272         }
1273
1274         pt.x = x + int_from_fixed(header->pfxStart.x);
1275         pt.y = y - int_from_fixed(header->pfxStart.y);
1276         PATH_AddEntry(pPath, &pt, PT_MOVETO);
1277
1278         curve = (TTPOLYCURVE *)(header + 1);
1279
1280         while ((char *)curve < (char *)header + header->cb)
1281         {
1282             /*TRACE("curve->wType %d\n", curve->wType);*/
1283
1284             switch(curve->wType)
1285             {
1286             case TT_PRIM_LINE:
1287             {
1288                 WORD i;
1289
1290                 for (i = 0; i < curve->cpfx; i++)
1291                 {
1292                     pt.x = x + int_from_fixed(curve->apfx[i].x);
1293                     pt.y = y - int_from_fixed(curve->apfx[i].y);
1294                     PATH_AddEntry(pPath, &pt, PT_LINETO);
1295                 }
1296                 break;
1297             }
1298
1299             case TT_PRIM_QSPLINE:
1300             case TT_PRIM_CSPLINE:
1301             {
1302                 WORD i;
1303                 POINTFX ptfx;
1304                 POINT *pts = HeapAlloc(GetProcessHeap(), 0, (curve->cpfx + 1) * sizeof(POINT));
1305
1306                 if (!pts) return FALSE;
1307
1308                 ptfx = *(POINTFX *)((char *)curve - sizeof(POINTFX));
1309
1310                 pts[0].x = x + int_from_fixed(ptfx.x);
1311                 pts[0].y = y - int_from_fixed(ptfx.y);
1312
1313                 for(i = 0; i < curve->cpfx; i++)
1314                 {
1315                     pts[i + 1].x = x + int_from_fixed(curve->apfx[i].x);
1316                     pts[i + 1].y = y - int_from_fixed(curve->apfx[i].y);
1317                 }
1318
1319                 PATH_BezierTo(pPath, pts, curve->cpfx + 1);
1320
1321                 HeapFree(GetProcessHeap(), 0, pts);
1322                 break;
1323             }
1324
1325             default:
1326                 FIXME("Unknown curve type %04x\n", curve->wType);
1327                 return FALSE;
1328             }
1329
1330             curve = (TTPOLYCURVE *)&curve->apfx[curve->cpfx];
1331         }
1332
1333         header = (TTPOLYGONHEADER *)((char *)header + header->cb);
1334     }
1335
1336     return CloseFigure(dc->hSelf);
1337 }
1338
1339 /**********************************************************************
1340  *      PATH_ExtTextOut
1341  */
1342 BOOL PATH_ExtTextOut(DC *dc, INT x, INT y, UINT flags, const RECT *lprc,
1343                      LPCWSTR str, UINT count, const INT *dx)
1344 {
1345     unsigned int idx;
1346     HDC hdc = dc->hSelf;
1347     POINT offset = {0, 0};
1348
1349     TRACE("%p, %d, %d, %08x, %s, %s, %d, %p)\n", hdc, x, y, flags,
1350           wine_dbgstr_rect(lprc), debugstr_wn(str, count), count, dx);
1351
1352     if (!count) return TRUE;
1353
1354     for (idx = 0; idx < count; idx++)
1355     {
1356         static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
1357         GLYPHMETRICS gm;
1358         DWORD dwSize;
1359         void *outline;
1360
1361         dwSize = GetGlyphOutlineW(hdc, str[idx], GGO_GLYPH_INDEX | GGO_NATIVE, &gm, 0, NULL, &identity);
1362         if (dwSize == GDI_ERROR) return FALSE;
1363
1364         /* add outline only if char is printable */
1365         if(dwSize)
1366         {
1367             outline = HeapAlloc(GetProcessHeap(), 0, dwSize);
1368             if (!outline) return FALSE;
1369
1370             GetGlyphOutlineW(hdc, str[idx], GGO_GLYPH_INDEX | GGO_NATIVE, &gm, dwSize, outline, &identity);
1371
1372             PATH_add_outline(dc, x + offset.x, y + offset.y, outline, dwSize);
1373
1374             HeapFree(GetProcessHeap(), 0, outline);
1375         }
1376
1377         if (dx)
1378         {
1379             if(flags & ETO_PDY)
1380             {
1381                 offset.x += dx[idx * 2];
1382                 offset.y += dx[idx * 2 + 1];
1383             }
1384             else
1385                 offset.x += dx[idx];
1386         }
1387         else
1388         {
1389             offset.x += gm.gmCellIncX;
1390             offset.y += gm.gmCellIncY;
1391         }
1392     }
1393     return TRUE;
1394 }
1395
1396 /* PATH_EmptyPath
1397  *
1398  * Removes all entries from the path and sets the path state to PATH_Null.
1399  */
1400 static void PATH_EmptyPath(GdiPath *pPath)
1401 {
1402    assert(pPath!=NULL);
1403
1404    pPath->state=PATH_Null;
1405    pPath->numEntriesUsed=0;
1406 }
1407
1408 /* PATH_AddEntry
1409  *
1410  * Adds an entry to the path. For "flags", pass either PT_MOVETO, PT_LINETO
1411  * or PT_BEZIERTO, optionally ORed with PT_CLOSEFIGURE. Returns TRUE if
1412  * successful, FALSE otherwise (e.g. if not enough memory was available).
1413  */
1414 static BOOL PATH_AddEntry(GdiPath *pPath, const POINT *pPoint, BYTE flags)
1415 {
1416    assert(pPath!=NULL);
1417
1418    /* FIXME: If newStroke is true, perhaps we want to check that we're
1419     * getting a PT_MOVETO
1420     */
1421    TRACE("(%d,%d) - %d\n", pPoint->x, pPoint->y, flags);
1422
1423    /* Check that path is open */
1424    if(pPath->state!=PATH_Open)
1425       return FALSE;
1426
1427    /* Reserve enough memory for an extra path entry */
1428    if(!PATH_ReserveEntries(pPath, pPath->numEntriesUsed+1))
1429       return FALSE;
1430
1431    /* Store information in path entry */
1432    pPath->pPoints[pPath->numEntriesUsed]=*pPoint;
1433    pPath->pFlags[pPath->numEntriesUsed]=flags;
1434
1435    /* If this is PT_CLOSEFIGURE, we have to start a new stroke next time */
1436    if((flags & PT_CLOSEFIGURE) == PT_CLOSEFIGURE)
1437       pPath->newStroke=TRUE;
1438
1439    /* Increment entry count */
1440    pPath->numEntriesUsed++;
1441
1442    return TRUE;
1443 }
1444
1445 /* PATH_ReserveEntries
1446  *
1447  * Ensures that at least "numEntries" entries (for points and flags) have
1448  * been allocated; allocates larger arrays and copies the existing entries
1449  * to those arrays, if necessary. Returns TRUE if successful, else FALSE.
1450  */
1451 static BOOL PATH_ReserveEntries(GdiPath *pPath, INT numEntries)
1452 {
1453    INT   numEntriesToAllocate;
1454    POINT *pPointsNew;
1455    BYTE    *pFlagsNew;
1456
1457    assert(pPath!=NULL);
1458    assert(numEntries>=0);
1459
1460    /* Do we have to allocate more memory? */
1461    if(numEntries > pPath->numEntriesAllocated)
1462    {
1463       /* Find number of entries to allocate. We let the size of the array
1464        * grow exponentially, since that will guarantee linear time
1465        * complexity. */
1466       if(pPath->numEntriesAllocated)
1467       {
1468          numEntriesToAllocate=pPath->numEntriesAllocated;
1469          while(numEntriesToAllocate<numEntries)
1470             numEntriesToAllocate=numEntriesToAllocate*GROW_FACTOR_NUMER/
1471                GROW_FACTOR_DENOM;
1472       }
1473       else
1474          numEntriesToAllocate=numEntries;
1475
1476       /* Allocate new arrays */
1477       pPointsNew=HeapAlloc( GetProcessHeap(), 0, numEntriesToAllocate * sizeof(POINT) );
1478       if(!pPointsNew)
1479          return FALSE;
1480       pFlagsNew=HeapAlloc( GetProcessHeap(), 0, numEntriesToAllocate * sizeof(BYTE) );
1481       if(!pFlagsNew)
1482       {
1483          HeapFree( GetProcessHeap(), 0, pPointsNew );
1484          return FALSE;
1485       }
1486
1487       /* Copy old arrays to new arrays and discard old arrays */
1488       if(pPath->pPoints)
1489       {
1490          assert(pPath->pFlags);
1491
1492          memcpy(pPointsNew, pPath->pPoints,
1493              sizeof(POINT)*pPath->numEntriesUsed);
1494          memcpy(pFlagsNew, pPath->pFlags,
1495              sizeof(BYTE)*pPath->numEntriesUsed);
1496
1497          HeapFree( GetProcessHeap(), 0, pPath->pPoints );
1498          HeapFree( GetProcessHeap(), 0, pPath->pFlags );
1499       }
1500       pPath->pPoints=pPointsNew;
1501       pPath->pFlags=pFlagsNew;
1502       pPath->numEntriesAllocated=numEntriesToAllocate;
1503    }
1504
1505    return TRUE;
1506 }
1507
1508 /* PATH_DoArcPart
1509  *
1510  * Creates a Bezier spline that corresponds to part of an arc and appends the
1511  * corresponding points to the path. The start and end angles are passed in
1512  * "angleStart" and "angleEnd"; these angles should span a quarter circle
1513  * at most. If "startEntryType" is non-zero, an entry of that type for the first
1514  * control point is added to the path; otherwise, it is assumed that the current
1515  * position is equal to the first control point.
1516  */
1517 static BOOL PATH_DoArcPart(GdiPath *pPath, FLOAT_POINT corners[],
1518    double angleStart, double angleEnd, BYTE startEntryType)
1519 {
1520    double  halfAngle, a;
1521    double  xNorm[4], yNorm[4];
1522    POINT point;
1523    int     i;
1524
1525    assert(fabs(angleEnd-angleStart)<=M_PI_2);
1526
1527    /* FIXME: Is there an easier way of computing this? */
1528
1529    /* Compute control points */
1530    halfAngle=(angleEnd-angleStart)/2.0;
1531    if(fabs(halfAngle)>1e-8)
1532    {
1533       a=4.0/3.0*(1-cos(halfAngle))/sin(halfAngle);
1534       xNorm[0]=cos(angleStart);
1535       yNorm[0]=sin(angleStart);
1536       xNorm[1]=xNorm[0] - a*yNorm[0];
1537       yNorm[1]=yNorm[0] + a*xNorm[0];
1538       xNorm[3]=cos(angleEnd);
1539       yNorm[3]=sin(angleEnd);
1540       xNorm[2]=xNorm[3] + a*yNorm[3];
1541       yNorm[2]=yNorm[3] - a*xNorm[3];
1542    }
1543    else
1544       for(i=0; i<4; i++)
1545       {
1546          xNorm[i]=cos(angleStart);
1547          yNorm[i]=sin(angleStart);
1548       }
1549
1550    /* Add starting point to path if desired */
1551    if(startEntryType)
1552    {
1553       PATH_ScaleNormalizedPoint(corners, xNorm[0], yNorm[0], &point);
1554       if(!PATH_AddEntry(pPath, &point, startEntryType))
1555          return FALSE;
1556    }
1557
1558    /* Add remaining control points */
1559    for(i=1; i<4; i++)
1560    {
1561       PATH_ScaleNormalizedPoint(corners, xNorm[i], yNorm[i], &point);
1562       if(!PATH_AddEntry(pPath, &point, PT_BEZIERTO))
1563          return FALSE;
1564    }
1565
1566    return TRUE;
1567 }
1568
1569 /* PATH_ScaleNormalizedPoint
1570  *
1571  * Scales a normalized point (x, y) with respect to the box whose corners are
1572  * passed in "corners". The point is stored in "*pPoint". The normalized
1573  * coordinates (-1.0, -1.0) correspond to corners[0], the coordinates
1574  * (1.0, 1.0) correspond to corners[1].
1575  */
1576 static void PATH_ScaleNormalizedPoint(FLOAT_POINT corners[], double x,
1577    double y, POINT *pPoint)
1578 {
1579    pPoint->x=GDI_ROUND( (double)corners[0].x +
1580       (double)(corners[1].x-corners[0].x)*0.5*(x+1.0) );
1581    pPoint->y=GDI_ROUND( (double)corners[0].y +
1582       (double)(corners[1].y-corners[0].y)*0.5*(y+1.0) );
1583 }
1584
1585 /* PATH_NormalizePoint
1586  *
1587  * Normalizes a point with respect to the box whose corners are passed in
1588  * "corners". The normalized coordinates are stored in "*pX" and "*pY".
1589  */
1590 static void PATH_NormalizePoint(FLOAT_POINT corners[],
1591    const FLOAT_POINT *pPoint,
1592    double *pX, double *pY)
1593 {
1594    *pX=(double)(pPoint->x-corners[0].x)/(double)(corners[1].x-corners[0].x) *
1595       2.0 - 1.0;
1596    *pY=(double)(pPoint->y-corners[0].y)/(double)(corners[1].y-corners[0].y) *
1597       2.0 - 1.0;
1598 }
1599
1600
1601 /*******************************************************************
1602  *      FlattenPath [GDI32.@]
1603  *
1604  *
1605  */
1606 BOOL WINAPI FlattenPath(HDC hdc)
1607 {
1608     BOOL ret = FALSE;
1609     DC *dc = get_dc_ptr( hdc );
1610
1611     if (dc)
1612     {
1613         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pFlattenPath );
1614         ret = physdev->funcs->pFlattenPath( physdev );
1615         release_dc_ptr( dc );
1616     }
1617     return ret;
1618 }
1619
1620
1621 static BOOL PATH_StrokePath(DC *dc, GdiPath *pPath)
1622 {
1623     INT i, nLinePts, nAlloc;
1624     POINT *pLinePts;
1625     POINT ptViewportOrg, ptWindowOrg;
1626     SIZE szViewportExt, szWindowExt;
1627     DWORD mapMode, graphicsMode;
1628     XFORM xform;
1629     BOOL ret = TRUE;
1630
1631     /* Save the mapping mode info */
1632     mapMode=GetMapMode(dc->hSelf);
1633     GetViewportExtEx(dc->hSelf, &szViewportExt);
1634     GetViewportOrgEx(dc->hSelf, &ptViewportOrg);
1635     GetWindowExtEx(dc->hSelf, &szWindowExt);
1636     GetWindowOrgEx(dc->hSelf, &ptWindowOrg);
1637     GetWorldTransform(dc->hSelf, &xform);
1638
1639     /* Set MM_TEXT */
1640     SetMapMode(dc->hSelf, MM_TEXT);
1641     SetViewportOrgEx(dc->hSelf, 0, 0, NULL);
1642     SetWindowOrgEx(dc->hSelf, 0, 0, NULL);
1643     graphicsMode=GetGraphicsMode(dc->hSelf);
1644     SetGraphicsMode(dc->hSelf, GM_ADVANCED);
1645     ModifyWorldTransform(dc->hSelf, &xform, MWT_IDENTITY);
1646     SetGraphicsMode(dc->hSelf, graphicsMode);
1647
1648     /* Allocate enough memory for the worst case without beziers (one PT_MOVETO
1649      * and the rest PT_LINETO with PT_CLOSEFIGURE at the end) plus some buffer 
1650      * space in case we get one to keep the number of reallocations small. */
1651     nAlloc = pPath->numEntriesUsed + 1 + 300; 
1652     pLinePts = HeapAlloc(GetProcessHeap(), 0, nAlloc * sizeof(POINT));
1653     nLinePts = 0;
1654     
1655     for(i = 0; i < pPath->numEntriesUsed; i++) {
1656         if((i == 0 || (pPath->pFlags[i-1] & PT_CLOSEFIGURE)) &&
1657            (pPath->pFlags[i] != PT_MOVETO)) {
1658             ERR("Expected PT_MOVETO %s, got path flag %d\n", 
1659                 i == 0 ? "as first point" : "after PT_CLOSEFIGURE",
1660                 (INT)pPath->pFlags[i]);
1661             ret = FALSE;
1662             goto end;
1663         }
1664         switch(pPath->pFlags[i]) {
1665         case PT_MOVETO:
1666             TRACE("Got PT_MOVETO (%d, %d)\n",
1667                   pPath->pPoints[i].x, pPath->pPoints[i].y);
1668             if(nLinePts >= 2)
1669                 Polyline(dc->hSelf, pLinePts, nLinePts);
1670             nLinePts = 0;
1671             pLinePts[nLinePts++] = pPath->pPoints[i];
1672             break;
1673         case PT_LINETO:
1674         case (PT_LINETO | PT_CLOSEFIGURE):
1675             TRACE("Got PT_LINETO (%d, %d)\n",
1676                   pPath->pPoints[i].x, pPath->pPoints[i].y);
1677             pLinePts[nLinePts++] = pPath->pPoints[i];
1678             break;
1679         case PT_BEZIERTO:
1680             TRACE("Got PT_BEZIERTO\n");
1681             if(pPath->pFlags[i+1] != PT_BEZIERTO ||
1682                (pPath->pFlags[i+2] & ~PT_CLOSEFIGURE) != PT_BEZIERTO) {
1683                 ERR("Path didn't contain 3 successive PT_BEZIERTOs\n");
1684                 ret = FALSE;
1685                 goto end;
1686             } else {
1687                 INT nBzrPts, nMinAlloc;
1688                 POINT *pBzrPts = GDI_Bezier(&pPath->pPoints[i-1], 4, &nBzrPts);
1689                 /* Make sure we have allocated enough memory for the lines of 
1690                  * this bezier and the rest of the path, assuming we won't get
1691                  * another one (since we won't reallocate again then). */
1692                 nMinAlloc = nLinePts + (pPath->numEntriesUsed - i) + nBzrPts;
1693                 if(nAlloc < nMinAlloc)
1694                 {
1695                     nAlloc = nMinAlloc * 2;
1696                     pLinePts = HeapReAlloc(GetProcessHeap(), 0, pLinePts,
1697                                            nAlloc * sizeof(POINT));
1698                 }
1699                 memcpy(&pLinePts[nLinePts], &pBzrPts[1],
1700                        (nBzrPts - 1) * sizeof(POINT));
1701                 nLinePts += nBzrPts - 1;
1702                 HeapFree(GetProcessHeap(), 0, pBzrPts);
1703                 i += 2;
1704             }
1705             break;
1706         default:
1707             ERR("Got path flag %d\n", (INT)pPath->pFlags[i]);
1708             ret = FALSE;
1709             goto end;
1710         }
1711         if(pPath->pFlags[i] & PT_CLOSEFIGURE)
1712             pLinePts[nLinePts++] = pLinePts[0];
1713     }
1714     if(nLinePts >= 2)
1715         Polyline(dc->hSelf, pLinePts, nLinePts);
1716
1717  end:
1718     HeapFree(GetProcessHeap(), 0, pLinePts);
1719
1720     /* Restore the old mapping mode */
1721     SetMapMode(dc->hSelf, mapMode);
1722     SetWindowExtEx(dc->hSelf, szWindowExt.cx, szWindowExt.cy, NULL);
1723     SetWindowOrgEx(dc->hSelf, ptWindowOrg.x, ptWindowOrg.y, NULL);
1724     SetViewportExtEx(dc->hSelf, szViewportExt.cx, szViewportExt.cy, NULL);
1725     SetViewportOrgEx(dc->hSelf, ptViewportOrg.x, ptViewportOrg.y, NULL);
1726
1727     /* Go to GM_ADVANCED temporarily to restore the world transform */
1728     graphicsMode=GetGraphicsMode(dc->hSelf);
1729     SetGraphicsMode(dc->hSelf, GM_ADVANCED);
1730     SetWorldTransform(dc->hSelf, &xform);
1731     SetGraphicsMode(dc->hSelf, graphicsMode);
1732
1733     /* If we've moved the current point then get its new position
1734        which will be in device (MM_TEXT) co-ords, convert it to
1735        logical co-ords and re-set it.  This basically updates
1736        dc->CurPosX|Y so that their values are in the correct mapping
1737        mode.
1738     */
1739     if(i > 0) {
1740         POINT pt;
1741         GetCurrentPositionEx(dc->hSelf, &pt);
1742         DPtoLP(dc->hSelf, &pt, 1);
1743         MoveToEx(dc->hSelf, pt.x, pt.y, NULL);
1744     }
1745
1746     return ret;
1747 }
1748
1749 #define round(x) ((int)((x)>0?(x)+0.5:(x)-0.5))
1750
1751 static BOOL PATH_WidenPath(DC *dc)
1752 {
1753     INT i, j, numStrokes, penWidth, penWidthIn, penWidthOut, size, penStyle;
1754     BOOL ret = FALSE;
1755     GdiPath *pPath, *pNewPath, **pStrokes = NULL, *pUpPath, *pDownPath;
1756     EXTLOGPEN *elp;
1757     DWORD obj_type, joint, endcap, penType;
1758
1759     pPath = &dc->path;
1760
1761     PATH_FlattenPath(pPath);
1762
1763     size = GetObjectW( dc->hPen, 0, NULL );
1764     if (!size) {
1765         SetLastError(ERROR_CAN_NOT_COMPLETE);
1766         return FALSE;
1767     }
1768
1769     elp = HeapAlloc( GetProcessHeap(), 0, size );
1770     GetObjectW( dc->hPen, size, elp );
1771
1772     obj_type = GetObjectType(dc->hPen);
1773     if(obj_type == OBJ_PEN) {
1774         penStyle = ((LOGPEN*)elp)->lopnStyle;
1775     }
1776     else if(obj_type == OBJ_EXTPEN) {
1777         penStyle = elp->elpPenStyle;
1778     }
1779     else {
1780         SetLastError(ERROR_CAN_NOT_COMPLETE);
1781         HeapFree( GetProcessHeap(), 0, elp );
1782         return FALSE;
1783     }
1784
1785     penWidth = elp->elpWidth;
1786     HeapFree( GetProcessHeap(), 0, elp );
1787
1788     endcap = (PS_ENDCAP_MASK & penStyle);
1789     joint = (PS_JOIN_MASK & penStyle);
1790     penType = (PS_TYPE_MASK & penStyle);
1791
1792     /* The function cannot apply to cosmetic pens */
1793     if(obj_type == OBJ_EXTPEN && penType == PS_COSMETIC) {
1794         SetLastError(ERROR_CAN_NOT_COMPLETE);
1795         return FALSE;
1796     }
1797
1798     penWidthIn = penWidth / 2;
1799     penWidthOut = penWidth / 2;
1800     if(penWidthIn + penWidthOut < penWidth)
1801         penWidthOut++;
1802
1803     numStrokes = 0;
1804
1805     for(i = 0, j = 0; i < pPath->numEntriesUsed; i++, j++) {
1806         POINT point;
1807         if((i == 0 || (pPath->pFlags[i-1] & PT_CLOSEFIGURE)) &&
1808             (pPath->pFlags[i] != PT_MOVETO)) {
1809             ERR("Expected PT_MOVETO %s, got path flag %c\n",
1810                 i == 0 ? "as first point" : "after PT_CLOSEFIGURE",
1811                 pPath->pFlags[i]);
1812             return FALSE;
1813         }
1814         switch(pPath->pFlags[i]) {
1815             case PT_MOVETO:
1816                 if(numStrokes > 0) {
1817                     pStrokes[numStrokes - 1]->state = PATH_Closed;
1818                 }
1819                 numStrokes++;
1820                 j = 0;
1821                 if(numStrokes == 1)
1822                     pStrokes = HeapAlloc(GetProcessHeap(), 0, sizeof(GdiPath*));
1823                 else
1824                     pStrokes = HeapReAlloc(GetProcessHeap(), 0, pStrokes, numStrokes * sizeof(GdiPath*));
1825                 if(!pStrokes) return FALSE;
1826                 pStrokes[numStrokes - 1] = HeapAlloc(GetProcessHeap(), 0, sizeof(GdiPath));
1827                 PATH_InitGdiPath(pStrokes[numStrokes - 1]);
1828                 pStrokes[numStrokes - 1]->state = PATH_Open;
1829             case PT_LINETO:
1830             case (PT_LINETO | PT_CLOSEFIGURE):
1831                 point.x = pPath->pPoints[i].x;
1832                 point.y = pPath->pPoints[i].y;
1833                 PATH_AddEntry(pStrokes[numStrokes - 1], &point, pPath->pFlags[i]);
1834                 break;
1835             case PT_BEZIERTO:
1836                 /* should never happen because of the FlattenPath call */
1837                 ERR("Should never happen\n");
1838                 break;
1839             default:
1840                 ERR("Got path flag %c\n", pPath->pFlags[i]);
1841                 return FALSE;
1842         }
1843     }
1844
1845     pNewPath = HeapAlloc(GetProcessHeap(), 0, sizeof(GdiPath));
1846     PATH_InitGdiPath(pNewPath);
1847     pNewPath->state = PATH_Open;
1848
1849     for(i = 0; i < numStrokes; i++) {
1850         pUpPath = HeapAlloc(GetProcessHeap(), 0, sizeof(GdiPath));
1851         PATH_InitGdiPath(pUpPath);
1852         pUpPath->state = PATH_Open;
1853         pDownPath = HeapAlloc(GetProcessHeap(), 0, sizeof(GdiPath));
1854         PATH_InitGdiPath(pDownPath);
1855         pDownPath->state = PATH_Open;
1856
1857         for(j = 0; j < pStrokes[i]->numEntriesUsed; j++) {
1858             /* Beginning or end of the path if not closed */
1859             if((!(pStrokes[i]->pFlags[pStrokes[i]->numEntriesUsed - 1] & PT_CLOSEFIGURE)) && (j == 0 || j == pStrokes[i]->numEntriesUsed - 1) ) {
1860                 /* Compute segment angle */
1861                 double xo, yo, xa, ya, theta;
1862                 POINT pt;
1863                 FLOAT_POINT corners[2];
1864                 if(j == 0) {
1865                     xo = pStrokes[i]->pPoints[j].x;
1866                     yo = pStrokes[i]->pPoints[j].y;
1867                     xa = pStrokes[i]->pPoints[1].x;
1868                     ya = pStrokes[i]->pPoints[1].y;
1869                 }
1870                 else {
1871                     xa = pStrokes[i]->pPoints[j - 1].x;
1872                     ya = pStrokes[i]->pPoints[j - 1].y;
1873                     xo = pStrokes[i]->pPoints[j].x;
1874                     yo = pStrokes[i]->pPoints[j].y;
1875                 }
1876                 theta = atan2( ya - yo, xa - xo );
1877                 switch(endcap) {
1878                     case PS_ENDCAP_SQUARE :
1879                         pt.x = xo + round(sqrt(2) * penWidthOut * cos(M_PI_4 + theta));
1880                         pt.y = yo + round(sqrt(2) * penWidthOut * sin(M_PI_4 + theta));
1881                         PATH_AddEntry(pUpPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO) );
1882                         pt.x = xo + round(sqrt(2) * penWidthIn * cos(- M_PI_4 + theta));
1883                         pt.y = yo + round(sqrt(2) * penWidthIn * sin(- M_PI_4 + theta));
1884                         PATH_AddEntry(pUpPath, &pt, PT_LINETO);
1885                         break;
1886                     case PS_ENDCAP_FLAT :
1887                         pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
1888                         pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
1889                         PATH_AddEntry(pUpPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO));
1890                         pt.x = xo - round( penWidthIn * cos(theta + M_PI_2) );
1891                         pt.y = yo - round( penWidthIn * sin(theta + M_PI_2) );
1892                         PATH_AddEntry(pUpPath, &pt, PT_LINETO);
1893                         break;
1894                     case PS_ENDCAP_ROUND :
1895                     default :
1896                         corners[0].x = xo - penWidthIn;
1897                         corners[0].y = yo - penWidthIn;
1898                         corners[1].x = xo + penWidthOut;
1899                         corners[1].y = yo + penWidthOut;
1900                         PATH_DoArcPart(pUpPath ,corners, theta + M_PI_2 , theta + 3 * M_PI_4, (j == 0 ? PT_MOVETO : FALSE));
1901                         PATH_DoArcPart(pUpPath ,corners, theta + 3 * M_PI_4 , theta + M_PI, FALSE);
1902                         PATH_DoArcPart(pUpPath ,corners, theta + M_PI, theta +  5 * M_PI_4, FALSE);
1903                         PATH_DoArcPart(pUpPath ,corners, theta + 5 * M_PI_4 , theta + 3 * M_PI_2, FALSE);
1904                         break;
1905                 }
1906             }
1907             /* Corpse of the path */
1908             else {
1909                 /* Compute angle */
1910                 INT previous, next;
1911                 double xa, ya, xb, yb, xo, yo;
1912                 double alpha, theta, miterWidth;
1913                 DWORD _joint = joint;
1914                 POINT pt;
1915                 GdiPath *pInsidePath, *pOutsidePath;
1916                 if(j > 0 && j < pStrokes[i]->numEntriesUsed - 1) {
1917                     previous = j - 1;
1918                     next = j + 1;
1919                 }
1920                 else if (j == 0) {
1921                     previous = pStrokes[i]->numEntriesUsed - 1;
1922                     next = j + 1;
1923                 }
1924                 else {
1925                     previous = j - 1;
1926                     next = 0;
1927                 }
1928                 xo = pStrokes[i]->pPoints[j].x;
1929                 yo = pStrokes[i]->pPoints[j].y;
1930                 xa = pStrokes[i]->pPoints[previous].x;
1931                 ya = pStrokes[i]->pPoints[previous].y;
1932                 xb = pStrokes[i]->pPoints[next].x;
1933                 yb = pStrokes[i]->pPoints[next].y;
1934                 theta = atan2( yo - ya, xo - xa );
1935                 alpha = atan2( yb - yo, xb - xo ) - theta;
1936                 if (alpha > 0) alpha -= M_PI;
1937                 else alpha += M_PI;
1938                 if(_joint == PS_JOIN_MITER && dc->miterLimit < fabs(1 / sin(alpha/2))) {
1939                     _joint = PS_JOIN_BEVEL;
1940                 }
1941                 if(alpha > 0) {
1942                     pInsidePath = pUpPath;
1943                     pOutsidePath = pDownPath;
1944                 }
1945                 else if(alpha < 0) {
1946                     pInsidePath = pDownPath;
1947                     pOutsidePath = pUpPath;
1948                 }
1949                 else {
1950                     continue;
1951                 }
1952                 /* Inside angle points */
1953                 if(alpha > 0) {
1954                     pt.x = xo - round( penWidthIn * cos(theta + M_PI_2) );
1955                     pt.y = yo - round( penWidthIn * sin(theta + M_PI_2) );
1956                 }
1957                 else {
1958                     pt.x = xo + round( penWidthIn * cos(theta + M_PI_2) );
1959                     pt.y = yo + round( penWidthIn * sin(theta + M_PI_2) );
1960                 }
1961                 PATH_AddEntry(pInsidePath, &pt, PT_LINETO);
1962                 if(alpha > 0) {
1963                     pt.x = xo + round( penWidthIn * cos(M_PI_2 + alpha + theta) );
1964                     pt.y = yo + round( penWidthIn * sin(M_PI_2 + alpha + theta) );
1965                 }
1966                 else {
1967                     pt.x = xo - round( penWidthIn * cos(M_PI_2 + alpha + theta) );
1968                     pt.y = yo - round( penWidthIn * sin(M_PI_2 + alpha + theta) );
1969                 }
1970                 PATH_AddEntry(pInsidePath, &pt, PT_LINETO);
1971                 /* Outside angle point */
1972                 switch(_joint) {
1973                      case PS_JOIN_MITER :
1974                         miterWidth = fabs(penWidthOut / cos(M_PI_2 - fabs(alpha) / 2));
1975                         pt.x = xo + round( miterWidth * cos(theta + alpha / 2) );
1976                         pt.y = yo + round( miterWidth * sin(theta + alpha / 2) );
1977                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1978                         break;
1979                     case PS_JOIN_BEVEL :
1980                         if(alpha > 0) {
1981                             pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
1982                             pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
1983                         }
1984                         else {
1985                             pt.x = xo - round( penWidthOut * cos(theta + M_PI_2) );
1986                             pt.y = yo - round( penWidthOut * sin(theta + M_PI_2) );
1987                         }
1988                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1989                         if(alpha > 0) {
1990                             pt.x = xo - round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1991                             pt.y = yo - round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1992                         }
1993                         else {
1994                             pt.x = xo + round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1995                             pt.y = yo + round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1996                         }
1997                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1998                         break;
1999                     case PS_JOIN_ROUND :
2000                     default :
2001                         if(alpha > 0) {
2002                             pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
2003                             pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
2004                         }
2005                         else {
2006                             pt.x = xo - round( penWidthOut * cos(theta + M_PI_2) );
2007                             pt.y = yo - round( penWidthOut * sin(theta + M_PI_2) );
2008                         }
2009                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
2010                         pt.x = xo + round( penWidthOut * cos(theta + alpha / 2) );
2011                         pt.y = yo + round( penWidthOut * sin(theta + alpha / 2) );
2012                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
2013                         if(alpha > 0) {
2014                             pt.x = xo - round( penWidthOut * cos(M_PI_2 + alpha + theta) );
2015                             pt.y = yo - round( penWidthOut * sin(M_PI_2 + alpha + theta) );
2016                         }
2017                         else {
2018                             pt.x = xo + round( penWidthOut * cos(M_PI_2 + alpha + theta) );
2019                             pt.y = yo + round( penWidthOut * sin(M_PI_2 + alpha + theta) );
2020                         }
2021                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
2022                         break;
2023                 }
2024             }
2025         }
2026         for(j = 0; j < pUpPath->numEntriesUsed; j++) {
2027             POINT pt;
2028             pt.x = pUpPath->pPoints[j].x;
2029             pt.y = pUpPath->pPoints[j].y;
2030             PATH_AddEntry(pNewPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO));
2031         }
2032         for(j = 0; j < pDownPath->numEntriesUsed; j++) {
2033             POINT pt;
2034             pt.x = pDownPath->pPoints[pDownPath->numEntriesUsed - j - 1].x;
2035             pt.y = pDownPath->pPoints[pDownPath->numEntriesUsed - j - 1].y;
2036             PATH_AddEntry(pNewPath, &pt, ( (j == 0 && (pStrokes[i]->pFlags[pStrokes[i]->numEntriesUsed - 1] & PT_CLOSEFIGURE)) ? PT_MOVETO : PT_LINETO));
2037         }
2038
2039         PATH_DestroyGdiPath(pStrokes[i]);
2040         HeapFree(GetProcessHeap(), 0, pStrokes[i]);
2041         PATH_DestroyGdiPath(pUpPath);
2042         HeapFree(GetProcessHeap(), 0, pUpPath);
2043         PATH_DestroyGdiPath(pDownPath);
2044         HeapFree(GetProcessHeap(), 0, pDownPath);
2045     }
2046     HeapFree(GetProcessHeap(), 0, pStrokes);
2047
2048     pNewPath->state = PATH_Closed;
2049     if (!(ret = PATH_AssignGdiPath(pPath, pNewPath)))
2050         ERR("Assign path failed\n");
2051     PATH_DestroyGdiPath(pNewPath);
2052     HeapFree(GetProcessHeap(), 0, pNewPath);
2053     return ret;
2054 }
2055
2056
2057 /*******************************************************************
2058  *      StrokeAndFillPath [GDI32.@]
2059  *
2060  *
2061  */
2062 BOOL WINAPI StrokeAndFillPath(HDC hdc)
2063 {
2064     BOOL ret = FALSE;
2065     DC *dc = get_dc_ptr( hdc );
2066
2067     if (dc)
2068     {
2069         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pStrokeAndFillPath );
2070         ret = physdev->funcs->pStrokeAndFillPath( physdev );
2071         release_dc_ptr( dc );
2072     }
2073     return ret;
2074 }
2075
2076
2077 /*******************************************************************
2078  *      StrokePath [GDI32.@]
2079  *
2080  *
2081  */
2082 BOOL WINAPI StrokePath(HDC hdc)
2083 {
2084     BOOL ret = FALSE;
2085     DC *dc = get_dc_ptr( hdc );
2086
2087     if (dc)
2088     {
2089         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pStrokePath );
2090         ret = physdev->funcs->pStrokePath( physdev );
2091         release_dc_ptr( dc );
2092     }
2093     return ret;
2094 }
2095
2096
2097 /*******************************************************************
2098  *      WidenPath [GDI32.@]
2099  *
2100  *
2101  */
2102 BOOL WINAPI WidenPath(HDC hdc)
2103 {
2104     BOOL ret = FALSE;
2105     DC *dc = get_dc_ptr( hdc );
2106
2107     if (dc)
2108     {
2109         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pWidenPath );
2110         ret = physdev->funcs->pWidenPath( physdev );
2111         release_dc_ptr( dc );
2112     }
2113     return ret;
2114 }
2115
2116
2117 /***********************************************************************
2118  *           null driver fallback implementations
2119  */
2120
2121 BOOL CDECL nulldrv_BeginPath( PHYSDEV dev )
2122 {
2123     DC *dc = get_nulldrv_dc( dev );
2124
2125     /* If path is already open, do nothing */
2126     if (dc->path.state != PATH_Open)
2127     {
2128         PATH_EmptyPath(&dc->path);
2129         dc->path.newStroke = TRUE;
2130         dc->path.state = PATH_Open;
2131     }
2132     return TRUE;
2133 }
2134
2135 BOOL CDECL nulldrv_EndPath( PHYSDEV dev )
2136 {
2137     DC *dc = get_nulldrv_dc( dev );
2138
2139     if (dc->path.state != PATH_Open)
2140     {
2141         SetLastError( ERROR_CAN_NOT_COMPLETE );
2142         return FALSE;
2143     }
2144     dc->path.state = PATH_Closed;
2145     return TRUE;
2146 }
2147
2148 BOOL CDECL nulldrv_AbortPath( PHYSDEV dev )
2149 {
2150     DC *dc = get_nulldrv_dc( dev );
2151
2152     PATH_EmptyPath( &dc->path );
2153     return TRUE;
2154 }
2155
2156 BOOL CDECL nulldrv_CloseFigure( PHYSDEV dev )
2157 {
2158     DC *dc = get_nulldrv_dc( dev );
2159
2160     if (dc->path.state != PATH_Open)
2161     {
2162         SetLastError( ERROR_CAN_NOT_COMPLETE );
2163         return FALSE;
2164     }
2165     /* Set PT_CLOSEFIGURE on the last entry and start a new stroke */
2166     /* It is not necessary to draw a line, PT_CLOSEFIGURE is a virtual closing line itself */
2167     if (dc->path.numEntriesUsed)
2168     {
2169         dc->path.pFlags[dc->path.numEntriesUsed - 1] |= PT_CLOSEFIGURE;
2170         dc->path.newStroke = TRUE;
2171     }
2172     return TRUE;
2173 }
2174
2175 BOOL CDECL nulldrv_SelectClipPath( PHYSDEV dev, INT mode )
2176 {
2177     BOOL ret;
2178     HRGN hrgn;
2179     DC *dc = get_nulldrv_dc( dev );
2180
2181     if (dc->path.state != PATH_Closed)
2182     {
2183         SetLastError( ERROR_CAN_NOT_COMPLETE );
2184         return FALSE;
2185     }
2186     if (!PATH_PathToRegion( &dc->path, GetPolyFillMode(dev->hdc), &hrgn )) return FALSE;
2187     ret = ExtSelectClipRgn( dev->hdc, hrgn, mode ) != ERROR;
2188     if (ret) PATH_EmptyPath( &dc->path );
2189     /* FIXME: Should this function delete the path even if it failed? */
2190     DeleteObject( hrgn );
2191     return ret;
2192 }
2193
2194 BOOL CDECL nulldrv_FillPath( PHYSDEV dev )
2195 {
2196     DC *dc = get_nulldrv_dc( dev );
2197
2198     if (dc->path.state != PATH_Closed)
2199     {
2200         SetLastError( ERROR_CAN_NOT_COMPLETE );
2201         return FALSE;
2202     }
2203     if (!PATH_FillPath( dc, &dc->path )) return FALSE;
2204     /* FIXME: Should the path be emptied even if conversion failed? */
2205     PATH_EmptyPath( &dc->path );
2206     return TRUE;
2207 }
2208
2209 BOOL CDECL nulldrv_StrokeAndFillPath( PHYSDEV dev )
2210 {
2211     DC *dc = get_nulldrv_dc( dev );
2212
2213     if (dc->path.state != PATH_Closed)
2214     {
2215         SetLastError( ERROR_CAN_NOT_COMPLETE );
2216         return FALSE;
2217     }
2218     if (!PATH_FillPath( dc, &dc->path )) return FALSE;
2219     if (!PATH_StrokePath( dc, &dc->path )) return FALSE;
2220     PATH_EmptyPath( &dc->path );
2221     return TRUE;
2222 }
2223
2224 BOOL CDECL nulldrv_StrokePath( PHYSDEV dev )
2225 {
2226     DC *dc = get_nulldrv_dc( dev );
2227
2228     if (dc->path.state != PATH_Closed)
2229     {
2230         SetLastError( ERROR_CAN_NOT_COMPLETE );
2231         return FALSE;
2232     }
2233     if (!PATH_StrokePath( dc, &dc->path )) return FALSE;
2234     PATH_EmptyPath( &dc->path );
2235     return TRUE;
2236 }
2237
2238 BOOL CDECL nulldrv_FlattenPath( PHYSDEV dev )
2239 {
2240     DC *dc = get_nulldrv_dc( dev );
2241
2242     if (dc->path.state == PATH_Closed)
2243     {
2244         SetLastError( ERROR_CAN_NOT_COMPLETE );
2245         return FALSE;
2246     }
2247     return PATH_FlattenPath( &dc->path );
2248 }
2249
2250 BOOL CDECL nulldrv_WidenPath( PHYSDEV dev )
2251 {
2252     DC *dc = get_nulldrv_dc( dev );
2253
2254     if (dc->path.state == PATH_Open)
2255     {
2256         SetLastError( ERROR_CAN_NOT_COMPLETE );
2257         return FALSE;
2258     }
2259     return PATH_WidenPath( dc );
2260 }