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