include: Assorted spelling fixes.
[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, ggo_flags = GGO_NATIVE;
1515     POINT offset = {0, 0};
1516
1517     if (!count) return TRUE;
1518     if (flags & ETO_GLYPH_INDEX) ggo_flags |= GGO_GLYPH_INDEX;
1519
1520     for (idx = 0; idx < count; idx++)
1521     {
1522         static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
1523         GLYPHMETRICS gm;
1524         DWORD dwSize;
1525         void *outline;
1526
1527         dwSize = GetGlyphOutlineW(dev->hdc, str[idx], ggo_flags, &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_flags, &gm, dwSize, outline, &identity);
1537             PATH_add_outline(physdev, x + offset.x, y + offset.y, outline, dwSize);
1538
1539             HeapFree(GetProcessHeap(), 0, outline);
1540         }
1541
1542         if (dx)
1543         {
1544             if(flags & ETO_PDY)
1545             {
1546                 offset.x += dx[idx * 2];
1547                 offset.y += dx[idx * 2 + 1];
1548             }
1549             else
1550                 offset.x += dx[idx];
1551         }
1552         else
1553         {
1554             offset.x += gm.gmCellIncX;
1555             offset.y += gm.gmCellIncY;
1556         }
1557     }
1558     return TRUE;
1559 }
1560
1561
1562 /*************************************************************
1563  *           pathdrv_CloseFigure
1564  */
1565 static BOOL pathdrv_CloseFigure( PHYSDEV dev )
1566 {
1567     struct path_physdev *physdev = get_path_physdev( dev );
1568
1569     /* Set PT_CLOSEFIGURE on the last entry and start a new stroke */
1570     /* It is not necessary to draw a line, PT_CLOSEFIGURE is a virtual closing line itself */
1571     if (physdev->path->count)
1572         physdev->path->flags[physdev->path->count - 1] |= PT_CLOSEFIGURE;
1573     return TRUE;
1574 }
1575
1576
1577 /*******************************************************************
1578  *      FlattenPath [GDI32.@]
1579  *
1580  *
1581  */
1582 BOOL WINAPI FlattenPath(HDC hdc)
1583 {
1584     BOOL ret = FALSE;
1585     DC *dc = get_dc_ptr( hdc );
1586
1587     if (dc)
1588     {
1589         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pFlattenPath );
1590         ret = physdev->funcs->pFlattenPath( physdev );
1591         release_dc_ptr( dc );
1592     }
1593     return ret;
1594 }
1595
1596
1597 static BOOL PATH_StrokePath( HDC hdc, const struct gdi_path *pPath )
1598 {
1599     INT i, nLinePts, nAlloc;
1600     POINT *pLinePts;
1601     POINT ptViewportOrg, ptWindowOrg;
1602     SIZE szViewportExt, szWindowExt;
1603     DWORD mapMode, graphicsMode;
1604     XFORM xform;
1605     BOOL ret = TRUE;
1606
1607     /* Save the mapping mode info */
1608     mapMode=GetMapMode(hdc);
1609     GetViewportExtEx(hdc, &szViewportExt);
1610     GetViewportOrgEx(hdc, &ptViewportOrg);
1611     GetWindowExtEx(hdc, &szWindowExt);
1612     GetWindowOrgEx(hdc, &ptWindowOrg);
1613     GetWorldTransform(hdc, &xform);
1614
1615     /* Set MM_TEXT */
1616     SetMapMode(hdc, MM_TEXT);
1617     SetViewportOrgEx(hdc, 0, 0, NULL);
1618     SetWindowOrgEx(hdc, 0, 0, NULL);
1619     graphicsMode=GetGraphicsMode(hdc);
1620     SetGraphicsMode(hdc, GM_ADVANCED);
1621     ModifyWorldTransform(hdc, &xform, MWT_IDENTITY);
1622     SetGraphicsMode(hdc, graphicsMode);
1623
1624     /* Allocate enough memory for the worst case without beziers (one PT_MOVETO
1625      * and the rest PT_LINETO with PT_CLOSEFIGURE at the end) plus some buffer 
1626      * space in case we get one to keep the number of reallocations small. */
1627     nAlloc = pPath->count + 1 + 300;
1628     pLinePts = HeapAlloc(GetProcessHeap(), 0, nAlloc * sizeof(POINT));
1629     nLinePts = 0;
1630     
1631     for(i = 0; i < pPath->count; i++) {
1632         if((i == 0 || (pPath->flags[i-1] & PT_CLOSEFIGURE)) &&
1633            (pPath->flags[i] != PT_MOVETO)) {
1634             ERR("Expected PT_MOVETO %s, got path flag %d\n", 
1635                 i == 0 ? "as first point" : "after PT_CLOSEFIGURE",
1636                 pPath->flags[i]);
1637             ret = FALSE;
1638             goto end;
1639         }
1640         switch(pPath->flags[i]) {
1641         case PT_MOVETO:
1642             TRACE("Got PT_MOVETO (%d, %d)\n",
1643                   pPath->points[i].x, pPath->points[i].y);
1644             if(nLinePts >= 2)
1645                 Polyline(hdc, pLinePts, nLinePts);
1646             nLinePts = 0;
1647             pLinePts[nLinePts++] = pPath->points[i];
1648             break;
1649         case PT_LINETO:
1650         case (PT_LINETO | PT_CLOSEFIGURE):
1651             TRACE("Got PT_LINETO (%d, %d)\n",
1652                   pPath->points[i].x, pPath->points[i].y);
1653             pLinePts[nLinePts++] = pPath->points[i];
1654             break;
1655         case PT_BEZIERTO:
1656             TRACE("Got PT_BEZIERTO\n");
1657             if(pPath->flags[i+1] != PT_BEZIERTO ||
1658                (pPath->flags[i+2] & ~PT_CLOSEFIGURE) != PT_BEZIERTO) {
1659                 ERR("Path didn't contain 3 successive PT_BEZIERTOs\n");
1660                 ret = FALSE;
1661                 goto end;
1662             } else {
1663                 INT nBzrPts, nMinAlloc;
1664                 POINT *pBzrPts = GDI_Bezier(&pPath->points[i-1], 4, &nBzrPts);
1665                 /* Make sure we have allocated enough memory for the lines of 
1666                  * this bezier and the rest of the path, assuming we won't get
1667                  * another one (since we won't reallocate again then). */
1668                 nMinAlloc = nLinePts + (pPath->count - i) + nBzrPts;
1669                 if(nAlloc < nMinAlloc)
1670                 {
1671                     nAlloc = nMinAlloc * 2;
1672                     pLinePts = HeapReAlloc(GetProcessHeap(), 0, pLinePts,
1673                                            nAlloc * sizeof(POINT));
1674                 }
1675                 memcpy(&pLinePts[nLinePts], &pBzrPts[1],
1676                        (nBzrPts - 1) * sizeof(POINT));
1677                 nLinePts += nBzrPts - 1;
1678                 HeapFree(GetProcessHeap(), 0, pBzrPts);
1679                 i += 2;
1680             }
1681             break;
1682         default:
1683             ERR("Got path flag %d\n", pPath->flags[i]);
1684             ret = FALSE;
1685             goto end;
1686         }
1687         if(pPath->flags[i] & PT_CLOSEFIGURE)
1688             pLinePts[nLinePts++] = pLinePts[0];
1689     }
1690     if(nLinePts >= 2)
1691         Polyline(hdc, pLinePts, nLinePts);
1692
1693  end:
1694     HeapFree(GetProcessHeap(), 0, pLinePts);
1695
1696     /* Restore the old mapping mode */
1697     SetMapMode(hdc, mapMode);
1698     SetWindowExtEx(hdc, szWindowExt.cx, szWindowExt.cy, NULL);
1699     SetWindowOrgEx(hdc, ptWindowOrg.x, ptWindowOrg.y, NULL);
1700     SetViewportExtEx(hdc, szViewportExt.cx, szViewportExt.cy, NULL);
1701     SetViewportOrgEx(hdc, ptViewportOrg.x, ptViewportOrg.y, NULL);
1702
1703     /* Go to GM_ADVANCED temporarily to restore the world transform */
1704     graphicsMode=GetGraphicsMode(hdc);
1705     SetGraphicsMode(hdc, GM_ADVANCED);
1706     SetWorldTransform(hdc, &xform);
1707     SetGraphicsMode(hdc, graphicsMode);
1708
1709     /* If we've moved the current point then get its new position
1710        which will be in device (MM_TEXT) co-ords, convert it to
1711        logical co-ords and re-set it.  This basically updates
1712        dc->CurPosX|Y so that their values are in the correct mapping
1713        mode.
1714     */
1715     if(i > 0) {
1716         POINT pt;
1717         GetCurrentPositionEx(hdc, &pt);
1718         DPtoLP(hdc, &pt, 1);
1719         MoveToEx(hdc, pt.x, pt.y, NULL);
1720     }
1721
1722     return ret;
1723 }
1724
1725 #define round(x) ((int)((x)>0?(x)+0.5:(x)-0.5))
1726
1727 static struct gdi_path *PATH_WidenPath(DC *dc)
1728 {
1729     INT i, j, numStrokes, penWidth, penWidthIn, penWidthOut, size, penStyle;
1730     struct gdi_path *flat_path, *pNewPath, **pStrokes = NULL, *pUpPath, *pDownPath;
1731     EXTLOGPEN *elp;
1732     DWORD obj_type, joint, endcap, penType;
1733
1734     size = GetObjectW( dc->hPen, 0, NULL );
1735     if (!size) {
1736         SetLastError(ERROR_CAN_NOT_COMPLETE);
1737         return NULL;
1738     }
1739
1740     elp = HeapAlloc( GetProcessHeap(), 0, size );
1741     GetObjectW( dc->hPen, size, elp );
1742
1743     obj_type = GetObjectType(dc->hPen);
1744     if(obj_type == OBJ_PEN) {
1745         penStyle = ((LOGPEN*)elp)->lopnStyle;
1746     }
1747     else if(obj_type == OBJ_EXTPEN) {
1748         penStyle = elp->elpPenStyle;
1749     }
1750     else {
1751         SetLastError(ERROR_CAN_NOT_COMPLETE);
1752         HeapFree( GetProcessHeap(), 0, elp );
1753         return NULL;
1754     }
1755
1756     penWidth = elp->elpWidth;
1757     HeapFree( GetProcessHeap(), 0, elp );
1758
1759     endcap = (PS_ENDCAP_MASK & penStyle);
1760     joint = (PS_JOIN_MASK & penStyle);
1761     penType = (PS_TYPE_MASK & penStyle);
1762
1763     /* The function cannot apply to cosmetic pens */
1764     if(obj_type == OBJ_EXTPEN && penType == PS_COSMETIC) {
1765         SetLastError(ERROR_CAN_NOT_COMPLETE);
1766         return NULL;
1767     }
1768
1769     if (!(flat_path = PATH_FlattenPath( dc->path ))) return NULL;
1770
1771     penWidthIn = penWidth / 2;
1772     penWidthOut = penWidth / 2;
1773     if(penWidthIn + penWidthOut < penWidth)
1774         penWidthOut++;
1775
1776     numStrokes = 0;
1777
1778     for(i = 0, j = 0; i < flat_path->count; i++, j++) {
1779         POINT point;
1780         if((i == 0 || (flat_path->flags[i-1] & PT_CLOSEFIGURE)) &&
1781             (flat_path->flags[i] != PT_MOVETO)) {
1782             ERR("Expected PT_MOVETO %s, got path flag %c\n",
1783                 i == 0 ? "as first point" : "after PT_CLOSEFIGURE",
1784                 flat_path->flags[i]);
1785             free_gdi_path( flat_path );
1786             return NULL;
1787         }
1788         switch(flat_path->flags[i]) {
1789             case PT_MOVETO:
1790                 numStrokes++;
1791                 j = 0;
1792                 if(numStrokes == 1)
1793                     pStrokes = HeapAlloc(GetProcessHeap(), 0, sizeof(*pStrokes));
1794                 else
1795                     pStrokes = HeapReAlloc(GetProcessHeap(), 0, pStrokes, numStrokes * sizeof(*pStrokes));
1796                 if(!pStrokes) return NULL;
1797                 pStrokes[numStrokes - 1] = alloc_gdi_path(0);
1798                 /* fall through */
1799             case PT_LINETO:
1800             case (PT_LINETO | PT_CLOSEFIGURE):
1801                 point.x = flat_path->points[i].x;
1802                 point.y = flat_path->points[i].y;
1803                 PATH_AddEntry(pStrokes[numStrokes - 1], &point, flat_path->flags[i]);
1804                 break;
1805             case PT_BEZIERTO:
1806                 /* should never happen because of the FlattenPath call */
1807                 ERR("Should never happen\n");
1808                 break;
1809             default:
1810                 ERR("Got path flag %c\n", flat_path->flags[i]);
1811                 return NULL;
1812         }
1813     }
1814
1815     pNewPath = alloc_gdi_path( flat_path->count );
1816
1817     for(i = 0; i < numStrokes; i++) {
1818         pUpPath = alloc_gdi_path( pStrokes[i]->count );
1819         pDownPath = alloc_gdi_path( pStrokes[i]->count );
1820
1821         for(j = 0; j < pStrokes[i]->count; j++) {
1822             /* Beginning or end of the path if not closed */
1823             if((!(pStrokes[i]->flags[pStrokes[i]->count - 1] & PT_CLOSEFIGURE)) && (j == 0 || j == pStrokes[i]->count - 1) ) {
1824                 /* Compute segment angle */
1825                 double xo, yo, xa, ya, theta;
1826                 POINT pt;
1827                 FLOAT_POINT corners[2];
1828                 if(j == 0) {
1829                     xo = pStrokes[i]->points[j].x;
1830                     yo = pStrokes[i]->points[j].y;
1831                     xa = pStrokes[i]->points[1].x;
1832                     ya = pStrokes[i]->points[1].y;
1833                 }
1834                 else {
1835                     xa = pStrokes[i]->points[j - 1].x;
1836                     ya = pStrokes[i]->points[j - 1].y;
1837                     xo = pStrokes[i]->points[j].x;
1838                     yo = pStrokes[i]->points[j].y;
1839                 }
1840                 theta = atan2( ya - yo, xa - xo );
1841                 switch(endcap) {
1842                     case PS_ENDCAP_SQUARE :
1843                         pt.x = xo + round(sqrt(2) * penWidthOut * cos(M_PI_4 + theta));
1844                         pt.y = yo + round(sqrt(2) * penWidthOut * sin(M_PI_4 + theta));
1845                         PATH_AddEntry(pUpPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO) );
1846                         pt.x = xo + round(sqrt(2) * penWidthIn * cos(- M_PI_4 + theta));
1847                         pt.y = yo + round(sqrt(2) * penWidthIn * sin(- M_PI_4 + theta));
1848                         PATH_AddEntry(pUpPath, &pt, PT_LINETO);
1849                         break;
1850                     case PS_ENDCAP_FLAT :
1851                         pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
1852                         pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
1853                         PATH_AddEntry(pUpPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO));
1854                         pt.x = xo - round( penWidthIn * cos(theta + M_PI_2) );
1855                         pt.y = yo - round( penWidthIn * sin(theta + M_PI_2) );
1856                         PATH_AddEntry(pUpPath, &pt, PT_LINETO);
1857                         break;
1858                     case PS_ENDCAP_ROUND :
1859                     default :
1860                         corners[0].x = xo - penWidthIn;
1861                         corners[0].y = yo - penWidthIn;
1862                         corners[1].x = xo + penWidthOut;
1863                         corners[1].y = yo + penWidthOut;
1864                         PATH_DoArcPart(pUpPath ,corners, theta + M_PI_2 , theta + 3 * M_PI_4, (j == 0 ? PT_MOVETO : FALSE));
1865                         PATH_DoArcPart(pUpPath ,corners, theta + 3 * M_PI_4 , theta + M_PI, FALSE);
1866                         PATH_DoArcPart(pUpPath ,corners, theta + M_PI, theta +  5 * M_PI_4, FALSE);
1867                         PATH_DoArcPart(pUpPath ,corners, theta + 5 * M_PI_4 , theta + 3 * M_PI_2, FALSE);
1868                         break;
1869                 }
1870             }
1871             /* Corpse of the path */
1872             else {
1873                 /* Compute angle */
1874                 INT previous, next;
1875                 double xa, ya, xb, yb, xo, yo;
1876                 double alpha, theta, miterWidth;
1877                 DWORD _joint = joint;
1878                 POINT pt;
1879                 struct gdi_path *pInsidePath, *pOutsidePath;
1880                 if(j > 0 && j < pStrokes[i]->count - 1) {
1881                     previous = j - 1;
1882                     next = j + 1;
1883                 }
1884                 else if (j == 0) {
1885                     previous = pStrokes[i]->count - 1;
1886                     next = j + 1;
1887                 }
1888                 else {
1889                     previous = j - 1;
1890                     next = 0;
1891                 }
1892                 xo = pStrokes[i]->points[j].x;
1893                 yo = pStrokes[i]->points[j].y;
1894                 xa = pStrokes[i]->points[previous].x;
1895                 ya = pStrokes[i]->points[previous].y;
1896                 xb = pStrokes[i]->points[next].x;
1897                 yb = pStrokes[i]->points[next].y;
1898                 theta = atan2( yo - ya, xo - xa );
1899                 alpha = atan2( yb - yo, xb - xo ) - theta;
1900                 if (alpha > 0) alpha -= M_PI;
1901                 else alpha += M_PI;
1902                 if(_joint == PS_JOIN_MITER && dc->miterLimit < fabs(1 / sin(alpha/2))) {
1903                     _joint = PS_JOIN_BEVEL;
1904                 }
1905                 if(alpha > 0) {
1906                     pInsidePath = pUpPath;
1907                     pOutsidePath = pDownPath;
1908                 }
1909                 else if(alpha < 0) {
1910                     pInsidePath = pDownPath;
1911                     pOutsidePath = pUpPath;
1912                 }
1913                 else {
1914                     continue;
1915                 }
1916                 /* Inside angle points */
1917                 if(alpha > 0) {
1918                     pt.x = xo - round( penWidthIn * cos(theta + M_PI_2) );
1919                     pt.y = yo - round( penWidthIn * sin(theta + M_PI_2) );
1920                 }
1921                 else {
1922                     pt.x = xo + round( penWidthIn * cos(theta + M_PI_2) );
1923                     pt.y = yo + round( penWidthIn * sin(theta + M_PI_2) );
1924                 }
1925                 PATH_AddEntry(pInsidePath, &pt, PT_LINETO);
1926                 if(alpha > 0) {
1927                     pt.x = xo + round( penWidthIn * cos(M_PI_2 + alpha + theta) );
1928                     pt.y = yo + round( penWidthIn * sin(M_PI_2 + alpha + theta) );
1929                 }
1930                 else {
1931                     pt.x = xo - round( penWidthIn * cos(M_PI_2 + alpha + theta) );
1932                     pt.y = yo - round( penWidthIn * sin(M_PI_2 + alpha + theta) );
1933                 }
1934                 PATH_AddEntry(pInsidePath, &pt, PT_LINETO);
1935                 /* Outside angle point */
1936                 switch(_joint) {
1937                      case PS_JOIN_MITER :
1938                         miterWidth = fabs(penWidthOut / cos(M_PI_2 - fabs(alpha) / 2));
1939                         pt.x = xo + round( miterWidth * cos(theta + alpha / 2) );
1940                         pt.y = yo + round( miterWidth * sin(theta + alpha / 2) );
1941                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1942                         break;
1943                     case PS_JOIN_BEVEL :
1944                         if(alpha > 0) {
1945                             pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
1946                             pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
1947                         }
1948                         else {
1949                             pt.x = xo - round( penWidthOut * cos(theta + M_PI_2) );
1950                             pt.y = yo - round( penWidthOut * sin(theta + M_PI_2) );
1951                         }
1952                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1953                         if(alpha > 0) {
1954                             pt.x = xo - round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1955                             pt.y = yo - round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1956                         }
1957                         else {
1958                             pt.x = xo + round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1959                             pt.y = yo + round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1960                         }
1961                         PATH_AddEntry(pOutsidePath, &pt, PT_LINETO);
1962                         break;
1963                     case PS_JOIN_ROUND :
1964                     default :
1965                         if(alpha > 0) {
1966                             pt.x = xo + round( penWidthOut * cos(theta + M_PI_2) );
1967                             pt.y = yo + round( penWidthOut * sin(theta + M_PI_2) );
1968                         }
1969                         else {
1970                             pt.x = xo - round( penWidthOut * cos(theta + M_PI_2) );
1971                             pt.y = yo - round( penWidthOut * sin(theta + M_PI_2) );
1972                         }
1973                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
1974                         pt.x = xo + round( penWidthOut * cos(theta + alpha / 2) );
1975                         pt.y = yo + round( penWidthOut * sin(theta + alpha / 2) );
1976                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
1977                         if(alpha > 0) {
1978                             pt.x = xo - round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1979                             pt.y = yo - round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1980                         }
1981                         else {
1982                             pt.x = xo + round( penWidthOut * cos(M_PI_2 + alpha + theta) );
1983                             pt.y = yo + round( penWidthOut * sin(M_PI_2 + alpha + theta) );
1984                         }
1985                         PATH_AddEntry(pOutsidePath, &pt, PT_BEZIERTO);
1986                         break;
1987                 }
1988             }
1989         }
1990         for(j = 0; j < pUpPath->count; j++) {
1991             POINT pt;
1992             pt.x = pUpPath->points[j].x;
1993             pt.y = pUpPath->points[j].y;
1994             PATH_AddEntry(pNewPath, &pt, (j == 0 ? PT_MOVETO : PT_LINETO));
1995         }
1996         for(j = 0; j < pDownPath->count; j++) {
1997             POINT pt;
1998             pt.x = pDownPath->points[pDownPath->count - j - 1].x;
1999             pt.y = pDownPath->points[pDownPath->count - j - 1].y;
2000             PATH_AddEntry(pNewPath, &pt, ( (j == 0 && (pStrokes[i]->flags[pStrokes[i]->count - 1] & PT_CLOSEFIGURE)) ? PT_MOVETO : PT_LINETO));
2001         }
2002
2003         free_gdi_path( pStrokes[i] );
2004         free_gdi_path( pUpPath );
2005         free_gdi_path( pDownPath );
2006     }
2007     HeapFree(GetProcessHeap(), 0, pStrokes);
2008     free_gdi_path( flat_path );
2009     return pNewPath;
2010 }
2011
2012
2013 /*******************************************************************
2014  *      StrokeAndFillPath [GDI32.@]
2015  *
2016  *
2017  */
2018 BOOL WINAPI StrokeAndFillPath(HDC hdc)
2019 {
2020     BOOL ret = FALSE;
2021     DC *dc = get_dc_ptr( hdc );
2022
2023     if (dc)
2024     {
2025         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pStrokeAndFillPath );
2026         ret = physdev->funcs->pStrokeAndFillPath( physdev );
2027         release_dc_ptr( dc );
2028     }
2029     return ret;
2030 }
2031
2032
2033 /*******************************************************************
2034  *      StrokePath [GDI32.@]
2035  *
2036  *
2037  */
2038 BOOL WINAPI StrokePath(HDC hdc)
2039 {
2040     BOOL ret = FALSE;
2041     DC *dc = get_dc_ptr( hdc );
2042
2043     if (dc)
2044     {
2045         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pStrokePath );
2046         ret = physdev->funcs->pStrokePath( physdev );
2047         release_dc_ptr( dc );
2048     }
2049     return ret;
2050 }
2051
2052
2053 /*******************************************************************
2054  *      WidenPath [GDI32.@]
2055  *
2056  *
2057  */
2058 BOOL WINAPI WidenPath(HDC hdc)
2059 {
2060     BOOL ret = FALSE;
2061     DC *dc = get_dc_ptr( hdc );
2062
2063     if (dc)
2064     {
2065         PHYSDEV physdev = GET_DC_PHYSDEV( dc, pWidenPath );
2066         ret = physdev->funcs->pWidenPath( physdev );
2067         release_dc_ptr( dc );
2068     }
2069     return ret;
2070 }
2071
2072
2073 /***********************************************************************
2074  *           null driver fallback implementations
2075  */
2076
2077 BOOL nulldrv_BeginPath( PHYSDEV dev )
2078 {
2079     DC *dc = get_nulldrv_dc( dev );
2080     struct path_physdev *physdev;
2081     struct gdi_path *path = alloc_gdi_path(0);
2082
2083     if (!path) return FALSE;
2084     if (!path_driver.pCreateDC( &dc->physDev, NULL, NULL, NULL, NULL ))
2085     {
2086         free_gdi_path( path );
2087         return FALSE;
2088     }
2089     physdev = get_path_physdev( find_dc_driver( dc, &path_driver ));
2090     physdev->path = path;
2091     if (dc->path) free_gdi_path( dc->path );
2092     dc->path = NULL;
2093     return TRUE;
2094 }
2095
2096 BOOL nulldrv_EndPath( PHYSDEV dev )
2097 {
2098     SetLastError( ERROR_CAN_NOT_COMPLETE );
2099     return FALSE;
2100 }
2101
2102 BOOL nulldrv_AbortPath( PHYSDEV dev )
2103 {
2104     DC *dc = get_nulldrv_dc( dev );
2105
2106     if (dc->path) free_gdi_path( dc->path );
2107     dc->path = NULL;
2108     return TRUE;
2109 }
2110
2111 BOOL nulldrv_CloseFigure( PHYSDEV dev )
2112 {
2113     SetLastError( ERROR_CAN_NOT_COMPLETE );
2114     return FALSE;
2115 }
2116
2117 BOOL nulldrv_SelectClipPath( PHYSDEV dev, INT mode )
2118 {
2119     BOOL ret;
2120     HRGN hrgn;
2121     DC *dc = get_nulldrv_dc( dev );
2122
2123     if (!dc->path)
2124     {
2125         SetLastError( ERROR_CAN_NOT_COMPLETE );
2126         return FALSE;
2127     }
2128     if (!(hrgn = PATH_PathToRegion( dc->path, GetPolyFillMode(dev->hdc)))) return FALSE;
2129     ret = ExtSelectClipRgn( dev->hdc, hrgn, mode ) != ERROR;
2130     if (ret)
2131     {
2132         free_gdi_path( dc->path );
2133         dc->path = NULL;
2134     }
2135     /* FIXME: Should this function delete the path even if it failed? */
2136     DeleteObject( hrgn );
2137     return ret;
2138 }
2139
2140 BOOL nulldrv_FillPath( PHYSDEV dev )
2141 {
2142     DC *dc = get_nulldrv_dc( dev );
2143
2144     if (!dc->path)
2145     {
2146         SetLastError( ERROR_CAN_NOT_COMPLETE );
2147         return FALSE;
2148     }
2149     if (!PATH_FillPath( dev->hdc, dc->path )) return FALSE;
2150     /* FIXME: Should the path be emptied even if conversion failed? */
2151     free_gdi_path( dc->path );
2152     dc->path = NULL;
2153     return TRUE;
2154 }
2155
2156 BOOL nulldrv_StrokeAndFillPath( PHYSDEV dev )
2157 {
2158     DC *dc = get_nulldrv_dc( dev );
2159
2160     if (!dc->path)
2161     {
2162         SetLastError( ERROR_CAN_NOT_COMPLETE );
2163         return FALSE;
2164     }
2165     if (!PATH_FillPath( dev->hdc, dc->path )) return FALSE;
2166     if (!PATH_StrokePath( dev->hdc, dc->path )) return FALSE;
2167     free_gdi_path( dc->path );
2168     dc->path = NULL;
2169     return TRUE;
2170 }
2171
2172 BOOL nulldrv_StrokePath( PHYSDEV dev )
2173 {
2174     DC *dc = get_nulldrv_dc( dev );
2175
2176     if (!dc->path)
2177     {
2178         SetLastError( ERROR_CAN_NOT_COMPLETE );
2179         return FALSE;
2180     }
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_FlattenPath( PHYSDEV dev )
2188 {
2189     DC *dc = get_nulldrv_dc( dev );
2190     struct gdi_path *path;
2191
2192     if (!dc->path)
2193     {
2194         SetLastError( ERROR_CAN_NOT_COMPLETE );
2195         return FALSE;
2196     }
2197     if (!(path = PATH_FlattenPath( dc->path ))) return FALSE;
2198     free_gdi_path( dc->path );
2199     dc->path = path;
2200     return TRUE;
2201 }
2202
2203 BOOL nulldrv_WidenPath( PHYSDEV dev )
2204 {
2205     DC *dc = get_nulldrv_dc( dev );
2206     struct gdi_path *path;
2207
2208     if (!dc->path)
2209     {
2210         SetLastError( ERROR_CAN_NOT_COMPLETE );
2211         return FALSE;
2212     }
2213     if (!(path = PATH_WidenPath( dc ))) return FALSE;
2214     free_gdi_path( dc->path );
2215     dc->path = path;
2216     return TRUE;
2217 }
2218
2219 const struct gdi_dc_funcs path_driver =
2220 {
2221     NULL,                               /* pAbortDoc */
2222     pathdrv_AbortPath,                  /* pAbortPath */
2223     NULL,                               /* pAlphaBlend */
2224     pathdrv_AngleArc,                   /* pAngleArc */
2225     pathdrv_Arc,                        /* pArc */
2226     pathdrv_ArcTo,                      /* pArcTo */
2227     pathdrv_BeginPath,                  /* pBeginPath */
2228     NULL,                               /* pBlendImage */
2229     pathdrv_Chord,                      /* pChord */
2230     pathdrv_CloseFigure,                /* pCloseFigure */
2231     NULL,                               /* pCreateCompatibleDC */
2232     pathdrv_CreateDC,                   /* pCreateDC */
2233     pathdrv_DeleteDC,                   /* pDeleteDC */
2234     NULL,                               /* pDeleteObject */
2235     NULL,                               /* pDeviceCapabilities */
2236     pathdrv_Ellipse,                    /* pEllipse */
2237     NULL,                               /* pEndDoc */
2238     NULL,                               /* pEndPage */
2239     pathdrv_EndPath,                    /* pEndPath */
2240     NULL,                               /* pEnumFonts */
2241     NULL,                               /* pEnumICMProfiles */
2242     NULL,                               /* pExcludeClipRect */
2243     NULL,                               /* pExtDeviceMode */
2244     NULL,                               /* pExtEscape */
2245     NULL,                               /* pExtFloodFill */
2246     NULL,                               /* pExtSelectClipRgn */
2247     pathdrv_ExtTextOut,                 /* pExtTextOut */
2248     NULL,                               /* pFillPath */
2249     NULL,                               /* pFillRgn */
2250     NULL,                               /* pFlattenPath */
2251     NULL,                               /* pFontIsLinked */
2252     NULL,                               /* pFrameRgn */
2253     NULL,                               /* pGdiComment */
2254     NULL,                               /* pGdiRealizationInfo */
2255     NULL,                               /* pGetBoundsRect */
2256     NULL,                               /* pGetCharABCWidths */
2257     NULL,                               /* pGetCharABCWidthsI */
2258     NULL,                               /* pGetCharWidth */
2259     NULL,                               /* pGetDeviceCaps */
2260     NULL,                               /* pGetDeviceGammaRamp */
2261     NULL,                               /* pGetFontData */
2262     NULL,                               /* pGetFontUnicodeRanges */
2263     NULL,                               /* pGetGlyphIndices */
2264     NULL,                               /* pGetGlyphOutline */
2265     NULL,                               /* pGetICMProfile */
2266     NULL,                               /* pGetImage */
2267     NULL,                               /* pGetKerningPairs */
2268     NULL,                               /* pGetNearestColor */
2269     NULL,                               /* pGetOutlineTextMetrics */
2270     NULL,                               /* pGetPixel */
2271     NULL,                               /* pGetSystemPaletteEntries */
2272     NULL,                               /* pGetTextCharsetInfo */
2273     NULL,                               /* pGetTextExtentExPoint */
2274     NULL,                               /* pGetTextExtentExPointI */
2275     NULL,                               /* pGetTextFace */
2276     NULL,                               /* pGetTextMetrics */
2277     NULL,                               /* pGradientFill */
2278     NULL,                               /* pIntersectClipRect */
2279     NULL,                               /* pInvertRgn */
2280     pathdrv_LineTo,                     /* pLineTo */
2281     NULL,                               /* pModifyWorldTransform */
2282     pathdrv_MoveTo,                     /* pMoveTo */
2283     NULL,                               /* pOffsetClipRgn */
2284     NULL,                               /* pOffsetViewportOrg */
2285     NULL,                               /* pOffsetWindowOrg */
2286     NULL,                               /* pPaintRgn */
2287     NULL,                               /* pPatBlt */
2288     pathdrv_Pie,                        /* pPie */
2289     pathdrv_PolyBezier,                 /* pPolyBezier */
2290     pathdrv_PolyBezierTo,               /* pPolyBezierTo */
2291     pathdrv_PolyDraw,                   /* pPolyDraw */
2292     pathdrv_PolyPolygon,                /* pPolyPolygon */
2293     pathdrv_PolyPolyline,               /* pPolyPolyline */
2294     pathdrv_Polygon,                    /* pPolygon */
2295     pathdrv_Polyline,                   /* pPolyline */
2296     pathdrv_PolylineTo,                 /* pPolylineTo */
2297     NULL,                               /* pPutImage */
2298     NULL,                               /* pRealizeDefaultPalette */
2299     NULL,                               /* pRealizePalette */
2300     pathdrv_Rectangle,                  /* pRectangle */
2301     NULL,                               /* pResetDC */
2302     NULL,                               /* pRestoreDC */
2303     pathdrv_RoundRect,                  /* pRoundRect */
2304     NULL,                               /* pSaveDC */
2305     NULL,                               /* pScaleViewportExt */
2306     NULL,                               /* pScaleWindowExt */
2307     NULL,                               /* pSelectBitmap */
2308     NULL,                               /* pSelectBrush */
2309     NULL,                               /* pSelectClipPath */
2310     NULL,                               /* pSelectFont */
2311     NULL,                               /* pSelectPalette */
2312     NULL,                               /* pSelectPen */
2313     NULL,                               /* pSetArcDirection */
2314     NULL,                               /* pSetBkColor */
2315     NULL,                               /* pSetBkMode */
2316     NULL,                               /* pSetDCBrushColor */
2317     NULL,                               /* pSetDCPenColor */
2318     NULL,                               /* pSetDIBColorTable */
2319     NULL,                               /* pSetDIBitsToDevice */
2320     NULL,                               /* pSetDeviceClipping */
2321     NULL,                               /* pSetDeviceGammaRamp */
2322     NULL,                               /* pSetLayout */
2323     NULL,                               /* pSetMapMode */
2324     NULL,                               /* pSetMapperFlags */
2325     NULL,                               /* pSetPixel */
2326     NULL,                               /* pSetPolyFillMode */
2327     NULL,                               /* pSetROP2 */
2328     NULL,                               /* pSetRelAbs */
2329     NULL,                               /* pSetStretchBltMode */
2330     NULL,                               /* pSetTextAlign */
2331     NULL,                               /* pSetTextCharacterExtra */
2332     NULL,                               /* pSetTextColor */
2333     NULL,                               /* pSetTextJustification */
2334     NULL,                               /* pSetViewportExt */
2335     NULL,                               /* pSetViewportOrg */
2336     NULL,                               /* pSetWindowExt */
2337     NULL,                               /* pSetWindowOrg */
2338     NULL,                               /* pSetWorldTransform */
2339     NULL,                               /* pStartDoc */
2340     NULL,                               /* pStartPage */
2341     NULL,                               /* pStretchBlt */
2342     NULL,                               /* pStretchDIBits */
2343     NULL,                               /* pStrokeAndFillPath */
2344     NULL,                               /* pStrokePath */
2345     NULL,                               /* pUnrealizePalette */
2346     NULL,                               /* pWidenPath */
2347     NULL,                               /* wine_get_wgl_driver */
2348     GDI_PRIORITY_PATH_DRV               /* priority */
2349 };