text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    A path is a sequence of lines and curves that may either form a closed shape
    or be open-ended.

    To use a path, you can create an empty one, then add lines and curves to it
    to create shapes, then it can be rendered by a Graphics context or used
    for geometric operations.

    e.g. @code
    Path myPath;

    myPath.startNewSubPath (10.0f, 10.0f);          // move the current position to (10, 10)
    myPath.lineTo (100.0f, 200.0f);                 // draw a line from here to (100, 200)
    myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
    myPath.closeSubPath();                          // close the subpath with a line back to (10, 10)

    // add an ellipse as well, which will form a second sub-path within the path..
    myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);

    // double the width of the whole thing..
    myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));

    // and draw it to a graphics context with a 5-pixel thick outline.
    g.strokePath (myPath, PathStrokeType (5.0f));

    @endcode

    A path object can actually contain multiple sub-paths, which may themselves
    be open or closed.

    @see PathFlatteningIterator, PathStrokeType, Graphics
*/
class JUCE_API  Path  final
{
public:
    //==============================================================================
    /** Creates an empty path. */
    Path();

    /** Creates a copy of another path. */
    Path (const Path&);

    /** Destructor. */
    ~Path();

    /** Copies this path from another one. */
    Path& operator= (const Path&);

    /** Move constructor */
    Path (Path&&) noexcept;

    /** Move assignment operator */
    Path& operator= (Path&&) noexcept;

    bool operator== (const Path&) const noexcept;
    bool operator!= (const Path&) const noexcept;

    static const float defaultToleranceForTesting;
    static const float defaultToleranceForMeasurement;

    //==============================================================================
    /** Returns true if the path doesn't contain any lines or curves. */
    bool isEmpty() const noexcept;

    /** Returns the smallest rectangle that contains all points within the path. */
    Rectangle<float> getBounds() const noexcept;

    /** Returns the smallest rectangle that contains all points within the path
        after it's been transformed with the given tranasform matrix.
    */
    Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;

    /** Checks whether a point lies within the path.

        This is only relevant for closed paths (see closeSubPath()), and
        may produce false results if used on a path which has open sub-paths.

        The path's winding rule is taken into account by this method.

        The tolerance parameter is the maximum error allowed when flattening the path,
        so this method could return a false positive when your point is up to this distance
        outside the path's boundary.

        @see closeSubPath, setUsingNonZeroWinding
    */
    bool contains (float x, float y,
                   float tolerance = defaultToleranceForTesting) const;

    /** Checks whether a point lies within the path.

        This is only relevant for closed paths (see closeSubPath()), and
        may produce false results if used on a path which has open sub-paths.

        The path's winding rule is taken into account by this method.

        The tolerance parameter is the maximum error allowed when flattening the path,
        so this method could return a false positive when your point is up to this distance
        outside the path's boundary.

        @see closeSubPath, setUsingNonZeroWinding
    */
    bool contains (Point<float> point,
                   float tolerance = defaultToleranceForTesting) const;

    /** Checks whether a line crosses the path.

        This will return positive if the line crosses any of the paths constituent
        lines or curves. It doesn't take into account whether the line is inside
        or outside the path, or whether the path is open or closed.

        The tolerance parameter is the maximum error allowed when flattening the path,
        so this method could return a false positive when your point is up to this distance
        outside the path's boundary.
    */
    bool intersectsLine (Line<float> line,
                         float tolerance = defaultToleranceForTesting);

    /** Cuts off parts of a line to keep the parts that are either inside or
        outside this path.

        Note that this isn't smart enough to cope with situations where the
        line would need to be cut into multiple pieces to correctly clip against
        a re-entrant shape.

        @param line                     the line to clip
        @param keepSectionOutsidePath   if true, it's the section outside the path
                                        that will be kept; if false its the section inside
                                        the path
    */
    Line<float> getClippedLine (Line<float> line, bool keepSectionOutsidePath) const;

    /** Returns the length of the path.
        @see getPointAlongPath
    */
    float getLength (const AffineTransform& transform = AffineTransform(),
                     float tolerance = defaultToleranceForMeasurement) const;

    /** Returns a point that is the specified distance along the path.
        If the distance is greater than the total length of the path, this will return the
        end point.
        @see getLength
    */
    Point<float> getPointAlongPath (float distanceFromStart,
                                    const AffineTransform& transform = AffineTransform(),
                                    float tolerance = defaultToleranceForMeasurement) const;

    /** Finds the point along the path which is nearest to a given position.
        This sets pointOnPath to the nearest point, and returns the distance of this point from the start
        of the path.
    */
    float getNearestPoint (Point<float> targetPoint,
                           Point<float>& pointOnPath,
                           const AffineTransform& transform = AffineTransform(),
                           float tolerance = defaultToleranceForMeasurement) const;

    //==============================================================================
    /** Removes all lines and curves, resetting the path completely. */
    void clear() noexcept;

    /** Begins a new subpath with a given starting position.

        This will move the path's current position to the coordinates passed in and
        make it ready to draw lines or curves starting from this position.

        After adding whatever lines and curves are needed, you can either
        close the current sub-path using closeSubPath() or call startNewSubPath()
        to move to a new sub-path, leaving the old one open-ended.

        @see lineTo, quadraticTo, cubicTo, closeSubPath
    */
    void startNewSubPath (float startX, float startY);

    /** Begins a new subpath with a given starting position.

        This will move the path's current position to the coordinates passed in and
        make it ready to draw lines or curves starting from this position.

        After adding whatever lines and curves are needed, you can either
        close the current sub-path using closeSubPath() or call startNewSubPath()
        to move to a new sub-path, leaving the old one open-ended.

        @see lineTo, quadraticTo, cubicTo, closeSubPath
    */
    void startNewSubPath (Point<float> start);

    /** Closes a the current sub-path with a line back to its start-point.

        When creating a closed shape such as a triangle, don't use 3 lineTo()
        calls - instead use two lineTo() calls, followed by a closeSubPath()
        to join the final point back to the start.

        This ensures that closes shapes are recognised as such, and this is
        important for tasks like drawing strokes, which needs to know whether to
        draw end-caps or not.

        @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
    */
    void closeSubPath();

    /** Adds a line from the shape's last position to a new end-point.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a straight line.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
    */
    void lineTo (float endX, float endY);

    /** Adds a line from the shape's last position to a new end-point.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a straight line.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
    */
    void lineTo (Point<float> end);

    /** Adds a quadratic bezier curve from the shape's last position to a new position.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a quadratic spline with one control-point.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, lineTo, cubicTo, closeSubPath
    */
    void quadraticTo (float controlPointX,
                      float controlPointY,
                      float endPointX,
                      float endPointY);

    /** Adds a quadratic bezier curve from the shape's last position to a new position.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a quadratic spline with one control-point.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, lineTo, cubicTo, closeSubPath
    */
    void quadraticTo (Point<float> controlPoint,
                      Point<float> endPoint);

    /** Adds a cubic bezier curve from the shape's last position to a new position.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a cubic spline with two control-points.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, lineTo, quadraticTo, closeSubPath
    */
    void cubicTo (float controlPoint1X,
                  float controlPoint1Y,
                  float controlPoint2X,
                  float controlPoint2Y,
                  float endPointX,
                  float endPointY);

    /** Adds a cubic bezier curve from the shape's last position to a new position.

        This will connect the end-point of the last line or curve that was added
        to a new point, using a cubic spline with two control-points.

        See the class description for an example of how to add lines and curves to a path.

        @see startNewSubPath, lineTo, quadraticTo, closeSubPath
    */
    void cubicTo (Point<float> controlPoint1,
                  Point<float> controlPoint2,
                  Point<float> endPoint);

    /** Returns the last point that was added to the path by one of the drawing methods.
    */
    Point<float> getCurrentPosition() const;

