VectorDrawable.java revision dbcccffc3760f702887faa95b2748125bac88a89
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14
15package android.graphics.drawable;
16
17import android.content.res.ColorStateList;
18import android.content.res.Resources;
19import android.content.res.Resources.Theme;
20import android.content.res.TypedArray;
21import android.graphics.Bitmap;
22import android.graphics.Canvas;
23import android.graphics.Color;
24import android.graphics.ColorFilter;
25import android.graphics.Matrix;
26import android.graphics.Paint;
27import android.graphics.Path;
28import android.graphics.PathMeasure;
29import android.graphics.PixelFormat;
30import android.graphics.PorterDuffColorFilter;
31import android.graphics.Rect;
32import android.graphics.Region;
33import android.graphics.PorterDuff.Mode;
34import android.util.ArrayMap;
35import android.util.AttributeSet;
36import android.util.LayoutDirection;
37import android.util.Log;
38import android.util.PathParser;
39import android.util.Xml;
40
41import com.android.internal.R;
42
43import org.xmlpull.v1.XmlPullParser;
44import org.xmlpull.v1.XmlPullParserException;
45
46import java.io.IOException;
47import java.util.ArrayList;
48import java.util.Stack;
49
50/**
51 * This lets you create a drawable based on an XML vector graphic. It can be
52 * defined in an XML file with the <code>&lt;vector></code> element.
53 * <p/>
54 * The vector drawable has the following elements:
55 * <p/>
56 * <dt><code>&lt;vector></code></dt>
57 * <dl>
58 * <dd>Used to defined a vector drawable
59 * <dl>
60 * <dt><code>android:width</code></dt>
61 * <dd>Used to defined the intrinsic width of the drawable.
62 * This support all the dimension units, normally specified with dp.</dd>
63 * <dt><code>android:height</code></dt>
64 * <dd>Used to defined the intrinsic height the drawable.
65 * This support all the dimension units, normally specified with dp.</dd>
66 * <dt><code>android:viewportWidth</code></dt>
67 * <dd>Used to defined the width of the viewport space. Viewport is basically
68 * the virtual canvas where the paths are drawn on.</dd>
69 * <dt><code>android:viewportHeight</code></dt>
70 * <dd>Used to defined the height of the viewport space. Viewport is basically
71 * the virtual canvas where the paths are drawn on.</dd>
72 * <dt><code>android:tint</code></dt>
73 * <dd>The color to apply to the drawable as a tint. By default, no tint is applied.</dd>
74 * <dt><code>android:tintMode</code></dt>
75 * <dd>The Porter-Duff blending mode for the tint color. The default value is src_in.</dd>
76 * <dt><code>android:autoMirrored</code></dt>
77 * <dd>Indicates if the drawable needs to be mirrored when its layout direction is
78 * RTL (right-to-left).</dd>
79 * </dl></dd>
80 * </dl>
81 *
82 * <dl>
83 * <dt><code>&lt;group></code></dt>
84 * <dd>Defines a group of paths or subgroups, plus transformation information.
85 * The transformations are defined in the same coordinates as the viewport.
86 * And the transformations are applied in the order of scale, rotate then translate.
87 * <dl>
88 * <dt><code>android:rotation</code></dt>
89 * <dd>The degrees of rotation of the group.</dd>
90 * <dt><code>android:pivotX</code></dt>
91 * <dd>The X coordinate of the pivot for the scale and rotation of the group.
92 * This is defined in the viewport space.</dd>
93 * <dt><code>android:pivotY</code></dt>
94 * <dd>The Y coordinate of the pivot for the scale and rotation of the group.
95 * This is defined in the viewport space.</dd>
96 * <dt><code>android:scaleX</code></dt>
97 * <dd>The amount of scale on the X Coordinate.</dd>
98 * <dt><code>android:scaleY</code></dt>
99 * <dd>The amount of scale on the Y coordinate.</dd>
100 * <dt><code>android:translateX</code></dt>
101 * <dd>The amount of translation on the X coordinate.
102 * This is defined in the viewport space.</dd>
103 * <dt><code>android:translateY</code></dt>
104 * <dd>The amount of translation on the Y coordinate.
105 * This is defined in the viewport space.</dd>
106 * </dl></dd>
107 * </dl>
108 *
109 * <dl>
110 * <dt><code>&lt;path></code></dt>
111 * <dd>Defines paths to be drawn.
112 * <dl>
113 * <dt><code>android:name</code></dt>
114 * <dd>Defines the name of the path.</dd>
115 * <dt><code>android:pathData</code></dt>
116 * <dd>Defines path string. This is using exactly same format as "d" attribute
117 * in the SVG's path data. This is defined in the viewport space.</dd>
118 * <dt><code>android:fillColor</code></dt>
119 * <dd>Defines the color to fill the path (none if not present).</dd>
120 * <dt><code>android:strokeColor</code></dt>
121 * <dd>Defines the color to draw the path outline (none if not present).</dd>
122 * <dt><code>android:strokeWidth</code></dt>
123 * <dd>The width a path stroke.</dd>
124 * <dt><code>android:strokeAlpha</code></dt>
125 * <dd>The opacity of a path stroke.</dd>
126 * <dt><code>android:fillAlpha</code></dt>
127 * <dd>The opacity to fill the path with.</dd>
128 * <dt><code>android:trimPathStart</code></dt>
129 * <dd>The fraction of the path to trim from the start, in the range from 0 to 1.</dd>
130 * <dt><code>android:trimPathEnd</code></dt>
131 * <dd>The fraction of the path to trim from the end, in the range from 0 to 1.</dd>
132 * <dt><code>android:trimPathOffset</code></dt>
133 * <dd>Shift trim region (allows showed region to include the start and end), in the range
134 * from 0 to 1.</dd>
135 * <dt><code>android:strokeLineCap</code></dt>
136 * <dd>Sets the linecap for a stroked path: butt, round, square.</dd>
137 * <dt><code>android:strokeLineJoin</code></dt>
138 * <dd>Sets the lineJoin for a stroked path: miter,round,bevel.</dd>
139 * <dt><code>android:strokeMiterLimit</code></dt>
140 * <dd>Sets the Miter limit for a stroked path.</dd>
141 * </dl></dd>
142 * </dl>
143 *
144 * <dl>
145 * <dt><code>&lt;clip-path></code></dt>
146 * <dd>Defines path to be the current clip.
147 * <dl>
148 * <dt><code>android:name</code></dt>
149 * <dd>Defines the name of the clip path.</dd>
150 * <dt><code>android:pathData</code></dt>
151 * <dd>Defines clip path string. This is using exactly same format as "d" attribute
152 * in the SVG's path data.</dd>
153 * </dl></dd>
154 * </dl>
155 * <li>Here is a simple VectorDrawable in this vectordrawable.xml file.
156 * <pre>
157 * &lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android";
158 *     android:height=&quot;64dp&quot;
159 *     android:width=&quot;64dp&quot;
160 *     android:viewportHeight=&quot;600&quot;
161 *     android:viewportWidth=&quot;600&quot; &gt;
162 *     &lt;group
163 *         android:name=&quot;rotationGroup&quot;
164 *         android:pivotX=&quot;300.0&quot;
165 *         android:pivotY=&quot;300.0&quot;
166 *         android:rotation=&quot;45.0&quot; &gt;
167 *         &lt;path
168 *             android:name=&quot;v&quot;
169 *             android:fillColor=&quot;#000000&quot;
170 *             android:pathData=&quot;M300,70 l 0,-70 70,70 0,0 -70,70z&quot; /&gt;
171 *     &lt;/group&gt;
172 * &lt;/vector&gt;
173 * </pre></li>
174 */
175
176public class VectorDrawable extends Drawable {
177    private static final String LOGTAG = VectorDrawable.class.getSimpleName();
178
179    private static final String SHAPE_CLIP_PATH = "clip-path";
180    private static final String SHAPE_GROUP = "group";
181    private static final String SHAPE_PATH = "path";
182    private static final String SHAPE_VECTOR = "vector";
183
184    private static final int LINECAP_BUTT = 0;
185    private static final int LINECAP_ROUND = 1;
186    private static final int LINECAP_SQUARE = 2;
187
188    private static final int LINEJOIN_MITER = 0;
189    private static final int LINEJOIN_ROUND = 1;
190    private static final int LINEJOIN_BEVEL = 2;
191
192    private static final boolean DBG_VECTOR_DRAWABLE = false;
193
194    private VectorDrawableState mVectorState;
195
196    private PorterDuffColorFilter mTintFilter;
197    private ColorFilter mColorFilter;
198
199    private boolean mMutated;
200
201    // AnimatedVectorDrawable needs to turn off the cache all the time, otherwise,
202    // caching the bitmap by default is allowed.
203    private boolean mAllowCaching = true;
204
205    public VectorDrawable() {
206        mVectorState = new VectorDrawableState();
207    }
208
209    private VectorDrawable(VectorDrawableState state, Resources res, Theme theme) {
210        if (theme != null && state.canApplyTheme()) {
211            // If we need to apply a theme, implicitly mutate.
212            mVectorState = new VectorDrawableState(state);
213            applyTheme(theme);
214        } else {
215            mVectorState = state;
216        }
217
218        mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
219    }
220
221    @Override
222    public Drawable mutate() {
223        if (!mMutated && super.mutate() == this) {
224            mVectorState = new VectorDrawableState(mVectorState);
225            mMutated = true;
226        }
227        return this;
228    }
229
230    Object getTargetByName(String name) {
231        return mVectorState.mVPathRenderer.mVGTargetsMap.get(name);
232    }
233
234    @Override
235    public ConstantState getConstantState() {
236        mVectorState.mChangingConfigurations = getChangingConfigurations();
237        return mVectorState;
238    }
239
240    @Override
241    public void draw(Canvas canvas) {
242        final Rect bounds = getBounds();
243        if (bounds.width() == 0 || bounds.height() == 0) {
244            // too small to draw
245            return;
246        }
247
248        final int saveCount = canvas.save();
249        final boolean needMirroring = needMirroring();
250
251        canvas.translate(bounds.left, bounds.top);
252        if (needMirroring) {
253            canvas.translate(bounds.width(), 0);
254            canvas.scale(-1.0f, 1.0f);
255        }
256
257        // Color filters always override tint filters.
258        final ColorFilter colorFilter = mColorFilter == null ? mTintFilter : mColorFilter;
259
260        if (!mAllowCaching) {
261            // AnimatedVectorDrawable
262            if (!mVectorState.hasTranslucentRoot()) {
263                mVectorState.mVPathRenderer.draw(
264                        canvas, bounds.width(), bounds.height(), colorFilter);
265            } else {
266                mVectorState.createCachedBitmapIfNeeded(bounds);
267                mVectorState.updateCachedBitmap(bounds);
268                mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
269            }
270        } else {
271            // Static Vector Drawable case.
272            mVectorState.createCachedBitmapIfNeeded(bounds);
273            if (!mVectorState.canReuseCache()) {
274                mVectorState.updateCachedBitmap(bounds);
275                mVectorState.updateCacheStates();
276            }
277            mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
278        }
279
280        canvas.restoreToCount(saveCount);
281    }
282
283    @Override
284    public int getAlpha() {
285        return mVectorState.mVPathRenderer.getRootAlpha();
286    }
287
288    @Override
289    public void setAlpha(int alpha) {
290        if (mVectorState.mVPathRenderer.getRootAlpha() != alpha) {
291            mVectorState.mVPathRenderer.setRootAlpha(alpha);
292            invalidateSelf();
293        }
294    }
295
296    @Override
297    public void setColorFilter(ColorFilter colorFilter) {
298        mColorFilter = colorFilter;
299        invalidateSelf();
300    }
301
302    @Override
303    public void setTintList(ColorStateList tint) {
304        final VectorDrawableState state = mVectorState;
305        if (state.mTint != tint) {
306            state.mTint = tint;
307            mTintFilter = updateTintFilter(mTintFilter, tint, state.mTintMode);
308            invalidateSelf();
309        }
310    }
311
312    @Override
313    public void setTintMode(Mode tintMode) {
314        final VectorDrawableState state = mVectorState;
315        if (state.mTintMode != tintMode) {
316            state.mTintMode = tintMode;
317            mTintFilter = updateTintFilter(mTintFilter, state.mTint, tintMode);
318            invalidateSelf();
319        }
320    }
321
322    @Override
323    public boolean isStateful() {
324        return super.isStateful() || (mVectorState != null && mVectorState.mTint != null
325                && mVectorState.mTint.isStateful());
326    }
327
328    @Override
329    protected boolean onStateChange(int[] stateSet) {
330        final VectorDrawableState state = mVectorState;
331        if (state.mTint != null && state.mTintMode != null) {
332            mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
333            invalidateSelf();
334            return true;
335        }
336        return false;
337    }
338
339    @Override
340    public int getOpacity() {
341        return PixelFormat.TRANSLUCENT;
342    }
343
344    @Override
345    public int getIntrinsicWidth() {
346        return (int) mVectorState.mVPathRenderer.mBaseWidth;
347    }
348
349    @Override
350    public int getIntrinsicHeight() {
351        return (int) mVectorState.mVPathRenderer.mBaseHeight;
352    }
353
354    @Override
355    public boolean canApplyTheme() {
356        return super.canApplyTheme() || mVectorState != null && mVectorState.canApplyTheme();
357    }
358
359    @Override
360    public void applyTheme(Theme t) {
361        super.applyTheme(t);
362
363        final VectorDrawableState state = mVectorState;
364        if (state != null && state.mThemeAttrs != null) {
365            final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.VectorDrawable);
366            try {
367                state.mCacheDirty = true;
368                updateStateFromTypedArray(a);
369            } catch (XmlPullParserException e) {
370                throw new RuntimeException(e);
371            } finally {
372                a.recycle();
373            }
374
375            mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
376        }
377
378        final VPathRenderer path = state.mVPathRenderer;
379        if (path != null && path.canApplyTheme()) {
380            path.applyTheme(t);
381        }
382    }
383
384    /**
385     * The size of a pixel when scaled from the intrinsic dimension to the viewport dimension.
386     * This is used to calculate the path animation accuracy.
387     *
388     * @hide
389     */
390    public float getPixelSize() {
391        if (mVectorState == null && mVectorState.mVPathRenderer == null ||
392                mVectorState.mVPathRenderer.mBaseWidth == 0 ||
393                mVectorState.mVPathRenderer.mBaseHeight == 0 ||
394                mVectorState.mVPathRenderer.mViewportHeight == 0 ||
395                mVectorState.mVPathRenderer.mViewportWidth == 0) {
396            return 1; // fall back to 1:1 pixel mapping.
397        }
398        float intrinsicWidth = mVectorState.mVPathRenderer.mBaseWidth;
399        float intrinsicHeight = mVectorState.mVPathRenderer.mBaseHeight;
400        float viewportWidth = mVectorState.mVPathRenderer.mViewportWidth;
401        float viewportHeight = mVectorState.mVPathRenderer.mViewportHeight;
402        float scaleX = viewportWidth / intrinsicWidth;
403        float scaleY = viewportHeight / intrinsicHeight;
404        return Math.min(scaleX, scaleY);
405    }
406
407    /** @hide */
408    public static VectorDrawable create(Resources resources, int rid) {
409        try {
410            final XmlPullParser parser = resources.getXml(rid);
411            final AttributeSet attrs = Xml.asAttributeSet(parser);
412            int type;
413            while ((type=parser.next()) != XmlPullParser.START_TAG &&
414                    type != XmlPullParser.END_DOCUMENT) {
415                // Empty loop
416            }
417            if (type != XmlPullParser.START_TAG) {
418                throw new XmlPullParserException("No start tag found");
419            }
420
421            final VectorDrawable drawable = new VectorDrawable();
422            drawable.inflate(resources, parser, attrs);
423
424            return drawable;
425        } catch (XmlPullParserException e) {
426            Log.e(LOGTAG, "parser error", e);
427        } catch (IOException e) {
428            Log.e(LOGTAG, "parser error", e);
429        }
430        return null;
431    }
432
433    private static int applyAlpha(int color, float alpha) {
434        int alphaBytes = Color.alpha(color);
435        color &= 0x00FFFFFF;
436        color |= ((int) (alphaBytes * alpha)) << 24;
437        return color;
438    }
439
440    @Override
441    public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
442            throws XmlPullParserException, IOException {
443        final VectorDrawableState state = mVectorState;
444        final VPathRenderer pathRenderer = new VPathRenderer();
445        state.mVPathRenderer = pathRenderer;
446
447        final TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawable);
448        updateStateFromTypedArray(a);
449        a.recycle();
450
451        state.mCacheDirty = true;
452        inflateInternal(res, parser, attrs, theme);
453
454        mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
455    }
456
457    private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException {
458        final VectorDrawableState state = mVectorState;
459        final VPathRenderer pathRenderer = state.mVPathRenderer;
460
461        // Account for any configuration changes.
462        state.mChangingConfigurations |= a.getChangingConfigurations();
463
464        // Extract the theme attributes, if any.
465        state.mThemeAttrs = a.extractThemeAttrs();
466
467        final int tintMode = a.getInt(R.styleable.VectorDrawable_tintMode, -1);
468        if (tintMode != -1) {
469            state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN);
470        }
471
472        final ColorStateList tint = a.getColorStateList(R.styleable.VectorDrawable_tint);
473        if (tint != null) {
474            state.mTint = tint;
475        }
476
477        state.mAutoMirrored = a.getBoolean(
478                R.styleable.VectorDrawable_autoMirrored, state.mAutoMirrored);
479
480        pathRenderer.mViewportWidth = a.getFloat(
481                R.styleable.VectorDrawable_viewportWidth, pathRenderer.mViewportWidth);
482        pathRenderer.mViewportHeight = a.getFloat(
483                R.styleable.VectorDrawable_viewportHeight, pathRenderer.mViewportHeight);
484
485        if (pathRenderer.mViewportWidth <= 0) {
486            throw new XmlPullParserException(a.getPositionDescription() +
487                    "<vector> tag requires viewportWidth > 0");
488        } else if (pathRenderer.mViewportHeight <= 0) {
489            throw new XmlPullParserException(a.getPositionDescription() +
490                    "<vector> tag requires viewportHeight > 0");
491        }
492
493        pathRenderer.mBaseWidth = a.getDimension(
494                R.styleable.VectorDrawable_width, pathRenderer.mBaseWidth);
495        pathRenderer.mBaseHeight = a.getDimension(
496                R.styleable.VectorDrawable_height, pathRenderer.mBaseHeight);
497
498        if (pathRenderer.mBaseWidth <= 0) {
499            throw new XmlPullParserException(a.getPositionDescription() +
500                    "<vector> tag requires width > 0");
501        } else if (pathRenderer.mBaseHeight <= 0) {
502            throw new XmlPullParserException(a.getPositionDescription() +
503                    "<vector> tag requires height > 0");
504        }
505
506        final float alphaInFloat = a.getFloat(R.styleable.VectorDrawable_alpha,
507                pathRenderer.getAlpha());
508        pathRenderer.setAlpha(alphaInFloat);
509
510        pathRenderer.mRootName = a.getString(R.styleable.VectorDrawable_name);
511        if (pathRenderer.mRootName != null) {
512            pathRenderer.mVGTargetsMap.put(pathRenderer.mRootName, pathRenderer);
513        }
514    }
515
516    private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs,
517            Theme theme) throws XmlPullParserException, IOException {
518        final VectorDrawableState state = mVectorState;
519        final VPathRenderer pathRenderer = state.mVPathRenderer;
520        boolean noPathTag = true;
521
522        // Use a stack to help to build the group tree.
523        // The top of the stack is always the current group.
524        final Stack<VGroup> groupStack = new Stack<VGroup>();
525        groupStack.push(pathRenderer.mRootGroup);
526
527        int eventType = parser.getEventType();
528        while (eventType != XmlPullParser.END_DOCUMENT) {
529            if (eventType == XmlPullParser.START_TAG) {
530                final String tagName = parser.getName();
531                final VGroup currentGroup = groupStack.peek();
532
533                if (SHAPE_PATH.equals(tagName)) {
534                    final VFullPath path = new VFullPath();
535                    path.inflate(res, attrs, theme);
536                    currentGroup.mChildren.add(path);
537                    if (path.getPathName() != null) {
538                        pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
539                    }
540                    noPathTag = false;
541                    state.mChangingConfigurations |= path.mChangingConfigurations;
542                } else if (SHAPE_CLIP_PATH.equals(tagName)) {
543                    final VClipPath path = new VClipPath();
544                    path.inflate(res, attrs, theme);
545                    currentGroup.mChildren.add(path);
546                    if (path.getPathName() != null) {
547                        pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
548                    }
549                    state.mChangingConfigurations |= path.mChangingConfigurations;
550                } else if (SHAPE_GROUP.equals(tagName)) {
551                    VGroup newChildGroup = new VGroup();
552                    newChildGroup.inflate(res, attrs, theme);
553                    currentGroup.mChildren.add(newChildGroup);
554                    groupStack.push(newChildGroup);
555                    if (newChildGroup.getGroupName() != null) {
556                        pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(),
557                                newChildGroup);
558                    }
559                    state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
560                }
561            } else if (eventType == XmlPullParser.END_TAG) {
562                final String tagName = parser.getName();
563                if (SHAPE_GROUP.equals(tagName)) {
564                    groupStack.pop();
565                }
566            }
567            eventType = parser.next();
568        }
569
570        // Print the tree out for debug.
571        if (DBG_VECTOR_DRAWABLE) {
572            printGroupTree(pathRenderer.mRootGroup, 0);
573        }
574
575        if (noPathTag) {
576            final StringBuffer tag = new StringBuffer();
577
578            if (tag.length() > 0) {
579                tag.append(" or ");
580            }
581            tag.append(SHAPE_PATH);
582
583            throw new XmlPullParserException("no " + tag + " defined");
584        }
585    }
586
587    private void printGroupTree(VGroup currentGroup, int level) {
588        String indent = "";
589        for (int i = 0; i < level; i++) {
590            indent += "    ";
591        }
592        // Print the current node
593        Log.v(LOGTAG, indent + "current group is :" + currentGroup.getGroupName()
594                + " rotation is " + currentGroup.mRotate);
595        Log.v(LOGTAG, indent + "matrix is :" + currentGroup.getLocalMatrix().toString());
596        // Then print all the children groups
597        for (int i = 0; i < currentGroup.mChildren.size(); i++) {
598            Object child = currentGroup.mChildren.get(i);
599            if (child instanceof VGroup) {
600                printGroupTree((VGroup) child, level + 1);
601            }
602        }
603    }
604
605    @Override
606    public int getChangingConfigurations() {
607        return super.getChangingConfigurations() | mVectorState.mChangingConfigurations;
608    }
609
610    void setAllowCaching(boolean allowCaching) {
611        mAllowCaching = allowCaching;
612    }
613
614    private boolean needMirroring() {
615        return isAutoMirrored() && getLayoutDirection() == LayoutDirection.RTL;
616    }
617
618    @Override
619    public void setAutoMirrored(boolean mirrored) {
620        if (mVectorState.mAutoMirrored != mirrored) {
621            mVectorState.mAutoMirrored = mirrored;
622            invalidateSelf();
623        }
624    }
625
626    @Override
627    public boolean isAutoMirrored() {
628        return mVectorState.mAutoMirrored;
629    }
630
631    private static class VectorDrawableState extends ConstantState {
632        int[] mThemeAttrs;
633        int mChangingConfigurations;
634        VPathRenderer mVPathRenderer;
635        ColorStateList mTint = null;
636        Mode mTintMode = DEFAULT_TINT_MODE;
637        boolean mAutoMirrored;
638
639        Bitmap mCachedBitmap;
640        int[] mCachedThemeAttrs;
641        ColorStateList mCachedTint;
642        Mode mCachedTintMode;
643        int mCachedRootAlpha;
644        boolean mCachedAutoMirrored;
645        boolean mCacheDirty;
646
647        /** Temporary paint object used to draw cached bitmaps. */
648        Paint mTempPaint;
649
650        // Deep copy for mutate() or implicitly mutate.
651        public VectorDrawableState(VectorDrawableState copy) {
652            if (copy != null) {
653                mThemeAttrs = copy.mThemeAttrs;
654                mChangingConfigurations = copy.mChangingConfigurations;
655                mVPathRenderer = new VPathRenderer(copy.mVPathRenderer);
656                if (copy.mVPathRenderer.mFillPaint != null) {
657                    mVPathRenderer.mFillPaint = new Paint(copy.mVPathRenderer.mFillPaint);
658                }
659                if (copy.mVPathRenderer.mStrokePaint != null) {
660                    mVPathRenderer.mStrokePaint = new Paint(copy.mVPathRenderer.mStrokePaint);
661                }
662                mTint = copy.mTint;
663                mTintMode = copy.mTintMode;
664                mAutoMirrored = copy.mAutoMirrored;
665            }
666        }
667
668        public void drawCachedBitmapWithRootAlpha(Canvas canvas, ColorFilter filter) {
669            // The bitmap's size is the same as the bounds.
670            final Paint p = getPaint(filter);
671            canvas.drawBitmap(mCachedBitmap, 0, 0, p);
672        }
673
674        public boolean hasTranslucentRoot() {
675            return mVPathRenderer.getRootAlpha() < 255;
676        }
677
678        /**
679         * @return null when there is no need for alpha paint.
680         */
681        public Paint getPaint(ColorFilter filter) {
682            if (!hasTranslucentRoot() && filter == null) {
683                return null;
684            }
685
686            if (mTempPaint == null) {
687                mTempPaint = new Paint();
688            }
689            mTempPaint.setAlpha(mVPathRenderer.getRootAlpha());
690            mTempPaint.setColorFilter(filter);
691            return mTempPaint;
692        }
693
694        public void updateCachedBitmap(Rect bounds) {
695            mCachedBitmap.eraseColor(Color.TRANSPARENT);
696            Canvas tmpCanvas = new Canvas(mCachedBitmap);
697            mVPathRenderer.draw(tmpCanvas, bounds.width(), bounds.height(), null);
698        }
699
700        public void createCachedBitmapIfNeeded(Rect bounds) {
701            if (mCachedBitmap == null || !canReuseBitmap(bounds.width(),
702                    bounds.height())) {
703                mCachedBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(),
704                        Bitmap.Config.ARGB_8888);
705                mCacheDirty = true;
706            }
707
708        }
709
710        public boolean canReuseBitmap(int width, int height) {
711            if (width == mCachedBitmap.getWidth()
712                    && height == mCachedBitmap.getHeight()) {
713                return true;
714            }
715            return false;
716        }
717
718        public boolean canReuseCache() {
719            if (!mCacheDirty
720                    && mCachedThemeAttrs == mThemeAttrs
721                    && mCachedTint == mTint
722                    && mCachedTintMode == mTintMode
723                    && mCachedAutoMirrored == mAutoMirrored
724                    && mCachedRootAlpha == mVPathRenderer.getRootAlpha()) {
725                return true;
726            }
727            return false;
728        }
729
730        public void updateCacheStates() {
731            // Use shallow copy here and shallow comparison in canReuseCache(),
732            // likely hit cache miss more, but practically not much difference.
733            mCachedThemeAttrs = mThemeAttrs;
734            mCachedTint = mTint;
735            mCachedTintMode = mTintMode;
736            mCachedRootAlpha = mVPathRenderer.getRootAlpha();
737            mCachedAutoMirrored = mAutoMirrored;
738            mCacheDirty = false;
739        }
740
741        @Override
742        public boolean canApplyTheme() {
743            return super.canApplyTheme() || mThemeAttrs != null
744                    || (mVPathRenderer != null && mVPathRenderer.canApplyTheme());
745        }
746
747        public VectorDrawableState() {
748            mVPathRenderer = new VPathRenderer();
749        }
750
751        @Override
752        public Drawable newDrawable() {
753            return new VectorDrawable(this, null, null);
754        }
755
756        @Override
757        public Drawable newDrawable(Resources res) {
758            return new VectorDrawable(this, res, null);
759        }
760
761        @Override
762        public Drawable newDrawable(Resources res, Theme theme) {
763            return new VectorDrawable(this, res, theme);
764        }
765
766        @Override
767        public int getChangingConfigurations() {
768            return mChangingConfigurations;
769        }
770    }
771
772    private static class VPathRenderer {
773        /* Right now the internal data structure is organized as a tree.
774         * Each node can be a group node, or a path.
775         * A group node can have groups or paths as children, but a path node has
776         * no children.
777         * One example can be:
778         *                 Root Group
779         *                /    |     \
780         *           Group    Path    Group
781         *          /     \             |
782         *         Path   Path         Path
783         *
784         */
785        // Variables that only used temporarily inside the draw() call, so there
786        // is no need for deep copying.
787        private final Path mPath;
788        private final Path mRenderPath;
789        private static final Matrix IDENTITY_MATRIX = new Matrix();
790        private final Matrix mFinalPathMatrix = new Matrix();
791
792        private Paint mStrokePaint;
793        private Paint mFillPaint;
794        private PathMeasure mPathMeasure;
795
796        /////////////////////////////////////////////////////
797        // Variables below need to be copied (deep copy if applicable) for mutation.
798        private int mChangingConfigurations;
799        private final VGroup mRootGroup;
800        float mBaseWidth = 0;
801        float mBaseHeight = 0;
802        float mViewportWidth = 0;
803        float mViewportHeight = 0;
804        int mRootAlpha = 0xFF;
805        String mRootName = null;
806
807        final ArrayMap<String, Object> mVGTargetsMap = new ArrayMap<String, Object>();
808
809        public VPathRenderer() {
810            mRootGroup = new VGroup();
811            mPath = new Path();
812            mRenderPath = new Path();
813        }
814
815        public void setRootAlpha(int alpha) {
816            mRootAlpha = alpha;
817        }
818
819        public int getRootAlpha() {
820            return mRootAlpha;
821        }
822
823        // setAlpha() and getAlpha() are used mostly for animation purpose, since
824        // Animator like to use alpha from 0 to 1.
825        public void setAlpha(float alpha) {
826            setRootAlpha((int) (alpha * 255));
827        }
828
829        @SuppressWarnings("unused")
830        public float getAlpha() {
831            return getRootAlpha() / 255.0f;
832        }
833
834        public VPathRenderer(VPathRenderer copy) {
835            mRootGroup = new VGroup(copy.mRootGroup, mVGTargetsMap);
836            mPath = new Path(copy.mPath);
837            mRenderPath = new Path(copy.mRenderPath);
838            mBaseWidth = copy.mBaseWidth;
839            mBaseHeight = copy.mBaseHeight;
840            mViewportWidth = copy.mViewportWidth;
841            mViewportHeight = copy.mViewportHeight;
842            mChangingConfigurations = copy.mChangingConfigurations;
843            mRootAlpha = copy.mRootAlpha;
844            mRootName = copy.mRootName;
845            if (copy.mRootName != null) {
846                mVGTargetsMap.put(copy.mRootName, this);
847            }
848        }
849
850        public boolean canApplyTheme() {
851            // If one of the paths can apply theme, then return true;
852            return recursiveCanApplyTheme(mRootGroup);
853        }
854
855        private boolean recursiveCanApplyTheme(VGroup currentGroup) {
856            // We can do a tree traverse here, if there is one path return true,
857            // then we return true for the whole tree.
858            final ArrayList<Object> children = currentGroup.mChildren;
859
860            for (int i = 0; i < children.size(); i++) {
861                Object child = children.get(i);
862                if (child instanceof VGroup) {
863                    VGroup childGroup = (VGroup) child;
864                    if (childGroup.canApplyTheme()
865                            || recursiveCanApplyTheme(childGroup)) {
866                        return true;
867                    }
868                } else if (child instanceof VPath) {
869                    VPath childPath = (VPath) child;
870                    if (childPath.canApplyTheme()) {
871                        return true;
872                    }
873                }
874            }
875            return false;
876        }
877
878        public void applyTheme(Theme t) {
879            // Apply theme to every path of the tree.
880            recursiveApplyTheme(mRootGroup, t);
881        }
882
883        private void recursiveApplyTheme(VGroup currentGroup, Theme t) {
884            // We can do a tree traverse here, apply theme to all paths which
885            // can apply theme.
886            final ArrayList<Object> children = currentGroup.mChildren;
887            for (int i = 0; i < children.size(); i++) {
888                Object child = children.get(i);
889                if (child instanceof VGroup) {
890                    VGroup childGroup = (VGroup) child;
891                    if (childGroup.canApplyTheme()) {
892                        childGroup.applyTheme(t);
893                    }
894                    recursiveApplyTheme(childGroup, t);
895                } else if (child instanceof VPath) {
896                    VPath childPath = (VPath) child;
897                    if (childPath.canApplyTheme()) {
898                        childPath.applyTheme(t);
899                    }
900                }
901            }
902        }
903
904        private void drawGroupTree(VGroup currentGroup, Matrix currentMatrix,
905                Canvas canvas, int w, int h, ColorFilter filter) {
906            // Calculate current group's matrix by preConcat the parent's and
907            // and the current one on the top of the stack.
908            // Basically the Mfinal = Mviewport * M0 * M1 * M2;
909            // Mi the local matrix at level i of the group tree.
910            currentGroup.mStackedMatrix.set(currentMatrix);
911
912            currentGroup.mStackedMatrix.preConcat(currentGroup.mLocalMatrix);
913
914            // Draw the group tree in the same order as the XML file.
915            for (int i = 0; i < currentGroup.mChildren.size(); i++) {
916                Object child = currentGroup.mChildren.get(i);
917                if (child instanceof VGroup) {
918                    VGroup childGroup = (VGroup) child;
919                    drawGroupTree(childGroup, currentGroup.mStackedMatrix,
920                            canvas, w, h, filter);
921                } else if (child instanceof VPath) {
922                    VPath childPath = (VPath) child;
923                    drawPath(currentGroup, childPath, canvas, w, h, filter);
924                }
925            }
926        }
927
928        public void draw(Canvas canvas, int w, int h, ColorFilter filter) {
929            // Travese the tree in pre-order to draw.
930            drawGroupTree(mRootGroup, IDENTITY_MATRIX, canvas, w, h, filter);
931        }
932
933        private void drawPath(VGroup vGroup, VPath vPath, Canvas canvas, int w, int h,
934                ColorFilter filter) {
935            final float scaleX = w / mViewportWidth;
936            final float scaleY = h / mViewportHeight;
937            final float minScale = Math.min(scaleX, scaleY);
938
939            mFinalPathMatrix.set(vGroup.mStackedMatrix);
940            mFinalPathMatrix.postScale(scaleX, scaleY);
941
942            vPath.toPath(mPath);
943            final Path path = mPath;
944
945            mRenderPath.reset();
946
947            if (vPath.isClipPath()) {
948                mRenderPath.addPath(path, mFinalPathMatrix);
949                canvas.clipPath(mRenderPath, Region.Op.REPLACE);
950            } else {
951                VFullPath fullPath = (VFullPath) vPath;
952                if (fullPath.mTrimPathStart != 0.0f || fullPath.mTrimPathEnd != 1.0f) {
953                    float start = (fullPath.mTrimPathStart + fullPath.mTrimPathOffset) % 1.0f;
954                    float end = (fullPath.mTrimPathEnd + fullPath.mTrimPathOffset) % 1.0f;
955
956                    if (mPathMeasure == null) {
957                        mPathMeasure = new PathMeasure();
958                    }
959                    mPathMeasure.setPath(mPath, false);
960
961                    float len = mPathMeasure.getLength();
962                    start = start * len;
963                    end = end * len;
964                    path.reset();
965                    if (start > end) {
966                        mPathMeasure.getSegment(start, len, path, true);
967                        mPathMeasure.getSegment(0f, end, path, true);
968                    } else {
969                        mPathMeasure.getSegment(start, end, path, true);
970                    }
971                    path.rLineTo(0, 0); // fix bug in measure
972                }
973                mRenderPath.addPath(path, mFinalPathMatrix);
974
975                if (fullPath.mFillColor != Color.TRANSPARENT) {
976                    if (mFillPaint == null) {
977                        mFillPaint = new Paint();
978                        mFillPaint.setStyle(Paint.Style.FILL);
979                        mFillPaint.setAntiAlias(true);
980                    }
981
982                    final Paint fillPaint = mFillPaint;
983                    fillPaint.setColor(applyAlpha(fullPath.mFillColor, fullPath.mFillAlpha));
984                    fillPaint.setColorFilter(filter);
985                    canvas.drawPath(mRenderPath, fillPaint);
986                }
987
988                if (fullPath.mStrokeColor != Color.TRANSPARENT) {
989                    if (mStrokePaint == null) {
990                        mStrokePaint = new Paint();
991                        mStrokePaint.setStyle(Paint.Style.STROKE);
992                        mStrokePaint.setAntiAlias(true);
993                    }
994
995                    final Paint strokePaint = mStrokePaint;
996                    if (fullPath.mStrokeLineJoin != null) {
997                        strokePaint.setStrokeJoin(fullPath.mStrokeLineJoin);
998                    }
999
1000                    if (fullPath.mStrokeLineCap != null) {
1001                        strokePaint.setStrokeCap(fullPath.mStrokeLineCap);
1002                    }
1003
1004                    strokePaint.setStrokeMiter(fullPath.mStrokeMiterlimit);
1005                    strokePaint.setColor(applyAlpha(fullPath.mStrokeColor, fullPath.mStrokeAlpha));
1006                    strokePaint.setColorFilter(filter);
1007                    strokePaint.setStrokeWidth(fullPath.mStrokeWidth * minScale);
1008                    canvas.drawPath(mRenderPath, strokePaint);
1009                }
1010            }
1011        }
1012    }
1013
1014    private static class VGroup {
1015        // mStackedMatrix is only used temporarily when drawing, it combines all
1016        // the parents' local matrices with the current one.
1017        private final Matrix mStackedMatrix = new Matrix();
1018
1019        /////////////////////////////////////////////////////
1020        // Variables below need to be copied (deep copy if applicable) for mutation.
1021        final ArrayList<Object> mChildren = new ArrayList<Object>();
1022
1023        private float mRotate = 0;
1024        private float mPivotX = 0;
1025        private float mPivotY = 0;
1026        private float mScaleX = 1;
1027        private float mScaleY = 1;
1028        private float mTranslateX = 0;
1029        private float mTranslateY = 0;
1030
1031        // mLocalMatrix is updated based on the update of transformation information,
1032        // either parsed from the XML or by animation.
1033        private final Matrix mLocalMatrix = new Matrix();
1034        private int mChangingConfigurations;
1035        private int[] mThemeAttrs;
1036        private String mGroupName = null;
1037
1038        public VGroup(VGroup copy, ArrayMap<String, Object> targetsMap) {
1039            mRotate = copy.mRotate;
1040            mPivotX = copy.mPivotX;
1041            mPivotY = copy.mPivotY;
1042            mScaleX = copy.mScaleX;
1043            mScaleY = copy.mScaleY;
1044            mTranslateX = copy.mTranslateX;
1045            mTranslateY = copy.mTranslateY;
1046            mThemeAttrs = copy.mThemeAttrs;
1047            mGroupName = copy.mGroupName;
1048            mChangingConfigurations = copy.mChangingConfigurations;
1049            if (mGroupName != null) {
1050                targetsMap.put(mGroupName, this);
1051            }
1052
1053            mLocalMatrix.set(copy.mLocalMatrix);
1054
1055            final ArrayList<Object> children = copy.mChildren;
1056            for (int i = 0; i < children.size(); i++) {
1057                Object copyChild = children.get(i);
1058                if (copyChild instanceof VGroup) {
1059                    VGroup copyGroup = (VGroup) copyChild;
1060                    mChildren.add(new VGroup(copyGroup, targetsMap));
1061                } else {
1062                    VPath newPath = null;
1063                    if (copyChild instanceof VFullPath) {
1064                        newPath = new VFullPath((VFullPath) copyChild);
1065                    } else if (copyChild instanceof VClipPath) {
1066                        newPath = new VClipPath((VClipPath) copyChild);
1067                    } else {
1068                        throw new IllegalStateException("Unknown object in the tree!");
1069                    }
1070                    mChildren.add(newPath);
1071                    if (newPath.mPathName != null) {
1072                        targetsMap.put(newPath.mPathName, newPath);
1073                    }
1074                }
1075            }
1076        }
1077
1078        public VGroup() {
1079        }
1080
1081        public String getGroupName() {
1082            return mGroupName;
1083        }
1084
1085        public Matrix getLocalMatrix() {
1086            return mLocalMatrix;
1087        }
1088
1089        public void inflate(Resources res, AttributeSet attrs, Theme theme) {
1090            final TypedArray a = obtainAttributes(res, theme, attrs,
1091                    R.styleable.VectorDrawableGroup);
1092            updateStateFromTypedArray(a);
1093            a.recycle();
1094        }
1095
1096        private void updateStateFromTypedArray(TypedArray a) {
1097            // Account for any configuration changes.
1098            mChangingConfigurations |= a.getChangingConfigurations();
1099
1100            // Extract the theme attributes, if any.
1101            mThemeAttrs = a.extractThemeAttrs();
1102
1103            mRotate = a.getFloat(R.styleable.VectorDrawableGroup_rotation, mRotate);
1104            mPivotX = a.getFloat(R.styleable.VectorDrawableGroup_pivotX, mPivotX);
1105            mPivotY = a.getFloat(R.styleable.VectorDrawableGroup_pivotY, mPivotY);
1106            mScaleX = a.getFloat(R.styleable.VectorDrawableGroup_scaleX, mScaleX);
1107            mScaleY = a.getFloat(R.styleable.VectorDrawableGroup_scaleY, mScaleY);
1108            mTranslateX = a.getFloat(R.styleable.VectorDrawableGroup_translateX, mTranslateX);
1109            mTranslateY = a.getFloat(R.styleable.VectorDrawableGroup_translateY, mTranslateY);
1110
1111            final String groupName = a.getString(R.styleable.VectorDrawableGroup_name);
1112            if (groupName != null) {
1113                mGroupName = groupName;
1114            }
1115
1116            updateLocalMatrix();
1117        }
1118
1119        public boolean canApplyTheme() {
1120            return mThemeAttrs != null;
1121        }
1122
1123        public void applyTheme(Theme t) {
1124            if (mThemeAttrs == null) {
1125                return;
1126            }
1127
1128            final TypedArray a = t.resolveAttributes(mThemeAttrs, R.styleable.VectorDrawableGroup);
1129            updateStateFromTypedArray(a);
1130            a.recycle();
1131        }
1132
1133        private void updateLocalMatrix() {
1134            // The order we apply is the same as the
1135            // RenderNode.cpp::applyViewPropertyTransforms().
1136            mLocalMatrix.reset();
1137            mLocalMatrix.postTranslate(-mPivotX, -mPivotY);
1138            mLocalMatrix.postScale(mScaleX, mScaleY);
1139            mLocalMatrix.postRotate(mRotate, 0, 0);
1140            mLocalMatrix.postTranslate(mTranslateX + mPivotX, mTranslateY + mPivotY);
1141        }
1142
1143        /* Setters and Getters, used by animator from AnimatedVectorDrawable. */
1144        @SuppressWarnings("unused")
1145        public float getRotation() {
1146            return mRotate;
1147        }
1148
1149        @SuppressWarnings("unused")
1150        public void setRotation(float rotation) {
1151            if (rotation != mRotate) {
1152                mRotate = rotation;
1153                updateLocalMatrix();
1154            }
1155        }
1156
1157        @SuppressWarnings("unused")
1158        public float getPivotX() {
1159            return mPivotX;
1160        }
1161
1162        @SuppressWarnings("unused")
1163        public void setPivotX(float pivotX) {
1164            if (pivotX != mPivotX) {
1165                mPivotX = pivotX;
1166                updateLocalMatrix();
1167            }
1168        }
1169
1170        @SuppressWarnings("unused")
1171        public float getPivotY() {
1172            return mPivotY;
1173        }
1174
1175        @SuppressWarnings("unused")
1176        public void setPivotY(float pivotY) {
1177            if (pivotY != mPivotY) {
1178                mPivotY = pivotY;
1179                updateLocalMatrix();
1180            }
1181        }
1182
1183        @SuppressWarnings("unused")
1184        public float getScaleX() {
1185            return mScaleX;
1186        }
1187
1188        @SuppressWarnings("unused")
1189        public void setScaleX(float scaleX) {
1190            if (scaleX != mScaleX) {
1191                mScaleX = scaleX;
1192                updateLocalMatrix();
1193            }
1194        }
1195
1196        @SuppressWarnings("unused")
1197        public float getScaleY() {
1198            return mScaleY;
1199        }
1200
1201        @SuppressWarnings("unused")
1202        public void setScaleY(float scaleY) {
1203            if (scaleY != mScaleY) {
1204                mScaleY = scaleY;
1205                updateLocalMatrix();
1206            }
1207        }
1208
1209        @SuppressWarnings("unused")
1210        public float getTranslateX() {
1211            return mTranslateX;
1212        }
1213
1214        @SuppressWarnings("unused")
1215        public void setTranslateX(float translateX) {
1216            if (translateX != mTranslateX) {
1217                mTranslateX = translateX;
1218                updateLocalMatrix();
1219            }
1220        }
1221
1222        @SuppressWarnings("unused")
1223        public float getTranslateY() {
1224            return mTranslateY;
1225        }
1226
1227        @SuppressWarnings("unused")
1228        public void setTranslateY(float translateY) {
1229            if (translateY != mTranslateY) {
1230                mTranslateY = translateY;
1231                updateLocalMatrix();
1232            }
1233        }
1234    }
1235
1236    /**
1237     * Common Path information for clip path and normal path.
1238     */
1239    private static class VPath {
1240        protected PathParser.PathDataNode[] mNodes = null;
1241        String mPathName;
1242        int mChangingConfigurations;
1243
1244        public VPath() {
1245            // Empty constructor.
1246        }
1247
1248        public VPath(VPath copy) {
1249            mPathName = copy.mPathName;
1250            mChangingConfigurations = copy.mChangingConfigurations;
1251            mNodes = PathParser.deepCopyNodes(copy.mNodes);
1252        }
1253
1254        public void toPath(Path path) {
1255            path.reset();
1256            if (mNodes != null) {
1257                PathParser.PathDataNode.nodesToPath(mNodes, path);
1258            }
1259        }
1260
1261        public String getPathName() {
1262            return mPathName;
1263        }
1264
1265        public boolean canApplyTheme() {
1266            return false;
1267        }
1268
1269        public void applyTheme(Theme t) {
1270        }
1271
1272        public boolean isClipPath() {
1273            return false;
1274        }
1275
1276        /* Setters and Getters, used by animator from AnimatedVectorDrawable. */
1277        @SuppressWarnings("unused")
1278        public PathParser.PathDataNode[] getPathData() {
1279            return mNodes;
1280        }
1281
1282        @SuppressWarnings("unused")
1283        public void setPathData(PathParser.PathDataNode[] nodes) {
1284            if (!PathParser.canMorph(mNodes, nodes)) {
1285                // This should not happen in the middle of animation.
1286                mNodes = PathParser.deepCopyNodes(nodes);
1287            } else {
1288                PathParser.updateNodes(mNodes, nodes);
1289            }
1290        }
1291    }
1292
1293    /**
1294     * Clip path, which only has name and pathData.
1295     */
1296    private static class VClipPath extends VPath {
1297        public VClipPath() {
1298            // Empty constructor.
1299        }
1300
1301        public VClipPath(VClipPath copy) {
1302            super(copy);
1303        }
1304
1305        public void inflate(Resources r, AttributeSet attrs, Theme theme) {
1306            final TypedArray a = obtainAttributes(r, theme, attrs,
1307                    R.styleable.VectorDrawableClipPath);
1308            updateStateFromTypedArray(a);
1309            a.recycle();
1310        }
1311
1312        private void updateStateFromTypedArray(TypedArray a) {
1313            // Account for any configuration changes.
1314            mChangingConfigurations |= a.getChangingConfigurations();
1315
1316            mPathName = a.getString(R.styleable.VectorDrawableClipPath_name);
1317            mNodes = PathParser.createNodesFromPathData(a.getString(
1318                    R.styleable.VectorDrawableClipPath_pathData));
1319        }
1320
1321        @Override
1322        public boolean isClipPath() {
1323            return true;
1324        }
1325    }
1326
1327    /**
1328     * Normal path, which contains all the fill / paint information.
1329     */
1330    private static class VFullPath extends VPath {
1331        /////////////////////////////////////////////////////
1332        // Variables below need to be copied (deep copy if applicable) for mutation.
1333        private int[] mThemeAttrs;
1334
1335        int mStrokeColor = Color.TRANSPARENT;
1336        float mStrokeWidth = 0;
1337
1338        int mFillColor = Color.TRANSPARENT;
1339        float mStrokeAlpha = 1.0f;
1340        int mFillRule;
1341        float mFillAlpha = 1.0f;
1342        float mTrimPathStart = 0;
1343        float mTrimPathEnd = 1;
1344        float mTrimPathOffset = 0;
1345
1346        Paint.Cap mStrokeLineCap = Paint.Cap.BUTT;
1347        Paint.Join mStrokeLineJoin = Paint.Join.MITER;
1348        float mStrokeMiterlimit = 4;
1349
1350        public VFullPath() {
1351            // Empty constructor.
1352        }
1353
1354        public VFullPath(VFullPath copy) {
1355            super(copy);
1356            mThemeAttrs = copy.mThemeAttrs;
1357
1358            mStrokeColor = copy.mStrokeColor;
1359            mStrokeWidth = copy.mStrokeWidth;
1360            mStrokeAlpha = copy.mStrokeAlpha;
1361            mFillColor = copy.mFillColor;
1362            mFillRule = copy.mFillRule;
1363            mFillAlpha = copy.mFillAlpha;
1364            mTrimPathStart = copy.mTrimPathStart;
1365            mTrimPathEnd = copy.mTrimPathEnd;
1366            mTrimPathOffset = copy.mTrimPathOffset;
1367
1368            mStrokeLineCap = copy.mStrokeLineCap;
1369            mStrokeLineJoin = copy.mStrokeLineJoin;
1370            mStrokeMiterlimit = copy.mStrokeMiterlimit;
1371        }
1372
1373        private Paint.Cap getStrokeLineCap(int id, Paint.Cap defValue) {
1374            switch (id) {
1375                case LINECAP_BUTT:
1376                    return Paint.Cap.BUTT;
1377                case LINECAP_ROUND:
1378                    return Paint.Cap.ROUND;
1379                case LINECAP_SQUARE:
1380                    return Paint.Cap.SQUARE;
1381                default:
1382                    return defValue;
1383            }
1384        }
1385
1386        private Paint.Join getStrokeLineJoin(int id, Paint.Join defValue) {
1387            switch (id) {
1388                case LINEJOIN_MITER:
1389                    return Paint.Join.MITER;
1390                case LINEJOIN_ROUND:
1391                    return Paint.Join.ROUND;
1392                case LINEJOIN_BEVEL:
1393                    return Paint.Join.BEVEL;
1394                default:
1395                    return defValue;
1396            }
1397        }
1398
1399        @Override
1400        public boolean canApplyTheme() {
1401            return mThemeAttrs != null;
1402        }
1403
1404        public void inflate(Resources r, AttributeSet attrs, Theme theme) {
1405            final TypedArray a = obtainAttributes(r, theme, attrs,
1406                    R.styleable.VectorDrawablePath);
1407            updateStateFromTypedArray(a);
1408            a.recycle();
1409        }
1410
1411        private void updateStateFromTypedArray(TypedArray a) {
1412            // Account for any configuration changes.
1413            mChangingConfigurations |= a.getChangingConfigurations();
1414
1415            // Extract the theme attributes, if any.
1416            mThemeAttrs = a.extractThemeAttrs();
1417
1418            mPathName = a.getString(R.styleable.VectorDrawablePath_name);
1419            mNodes = PathParser.createNodesFromPathData(a.getString(
1420                    R.styleable.VectorDrawablePath_pathData));
1421
1422            mFillColor = a.getColor(R.styleable.VectorDrawablePath_fillColor,
1423                    mFillColor);
1424            mFillAlpha = a.getFloat(R.styleable.VectorDrawablePath_fillAlpha,
1425                    mFillAlpha);
1426            mStrokeLineCap = getStrokeLineCap(a.getInt(
1427                    R.styleable.VectorDrawablePath_strokeLineCap, -1), mStrokeLineCap);
1428            mStrokeLineJoin = getStrokeLineJoin(a.getInt(
1429                    R.styleable.VectorDrawablePath_strokeLineJoin, -1), mStrokeLineJoin);
1430            mStrokeMiterlimit = a.getFloat(
1431                    R.styleable.VectorDrawablePath_strokeMiterLimit, mStrokeMiterlimit);
1432            mStrokeColor = a.getColor(R.styleable.VectorDrawablePath_strokeColor,
1433                    mStrokeColor);
1434            mStrokeAlpha = a.getFloat(R.styleable.VectorDrawablePath_strokeAlpha,
1435                    mStrokeAlpha);
1436            mStrokeWidth = a.getFloat(R.styleable.VectorDrawablePath_strokeWidth,
1437                    mStrokeWidth);
1438            mTrimPathEnd = a.getFloat(R.styleable.VectorDrawablePath_trimPathEnd,
1439                    mTrimPathEnd);
1440            mTrimPathOffset = a.getFloat(
1441                    R.styleable.VectorDrawablePath_trimPathOffset, mTrimPathOffset);
1442            mTrimPathStart = a.getFloat(
1443                    R.styleable.VectorDrawablePath_trimPathStart, mTrimPathStart);
1444        }
1445
1446        @Override
1447        public void applyTheme(Theme t) {
1448            if (mThemeAttrs == null) {
1449                return;
1450            }
1451
1452            final TypedArray a = t.resolveAttributes(mThemeAttrs, R.styleable.VectorDrawablePath);
1453            updateStateFromTypedArray(a);
1454            a.recycle();
1455        }
1456
1457        /* Setters and Getters, used by animator from AnimatedVectorDrawable. */
1458        @SuppressWarnings("unused")
1459        int getStrokeColor() {
1460            return mStrokeColor;
1461        }
1462
1463        @SuppressWarnings("unused")
1464        void setStrokeColor(int strokeColor) {
1465            mStrokeColor = strokeColor;
1466        }
1467
1468        @SuppressWarnings("unused")
1469        float getStrokeWidth() {
1470            return mStrokeWidth;
1471        }
1472
1473        @SuppressWarnings("unused")
1474        void setStrokeWidth(float strokeWidth) {
1475            mStrokeWidth = strokeWidth;
1476        }
1477
1478        @SuppressWarnings("unused")
1479        float getStrokeAlpha() {
1480            return mStrokeAlpha;
1481        }
1482
1483        @SuppressWarnings("unused")
1484        void setStrokeAlpha(float strokeAlpha) {
1485            mStrokeAlpha = strokeAlpha;
1486        }
1487
1488        @SuppressWarnings("unused")
1489        int getFillColor() {
1490            return mFillColor;
1491        }
1492
1493        @SuppressWarnings("unused")
1494        void setFillColor(int fillColor) {
1495            mFillColor = fillColor;
1496        }
1497
1498        @SuppressWarnings("unused")
1499        float getFillAlpha() {
1500            return mFillAlpha;
1501        }
1502
1503        @SuppressWarnings("unused")
1504        void setFillAlpha(float fillAlpha) {
1505            mFillAlpha = fillAlpha;
1506        }
1507
1508        @SuppressWarnings("unused")
1509        float getTrimPathStart() {
1510            return mTrimPathStart;
1511        }
1512
1513        @SuppressWarnings("unused")
1514        void setTrimPathStart(float trimPathStart) {
1515            mTrimPathStart = trimPathStart;
1516        }
1517
1518        @SuppressWarnings("unused")
1519        float getTrimPathEnd() {
1520            return mTrimPathEnd;
1521        }
1522
1523        @SuppressWarnings("unused")
1524        void setTrimPathEnd(float trimPathEnd) {
1525            mTrimPathEnd = trimPathEnd;
1526        }
1527
1528        @SuppressWarnings("unused")
1529        float getTrimPathOffset() {
1530            return mTrimPathOffset;
1531        }
1532
1533        @SuppressWarnings("unused")
1534        void setTrimPathOffset(float trimPathOffset) {
1535            mTrimPathOffset = trimPathOffset;
1536        }
1537    }
1538}
1539