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