Merge mozilla-central to autoland on a CLOSED TREE
[gecko.git] / dom / svg / SVGPathData.h
blob10c3acf272cabbf3d32afc9e6a19d27bf5e602f2
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef DOM_SVG_SVGPATHDATA_H_
8 #define DOM_SVG_SVGPATHDATA_H_
10 #include "nsCOMPtr.h"
11 #include "nsDebug.h"
12 #include "nsIContent.h"
13 #include "nsINode.h"
14 #include "nsIWeakReferenceUtils.h"
15 #include "mozilla/dom/SVGElement.h"
16 #include "mozilla/gfx/2D.h"
17 #include "mozilla/gfx/Types.h"
18 #include "mozilla/MemoryReporting.h"
19 #include "mozilla/RefPtr.h"
20 #include "nsTArray.h"
22 #include <string.h>
24 namespace mozilla {
26 struct StylePathCommand;
27 struct SVGMark;
28 enum class StyleStrokeLinecap : uint8_t;
30 class SVGPathDataParser; // IWYU pragma: keep
32 namespace dom {
33 class DOMSVGPathSeg;
34 class DOMSVGPathSegList;
35 } // namespace dom
37 /**
38 * ATTENTION! WARNING! WATCH OUT!!
40 * Consumers that modify objects of this type absolutely MUST keep the DOM
41 * wrappers for those lists (if any) in sync!! That's why this class is so
42 * locked down.
44 * The DOM wrapper class for this class is DOMSVGPathSegList.
46 * This class is not called |class SVGPathSegList| for one very good reason;
47 * this class does not provide a list of "SVGPathSeg" items, it provides an
48 * array of floats into which path segments are encoded. See the paragraphs
49 * that follow for why. Note that the Length() method returns the number of
50 * floats in our array, not the number of encoded segments, and the index
51 * operator indexes floats in the array, not segments. If this class were
52 * called SVGPathSegList the names of these methods would be very misleading.
54 * The reason this class is designed in this way is because there are many
55 * different types of path segment, each taking a different numbers of
56 * arguments. We want to store the segments in an nsTArray to avoid individual
57 * allocations for each item, but the different size of segments means we can't
58 * have one single segment type for the nsTArray (not without using a space
59 * wasteful union or something similar). Since the internal code does not need
60 * to index into the list (the DOM wrapper does, but it handles that itself)
61 * the obvious solution is to have the items in this class take up variable
62 * width and have the internal code iterate over these lists rather than index
63 * into them.
65 * Implementing indexing to segments with O(1) performance would require us to
66 * allocate and maintain a separate segment index table (keeping that table in
67 * sync when items are inserted or removed from the list). So long as the
68 * internal code doesn't require indexing to segments, we can avoid that
69 * overhead and additional complexity.
71 * Segment encoding: the first float in the encoding of a segment contains the
72 * segment's type. The segment's type is encoded to/decoded from this float
73 * using the static methods SVGPathSegUtils::EncodeType(uint32_t)/
74 * SVGPathSegUtils::DecodeType(float). If the path segment type in question
75 * takes any arguments then these follow the first float, and are in the same
76 * order as they are given in a <path> element's 'd' attribute (NOT in the
77 * order of the createSVGPathSegXxx() methods' arguments from the SVG DOM
78 * interface SVGPathElement, which are different...grr). Consumers can use
79 * SVGPathSegUtils::ArgCountForType(type) to determine how many arguments
80 * there are (if any), and thus where the current encoded segment ends, and
81 * where the next segment (if any) begins.
83 class SVGPathData {
84 friend class SVGAnimatedPathSegList;
85 friend class dom::DOMSVGPathSeg;
86 friend class dom::DOMSVGPathSegList;
87 friend class SVGPathDataParser;
88 // SVGPathDataParser will not keep wrappers in sync, so consumers
89 // are responsible for that!
91 using DrawTarget = gfx::DrawTarget;
92 using Path = gfx::Path;
93 using PathBuilder = gfx::PathBuilder;
94 using FillRule = gfx::FillRule;
95 using Float = gfx::Float;
96 using CapStyle = gfx::CapStyle;
98 public:
99 using const_iterator = const float*;
101 SVGPathData() = default;
102 ~SVGPathData() = default;
104 SVGPathData& operator=(const SVGPathData& aOther) {
105 mData.ClearAndRetainStorage();
106 // Best-effort, really.
107 Unused << mData.AppendElements(aOther.mData, fallible);
108 return *this;
111 SVGPathData(const SVGPathData& aOther) { *this = aOther; }
113 // Only methods that don't make/permit modification to this list are public.
114 // Only our friend classes can access methods that may change us.
116 /// This may return an incomplete string on OOM, but that's acceptable.
117 void GetValueAsString(nsAString& aValue) const;
119 bool IsEmpty() const { return mData.IsEmpty(); }
121 #ifdef DEBUG
123 * This method iterates over the encoded segment data and counts the number
124 * of segments we currently have.
126 uint32_t CountItems() const;
127 #endif
130 * Returns the number of *floats* in the encoding array, and NOT the number
131 * of segments encoded in this object. (For that, see CountItems() above.)
133 uint32_t Length() const { return mData.Length(); }
135 const nsTArray<float>& RawData() const { return mData; }
137 const float& operator[](uint32_t aIndex) const { return mData[aIndex]; }
139 // Used by SMILCompositor to check if the cached base val is out of date
140 bool operator==(const SVGPathData& rhs) const {
141 // We use memcmp so that we don't need to worry that the data encoded in
142 // the first float may have the same bit pattern as a NaN.
143 return mData.Length() == rhs.mData.Length() &&
144 memcmp(mData.Elements(), rhs.mData.Elements(),
145 mData.Length() * sizeof(float)) == 0;
148 bool SetCapacity(uint32_t aSize) {
149 return mData.SetCapacity(aSize, fallible);
152 void Compact() { mData.Compact(); }
154 float GetPathLength() const;
156 uint32_t GetPathSegAtLength(float aDistance) const;
158 static uint32_t GetPathSegAtLength(Span<const StylePathCommand> aPath,
159 float aDistance);
161 void GetMarkerPositioningData(nsTArray<SVGMark>* aMarks) const;
163 static void GetMarkerPositioningData(Span<const StylePathCommand> aPath,
164 nsTArray<SVGMark>* aMarks);
167 * Returns true, except on OOM, in which case returns false.
169 bool GetDistancesFromOriginToEndsOfVisibleSegments(
170 FallibleTArray<double>* aOutput) const;
173 * This is identical to the above one but accepts StylePathCommand.
175 static bool GetDistancesFromOriginToEndsOfVisibleSegments(
176 Span<const StylePathCommand> aPath, FallibleTArray<double>* aOutput);
179 * This returns a path without the extra little line segments that
180 * ApproximateZeroLengthSubpathSquareCaps can insert if we have square-caps.
181 * See the comment for that function for more info on that.
183 already_AddRefed<Path> BuildPathForMeasuring() const;
185 already_AddRefed<Path> BuildPath(PathBuilder* aBuilder,
186 StyleStrokeLinecap aStrokeLineCap,
187 Float aStrokeWidth) const;
189 static already_AddRefed<Path> BuildPathForMeasuring(
190 Span<const StylePathCommand> aPath);
193 * This function tries to build the path from an array of StylePathCommand,
194 * which is generated by cbindgen from Rust (see ServoStyleConsts.h).
195 * Basically, this is a variant of the above BuildPath() functions.
197 static already_AddRefed<Path> BuildPath(Span<const StylePathCommand> aPath,
198 PathBuilder* aBuilder,
199 StyleStrokeLinecap aStrokeLineCap,
200 Float aStrokeWidth,
201 float aZoomFactor = 1.0);
203 const_iterator begin() const { return mData.Elements(); }
204 const_iterator end() const { return mData.Elements() + mData.Length(); }
206 // memory reporting methods
207 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
208 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
210 // Access to methods that can modify objects of this type is deliberately
211 // limited. This is to reduce the chances of someone modifying objects of
212 // this type without taking the necessary steps to keep DOM wrappers in sync.
213 // If you need wider access to these methods, consider adding a method to
214 // SVGAnimatedPathSegList and having that class act as an intermediary so it
215 // can take care of keeping DOM wrappers in sync.
217 protected:
218 using iterator = float*;
221 * This may fail on OOM if the internal capacity needs to be increased, in
222 * which case the list will be left unmodified.
224 nsresult CopyFrom(const SVGPathData& rhs);
225 void SwapWith(SVGPathData& aRhs) { mData.SwapElements(aRhs.mData); }
227 float& operator[](uint32_t aIndex) { return mData[aIndex]; }
230 * This may fail (return false) on OOM if the internal capacity is being
231 * increased, in which case the list will be left unmodified.
233 bool SetLength(uint32_t aLength) {
234 return mData.SetLength(aLength, fallible);
237 nsresult SetValueFromString(const nsAString& aValue);
239 void Clear() { mData.Clear(); }
241 // Our DOM wrappers have direct access to our mData, so they directly
242 // manipulate it rather than us implementing:
244 // * InsertItem(uint32_t aDataIndex, uint32_t aType, const float *aArgs);
245 // * ReplaceItem(uint32_t aDataIndex, uint32_t aType, const float *aArgs);
246 // * RemoveItem(uint32_t aDataIndex);
247 // * bool AppendItem(uint32_t aType, const float *aArgs);
249 nsresult AppendSeg(uint32_t aType, ...); // variable number of float args
251 iterator begin() { return mData.Elements(); }
252 iterator end() { return mData.Elements() + mData.Length(); }
254 FallibleTArray<float> mData;
258 * This SVGPathData subclass is for SVGPathSegListSMILType which needs to
259 * have write access to the lists it works with.
261 * Instances of this class do not have DOM wrappers that need to be kept in
262 * sync, so we can safely expose any protected base class methods required by
263 * the SMIL code.
265 class SVGPathDataAndInfo final : public SVGPathData {
266 public:
267 explicit SVGPathDataAndInfo(dom::SVGElement* aElement = nullptr)
268 : mElement(do_GetWeakReference(static_cast<nsINode*>(aElement))) {}
270 void SetElement(dom::SVGElement* aElement) {
271 mElement = do_GetWeakReference(static_cast<nsINode*>(aElement));
274 dom::SVGElement* Element() const {
275 nsCOMPtr<nsIContent> e = do_QueryReferent(mElement);
276 return static_cast<dom::SVGElement*>(e.get());
279 nsresult CopyFrom(const SVGPathDataAndInfo& rhs) {
280 mElement = rhs.mElement;
281 return SVGPathData::CopyFrom(rhs);
285 * Returns true if this object is an "identity" value, from the perspective
286 * of SMIL. In other words, returns true until the initial value set up in
287 * SVGPathSegListSMILType::Init() has been changed with a SetElement() call.
289 bool IsIdentity() const {
290 if (!mElement) {
291 MOZ_ASSERT(IsEmpty(), "target element propagation failure");
292 return true;
294 return false;
298 * Exposed so that SVGPathData baseVals can be copied to
299 * SVGPathDataAndInfo objects. Note that callers should also call
300 * SetElement() when using this method!
302 using SVGPathData::CopyFrom;
304 // Exposed since SVGPathData objects can be modified.
305 using SVGPathData::iterator;
306 using SVGPathData::operator[];
307 using SVGPathData::begin;
308 using SVGPathData::end;
309 using SVGPathData::SetLength;
311 private:
312 // We must keep a weak reference to our element because we may belong to a
313 // cached baseVal SMILValue. See the comments starting at:
314 // https://bugzilla.mozilla.org/show_bug.cgi?id=515116#c15
315 // See also https://bugzilla.mozilla.org/show_bug.cgi?id=653497
316 nsWeakPtr mElement;
319 } // namespace mozilla
321 #endif // DOM_SVG_SVGPATHDATA_H_