VectorDrawable.java revision 5ff885cd3b8013da4d122127bcf9c30b95e3aeb2
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.Canvas;
22import android.graphics.Color;
23import android.graphics.ColorFilter;
24import android.graphics.Matrix;
25import android.graphics.Paint;
26import android.graphics.Path;
27import android.graphics.PathMeasure;
28import android.graphics.PixelFormat;
29import android.graphics.PorterDuffColorFilter;
30import android.graphics.Rect;
31import android.graphics.Region;
32import android.graphics.PorterDuff.Mode;
33import android.util.ArrayMap;
34import android.util.AttributeSet;
35import android.util.Log;
36import android.util.PathParser;
37import android.util.Xml;
38
39import com.android.internal.R;
40
41import org.xmlpull.v1.XmlPullParser;
42import org.xmlpull.v1.XmlPullParserException;
43import org.xmlpull.v1.XmlPullParserFactory;
44
45import java.io.IOException;
46import java.util.ArrayList;
47import java.util.Arrays;
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 * <dl>
57 * <dt><code>&lt;vector></code></dt>
58 * <dd>Used to defined a vector drawable</dd>
59 * <dt><code>&lt;size></code></dt>
60 * <dd>Used to defined the intrinsic Width Height size of the drawable using
61 * <code>android:width</code> and <code>android:height</code></dd>
62 * <dt><code>&lt;viewport></code></dt>
63 * <dd>Used to defined the size of the virtual canvas the paths are drawn on.
64 * The size is defined using the attributes <code>android:viewportHeight</code>
65 * <code>android:viewportWidth</code></dd>
66 * <dt><code>&lt;group></code></dt>
67 * <dd>Defines a group of paths or subgroups, plus transformation information.
68 * The transformations are defined in the same coordinates as the viewport.
69 * And the transformations are applied in the order of scale, rotate then translate. </dd>
70 * <dt><code>android:rotation</code>
71 * <dd>The degrees of rotation of the group.</dd></dt>
72 * <dt><code>android:pivotX</code>
73 * <dd>The X coordinate of the pivot for the scale and rotation of the group</dd></dt>
74 * <dt><code>android:pivotY</code>
75 * <dd>The Y coordinate of the pivot for the scale and rotation of the group</dd></dt>
76 * <dt><code>android:scaleX</code>
77 * <dd>The amount of scale on the X Coordinate</dd></dt>
78 * <dt><code>android:scaleY</code>
79 * <dd>The amount of scale on the Y coordinate</dd></dt>
80 * <dt><code>android:translateX</code>
81 * <dd>The amount of translation on the X coordinate</dd></dt>
82 * <dt><code>android:translateY</code>
83 * <dd>The amount of translation on the Y coordinate</dd></dt>
84 * <dt><code>&lt;path></code></dt>
85 * <dd>Defines paths to be drawn.
86 * <dl>
87 * <dt><code>android:name</code>
88 * <dd>Defines the name of the path.</dd></dt>
89 * <dt><code>android:pathData</code>
90 * <dd>Defines path string. This is using exactly same format as "d" attribute
91 * in the SVG's path data</dd></dt>
92 * <dt><code>android:fill</code>
93 * <dd>Defines the color to fill the path (none if not present).</dd></dt>
94 * <dt><code>android:stroke</code>
95 * <dd>Defines the color to draw the path outline (none if not present).</dd>
96 * </dt>
97 * <dt><code>android:strokeWidth</code>
98 * <dd>The width a path stroke</dd></dt>
99 * <dt><code>android:strokeOpacity</code>
100 * <dd>The opacity of a path stroke</dd></dt>
101 * <dt><code>android:fillOpacity</code>
102 * <dd>The opacity to fill the path with</dd></dt>
103 * <dt><code>android:trimPathStart</code>
104 * <dd>The fraction of the path to trim from the start from 0 to 1</dd></dt>
105 * <dt><code>android:trimPathEnd</code>
106 * <dd>The fraction of the path to trim from the end from 0 to 1</dd></dt>
107 * <dt><code>android:trimPathOffset</code>
108 * <dd>Shift trim region (allows showed region to include the start and end)
109 * from 0 to 1</dd></dt>
110 * <dt><code>android:clipToPath</code>
111 * <dd>Path will set the clip path</dd></dt>
112 * <dt><code>android:strokeLineCap</code>
113 * <dd>Sets the linecap for a stroked path: butt, round, square</dd></dt>
114 * <dt><code>android:strokeLineJoin</code>
115 * <dd>Sets the lineJoin for a stroked path: miter,round,bevel</dd></dt>
116 * <dt><code>android:strokeMiterLimit</code>
117 * <dd>Sets the Miter limit for a stroked path</dd></dt>
118 * </dl>
119 * </dd>
120 */
121public class VectorDrawable extends Drawable {
122    private static final String LOGTAG = VectorDrawable.class.getSimpleName();
123
124    private static final String SHAPE_SIZE = "size";
125    private static final String SHAPE_VIEWPORT = "viewport";
126    private static final String SHAPE_GROUP = "group";
127    private static final String SHAPE_PATH = "path";
128    private static final String SHAPE_VECTOR = "vector";
129
130    private static final int LINECAP_BUTT = 0;
131    private static final int LINECAP_ROUND = 1;
132    private static final int LINECAP_SQUARE = 2;
133
134    private static final int LINEJOIN_MITER = 0;
135    private static final int LINEJOIN_ROUND = 1;
136    private static final int LINEJOIN_BEVEL = 2;
137
138    private static final boolean DBG_VECTOR_DRAWABLE = false;
139
140    private final VectorDrawableState mVectorState;
141
142    private final ArrayMap<String, Object> mVGTargetsMap = new ArrayMap<String, Object>();
143
144    private PorterDuffColorFilter mTintFilter;
145
146    public VectorDrawable() {
147        mVectorState = new VectorDrawableState(null);
148    }
149
150    private VectorDrawable(VectorDrawableState state, Resources res, Theme theme) {
151        if (theme != null && state.canApplyTheme()) {
152            // If we need to apply a theme, implicitly mutate.
153            mVectorState = new VectorDrawableState(state);
154            applyTheme(theme);
155        } else {
156            mVectorState = state;
157        }
158
159        mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
160        mVectorState.mVPathRenderer.setColorFilter(mTintFilter);
161    }
162
163    Object getTargetByName(String name) {
164        return mVGTargetsMap.get(name);
165    }
166
167    @Override
168    public ConstantState getConstantState() {
169        return mVectorState;
170    }
171
172    @Override
173    public void draw(Canvas canvas) {
174        final int saveCount = canvas.save();
175        final Rect bounds = getBounds();
176        canvas.translate(bounds.left, bounds.top);
177        mVectorState.mVPathRenderer.draw(canvas, bounds.width(), bounds.height());
178        canvas.restoreToCount(saveCount);
179    }
180
181    @Override
182    public int getAlpha() {
183        return mVectorState.mVPathRenderer.getRootAlpha();
184    }
185
186    @Override
187    public void setAlpha(int alpha) {
188        if (mVectorState.mVPathRenderer.getRootAlpha() != alpha) {
189            mVectorState.mVPathRenderer.setRootAlpha(alpha);
190            invalidateSelf();
191        }
192    }
193
194    @Override
195    public void setColorFilter(ColorFilter colorFilter) {
196        final VectorDrawableState state = mVectorState;
197        if (colorFilter != null) {
198            // Color filter overrides tint.
199            mTintFilter = null;
200        } else if (state.mTint != null && state.mTintMode != null) {
201            // Restore the tint filter, if we need one.
202            final int color = state.mTint.getColorForState(getState(), Color.TRANSPARENT);
203            mTintFilter = new PorterDuffColorFilter(color, state.mTintMode);
204            colorFilter = mTintFilter;
205        }
206
207        state.mVPathRenderer.setColorFilter(colorFilter);
208        invalidateSelf();
209    }
210
211    @Override
212    public void setTint(ColorStateList tint, Mode tintMode) {
213        final VectorDrawableState state = mVectorState;
214        if (state.mTint != tint || state.mTintMode != tintMode) {
215            state.mTint = tint;
216            state.mTintMode = tintMode;
217
218            mTintFilter = updateTintFilter(mTintFilter, tint, tintMode);
219            mVectorState.mVPathRenderer.setColorFilter(mTintFilter);
220            invalidateSelf();
221        }
222    }
223
224    @Override
225    protected boolean onStateChange(int[] stateSet) {
226        final VectorDrawableState state = mVectorState;
227        if (state.mTint != null && state.mTintMode != null) {
228            mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
229            mVectorState.mVPathRenderer.setColorFilter(mTintFilter);
230            return true;
231        }
232        return false;
233    }
234
235    @Override
236    public int getOpacity() {
237        return PixelFormat.TRANSLUCENT;
238    }
239
240    /**
241     * Sets padding for this shape, defined by a Rect object. Define the padding
242     * in the Rect object as: left, top, right, bottom.
243     */
244    public void setPadding(Rect padding) {
245        setPadding(padding.left, padding.top, padding.right, padding.bottom);
246    }
247
248    /**
249     * Sets padding for the shape.
250     *
251     * @param left padding for the left side (in pixels)
252     * @param top padding for the top (in pixels)
253     * @param right padding for the right side (in pixels)
254     * @param bottom padding for the bottom (in pixels)
255     */
256    public void setPadding(int left, int top, int right, int bottom) {
257        if ((left | top | right | bottom) == 0) {
258            mVectorState.mPadding = null;
259        } else {
260            if (mVectorState.mPadding == null) {
261                mVectorState.mPadding = new Rect();
262            }
263            mVectorState.mPadding.set(left, top, right, bottom);
264        }
265        invalidateSelf();
266    }
267
268    @Override
269    public int getIntrinsicWidth() {
270        return (int) mVectorState.mVPathRenderer.mBaseWidth;
271    }
272
273    @Override
274    public int getIntrinsicHeight() {
275        return (int) mVectorState.mVPathRenderer.mBaseHeight;
276    }
277
278    @Override
279    public boolean getPadding(Rect padding) {
280        if (mVectorState.mPadding != null) {
281            padding.set(mVectorState.mPadding);
282            return true;
283        } else {
284            return super.getPadding(padding);
285        }
286    }
287
288    @Override
289    public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
290            throws XmlPullParserException, IOException {
291        final VPathRenderer p = inflateInternal(res, parser, attrs, theme);
292        setPathRenderer(p);
293    }
294
295    @Override
296    public boolean canApplyTheme() {
297        return super.canApplyTheme() || mVectorState != null && mVectorState.canApplyTheme();
298    }
299
300    @Override
301    public void applyTheme(Theme t) {
302        super.applyTheme(t);
303
304        final VectorDrawableState state = mVectorState;
305        final VPathRenderer path = state.mVPathRenderer;
306        if (path != null && path.canApplyTheme()) {
307            path.applyTheme(t);
308        }
309    }
310
311    /** @hide */
312    public static VectorDrawable create(Resources resources, int rid) {
313        try {
314            final XmlPullParser xpp = resources.getXml(rid);
315            final AttributeSet attrs = Xml.asAttributeSet(xpp);
316            final XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
317            factory.setNamespaceAware(true);
318
319            final VectorDrawable drawable = new VectorDrawable();
320            drawable.inflate(resources, xpp, attrs);
321
322            return drawable;
323        } catch (XmlPullParserException e) {
324            Log.e(LOGTAG, "parser error", e);
325        } catch (IOException e) {
326            Log.e(LOGTAG, "parser error", e);
327        }
328        return null;
329    }
330
331    private static int applyAlpha(int color, float alpha) {
332        int alphaBytes = Color.alpha(color);
333        color &= 0x00FFFFFF;
334        color |= ((int) (alphaBytes * alpha)) << 24;
335        return color;
336    }
337
338    private VPathRenderer inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs,
339            Theme theme) throws XmlPullParserException, IOException {
340        final VPathRenderer pathRenderer = new VPathRenderer();
341
342        boolean noSizeTag = true;
343        boolean noViewportTag = true;
344        boolean noGroupTag = true;
345        boolean noPathTag = true;
346
347        // Use a stack to help to build the group tree.
348        // The top of the stack is always the current group.
349        final Stack<VGroup> groupStack = new Stack<VGroup>();
350        groupStack.push(pathRenderer.mRootGroup);
351
352        int eventType = parser.getEventType();
353        while (eventType != XmlPullParser.END_DOCUMENT) {
354            if (eventType == XmlPullParser.START_TAG) {
355                final String tagName = parser.getName();
356                final VGroup currentGroup = groupStack.peek();
357
358                if (SHAPE_PATH.equals(tagName)) {
359                    final VPath path = new VPath();
360                    path.inflate(res, attrs, theme);
361                    currentGroup.add(path);
362                    if (path.getPathName() != null) {
363                        mVGTargetsMap.put(path.getPathName(), path);
364                    }
365                    noPathTag = false;
366                } else if (SHAPE_SIZE.equals(tagName)) {
367                    pathRenderer.parseSize(res, attrs);
368                    noSizeTag = false;
369                } else if (SHAPE_VIEWPORT.equals(tagName)) {
370                    pathRenderer.parseViewport(res, attrs);
371                    noViewportTag = false;
372                } else if (SHAPE_GROUP.equals(tagName)) {
373                    VGroup newChildGroup = new VGroup();
374                    newChildGroup.inflate(res, attrs, theme);
375                    currentGroup.mChildGroupList.add(newChildGroup);
376                    groupStack.push(newChildGroup);
377                    if (newChildGroup.getGroupName() != null) {
378                        mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup);
379                    }
380                    noGroupTag = false;
381                }
382            } else if (eventType == XmlPullParser.END_TAG) {
383                final String tagName = parser.getName();
384                if (SHAPE_GROUP.equals(tagName)) {
385                    groupStack.pop();
386                }
387            }
388            eventType = parser.next();
389        }
390
391        // Print the tree out for debug.
392        if (DBG_VECTOR_DRAWABLE) {
393            printGroupTree(pathRenderer.mRootGroup, 0);
394        }
395
396        if (noSizeTag || noViewportTag || noPathTag) {
397            final StringBuffer tag = new StringBuffer();
398
399            if (noSizeTag) {
400                tag.append(SHAPE_SIZE);
401            }
402
403            if (noViewportTag) {
404                if (tag.length() > 0) {
405                    tag.append(" & ");
406                }
407                tag.append(SHAPE_SIZE);
408            }
409
410            if (noPathTag) {
411                if (tag.length() > 0) {
412                    tag.append(" or ");
413                }
414                tag.append(SHAPE_PATH);
415            }
416
417            throw new XmlPullParserException("no " + tag + " defined");
418        }
419
420        return pathRenderer;
421    }
422
423    private void printGroupTree(VGroup currentGroup, int level) {
424        String indent = "";
425        for (int i = 0 ; i < level ; i++) {
426            indent += "    ";
427        }
428        // Print the current node
429        Log.v(LOGTAG, indent + "current group is :" +  currentGroup.getGroupName()
430                + " rotation is " + currentGroup.mRotate);
431        Log.v(LOGTAG, indent + "matrix is :" +  currentGroup.getLocalMatrix().toString());
432        // Then print all the children
433        for (int i = 0 ; i < currentGroup.mChildGroupList.size(); i++) {
434            printGroupTree(currentGroup.mChildGroupList.get(i), level + 1);
435        }
436    }
437
438    private void setPathRenderer(VPathRenderer pathRenderer) {
439        mVectorState.mVPathRenderer = pathRenderer;
440    }
441
442    private static class VectorDrawableState extends ConstantState {
443        int mChangingConfigurations;
444        VPathRenderer mVPathRenderer;
445        Rect mPadding;
446        ColorStateList mTint;
447        Mode mTintMode;
448
449        public VectorDrawableState(VectorDrawableState copy) {
450            if (copy != null) {
451                mChangingConfigurations = copy.mChangingConfigurations;
452                // TODO: Make sure the constant state are handled correctly.
453                mVPathRenderer = new VPathRenderer(copy.mVPathRenderer);
454                mPadding = new Rect(copy.mPadding);
455                mTint = copy.mTint;
456                mTintMode = copy.mTintMode;
457            }
458        }
459
460        @Override
461        public Drawable newDrawable() {
462            return new VectorDrawable(this, null, null);
463        }
464
465        @Override
466        public Drawable newDrawable(Resources res) {
467            return new VectorDrawable(this, res, null);
468        }
469
470        @Override
471        public Drawable newDrawable(Resources res, Theme theme) {
472            return new VectorDrawable(this, res, theme);
473        }
474
475        @Override
476        public int getChangingConfigurations() {
477            return mChangingConfigurations;
478        }
479    }
480
481    private static class VPathRenderer {
482        /* Right now the internal data structure is organized as a tree.
483         * Each node can be a group node, or a path.
484         * A group node can have groups or paths as children, but a path node has
485         * no children.
486         * One example can be:
487         *                 Root Group
488         *                /    |     \
489         *           Group    Path    Group
490         *          /     \             |
491         *         Path   Path         Path
492         *
493         */
494        private final VGroup mRootGroup;
495
496        private final Path mPath = new Path();
497        private final Path mRenderPath = new Path();
498        private static final Matrix IDENTITY_MATRIX = new Matrix();
499
500        private Paint mStrokePaint;
501        private Paint mFillPaint;
502        private ColorFilter mColorFilter;
503        private PathMeasure mPathMeasure;
504
505        private float mBaseWidth = 0;
506        private float mBaseHeight = 0;
507        private float mViewportWidth = 0;
508        private float mViewportHeight = 0;
509        private int mRootAlpha = 0xFF;
510
511        private final Matrix mFinalPathMatrix = new Matrix();
512
513        public VPathRenderer() {
514            mRootGroup = new VGroup();
515        }
516
517        public void setRootAlpha(int alpha) {
518            mRootAlpha = alpha;
519        }
520
521        public int getRootAlpha() {
522            return mRootAlpha;
523        }
524
525        public VPathRenderer(VPathRenderer copy) {
526            mRootGroup = copy.mRootGroup;
527            mBaseWidth = copy.mBaseWidth;
528            mBaseHeight = copy.mBaseHeight;
529            mViewportWidth = copy.mViewportHeight;
530            mViewportHeight = copy.mViewportHeight;
531        }
532
533        public boolean canApplyTheme() {
534            // If one of the paths can apply theme, then return true;
535            return recursiveCanApplyTheme(mRootGroup);
536        }
537
538        private boolean recursiveCanApplyTheme(VGroup currentGroup) {
539            // We can do a tree traverse here, if there is one path return true,
540            // then we return true for the whole tree.
541            final ArrayList<VPath> paths = currentGroup.mPathList;
542            for (int j = paths.size() - 1; j >= 0; j--) {
543                final VPath path = paths.get(j);
544                if (path.canApplyTheme()) {
545                    return true;
546                }
547            }
548
549            final ArrayList<VGroup> childGroups = currentGroup.mChildGroupList;
550
551            for (int i = 0; i < childGroups.size(); i++) {
552                VGroup childGroup = childGroups.get(i);
553                if (childGroup.canApplyTheme()
554                        || recursiveCanApplyTheme(childGroup)) {
555                    return true;
556                }
557            }
558            return false;
559        }
560
561        public void applyTheme(Theme t) {
562            // Apply theme to every path of the tree.
563            recursiveApplyTheme(mRootGroup, t);
564        }
565
566        private void recursiveApplyTheme(VGroup currentGroup, Theme t) {
567            // We can do a tree traverse here, apply theme to all paths which
568            // can apply theme.
569            final ArrayList<VPath> paths = currentGroup.mPathList;
570            for (int j = paths.size() - 1; j >= 0; j--) {
571                final VPath path = paths.get(j);
572                if (path.canApplyTheme()) {
573                    path.applyTheme(t);
574                }
575            }
576
577            final ArrayList<VGroup> childGroups = currentGroup.mChildGroupList;
578
579            for (int i = 0; i < childGroups.size(); i++) {
580                VGroup childGroup = childGroups.get(i);
581                if (childGroup.canApplyTheme()) {
582                    childGroup.applyTheme(t);
583                }
584                recursiveApplyTheme(childGroup, t);
585            }
586
587        }
588
589        public void setColorFilter(ColorFilter colorFilter) {
590            mColorFilter = colorFilter;
591
592            if (mFillPaint != null) {
593                mFillPaint.setColorFilter(colorFilter);
594            }
595
596            if (mStrokePaint != null) {
597                mStrokePaint.setColorFilter(colorFilter);
598            }
599
600        }
601
602        private void drawGroupTree(VGroup currentGroup, Matrix currentMatrix,
603                float currentAlpha, Canvas canvas, int w, int h) {
604            // Calculate current group's matrix by preConcat the parent's and
605            // and the current one on the top of the stack.
606            // Basically the Mfinal = Mviewport * M0 * M1 * M2;
607            // Mi the local matrix at level i of the group tree.
608            currentGroup.mStackedMatrix.set(currentMatrix);
609
610            currentGroup.mStackedMatrix.preConcat(currentGroup.mLocalMatrix);
611
612            float stackedAlpha = currentAlpha * currentGroup.mGroupAlpha;
613            drawPath(currentGroup, stackedAlpha, canvas, w, h);
614            // Draw the group tree in post order.
615            for (int i = 0 ; i < currentGroup.mChildGroupList.size(); i++) {
616                drawGroupTree(currentGroup.mChildGroupList.get(i),
617                        currentGroup.mStackedMatrix, stackedAlpha, canvas, w, h);
618            }
619        }
620
621        public void draw(Canvas canvas, int w, int h) {
622            // Travese the tree in pre-order to draw.
623            drawGroupTree(mRootGroup, IDENTITY_MATRIX, ((float) mRootAlpha) / 0xFF, canvas, w, h);
624        }
625
626        private void drawPath(VGroup vGroup, float stackedAlpha, Canvas canvas, int w, int h) {
627            final float scale = Math.min(h / mViewportHeight, w / mViewportWidth);
628
629            mFinalPathMatrix.set(vGroup.mStackedMatrix);
630            mFinalPathMatrix.postScale(scale, scale, mViewportWidth / 2f, mViewportHeight / 2f);
631            mFinalPathMatrix.postTranslate(w / 2f - mViewportWidth / 2f, h / 2f - mViewportHeight / 2f);
632
633            ArrayList<VPath> paths = vGroup.getPaths();
634            for (int i = 0; i < paths.size(); i++) {
635                VPath vPath = paths.get(i);
636                vPath.toPath(mPath);
637                final Path path = mPath;
638
639                if (vPath.mTrimPathStart != 0.0f || vPath.mTrimPathEnd != 1.0f) {
640                    float start = (vPath.mTrimPathStart + vPath.mTrimPathOffset) % 1.0f;
641                    float end = (vPath.mTrimPathEnd + vPath.mTrimPathOffset) % 1.0f;
642
643                    if (mPathMeasure == null) {
644                        mPathMeasure = new PathMeasure();
645                    }
646                    mPathMeasure.setPath(mPath, false);
647
648                    float len = mPathMeasure.getLength();
649                    start = start * len;
650                    end = end * len;
651                    path.reset();
652                    if (start > end) {
653                        mPathMeasure.getSegment(start, len, path, true);
654                        mPathMeasure.getSegment(0f, end, path, true);
655                    } else {
656                        mPathMeasure.getSegment(start, end, path, true);
657                    }
658                    path.rLineTo(0, 0); // fix bug in measure
659                }
660
661                mRenderPath.reset();
662
663                mRenderPath.addPath(path, mFinalPathMatrix);
664
665                if (vPath.mClip) {
666                    canvas.clipPath(mRenderPath, Region.Op.REPLACE);
667                } else {
668                   if (vPath.mFillColor != 0) {
669                        if (mFillPaint == null) {
670                            mFillPaint = new Paint();
671                            mFillPaint.setColorFilter(mColorFilter);
672                            mFillPaint.setStyle(Paint.Style.FILL);
673                            mFillPaint.setAntiAlias(true);
674                        }
675                        mFillPaint.setColor(applyAlpha(vPath.mFillColor, stackedAlpha));
676                        canvas.drawPath(mRenderPath, mFillPaint);
677                    }
678
679                    if (vPath.mStrokeColor != 0) {
680                        if (mStrokePaint == null) {
681                            mStrokePaint = new Paint();
682                            mStrokePaint.setColorFilter(mColorFilter);
683                            mStrokePaint.setStyle(Paint.Style.STROKE);
684                            mStrokePaint.setAntiAlias(true);
685                        }
686
687                        final Paint strokePaint = mStrokePaint;
688                        if (vPath.mStrokeLineJoin != null) {
689                            strokePaint.setStrokeJoin(vPath.mStrokeLineJoin);
690                        }
691
692                        if (vPath.mStrokeLineCap != null) {
693                            strokePaint.setStrokeCap(vPath.mStrokeLineCap);
694                        }
695
696                        strokePaint.setStrokeMiter(vPath.mStrokeMiterlimit * scale);
697
698                        strokePaint.setColor(applyAlpha(vPath.mStrokeColor, stackedAlpha));
699                        strokePaint.setStrokeWidth(vPath.mStrokeWidth * scale);
700                        canvas.drawPath(mRenderPath, strokePaint);
701                    }
702                }
703            }
704        }
705
706        private void parseViewport(Resources r, AttributeSet attrs)
707                throws XmlPullParserException {
708            final TypedArray a = r.obtainAttributes(attrs, R.styleable.VectorDrawableViewport);
709            mViewportWidth = a.getFloat(R.styleable.VectorDrawableViewport_viewportWidth, mViewportWidth);
710            mViewportHeight = a.getFloat(R.styleable.VectorDrawableViewport_viewportHeight, mViewportHeight);
711
712            if (mViewportWidth <= 0) {
713                throw new XmlPullParserException(a.getPositionDescription() +
714                        "<viewport> tag requires viewportWidth > 0");
715            } else if (mViewportHeight <= 0) {
716                throw new XmlPullParserException(a.getPositionDescription() +
717                        "<viewport> tag requires viewportHeight > 0");
718            }
719
720            a.recycle();
721        }
722
723        private void parseSize(Resources r, AttributeSet attrs)
724                throws XmlPullParserException  {
725            final TypedArray a = r.obtainAttributes(attrs, R.styleable.VectorDrawableSize);
726            mBaseWidth = a.getDimension(R.styleable.VectorDrawableSize_width, mBaseWidth);
727            mBaseHeight = a.getDimension(R.styleable.VectorDrawableSize_height, mBaseHeight);
728
729            if (mBaseWidth <= 0) {
730                throw new XmlPullParserException(a.getPositionDescription() +
731                        "<size> tag requires width > 0");
732            } else if (mBaseHeight <= 0) {
733                throw new XmlPullParserException(a.getPositionDescription() +
734                        "<size> tag requires height > 0");
735            }
736
737            a.recycle();
738        }
739
740    }
741
742    static class VGroup {
743        private final ArrayList<VPath> mPathList = new ArrayList<VPath>();
744        private final ArrayList<VGroup> mChildGroupList = new ArrayList<VGroup>();
745
746        private float mRotate = 0;
747        private float mPivotX = 0;
748        private float mPivotY = 0;
749        private float mScaleX = 1;
750        private float mScaleY = 1;
751        private float mTranslateX = 0;
752        private float mTranslateY = 0;
753        private float mGroupAlpha = 1;
754
755        // mLocalMatrix is parsed from the XML.
756        private final Matrix mLocalMatrix = new Matrix();
757        // mStackedMatrix is only used when drawing, it combines all the
758        // parents' local matrices with the current one.
759        private final Matrix mStackedMatrix = new Matrix();
760
761        private int[] mThemeAttrs;
762
763        private String mGroupName = null;
764
765        /* Getter and Setter */
766        public float getRotation() {
767            return mRotate;
768        }
769
770        public void setRotation(float rotation) {
771            if (rotation != mRotate) {
772                mRotate = rotation;
773                updateLocalMatrix();
774            }
775        }
776
777        public float getPivotX() {
778            return mPivotX;
779        }
780
781        public void setPivotX(float pivotX) {
782            if (pivotX != mPivotX) {
783                mPivotX = pivotX;
784                updateLocalMatrix();
785            }
786        }
787
788        public float getPivotY() {
789            return mPivotY;
790        }
791
792        public void setPivotY(float pivotY) {
793            if (pivotY != mPivotY) {
794                mPivotY = pivotY;
795                updateLocalMatrix();
796            }
797        }
798
799        public float getScaleX() {
800            return mScaleX;
801        }
802
803        public void setScaleX(float scaleX) {
804            if (scaleX != mScaleX) {
805                mScaleX = scaleX;
806                updateLocalMatrix();
807            }
808        }
809
810        public float getScaleY() {
811            return mScaleY;
812        }
813
814        public void setScaleY(float scaleY) {
815            if (scaleY != mScaleY) {
816                mScaleY = scaleY;
817                updateLocalMatrix();
818            }
819        }
820
821        public float getTranslateX() {
822            return mTranslateX;
823        }
824
825        public void setTranslateX(float translateX) {
826            if (translateX != mTranslateX) {
827                mTranslateX = translateX;
828                updateLocalMatrix();
829            }
830        }
831
832        public float getTranslateY() {
833            return mTranslateY;
834        }
835
836        public void setTranslateY(float translateY) {
837            if (translateY != mTranslateY) {
838                mTranslateY = translateY;
839                updateLocalMatrix();
840            }
841        }
842
843        public float getAlpha() {
844            return mGroupAlpha;
845        }
846
847        public void setAlpha(float groupAlpha) {
848            if (groupAlpha != mGroupAlpha) {
849                mGroupAlpha = groupAlpha;
850            }
851        }
852
853        public String getGroupName() {
854            return mGroupName;
855        }
856
857        public Matrix getLocalMatrix() {
858            return mLocalMatrix;
859        }
860
861        public void add(VPath path) {
862            mPathList.add(path);
863         }
864
865        public boolean canApplyTheme() {
866            return mThemeAttrs != null;
867        }
868
869        public void applyTheme(Theme t) {
870            if (mThemeAttrs == null) {
871                return;
872            }
873
874            final TypedArray a = t.resolveAttributes(
875                    mThemeAttrs, R.styleable.VectorDrawablePath);
876
877            mRotate = a.getFloat(R.styleable.VectorDrawableGroup_rotation, mRotate);
878            mPivotX = a.getFloat(R.styleable.VectorDrawableGroup_pivotX, mPivotX);
879            mPivotY = a.getFloat(R.styleable.VectorDrawableGroup_pivotY, mPivotY);
880            mScaleX = a.getFloat(R.styleable.VectorDrawableGroup_scaleX, mScaleX);
881            mScaleY = a.getFloat(R.styleable.VectorDrawableGroup_scaleY, mScaleY);
882            mTranslateX = a.getFloat(R.styleable.VectorDrawableGroup_translateX, mTranslateX);
883            mTranslateY = a.getFloat(R.styleable.VectorDrawableGroup_translateY, mTranslateY);
884            mGroupAlpha = a.getFloat(R.styleable.VectorDrawableGroup_alpha, mGroupAlpha);
885            updateLocalMatrix();
886            if (a.hasValue(R.styleable.VectorDrawableGroup_name)) {
887                mGroupName = a.getString(R.styleable.VectorDrawableGroup_name);
888            }
889            a.recycle();
890        }
891
892        public void inflate(Resources res, AttributeSet attrs, Theme theme) {
893            final TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawableGroup);
894            final int[] themeAttrs = a.extractThemeAttrs();
895
896            mThemeAttrs = themeAttrs;
897            // NOTE: The set of attributes loaded here MUST match the
898            // set of attributes loaded in applyTheme.
899
900            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_rotation] == 0) {
901                mRotate = a.getFloat(R.styleable.VectorDrawableGroup_rotation, mRotate);
902            }
903
904            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_pivotX] == 0) {
905                mPivotX = a.getFloat(R.styleable.VectorDrawableGroup_pivotX, mPivotX);
906            }
907
908            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_pivotY] == 0) {
909                mPivotY = a.getFloat(R.styleable.VectorDrawableGroup_pivotY, mPivotY);
910            }
911
912            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_scaleX] == 0) {
913                mScaleX = a.getFloat(R.styleable.VectorDrawableGroup_scaleX, mScaleX);
914            }
915
916            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_scaleY] == 0) {
917                mScaleY = a.getFloat(R.styleable.VectorDrawableGroup_scaleY, mScaleY);
918            }
919
920            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_translateX] == 0) {
921                mTranslateX = a.getFloat(R.styleable.VectorDrawableGroup_translateX, mTranslateX);
922            }
923
924            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_translateY] == 0) {
925                mTranslateY = a.getFloat(R.styleable.VectorDrawableGroup_translateY, mTranslateY);
926            }
927
928            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_name] == 0) {
929                mGroupName = a.getString(R.styleable.VectorDrawableGroup_name);
930            }
931
932            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawableGroup_alpha] == 0) {
933                mGroupAlpha = a.getFloat(R.styleable.VectorDrawableGroup_alpha, mGroupAlpha);
934            }
935
936            updateLocalMatrix();
937            a.recycle();
938        }
939
940        private void updateLocalMatrix() {
941            // The order we apply is the same as the
942            // RenderNode.cpp::applyViewPropertyTransforms().
943            mLocalMatrix.reset();
944            mLocalMatrix.postTranslate(-mPivotX, -mPivotY);
945            mLocalMatrix.postScale(mScaleX, mScaleY);
946            mLocalMatrix.postRotate(mRotate, 0, 0);
947            mLocalMatrix.postTranslate(mTranslateX + mPivotX, mTranslateY + mPivotY);
948        }
949
950        /**
951         * Must return in order of adding
952         * @return ordered list of paths
953         */
954        public ArrayList<VPath> getPaths() {
955            return mPathList;
956        }
957
958    }
959
960    private static class VPath {
961        private int[] mThemeAttrs;
962
963        int mStrokeColor = 0;
964        float mStrokeWidth = 0;
965        float mStrokeOpacity = Float.NaN;
966        int mFillColor = Color.BLACK;
967        int mFillRule;
968        float mFillOpacity = Float.NaN;
969        float mTrimPathStart = 0;
970        float mTrimPathEnd = 1;
971        float mTrimPathOffset = 0;
972
973        boolean mClip = false;
974        Paint.Cap mStrokeLineCap = Paint.Cap.BUTT;
975        Paint.Join mStrokeLineJoin = Paint.Join.MITER;
976        float mStrokeMiterlimit = 4;
977
978        private PathParser.PathDataNode[] mNode = null;
979        private String mPathName;
980
981        public VPath() {
982            // Empty constructor.
983        }
984
985        public void toPath(Path path) {
986            path.reset();
987            if (mNode != null) {
988                PathParser.PathDataNode.nodesToPath(mNode, path);
989            }
990        }
991
992        public String getPathName() {
993            return mPathName;
994        }
995
996        private Paint.Cap getStrokeLineCap(int id, Paint.Cap defValue) {
997            switch (id) {
998                case LINECAP_BUTT:
999                    return Paint.Cap.BUTT;
1000                case LINECAP_ROUND:
1001                    return Paint.Cap.ROUND;
1002                case LINECAP_SQUARE:
1003                    return Paint.Cap.SQUARE;
1004                default:
1005                    return defValue;
1006            }
1007        }
1008
1009        private Paint.Join getStrokeLineJoin(int id, Paint.Join defValue) {
1010            switch (id) {
1011                case LINEJOIN_MITER:
1012                    return Paint.Join.MITER;
1013                case LINEJOIN_ROUND:
1014                    return Paint.Join.ROUND;
1015                case LINEJOIN_BEVEL:
1016                    return Paint.Join.BEVEL;
1017                default:
1018                    return defValue;
1019            }
1020        }
1021
1022        /* Setters and Getters */
1023        int getStroke() {
1024            return mStrokeColor;
1025        }
1026
1027        void setStroke(int strokeColor) {
1028            mStrokeColor = strokeColor;
1029        }
1030
1031        float getStrokeWidth() {
1032            return mStrokeWidth;
1033        }
1034
1035        void setStrokeWidth(float strokeWidth) {
1036            mStrokeWidth = strokeWidth;
1037        }
1038
1039        float getStrokeOpacity() {
1040            return mStrokeOpacity;
1041        }
1042
1043        void setStrokeOpacity(float strokeOpacity) {
1044            mStrokeOpacity = strokeOpacity;
1045        }
1046
1047        int getFill() {
1048            return mFillColor;
1049        }
1050
1051        void setFill(int fillColor) {
1052            mFillColor = fillColor;
1053        }
1054
1055        float getFillOpacity() {
1056            return mFillOpacity;
1057        }
1058
1059        void setFillOpacity(float fillOpacity) {
1060            mFillOpacity = fillOpacity;
1061        }
1062
1063        float getTrimPathStart() {
1064            return mTrimPathStart;
1065        }
1066
1067        void setTrimPathStart(float trimPathStart) {
1068            mTrimPathStart = trimPathStart;
1069        }
1070
1071        float getTrimPathEnd() {
1072            return mTrimPathEnd;
1073        }
1074
1075        void setTrimPathEnd(float trimPathEnd) {
1076            mTrimPathEnd = trimPathEnd;
1077        }
1078
1079        float getTrimPathOffset() {
1080            return mTrimPathOffset;
1081        }
1082
1083        void setTrimPathOffset(float trimPathOffset) {
1084            mTrimPathOffset = trimPathOffset;
1085        }
1086
1087        public void inflate(Resources r, AttributeSet attrs, Theme theme) {
1088            final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.VectorDrawablePath);
1089            final int[] themeAttrs = a.extractThemeAttrs();
1090            mThemeAttrs = themeAttrs;
1091
1092            // NOTE: The set of attributes loaded here MUST match the
1093            // set of attributes loaded in applyTheme.
1094            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_clipToPath] == 0) {
1095                mClip = a.getBoolean(R.styleable.VectorDrawablePath_clipToPath, mClip);
1096            }
1097
1098            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_name] == 0) {
1099                mPathName = a.getString(R.styleable.VectorDrawablePath_name);
1100            }
1101
1102            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_pathData] == 0) {
1103                mNode = PathParser.createNodesFromPathData(a.getString(
1104                        R.styleable.VectorDrawablePath_pathData));
1105            }
1106
1107            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_fill] == 0) {
1108                mFillColor = a.getColor(R.styleable.VectorDrawablePath_fill, mFillColor);
1109            }
1110
1111            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_fillOpacity] == 0) {
1112                mFillOpacity = a.getFloat(R.styleable.VectorDrawablePath_fillOpacity, mFillOpacity);
1113            }
1114
1115            if (themeAttrs == null
1116                    || themeAttrs[R.styleable.VectorDrawablePath_strokeLineCap] == 0) {
1117                mStrokeLineCap = getStrokeLineCap(
1118                        a.getInt(R.styleable.VectorDrawablePath_strokeLineCap, -1), mStrokeLineCap);
1119            }
1120
1121            if (themeAttrs == null
1122                    || themeAttrs[R.styleable.VectorDrawablePath_strokeLineJoin] == 0) {
1123                mStrokeLineJoin = getStrokeLineJoin(
1124                        a.getInt(R.styleable.VectorDrawablePath_strokeLineJoin, -1), mStrokeLineJoin);
1125            }
1126
1127            if (themeAttrs == null
1128                    || themeAttrs[R.styleable.VectorDrawablePath_strokeMiterLimit] == 0) {
1129                mStrokeMiterlimit = a.getFloat(
1130                        R.styleable.VectorDrawablePath_strokeMiterLimit, mStrokeMiterlimit);
1131            }
1132
1133            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_stroke] == 0) {
1134                mStrokeColor = a.getColor(R.styleable.VectorDrawablePath_stroke, mStrokeColor);
1135            }
1136
1137            if (themeAttrs == null
1138                    || themeAttrs[R.styleable.VectorDrawablePath_strokeOpacity] == 0) {
1139                mStrokeOpacity = a.getFloat(
1140                        R.styleable.VectorDrawablePath_strokeOpacity, mStrokeOpacity);
1141            }
1142
1143            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_strokeWidth] == 0) {
1144                mStrokeWidth = a.getFloat(R.styleable.VectorDrawablePath_strokeWidth, mStrokeWidth);
1145            }
1146
1147            if (themeAttrs == null || themeAttrs[R.styleable.VectorDrawablePath_trimPathEnd] == 0) {
1148                mTrimPathEnd = a.getFloat(R.styleable.VectorDrawablePath_trimPathEnd, mTrimPathEnd);
1149            }
1150
1151            if (themeAttrs == null
1152                    || themeAttrs[R.styleable.VectorDrawablePath_trimPathOffset] == 0) {
1153                mTrimPathOffset = a.getFloat(
1154                        R.styleable.VectorDrawablePath_trimPathOffset, mTrimPathOffset);
1155            }
1156
1157            if (themeAttrs == null
1158                    || themeAttrs[R.styleable.VectorDrawablePath_trimPathStart] == 0) {
1159                mTrimPathStart = a.getFloat(
1160                        R.styleable.VectorDrawablePath_trimPathStart, mTrimPathStart);
1161            }
1162
1163            updateColorAlphas();
1164
1165            a.recycle();
1166        }
1167
1168        public boolean canApplyTheme() {
1169            return mThemeAttrs != null;
1170        }
1171
1172        public void applyTheme(Theme t) {
1173            if (mThemeAttrs == null) {
1174                return;
1175            }
1176
1177            final TypedArray a = t.resolveAttributes(
1178                    mThemeAttrs, R.styleable.VectorDrawablePath);
1179
1180            mClip = a.getBoolean(R.styleable.VectorDrawablePath_clipToPath, mClip);
1181
1182            if (a.hasValue(R.styleable.VectorDrawablePath_name)) {
1183                mPathName = a.getString(R.styleable.VectorDrawablePath_name);
1184            }
1185
1186            if (a.hasValue(R.styleable.VectorDrawablePath_pathData)) {
1187                mNode = PathParser.createNodesFromPathData(a.getString(
1188                        R.styleable.VectorDrawablePath_pathData));
1189            }
1190
1191            mFillColor = a.getColor(R.styleable.VectorDrawablePath_fill, mFillColor);
1192            mFillOpacity = a.getFloat(R.styleable.VectorDrawablePath_fillOpacity, mFillOpacity);
1193
1194            mStrokeLineCap = getStrokeLineCap(a.getInt(
1195                    R.styleable.VectorDrawablePath_strokeLineCap, -1), mStrokeLineCap);
1196            mStrokeLineJoin = getStrokeLineJoin(a.getInt(
1197                    R.styleable.VectorDrawablePath_strokeLineJoin, -1), mStrokeLineJoin);
1198            mStrokeMiterlimit = a.getFloat(
1199                    R.styleable.VectorDrawablePath_strokeMiterLimit, mStrokeMiterlimit);
1200            mStrokeColor = a.getColor(R.styleable.VectorDrawablePath_stroke, mStrokeColor);
1201            mStrokeOpacity = a.getFloat(
1202                    R.styleable.VectorDrawablePath_strokeOpacity, mStrokeOpacity);
1203            mStrokeWidth = a.getFloat(R.styleable.VectorDrawablePath_strokeWidth, mStrokeWidth);
1204
1205            mTrimPathEnd = a.getFloat(R.styleable.VectorDrawablePath_trimPathEnd, mTrimPathEnd);
1206            mTrimPathOffset = a.getFloat(
1207                    R.styleable.VectorDrawablePath_trimPathOffset, mTrimPathOffset);
1208            mTrimPathStart = a.getFloat(
1209                    R.styleable.VectorDrawablePath_trimPathStart, mTrimPathStart);
1210
1211            updateColorAlphas();
1212            a.recycle();
1213        }
1214
1215        private void updateColorAlphas() {
1216            if (!Float.isNaN(mFillOpacity)) {
1217                mFillColor = applyAlpha(mFillColor, mFillOpacity);
1218            }
1219
1220            if (!Float.isNaN(mStrokeOpacity)) {
1221                mStrokeColor = applyAlpha(mStrokeColor, mStrokeOpacity);
1222            }
1223        }
1224    }
1225}
1226