    //==============================================================================
    /** Adds a rectangle to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRoundedRectangle, addTriangle
    */
    void addRectangle (float x, float y, float width, float height);

    /** Adds a rectangle to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRoundedRectangle, addTriangle
    */
    template <typename ValueType>
    void addRectangle (Rectangle<ValueType> rectangle)
    {
        addRectangle (static_cast<float> (rectangle.getX()), static_cast<float> (rectangle.getY()),
                      static_cast<float> (rectangle.getWidth()), static_cast<float> (rectangle.getHeight()));
    }

    /** Adds a rectangle with rounded corners to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRectangle, addTriangle
    */
    void addRoundedRectangle (float x, float y, float width, float height,
                              float cornerSize);

    /** Adds a rectangle with rounded corners to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRectangle, addTriangle
    */
    void addRoundedRectangle (float x, float y, float width, float height,
                              float cornerSizeX,
                              float cornerSizeY);

    /** Adds a rectangle with rounded corners to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRectangle, addTriangle
    */
    void addRoundedRectangle (float x, float y, float width, float height,
                              float cornerSizeX, float cornerSizeY,
                              bool curveTopLeft, bool curveTopRight,
                              bool curveBottomLeft, bool curveBottomRight);

    /** Adds a rectangle with rounded corners to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRectangle, addTriangle
    */
    template <typename ValueType>
    void addRoundedRectangle (Rectangle<ValueType> rectangle, float cornerSizeX, float cornerSizeY)
    {
        addRoundedRectangle (static_cast<float> (rectangle.getX()), static_cast<float> (rectangle.getY()),
                             static_cast<float> (rectangle.getWidth()), static_cast<float> (rectangle.getHeight()),
                             cornerSizeX, cornerSizeY);
    }

    /** Adds a rectangle with rounded corners to the path.
        The rectangle is added as a new sub-path. (Any currently open paths will be left open).
        @see addRectangle, addTriangle
    */
    template <typename ValueType>
    void addRoundedRectangle (Rectangle<ValueType> rectangle, float cornerSize)
    {
        addRoundedRectangle (rectangle, cornerSize, cornerSize);
    }

    /** Adds a triangle to the path.

        The triangle is added as a new closed sub-path. (Any currently open paths will be left open).

        Note that whether the vertices are specified in clockwise or anticlockwise
        order will affect how the triangle is filled when it overlaps other
        shapes (the winding order setting will affect this of course).
    */
    void addTriangle (float x1, float y1,
                      float x2, float y2,
                      float x3, float y3);

    /** Adds a triangle to the path.

        The triangle is added as a new closed sub-path. (Any currently open paths will be left open).

        Note that whether the vertices are specified in clockwise or anticlockwise
        order will affect how the triangle is filled when it overlaps other
        shapes (the winding order setting will affect this of course).
    */
    void addTriangle (Point<float> point1,
                      Point<float> point2,
                      Point<float> point3);

    /** Adds a quadrilateral to the path.

        The quad is added as a new closed sub-path. (Any currently open paths will be left open).

        Note that whether the vertices are specified in clockwise or anticlockwise
        order will affect how the quad is filled when it overlaps other
        shapes (the winding order setting will affect this of course).
    */
    void addQuadrilateral (float x1, float y1,
                           float x2, float y2,
                           float x3, float y3,
                           float x4, float y4);

    /** Adds an ellipse to the path.
        The shape is added as a new sub-path. (Any currently open paths will be left open).
        @see addArc
    */
    void addEllipse (float x, float y, float width, float height);

    /** Adds an ellipse to the path.
        The shape is added as a new sub-path. (Any currently open paths will be left open).
        @see addArc
    */
    void addEllipse (Rectangle<float> area);

    /** Adds an elliptical arc to the current path.

        Note that when specifying the start and end angles, the curve will be drawn either clockwise
        or anti-clockwise according to whether the end angle is greater than the start. This means
        that sometimes you may need to use values greater than 2*Pi for the end angle.

        @param x            the left-hand edge of the rectangle in which the elliptical outline fits
        @param y            the top edge of the rectangle in which the elliptical outline fits
        @param width        the width of the rectangle in which the elliptical outline fits
        @param height       the height of the rectangle in which the elliptical outline fits
        @param fromRadians  the angle (clockwise) in radians at which to start the arc segment (where 0 is the
                            top-centre of the ellipse)
        @param toRadians    the angle (clockwise) in radians at which to end the arc segment (where 0 is the
                            top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
                            draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
                            12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
        @param startAsNewSubPath    if true, the arc will begin a new subpath from its starting point; if false,
                            it will be added to the current sub-path, continuing from the current postition

        @see addCentredArc, arcTo, addPieSegment, addEllipse
    */
    void addArc (float x, float y, float width, float height,
                 float fromRadians,
                 float toRadians,
                 bool startAsNewSubPath = false);

    /** Adds an arc which is centred at a given point, and can have a rotation specified.

        Note that when specifying the start and end angles, the curve will be drawn either clockwise
        or anti-clockwise according to whether the end angle is greater than the start. This means
        that sometimes you may need to use values greater than 2*Pi for the end angle.

        @param centreX      the centre x of the ellipse
        @param centreY      the centre y of the ellipse
        @param radiusX      the horizontal radius of the ellipse
        @param radiusY      the vertical radius of the ellipse
        @param rotationOfEllipse    an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
        @param fromRadians  the angle (clockwise) in radians at which to start the arc segment (where 0 is the
                            top-centre of the ellipse)
        @param toRadians    the angle (clockwise) in radians at which to end the arc segment (where 0 is the
                            top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
                            draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
                            12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
        @param startAsNewSubPath    if true, the arc will begin a new subpath from its starting point; if false,
                            it will be added to the current sub-path, continuing from the current postition

        @see addArc, arcTo
    */
    void addCentredArc (float centreX, float centreY,
                        float radiusX, float radiusY,
                        float rotationOfEllipse,
                        float fromRadians,
                        float toRadians,
                        bool startAsNewSubPath = false);

    /** Adds a "pie-chart" shape to the path.

        The shape is added as a new sub-path. (Any currently open paths will be
        left open).

        Note that when specifying the start and end angles, the curve will be drawn either clockwise
        or anti-clockwise according to whether the end angle is greater than the start. This means
        that sometimes you may need to use values greater than 2*Pi for the end angle.

        @param x            the left-hand edge of the rectangle in which the elliptical outline fits
        @param y            the top edge of the rectangle in which the elliptical outline fits
        @param width        the width of the rectangle in which the elliptical outline fits
        @param height       the height of the rectangle in which the elliptical outline fits
        @param fromRadians  the angle (clockwise) in radians at which to start the arc segment (where 0 is the
                            top-centre of the ellipse)
        @param toRadians    the angle (clockwise) in radians at which to end the arc segment (where 0 is the
                            top-centre of the ellipse)
        @param innerCircleProportionalSize  if this is > 0, then the pie will be drawn as a curved band around a hollow
                            ellipse at its centre, where this value indicates the inner ellipse's size with
                            respect to the outer one.
        @see addArc
    */
    void addPieSegment (float x, float y,
                        float width, float height,
                        float fromRadians,
                        float toRadians,
                        float innerCircleProportionalSize);

    /** Adds a "pie-chart" shape to the path.

        The shape is added as a new sub-path. (Any currently open paths will be left open).

        Note that when specifying the start and end angles, the curve will be drawn either clockwise
        or anti-clockwise according to whether the end angle is greater than the start. This means
        that sometimes you may need to use values greater than 2*Pi for the end angle.

        @param segmentBounds the outer rectangle in which the elliptical outline fits
        @param fromRadians   the angle (clockwise) in radians at which to start the arc segment (where 0 is the
                             top-centre of the ellipse)
        @param toRadians     the angle (clockwise) in radians at which to end the arc segment (where 0 is the
                             top-centre of the ellipse)
        @param innerCircleProportionalSize  if this is > 0, then the pie will be drawn as a curved band around a hollow
                             ellipse at its centre, where this value indicates the inner ellipse's size with
                             respect to the outer one.
        @see addArc
    */
    void addPieSegment (Rectangle<float> segmentBounds,
                        float fromRadians,
                        float toRadians,
                        float innerCircleProportionalSize);

