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