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