    /** Adds a line with a specified thickness.

        The line is added as a new closed sub-path. (Any currently open paths will be
        left open).

        @see addArrow
    */
    void addLineSegment (Line<float> line, float lineThickness);

    /** Adds a line with an arrowhead on the end.
        The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
        @see PathStrokeType::createStrokeWithArrowheads
    */
    void addArrow (Line<float> line,
                   float lineThickness,
                   float arrowheadWidth,
                   float arrowheadLength);

    /** Adds a polygon shape to the path.
        @see addStar
    */
    void addPolygon (Point<float> centre,
                     int numberOfSides,
                     float radius,
                     float startAngle = 0.0f);

    /** Adds a star shape to the path.
        @see addPolygon
    */
    void addStar (Point<float> centre,
                  int numberOfPoints,
                  float innerRadius,
                  float outerRadius,
                  float startAngle = 0.0f);

    /** Adds a speech-bubble shape to the path.

        @param bodyArea         the area of the body of the bubble shape
        @param maximumArea      an area which encloses the body area and defines the limits within which
                                the arrow tip can be drawn - if the tip lies outside this area, the bubble
                                will be drawn without an arrow
        @param arrowTipPosition the location of the tip of the arrow
        @param cornerSize       the size of the rounded corners
        @param arrowBaseWidth   the width of the base of the arrow where it joins the main rectangle
    */
    void addBubble (Rectangle<float> bodyArea,
                    Rectangle<float> maximumArea,
                    const Point<float> arrowTipPosition,
                    const float cornerSize,
                    const float arrowBaseWidth);

    /** Adds another path to this one.

        The new path is added as a new sub-path. (Any currently open paths in this
        path will be left open).

        @param pathToAppend     the path to add
    */
    void addPath (const Path& pathToAppend);

    /** Adds another path to this one, transforming it on the way in.

        The new path is added as a new sub-path, its points being transformed by the given
        matrix before being added.

        @param pathToAppend     the path to add
        @param transformToApply an optional transform to apply to the incoming vertices
    */
    void addPath (const Path& pathToAppend,
                  const AffineTransform& transformToApply);

    /** Swaps the contents of this path with another one.

        The internal data of the two paths is swapped over, so this is much faster than
        copying it to a temp variable and back.
    */
    void swapWithPath (Path&) noexcept;

    //==============================================================================
    /** Preallocates enough space for adding the given number of coordinates to the path.
        If you're about to add a large number of lines or curves to the path, it can make
        the task much more efficient to call this first and avoid costly reallocations
        as the structure grows.
        The actual value to pass is a bit tricky to calculate because the space required
        depends on what you're adding - e.g. each lineTo() or startNewSubPath() will
        require 3 coords (x, y and a type marker). Each quadraticTo() will need 5, and
        a cubicTo() will require 7. Closing a sub-path will require 1.
    */
    void preallocateSpace (int numExtraCoordsToMakeSpaceFor);

    //==============================================================================
    /** Applies a 2D transform to all the vertices in the path.

        @see AffineTransform, scaleToFit, getTransformToScaleToFit
    */
    void applyTransform (const AffineTransform& transform) noexcept;

    /** Rescales this path to make it fit neatly into a given space.

        This is effectively a quick way of calling
        applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))

        @param x                    the x position of the rectangle to fit the path inside
        @param y                    the y position of the rectangle to fit the path inside
        @param width                the width of the rectangle to fit the path inside
        @param height               the height of the rectangle to fit the path inside
        @param preserveProportions  if true, it will fit the path into the space without altering its
                                    horizontal/vertical scale ratio; if false, it will distort the
                                    path to fill the specified ratio both horizontally and vertically

        @see applyTransform, getTransformToScaleToFit
    */
    void scaleToFit (float x, float y, float width, float height,
                     bool preserveProportions) noexcept;

    /** Returns a transform that can be used to rescale the path to fit into a given space.

        @param x                    the x position of the rectangle to fit the path inside
        @param y                    the y position of the rectangle to fit the path inside
        @param width                the width of the rectangle to fit the path inside
        @param height               the height of the rectangle to fit the path inside
        @param preserveProportions  if true, it will fit the path into the space without altering its
                                    horizontal/vertical scale ratio; if false, it will distort the
                                    path to fill the specified ratio both horizontally and vertically
        @param justificationType    if the proportions are preseved, the resultant path may be smaller
                                    than the available rectangle, so this describes how it should be
                                    positioned within the space.
        @returns                    an appropriate transformation

        @see applyTransform, scaleToFit

    */
    AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
                                              bool preserveProportions,
                                              Justification justificationType = Justification::centred) const;

    /** Returns a transform that can be used to rescale the path to fit into a given space.

        @param area                 the rectangle to fit the path inside
        @param preserveProportions  if true, it will fit the path into the space without altering its
                                    horizontal/vertical scale ratio; if false, it will distort the
                                    path to fill the specified ratio both horizontally and vertically
        @param justificationType    if the proportions are preseved, the resultant path may be smaller
                                    than the available rectangle, so this describes how it should be
                                    positioned within the space.
        @returns                    an appropriate transformation

        @see applyTransform, scaleToFit

    */
    AffineTransform getTransformToScaleToFit (Rectangle<float> area,
                                              bool preserveProportions,
                                              Justification justificationType = Justification::centred) const;

    /** Creates a version of this path where all sharp corners have been replaced by curves.

        Wherever two lines meet at an angle, this will replace the corner with a curve
        of the given radius.
    */
    Path createPathWithRoundedCorners (float cornerRadius) const;

    //==============================================================================
    /** Changes the winding-rule to be used when filling the path.

        If set to true (which is the default), then the path uses a non-zero-winding rule
        to determine which points are inside the path. If set to false, it uses an
        alternate-winding rule.

        The winding-rule comes into play when areas of the shape overlap other
        areas, and determines whether the overlapping regions are considered to be
        inside or outside.

        Changing this value just sets a flag - it doesn't affect the contents of the
        path.

        @see isUsingNonZeroWinding
    */
    void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;

    /** Returns the flag that indicates whether the path should use a non-zero winding rule.

        The default for a new path is true.

        @see setUsingNonZeroWinding
    */
    bool isUsingNonZeroWinding() const                  { return useNonZeroWinding; }

    //==============================================================================
    /** Iterates the lines and curves that a path contains.

        @see Path, PathFlatteningIterator
    */
    class JUCE_API  Iterator
    {
    public:
        //==============================================================================
        Iterator (const Path& path) noexcept;
        ~Iterator() noexcept;

        //==============================================================================
        /** Moves onto the next element in the path.

            If this returns false, there are no more elements. If it returns true,
            the elementType variable will be set to the type of the current element,
            and some of the x and y variables will be filled in with values.
        */
        bool next() noexcept;

        //==============================================================================
        enum PathElementType
        {
            startNewSubPath,    /**< For this type, x1 and y1 will be set to indicate the first point in the subpath.  */
            lineTo,             /**< For this type, x1 and y1 indicate the end point of the line.  */
            quadraticTo,        /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
            cubicTo,            /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
            closePath           /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
        };

        PathElementType elementType;

        float x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0;

        //==============================================================================
    private:
        const Path& path;
        size_t index = 0;

        JUCE_DECLARE_NON_COPYABLE (Iterator)
    };

    //==============================================================================
    /** Loads a stored path from a data stream.

        The data in the stream must have been written using writePathToStream().

        Note that this will append the stored path to whatever is currently in
        this path, so you might need to call clear() beforehand.

        @see loadPathFromData, writePathToStream
    */
    void loadPathFromStream (InputStream& source);

    /** Loads a stored path from a block of data.

        This is similar to loadPathFromStream(), but just reads from a block
        of data. Useful if you're including stored shapes in your code as a
        block of static data.

        @see loadPathFromStream, writePathToStream
    */
    void loadPathFromData (const void* data, size_t numberOfBytes);

    /** Stores the path by writing it out to a stream.
        After writing out a path, you can reload it using loadPathFromStream().
        @see loadPathFromStream, loadPathFromData
    */
    void writePathToStream (OutputStream& destination) const;

    //==============================================================================
    /** Creates a string containing a textual representation of this path.
        @see restoreFromString
    */
    String toString() const;

    /** Restores this path from a string that was created with the toString() method.
        @see toString()
    */
    void restoreFromString (StringRef stringVersion);

