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