private:
    //==============================================================================
    friend class PathFlatteningIterator;
    friend class Path::Iterator;
    friend class EdgeTable;

    ArrayAllocationBase<float, DummyCriticalSection> data;
    size_t numElements = 0;

    struct PathBounds
    {
        PathBounds() noexcept;
        Rectangle<float> getRectangle() const noexcept;
        void reset() noexcept;
        void reset (float, float) noexcept;
        void extend (float, float) noexcept;
        void extend (float, float, float, float) noexcept;

        float pathXMin = 0, pathXMax = 0, pathYMin = 0, pathYMax = 0;
    };

    PathBounds bounds;
    bool useNonZeroWinding = true;

    static const float lineMarker;
    static const float moveMarker;
    static const float quadMarker;
    static const float cubicMarker;
    static const float closeSubPathMarker;

    JUCE_LEAK_DETECTOR (Path)
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{
    Image JUCE_API getIconFromApplication (const String&, int)  { return {}; }
}

repo_name: fedden/RenderMan

mime_type: text/x-c++


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

namespace GraphicsHelpers
{
    jobject createPaint (Graphics::ResamplingQuality quality)
    {
        jint constructorFlags = 1 /*ANTI_ALIAS_FLAG*/
                                | 4 /*DITHER_FLAG*/
                                | 128 /*SUBPIXEL_TEXT_FLAG*/;

        if (quality > Graphics::lowResamplingQuality)
            constructorFlags |= 2; /*FILTER_BITMAP_FLAG*/

        return getEnv()->NewObject (Paint, Paint.constructor, constructorFlags);
    }

    const jobject createMatrix (JNIEnv* env, const AffineTransform& t)
    {
        jobject m = env->NewObject (Matrix, Matrix.constructor);

        jfloat values[9] = { t.mat00, t.mat01, t.mat02,
                             t.mat10, t.mat11, t.mat12,
                             0.0f, 0.0f, 1.0f };

        jfloatArray javaArray = env->NewFloatArray (9);
        env->SetFloatArrayRegion (javaArray, 0, 9, values);

        env->CallVoidMethod (m, Matrix.setValues, javaArray);
        env->DeleteLocalRef (javaArray);

        return m;
    }
}

ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
{
    return SoftwareImageType().create (format, width, height, clearImage);
}

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

template <typename Type>
D2D1_RECT_F rectangleToRectF (const Rectangle<Type>& r)
{
    return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
}

static D2D1_COLOR_F colourToD2D (Colour c)
{
    return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
}

static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform)
{
    Path::Iterator it (path);

    while (it.next())
    {
        switch (it.elementType)
        {
        case Path::Iterator::cubicTo:
        {
            D2D1_BEZIER_SEGMENT seg;

            transform.transformPoint   (it.x1, it.y1);
            seg.point1 = D2D1::Point2F (it.x1, it.y1);

            transform.transformPoint   (it.x2, it.y2);
            seg.point2 = D2D1::Point2F (it.x2, it.y2);

            transform.transformPoint   (it.x3, it.y3);
            seg.point3 = D2D1::Point2F (it.x3, it.y3);

            sink->AddBezier (seg);
            break;
        }

        case Path::Iterator::lineTo:
        {
            transform.transformPoint     (it.x1, it.y1);
            sink->AddLine (D2D1::Point2F (it.x1, it.y1));
            break;
        }

        case Path::Iterator::quadraticTo:
        {
            D2D1_QUADRATIC_BEZIER_SEGMENT seg;

            transform.transformPoint   (it.x1, it.y1);
            seg.point1 = D2D1::Point2F (it.x1, it.y1);

            transform.transformPoint   (it.x2, it.y2);
            seg.point2 = D2D1::Point2F (it.x2, it.y2);

            sink->AddQuadraticBezier (seg);
            break;
        }

        case Path::Iterator::closePath:
        {
            sink->EndFigure (D2D1_FIGURE_END_CLOSED);
            break;
        }

        case Path::Iterator::startNewSubPath:
        {
            transform.transformPoint         (it.x1, it.y1);
            sink->BeginFigure (D2D1::Point2F (it.x1, it.y1), D2D1_FIGURE_BEGIN_FILLED);
            break;
        }
        }
    }
}

static D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
{
    D2D1::Matrix3x2F matrix;
    matrix._11 = transform.mat00;
    matrix._12 = transform.mat10;
    matrix._21 = transform.mat01;
    matrix._22 = transform.mat11;
    matrix._31 = transform.mat02;
    matrix._32 = transform.mat12;
    return matrix;
}

static D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform)
{
    transform.transformPoint (x, y);
    return D2D1::Point2F ((FLOAT) x, (FLOAT) y);
}

static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink, const AffineTransform& transform)
{
    sink->BeginFigure (pointTransformed (rect.getX(),     rect.getY(),       transform), D2D1_FIGURE_BEGIN_FILLED);
    sink->AddLine     (pointTransformed (rect.getRight(), rect.getY(),       transform));
    sink->AddLine     (pointTransformed (rect.getRight(), rect.getBottom(),  transform));
    sink->AddLine     (pointTransformed (rect.getX(),     rect.getBottom(),  transform));
    sink->EndFigure (D2D1_FIGURE_END_CLOSED);
}

//==============================================================================
struct Direct2DLowLevelGraphicsContext::Pimpl
{
    ID2D1PathGeometry* rectListToPathGeometry (const RectangleList<int>& clipRegion)
    {
        ID2D1PathGeometry* p = nullptr;
        factories->d2dFactory->CreatePathGeometry (&p);

        ComSmartPtr<ID2D1GeometrySink> sink;
        HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
        sink->SetFillMode (D2D1_FILL_MODE_WINDING);

        for (int i = clipRegion.getNumRectangles(); --i >= 0;)
            rectToGeometrySink (clipRegion.getRectangle(i), sink, AffineTransform());

        hr = sink->Close();
        return p;
    }

    ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform)
    {
        ID2D1PathGeometry* p = nullptr;
        factories->d2dFactory->CreatePathGeometry (&p);

        ComSmartPtr<ID2D1GeometrySink> sink;
        HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
        sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()

        pathToGeometrySink (path, sink, transform);

        hr = sink->Close();
        return p;
    }

    SharedResourcePointer<Direct2DFactories> factories;

    ComSmartPtr<ID2D1HwndRenderTarget> renderingTarget;
    ComSmartPtr<ID2D1SolidColorBrush> colourBrush;
};

//==============================================================================
struct Direct2DLowLevelGraphicsContext::SavedState
{
public:
    SavedState (Direct2DLowLevelGraphicsContext& owner_)
        : owner (owner_)
    {
        if (owner.currentState != nullptr)
        {
            // xxx seems like a very slow way to create one of these, and this is a performance
            // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
            setFill (owner.currentState->fillType);
            currentBrush = owner.currentState->currentBrush;
            clipRect = owner.currentState->clipRect;
            transform = owner.currentState->transform;

            font = owner.currentState->font;
            currentFontFace = owner.currentState->currentFontFace;
        }
        else
        {
            const D2D1_SIZE_U size (owner.pimpl->renderingTarget->GetPixelSize());
            clipRect.setSize (size.width, size.height);
            setFill (FillType (Colours::black));
        }
    }

    ~SavedState()
    {
        clearClip();
        clearFont();
        clearFill();
        clearPathClip();
        clearImageClip();
        complexClipLayer = nullptr;
        bitmapMaskLayer = nullptr;
    }

    void clearClip()
    {
        popClips();
        shouldClipRect = false;
    }

    void clipToRectangle (const Rectangle<int>& r)
    {
        clearClip();
        clipRect = r.toFloat().transformed (transform).getSmallestIntegerContainer();
        shouldClipRect = true;
        pushClips();
    }

    void clearPathClip()
    {
        popClips();

        if (shouldClipComplex)
        {
            complexClipGeometry = nullptr;
            shouldClipComplex = false;
        }
    }

    void Direct2DLowLevelGraphicsContext::SavedState::clipToPath (ID2D1Geometry* geometry)
    {
        clearPathClip();

        if (complexClipLayer == nullptr)
            owner.pimpl->renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());

        complexClipGeometry = geometry;
        shouldClipComplex = true;
        pushClips();
    }

    void clearRectListClip()
    {
        popClips();

        if (shouldClipRectList)
        {
            rectListGeometry = nullptr;
            shouldClipRectList = false;
        }
    }

    void clipToRectList (ID2D1Geometry* geometry)
    {
        clearRectListClip();

        if (rectListLayer == nullptr)
            owner.pimpl->renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());

        rectListGeometry = geometry;
        shouldClipRectList = true;
        pushClips();
    }

    void clearImageClip()
    {
        popClips();

        if (shouldClipBitmap)
        {
            maskBitmap = nullptr;
            bitmapMaskBrush = nullptr;
            shouldClipBitmap = false;
        }
    }

    void clipToImage (const Image& clipImage, const AffineTransform& clipTransform)
    {
        clearImageClip();

        if (bitmapMaskLayer == nullptr)
            owner.pimpl->renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());

        D2D1_BRUSH_PROPERTIES brushProps;
        brushProps.opacity = 1;
        brushProps.transform = transformToMatrix (clipTransform);

        D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);

        D2D1_SIZE_U size;
        size.width  = clipImage.getWidth();
        size.height = clipImage.getHeight();

        D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();

        maskImage = clipImage.convertedToFormat (Image::ARGB);
        Image::BitmapData bd (maskImage, Image::BitmapData::readOnly); // xxx should be maskImage?
        bp.pixelFormat = owner.pimpl->renderingTarget->GetPixelFormat();
        bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;

        HRESULT hr = owner.pimpl->renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
        hr = owner.pimpl->renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());

        imageMaskLayerParams = D2D1::LayerParameters();
        imageMaskLayerParams.opacityBrush = bitmapMaskBrush;

        shouldClipBitmap = true;
        pushClips();
    }

    void popClips()
    {
        if (clipsBitmap)
        {
            owner.pimpl->renderingTarget->PopLayer();
            clipsBitmap = false;
        }

        if (clipsComplex)
        {
            owner.pimpl->renderingTarget->PopLayer();
            clipsComplex = false;
        }

        if (clipsRectList)
        {
            owner.pimpl->renderingTarget->PopLayer();
            clipsRectList = false;
        }

        if (clipsRect)
        {
            owner.pimpl->renderingTarget->PopAxisAlignedClip();
            clipsRect = false;
        }
    }

    void pushClips()
    {
        if (shouldClipRect && !clipsRect)
        {
            owner.pimpl->renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
            clipsRect = true;
        }

        if (shouldClipRectList && !clipsRectList)
        {
            D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
            rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
            layerParams.geometricMask = rectListGeometry;
            owner.pimpl->renderingTarget->PushLayer (layerParams, rectListLayer);
            clipsRectList = true;
        }

        if (shouldClipComplex && !clipsComplex)
        {
            D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
            complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
            layerParams.geometricMask = complexClipGeometry;
            owner.pimpl->renderingTarget->PushLayer (layerParams, complexClipLayer);
            clipsComplex = true;
        }

        if (shouldClipBitmap && !clipsBitmap)
        {
            owner.pimpl->renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
            clipsBitmap = true;
        }
    }

    void setFill (const FillType& newFillType)
    {
        if (fillType != newFillType)
        {
            fillType = newFillType;
            clearFill();
        }
    }

    void clearFont()
    {
        currentFontFace = localFontFace = nullptr;
    }

    void setFont (const Font& newFont)
    {
        if (font != newFont)
        {
            font = newFont;
            clearFont();
        }
    }

    void createFont()
    {
        if (currentFontFace == nullptr)
        {
            WindowsDirectWriteTypeface* typeface = dynamic_cast<WindowsDirectWriteTypeface*> (font.getTypeface());
            currentFontFace = typeface->getIDWriteFontFace();
            fontHeightToEmSizeFactor = typeface->getUnitsToHeightScaleFactor();
        }
    }

    void setOpacity (float newOpacity)
    {
        fillType.setOpacity (newOpacity);

        if (currentBrush != nullptr)
            currentBrush->SetOpacity (newOpacity);
    }

    void clearFill()
    {
        gradientStops = nullptr;
        linearGradient = nullptr;
        radialGradient = nullptr;
        bitmap = nullptr;
        bitmapBrush = nullptr;
        currentBrush = nullptr;
    }

    void createBrush()
    {
        if (currentBrush == nullptr)
        {
            if (fillType.isColour())
            {
                D2D1_COLOR_F colour = colourToD2D (fillType.colour);
                owner.pimpl->colourBrush->SetColor (colour);
                currentBrush = owner.pimpl->colourBrush;
            }
            else if (fillType.isTiledImage())
            {
                D2D1_BRUSH_PROPERTIES brushProps;
                brushProps.opacity = fillType.getOpacity();
                brushProps.transform = transformToMatrix (fillType.transform);

                D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);

                image = fillType.image;

                D2D1_SIZE_U size;
                size.width = image.getWidth();
                size.height = image.getHeight();

                D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();

                this->image = image.convertedToFormat (Image::ARGB);
                Image::BitmapData bd (this->image, Image::BitmapData::readOnly);
                bp.pixelFormat = owner.pimpl->renderingTarget->GetPixelFormat();
                bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;

                HRESULT hr = owner.pimpl->renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
                hr = owner.pimpl->renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());

                currentBrush = bitmapBrush;
            }
            else if (fillType.isGradient())
            {
                gradientStops = nullptr;

                D2D1_BRUSH_PROPERTIES brushProps;
                brushProps.opacity = fillType.getOpacity();
                brushProps.transform = transformToMatrix (fillType.transform.followedBy (transform));

                const int numColors = fillType.gradient->getNumColours();

                HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);

                for (int i = fillType.gradient->getNumColours(); --i >= 0;)
                {
                    stops[i].color = colourToD2D (fillType.gradient->getColour (i));
                    stops[i].position = (FLOAT) fillType.gradient->getColourPosition (i);
                }

                owner.pimpl->renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());

                if (fillType.gradient->isRadial)
                {
                    radialGradient = nullptr;

                    const Point<float> p1 = fillType.gradient->point1;
                    const Point<float> p2 = fillType.gradient->point2;
                    float r = p1.getDistanceFrom(p2);

                    D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
                        D2D1::RadialGradientBrushProperties(D2D1::Point2F(p1.x, p1.y),
                            D2D1::Point2F(0, 0),
                            r, r);

                    owner.pimpl->renderingTarget->CreateRadialGradientBrush(props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
                    currentBrush = radialGradient;
                }
                else
                {
                    linearGradient = 0;

                    const Point<float> p1 = fillType.gradient->point1;
                    const Point<float> p2 = fillType.gradient->point2;

                    D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
                        D2D1::LinearGradientBrushProperties(D2D1::Point2F(p1.x, p1.y),
                            D2D1::Point2F(p2.x, p2.y));

                    owner.pimpl->renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());

                    currentBrush = linearGradient;
                }
            }
        }
    }

    Direct2DLowLevelGraphicsContext& owner;

    AffineTransform transform;

    Font font;
    float fontHeightToEmSizeFactor = 1.0;

    IDWriteFontFace* currentFontFace = nullptr;
    ComSmartPtr<IDWriteFontFace> localFontFace;

    Rectangle<int> clipRect;
    bool clipsRect = false, shouldClipRect = false;

    Image image;
    ComSmartPtr<ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
    bool clipsBitmap = false, shouldClipBitmap = false;

    ComSmartPtr<ID2D1Geometry> complexClipGeometry;
    D2D1_LAYER_PARAMETERS complexClipLayerParams;
    ComSmartPtr<ID2D1Layer> complexClipLayer;
    bool clipsComplex = false, shouldClipComplex = false;

    ComSmartPtr<ID2D1Geometry> rectListGeometry;
    D2D1_LAYER_PARAMETERS rectListLayerParams;
    ComSmartPtr<ID2D1Layer> rectListLayer;
    bool clipsRectList = false, shouldClipRectList = false;

    Image maskImage;
    D2D1_LAYER_PARAMETERS imageMaskLayerParams;
    ComSmartPtr<ID2D1Layer> bitmapMaskLayer;
    ComSmartPtr<ID2D1Bitmap> maskBitmap;
    ComSmartPtr<ID2D1BitmapBrush> bitmapMaskBrush;

    ID2D1Brush* currentBrush = nullptr;
    ComSmartPtr<ID2D1BitmapBrush> bitmapBrush;
    ComSmartPtr<ID2D1LinearGradientBrush> linearGradient;
    ComSmartPtr<ID2D1RadialGradientBrush> radialGradient;
    ComSmartPtr<ID2D1GradientStopCollection> gradientStops;

    FillType fillType;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState)
};

//==============================================================================
Direct2DLowLevelGraphicsContext::Direct2DLowLevelGraphicsContext (HWND hwnd_)
    : hwnd (hwnd_),
      currentState (nullptr),
      pimpl (new Pimpl())
{
    RECT windowRect;
    GetClientRect (hwnd, &windowRect);
    D2D1_SIZE_U size = { (UINT32) (windowRect.right - windowRect.left), (UINT32) (windowRect.bottom - windowRect.top) };
    bounds.setSize (size.width, size.height);

    D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
    D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);

    if (pimpl->factories->d2dFactory != nullptr)
    {
        HRESULT hr = pimpl->factories->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, pimpl->renderingTarget.resetAndGetPointerAddress());
        jassert (SUCCEEDED (hr)); ignoreUnused (hr);
        hr = pimpl->renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), pimpl->colourBrush.resetAndGetPointerAddress());
    }
}

Direct2DLowLevelGraphicsContext::~Direct2DLowLevelGraphicsContext()
{
    states.clear();
}

void Direct2DLowLevelGraphicsContext::resized()
{
    RECT windowRect;
    GetClientRect (hwnd, &windowRect);
    D2D1_SIZE_U size = { (UINT32) (windowRect.right - windowRect.left), (UINT32) (windowRect.bottom - windowRect.top) };

    pimpl->renderingTarget->Resize (size);
    bounds.setSize (size.width, size.height);
}

void Direct2DLowLevelGraphicsContext::clear()
{
    pimpl->renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
}

void Direct2DLowLevelGraphicsContext::start()
{
    pimpl->renderingTarget->BeginDraw();
    saveState();
}

void Direct2DLowLevelGraphicsContext::end()
{
    states.clear();
    currentState = 0;
    pimpl->renderingTarget->EndDraw();
    pimpl->renderingTarget->CheckWindowState();
}

void Direct2DLowLevelGraphicsContext::setOrigin (Point<int> o)
{
    addTransform (AffineTransform::translation ((float) o.x, (float) o.y));
}

void Direct2DLowLevelGraphicsContext::addTransform (const AffineTransform& transform)
{
    currentState->transform = transform.followedBy (currentState->transform);
}

float Direct2DLowLevelGraphicsContext::getPhysicalPixelScaleFactor()
{
    return currentState->transform.getScaleFactor();
}

bool Direct2DLowLevelGraphicsContext::clipToRectangle (const Rectangle<int>& r)
{
    currentState->clipToRectangle (r);
    return ! isClipEmpty();
}

bool Direct2DLowLevelGraphicsContext::clipToRectangleList (const RectangleList<int>& clipRegion)
{
    currentState->clipToRectList (pimpl->rectListToPathGeometry (clipRegion));
    return ! isClipEmpty();
}

void Direct2DLowLevelGraphicsContext::excludeClipRectangle (const Rectangle<int>&)
{
    //xxx
}

void Direct2DLowLevelGraphicsContext::clipToPath (const Path& path, const AffineTransform& transform)
{
    currentState->clipToPath (pimpl->pathToPathGeometry (path, transform));
}

void Direct2DLowLevelGraphicsContext::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
{
    currentState->clipToImage (sourceImage, transform);
}

bool Direct2DLowLevelGraphicsContext::clipRegionIntersects (const Rectangle<int>& r)
{
    return currentState->clipRect.intersects (r.toFloat().transformed (currentState->transform).getSmallestIntegerContainer());
}

Rectangle<int> Direct2DLowLevelGraphicsContext::getClipBounds() const
{
    // xxx could this take into account complex clip regions?
    return currentState->clipRect.toFloat().transformed (currentState->transform.inverted()).getSmallestIntegerContainer();
}

bool Direct2DLowLevelGraphicsContext::isClipEmpty() const
{
    return currentState->clipRect.isEmpty();
}

void Direct2DLowLevelGraphicsContext::saveState()
{
    states.add (new SavedState (*this));
    currentState = states.getLast();
}

void Direct2DLowLevelGraphicsContext::restoreState()
{
        jassert (states.size() > 1); //you should never pop the last state!
    states.removeLast (1);
    currentState = states.getLast();
}

void Direct2DLowLevelGraphicsContext::beginTransparencyLayer (float /*opacity*/)
{
    jassertfalse; //xxx todo
}

void Direct2DLowLevelGraphicsContext::endTransparencyLayer()
{
    jassertfalse; //xxx todo
}

void Direct2DLowLevelGraphicsContext::setFill (const FillType& fillType)
{
    currentState->setFill (fillType);
}

void Direct2DLowLevelGraphicsContext::setOpacity (float newOpacity)
{
    currentState->setOpacity (newOpacity);
}

void Direct2DLowLevelGraphicsContext::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
{
}

void Direct2DLowLevelGraphicsContext::fillRect (const Rectangle<int>& r, bool /*replaceExistingContents*/)
{
    fillRect (r.toFloat());
}

void Direct2DLowLevelGraphicsContext::fillRect (const Rectangle<float>& r)
{
    pimpl->renderingTarget->SetTransform (transformToMatrix (currentState->transform));
    currentState->createBrush();
    pimpl->renderingTarget->FillRectangle (rectangleToRectF (r), currentState->currentBrush);
    pimpl->renderingTarget->SetTransform (D2D1::IdentityMatrix());
}

void Direct2DLowLevelGraphicsContext::fillRectList (const RectangleList<float>& list)
{
    for (auto& r : list)
        fillRect (r);
}

void Direct2DLowLevelGraphicsContext::fillPath (const Path& p, const AffineTransform& transform)
{
    currentState->createBrush();
    ComSmartPtr<ID2D1Geometry> geometry (pimpl->pathToPathGeometry (p, transform.followedBy (currentState->transform)));

    if (pimpl->renderingTarget != nullptr)
        pimpl->renderingTarget->FillGeometry (geometry, currentState->currentBrush);
}

void Direct2DLowLevelGraphicsContext::drawImage (const Image& image, const AffineTransform& transform)
{
    pimpl->renderingTarget->SetTransform (transformToMatrix (transform.followedBy (currentState->transform)));

    D2D1_SIZE_U size;
    size.width = image.getWidth();
    size.height = image.getHeight();

    D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();

    Image img (image.convertedToFormat (Image::ARGB));
    Image::BitmapData bd (img, Image::BitmapData::readOnly);
    bp.pixelFormat = pimpl->renderingTarget->GetPixelFormat();
    bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;

    {
        ComSmartPtr<ID2D1Bitmap> tempBitmap;
        pimpl->renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
        if (tempBitmap != nullptr)
            pimpl->renderingTarget->DrawBitmap (tempBitmap);
    }

    pimpl->renderingTarget->SetTransform (D2D1::IdentityMatrix());
}

void Direct2DLowLevelGraphicsContext::drawLine (const Line <float>& line)
{
    // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
    pimpl->renderingTarget->SetTransform (transformToMatrix (currentState->transform));
    currentState->createBrush();

    pimpl->renderingTarget->DrawLine (D2D1::Point2F (line.getStartX(), line.getStartY()),
                                      D2D1::Point2F (line.getEndX(), line.getEndY()),
                                      currentState->currentBrush);
    pimpl->renderingTarget->SetTransform (D2D1::IdentityMatrix());
}

void Direct2DLowLevelGraphicsContext::setFont (const Font& newFont)
{
    currentState->setFont (newFont);
}

const Font& Direct2DLowLevelGraphicsContext::getFont()
{
    return currentState->font;
}

void Direct2DLowLevelGraphicsContext::drawGlyph (int glyphNumber, const AffineTransform& transform)
{
    currentState->createBrush();
    currentState->createFont();

    float hScale = currentState->font.getHorizontalScale();

    pimpl->renderingTarget->SetTransform (transformToMatrix (AffineTransform::scale (hScale, 1.0f)
                                                                             .followedBy (transform)
                                                                             .followedBy (currentState->transform)));

    const UINT16 glyphIndices = (UINT16) glyphNumber;
    const FLOAT glyphAdvances = 0;
    DWRITE_GLYPH_OFFSET offset;
    offset.advanceOffset = 0;
    offset.ascenderOffset = 0;

    DWRITE_GLYPH_RUN glyphRun;
    glyphRun.fontFace = currentState->currentFontFace;
    glyphRun.fontEmSize = (FLOAT) (currentState->font.getHeight() * currentState->fontHeightToEmSizeFactor);
    glyphRun.glyphCount = 1;
    glyphRun.glyphIndices = &glyphIndices;
    glyphRun.glyphAdvances = &glyphAdvances;
    glyphRun.glyphOffsets = &offset;
    glyphRun.isSideways = FALSE;
    glyphRun.bidiLevel = 0;

    pimpl->renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyphRun, currentState->currentBrush);
    pimpl->renderingTarget->SetTransform (D2D1::IdentityMatrix());
}

bool Direct2DLowLevelGraphicsContext::drawTextLayout (const AttributedString& text, const Rectangle<float>& area)
{
    pimpl->renderingTarget->SetTransform (transformToMatrix (currentState->transform));

    DirectWriteTypeLayout::drawToD2DContext (text, area,
                                             *(pimpl->renderingTarget),
                                             *(pimpl->factories->directWriteFactory),
                                             *(pimpl->factories->systemFonts));

    pimpl->renderingTarget->SetTransform (D2D1::IdentityMatrix());
    return true;
}

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

struct FTLibWrapper     : public ReferenceCountedObject
{
    FTLibWrapper() : library (0)
    {
        if (FT_Init_FreeType (&library) != 0)
        {
            library = 0;
            DBG ("Failed to initialize FreeType");
        }
    }

    ~FTLibWrapper()
    {
        if (library != 0)
            FT_Done_FreeType (library);
    }

    FT_Library library;

    typedef ReferenceCountedObjectPtr<FTLibWrapper> Ptr;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FTLibWrapper)
};

//==============================================================================
struct FTFaceWrapper     : public ReferenceCountedObject
{
    FTFaceWrapper (const FTLibWrapper::Ptr& ftLib, const File& file, int faceIndex)
        : face (0), library (ftLib)
    {
        if (FT_New_Face (ftLib->library, file.getFullPathName().toUTF8(), faceIndex, &face) != 0)
            face = 0;
    }

    FTFaceWrapper (const FTLibWrapper::Ptr& ftLib, const void* data, size_t dataSize, int faceIndex)
        : face (0), library (ftLib), savedFaceData (data, dataSize)
    {
        if (FT_New_Memory_Face (ftLib->library, (const FT_Byte*) savedFaceData.getData(),
                                (FT_Long) savedFaceData.getSize(), faceIndex, &face) != 0)
            face = 0;
    }

    ~FTFaceWrapper()
    {
        if (face != 0)
            FT_Done_Face (face);
    }

    FT_Face face;
    FTLibWrapper::Ptr library;
    MemoryBlock savedFaceData;

    typedef ReferenceCountedObjectPtr<FTFaceWrapper> Ptr;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FTFaceWrapper)
};

//==============================================================================
class FTTypefaceList  : private DeletedAtShutdown
{
public:
    FTTypefaceList()  : library (new FTLibWrapper())
    {
        scanFontPaths (getDefaultFontDirectories());
    }

    ~FTTypefaceList()
    {
        clearSingletonInstance();
    }

    //==============================================================================
    struct KnownTypeface
    {
        KnownTypeface (const File& f, const int index, const FTFaceWrapper& face)
           : file (f),
             family (face.face->family_name),
             style (face.face->style_name),
             faceIndex (index),
             isMonospaced ((face.face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0),
             isSansSerif (isFaceSansSerif (family))
        {
        }

        const File file;
        const String family, style;
        const int faceIndex;
        const bool isMonospaced, isSansSerif;

        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownTypeface)
    };

    //==============================================================================
    static FTFaceWrapper::Ptr selectUnicodeCharmap (FTFaceWrapper* face)
    {
        if (face != nullptr)
            if (FT_Select_Charmap (face->face, ft_encoding_unicode) != 0)
                FT_Set_Charmap (face->face, face->face->charmaps[0]);

        return face;
    }

    FTFaceWrapper::Ptr createFace (const void* data, size_t dataSize, int index)
    {
        return selectUnicodeCharmap (new FTFaceWrapper (library, data, dataSize, index));
    }

    FTFaceWrapper::Ptr createFace (const File& file, int index)
    {
        return selectUnicodeCharmap (new FTFaceWrapper (library, file, index));
    }

    FTFaceWrapper::Ptr createFace (const String& fontName, const String& fontStyle)
    {
        const KnownTypeface* ftFace = matchTypeface (fontName, fontStyle);

        if (ftFace == nullptr)  ftFace = matchTypeface (fontName, "Regular");
        if (ftFace == nullptr)  ftFace = matchTypeface (fontName, String());

        if (ftFace != nullptr)
            return createFace (ftFace->file, ftFace->faceIndex);

        return nullptr;
    }

    //==============================================================================
    StringArray findAllFamilyNames() const
    {
        StringArray s;

        for (int i = 0; i < faces.size(); ++i)
            s.addIfNotAlreadyThere (faces.getUnchecked(i)->family);

        return s;
    }

    static int indexOfRegularStyle (const StringArray& styles)
    {
        int i = styles.indexOf ("Regular", true);

        if (i < 0)
            for (i = 0; i < styles.size(); ++i)
                if (! (styles[i].containsIgnoreCase ("Bold") || styles[i].containsIgnoreCase ("Italic")))
                    break;

        return i;
    }

    StringArray findAllTypefaceStyles (const String& family) const
    {
        StringArray s;

        for (int i = 0; i < faces.size(); ++i)
        {
            const KnownTypeface* const face = faces.getUnchecked(i);

            if (face->family == family)
                s.addIfNotAlreadyThere (face->style);
        }

        // try to get a regular style to be first in the list
        const int regular = indexOfRegularStyle (s);
        if (regular > 0)
            s.strings.swap (0, regular);

        return s;
    }

    void scanFontPaths (const StringArray& paths)
    {
        for (int i = 0; i < paths.size(); ++i)
        {
            DirectoryIterator iter (File::getCurrentWorkingDirectory()
                                       .getChildFile (paths[i]), true);

            while (iter.next())
                if (iter.getFile().hasFileExtension ("ttf;pfb;pcf;otf"))
                    scanFont (iter.getFile());
        }
    }

    void getMonospacedNames (StringArray& monoSpaced) const
    {
        for (int i = 0; i < faces.size(); ++i)
            if (faces.getUnchecked(i)->isMonospaced)
                monoSpaced.addIfNotAlreadyThere (faces.getUnchecked(i)->family);
    }

    void getSerifNames (StringArray& serif) const
    {
        for (int i = 0; i < faces.size(); ++i)
            if (! faces.getUnchecked(i)->isSansSerif)
                serif.addIfNotAlreadyThere (faces.getUnchecked(i)->family);
    }

    void getSansSerifNames (StringArray& sansSerif) const
    {
        for (int i = 0; i < faces.size(); ++i)
            if (faces.getUnchecked(i)->isSansSerif)
                sansSerif.addIfNotAlreadyThere (faces.getUnchecked(i)->family);
    }

    juce_DeclareSingleton_SingleThreaded_Minimal (FTTypefaceList)

private:
    FTLibWrapper::Ptr library;
    OwnedArray<KnownTypeface> faces;

    static StringArray getDefaultFontDirectories();

    void scanFont (const File& file)
    {
        int faceIndex = 0;
        int numFaces = 0;

        do
        {
            FTFaceWrapper face (library, file, faceIndex);

            if (face.face != 0)
            {
                if (faceIndex == 0)
                    numFaces = (int) face.face->num_faces;

                if ((face.face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
                    faces.add (new KnownTypeface (file, faceIndex, face));
            }

            ++faceIndex;
        }
        while (faceIndex < numFaces);
    }

    const KnownTypeface* matchTypeface (const String& familyName, const String& style) const noexcept
    {
        for (int i = 0; i < faces.size(); ++i)
        {
            const KnownTypeface* const face = faces.getUnchecked(i);

            if (face->family == familyName
                  && (face->style.equalsIgnoreCase (style) || style.isEmpty()))
                return face;
        }

        return nullptr;
    }

    static bool isFaceSansSerif (const String& family)
    {
        static const char* sansNames[] = { "Sans", "Verdana", "Arial", "Ubuntu" };

        for (int i = 0; i < numElementsInArray (sansNames); ++i)
            if (family.containsIgnoreCase (sansNames[i]))
                return true;

        return false;
    }

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FTTypefaceList)
};

juce_ImplementSingleton_SingleThreaded (FTTypefaceList)

//==============================================================================
class FreeTypeTypeface   : public CustomTypeface
{
public:
    FreeTypeTypeface (const Font& font)
        : faceWrapper (FTTypefaceList::getInstance()->createFace (font.getTypefaceName(),
                                                                  font.getTypefaceStyle()))
    {
        if (faceWrapper != nullptr)
            initialiseCharacteristics (font.getTypefaceName(),
                                       font.getTypefaceStyle());
    }

    FreeTypeTypeface (const void* data, size_t dataSize)
        : faceWrapper (FTTypefaceList::getInstance()->createFace (data, dataSize, 0))
    {
        if (faceWrapper != nullptr)
            initialiseCharacteristics (faceWrapper->face->family_name,
                                       faceWrapper->face->style_name);
    }

    void initialiseCharacteristics (const String& fontName, const String& fontStyle)
    {
        setCharacteristics (fontName, fontStyle,
                            faceWrapper->face->ascender / (float) (faceWrapper->face->ascender - faceWrapper->face->descender),
                            L' ');
    }

    bool loadGlyphIfPossible (const juce_wchar character)
    {
        if (faceWrapper != nullptr)
        {
            FT_Face face = faceWrapper->face;
            const unsigned int glyphIndex = FT_Get_Char_Index (face, (FT_ULong) character);

            if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM | FT_LOAD_NO_HINTING) == 0
                  && face->glyph->format == ft_glyph_format_outline)
            {
                const float scale = 1.0f / (float) (face->ascender - face->descender);
                Path destShape;

                if (getGlyphShape (destShape, face->glyph->outline, scale))
                {
                    addGlyph (character, destShape, face->glyph->metrics.horiAdvance * scale);

                    if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
                        addKerning (face, (uint32) character, glyphIndex);

                    return true;
                }
            }
        }

        return false;
    }

private:
    FTFaceWrapper::Ptr faceWrapper;

    bool getGlyphShape (Path& destShape, const FT_Outline& outline, const float scaleX)
    {
        const float scaleY = -scaleX;
        const short* const contours = outline.contours;
        const char* const tags = outline.tags;
        const FT_Vector* const points = outline.points;

        for (int c = 0; c < outline.n_contours; ++c)
        {
            const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
            const int endPoint = contours[c];

            for (int p = startPoint; p <= endPoint; ++p)
            {
                const float x = scaleX * points[p].x;
                const float y = scaleY * points[p].y;

                if (p == startPoint)
                {
                    if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
                    {
                        float x2 = scaleX * points [endPoint].x;
                        float y2 = scaleY * points [endPoint].y;

                        if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
                        {
                            x2 = (x + x2) * 0.5f;
                            y2 = (y + y2) * 0.5f;
                        }

                        destShape.startNewSubPath (x2, y2);
                    }
                    else
                    {
                        destShape.startNewSubPath (x, y);
                    }
                }

                if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
                {
                    if (p != startPoint)
                        destShape.lineTo (x, y);
                }
                else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
                {
                    const int nextIndex = (p == endPoint) ? startPoint : p + 1;
                    float x2 = scaleX * points [nextIndex].x;
                    float y2 = scaleY * points [nextIndex].y;

                    if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
                    {
                        x2 = (x + x2) * 0.5f;
                        y2 = (y + y2) * 0.5f;
                    }
                    else
                    {
                        ++p;
                    }

                    destShape.quadraticTo (x, y, x2, y2);
                }
                else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
                {
                    const int next1 = p + 1;
                    const int next2 = (p == (endPoint - 1)) ? startPoint : (p + 2);

                    if (p >= endPoint
                         || FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
                         || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
                        return false;

                    const float x2 = scaleX * points [next1].x;
                    const float y2 = scaleY * points [next1].y;
                    const float x3 = scaleX * points [next2].x;
                    const float y3 = scaleY * points [next2].y;

                    destShape.cubicTo (x, y, x2, y2, x3, y3);
                    p += 2;
                }
            }

            destShape.closeSubPath();
        }

        return true;
    }

    void addKerning (FT_Face face, const uint32 character, const uint32 glyphIndex)
    {
        const float height = (float) (face->ascender - face->descender);

        uint32 rightGlyphIndex;
        FT_ULong rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);

        while (rightGlyphIndex != 0)
        {
            FT_Vector kerning;

            if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0
                   && kerning.x != 0)
                addKerningPair ((juce_wchar) character, (juce_wchar) rightCharCode, kerning.x / height);

            rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
        }
    }

    JUCE_DECLARE_NON_COPYABLE (FreeTypeTypeface)
};

} // namespace juce