Full Code of Cricin/Folivora for AI

master e2beb4637a8b cached
45 files
247.9 KB
65.5k tokens
157 symbols
1 requests
Download .txt
Showing preview only (269K chars total). Download the full file or copy to clipboard to get everything.
Repository: Cricin/Folivora
Branch: master
Commit: e2beb4637a8b
Files: 45
Total size: 247.9 KB

Directory structure:
gitextract_92jzfoma/

├── .gitignore
├── LICENSE
├── README-zh.md
├── README.md
├── android_release_aar.gradle
├── build.gradle
├── folivora/
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── cn/
│           │       └── cricin/
│           │           └── folivora/
│           │               ├── DrawableParser.java
│           │               ├── Folivora.java
│           │               ├── FolivoraInflater.java
│           │               ├── FolivoraViewFactory.java
│           │               ├── OnViewCreatedListener.java
│           │               ├── ParseRequest.java
│           │               ├── RippleFallback.java
│           │               └── ShapeAttrs.java
│           └── res/
│               └── values/
│                   └── attrs.xml
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── lint/
│   ├── build.gradle
│   └── src/
│       └── main/
│           └── java/
│               └── cn/
│                   └── cricin/
│                       └── folivora/
│                           ├── dom/
│                           │   ├── AndroidFacetCompat.java
│                           │   ├── DrawableIdConverter.java
│                           │   ├── FolivoraAttrProcessing.java
│                           │   └── FolivoraDomExtender.java
│                           ├── lint/
│                           │   ├── FolivoraIssueRegistry.java
│                           │   ├── InstalledBeforeSuperDetector.java
│                           │   ├── InternalFolivoraApiDetector.java
│                           │   └── PreferStubViewDetector.java
│                           └── preview/
│                               ├── FolivoraPreview.java
│                               └── ViewFactory.java
├── sample/
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── cn/
│           │       └── cricin/
│           │           └── folivora/
│           │               └── sample/
│           │                   ├── MainActivity.java
│           │                   └── drawable/
│           │                       ├── AlphaBackgroundDrawable.java
│           │                       ├── UmbrellaDrawable.java
│           │                       └── WindmillDrawable.java
│           └── res/
│               ├── layout/
│               │   └── activity_main.xml
│               └── values/
│                   ├── attrs.xml
│                   ├── colors.xml
│                   ├── strings.xml
│                   └── styles.xml
└── settings.gradle

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches

# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# Google Services (e.g. APIs or Firebase)
google-services.json

# Freeline
freeline.py
freeline/
freeline_project_description.json

# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md

preview_support/libs/*.jar
.idea/

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README-zh.md
================================================
### 为什么需要Folivora
对于android开发者来说,在layout文件中引用drawable来设置`View`的背景或者`ImageView`的`src`是很常见的事情,需要我们在drawable文件夹下写好xml文件就可以应用了,但是有许多drawable文件可能只被使用了一次,也有可能我们只是为了实现一个简单的圆角背景的功能。越来越多的drawable文件导致开发和维护成本的增加,有没有什么方法可以直接在layout文件中去创建drawable呢,Folivora为你提供了这样的功能。

### Folivora能做什么
Folivora可以为你的View设置一个背景或者ImageView的src,当前支持的drawable类型有

* shape (GradientDrawable)
* selector (StateListDrawable)
* ripple (RippleDrawable)
* layerlist (LayerListDrawable)
* levellist (LevelListDrawable)
* inset (InsetDrawable)
* clip (ClipDrawable)
* scale (ScaleDrawable)
* animation (AnimationDrawable)
* 自定义的Drawable **(新增)**

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview.gif" width="50%" height="50%"></img>

### 使用方法
 - **STEP1** :
添加Gradle依赖,在项目的build.gradle中加入
```groovy
  dependencies {
    implementation 'cn.cricin:folivora:0.1.0'
  }
```

 - **STEP2** :
在layout.xml中加入自定义的属性, 告诉Folivora如何创建drawable,Folivora提供的内置drawable属性前缀如下

* shape       -> shape
* selectror   -> selector
* layer-list  -> layer
* level-list  -> level
* clip        -> clip
* scale       -> scale
* inset       -> inset
* ripple      -> ripple
* animation   -> anim

例如所有的shape属性设置的前缀都是shape, 如`shapeSolidColor`, `shapeCornerRadius`等, 在设置了`drawableType`
之后,敲出指定的前缀,IDE会自动的给出所有该drawableType可用的属性

> shape

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_shape.png"></img>

我们来试着在xml中书写Folivora为我们提供的属性来实现上图中第一个的圆角shape效果

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:text="shape1"
  android:gravity="center"
  android:textColor="@android:color/white"
  app:drawableType="shape"
  app:shapeCornerRadius="6dp"
  app:shapeSolidColor="@color/blue_light"/>
```

我们在看一下其他几种drawable的用法:

> layerlist

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_layerlist.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:text="layerlist"
  android:gravity="center"
  android:textColor="@android:color/white"
  app:drawableType="layer_list"
  app:layerItem0Drawable="@color/blue_light"
  app:layerItem1Drawable="@color/blue_dark"
  app:layerItem1Insets="4dp"
  app:layerItem2Drawable="@color/blue_bright"
  app:layerItem2Insets="8dp"/>
```

> levellist

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_levellist.png"></img>

```xml
<!-- this level-list level is 95, levelItem1 matches -->
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="levellist"
  android:textColor="@android:color/white"
  app:drawableType="level_list"
  app:levelCurrentLevel="95"
  app:levelItem0Drawable="@color/green_dark"
  app:levelItem1Drawable="@color/blue_light"
  app:levelItem1MaxLevel="100"
  app:levelItem1MinLevel="90"/>
```

> selector

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_selector.gif"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="selector"
  app:drawableType="selector"
  app:selectorStateNormal="@color/blue_light"
  app:selectorStatePressed="@color/blue_dark"/>
```

在0.0.7版本中,Folivora加入了对创建复杂state的selector支持,使用app:selectorItemXStates指定需要的state flags,使用app:selectorItemXDrawable指定对应states的drawable(X可以是0,1,2,3,4),现在可以用新的方式实现上面的drawable。

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="selector"
  app:drawableType="selector"
  app:selectorItem0States="pressed"
  app:selectorItem0Drawable="@color/blue_dark"
  app:selectorStateNormal="@color/blue_light"/>
```

注:两种selector写法最好不要混用,推荐使用新的selector写法,这种方式的selector顺序是严格按照item定义的顺序添加进selector的,唯一的限制是只能定义5个states和drawables,不过对于一般的selector应该够用了

> ripple

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_ripple.gif"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="ripple"
  app:drawableType="ripple"
  app:rippleColor="@android:color/white"
  app:rippleContent="@color/blue_light"/>
```

使用ripple的确是酷炫多了,但是ripple效果是5.0之后引入的,那5.0之前的设备怎么办呢,Folivora为你提供了`RippleFallback`接口,用来创建一个替换`RippleDrawable`的`Drawable`实例,让我们试着用一个selector来代替ripple:
```java
Folivora.setRippleFallback(new Folivora.RippleFallback()){
  @Override
  public Drawable onFallback(ColorStateList ripple, Drawable content, Drawable mask, Context ctx){
    StateListDrawable sld = new StateListDrawable();
    sld.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(ripple.getDefaultColor()));
    sld.addState(new int[0], content);
    return sld;
  }
}
```

> clip

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_clip.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="clip"
  android:textColor="@android:color/white"
  app:clipDrawable="@color/blue_light"
  app:clipLevel="6000"
  app:drawableType="clip"/>
```

> inset

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_inset.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="inset"
  android:textColor="@android:color/white"
  app:drawableType="inset"
  app:insetAll="4dp"
  app:insetDrawable="@color/blue_light"/>
```

> scale

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_scale.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="scale"
  android:textColor="@android:color/white"
  app:drawableType="scale"
  app:scaleDrawable="@color/blue_light"
  app:scaleGravity="center"
  app:scaleHeight="0.3"
  app:scaleWidth="0.3"/>
```

> animation

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_animation.gif"></img>

```xml
<TextView
  android:id="@+id/animation"
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="animation"
  android:textColor="@android:color/white"
  app:animAutoPlay="true"
  app:animDuration="300"
  app:animFrame0="@drawable/animation0"
  app:animFrame1="@drawable/animation1"
  app:animFrame2="@drawable/animation2"
  app:animFrame3="@drawable/animation3"
  app:animFrame4="@drawable/animation4"
  app:animFrame5="@drawable/animation5"
  app:animFrame6="@drawable/animation6"
  app:animFrame7="@drawable/animation7"
  app:animFrame8="@drawable/animation8"
  app:animFrame9="@drawable/animation9"
  app:drawableType="animation"/>
```

注: 如果你在layout文件中用Folivora为系统控件添加drawable,如`View`和`TextView`等,许多 IDE (Android Studio, IntelliJ) 会把这些Folivora提供的属性标注为错误,但是实际上是正确的。可以在这个View或者根ViewGroup上加上`tools:ignore="MissingPrefix"`来避免报错。为了使用 `ignore`属性,可以加上`xmlns:tools=" http://schemas.android.com/tools"`。关于这个问题,可以查看: https://code.google.com/p/android/issues/detail?id=65176.

 - **STEP3** :
在Activity中启用Folivora, 有两种方法:
1.
```java
public class MainActivity extends Activity {
  @Override
  protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(Folivora.wrap(newBase));
  }
}
```
2.
```java
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Folivora.installViewFactory(this);
    setContentView(R.layout.your_layout_xml_name);
  }
}

```

### 使用嵌套的shape

Folivora现在支持在drawable中嵌套shape了,除了animation以外,所有的drawable的子drawable除了可以使用`@drawable/xxx`和颜色之外,新增了shape/shape1/shape2/shape3/shape4这5个值,参考定义shape的例子,替换相应的前缀即可, 我们来定义嵌套了shape的selector试一试

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="selector"
  android:textColor="@android:color/white"
  app:drawableType="selector"
  app:selectorStateNormal="shape"
  app:shapeSolidColor="@color/blue_light"
  app:shapeCornerRadius="10dp"
  app:selectorStatePressed="shape1"
  app:shape1SolidColor="@color/blue_dark"
  app:shape1CornerRadius="10dp"/>
```

效果是这样的

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_shape_nested.gif"></img>

### 使用自定义Drawable

从0.0.4版本开始,Folivora除了支持自带的drawable以外,还支持使用自定的drawable类型了,让你使用自定义drawable就和使用自定义view一样轻松。这里我们以自定义一个绘制纸风车的`WindmillDrawable`为例,来让Folivora为我们提供支持:

1. 首先我们和自定义`View`一样,为`WindmillDrawable`提供自定义的属性:
```xml
<!-- 和自定义view相同,这里declare-styleable的name最好和自定义drawable的名字一样 -->
<declare-styleable name="WindmillDrawable">
    <attr name="wdSize" format="dimension"/> <!-- 纸风车的默认大小 -->
    <attr name="wdColor0" format="color"/> <!-- 纸风车第一个叶子的颜色 -->
    <attr name="wdColor1" format="color"/> <!-- 纸风车第二个叶子的颜色 -->
    <attr name="wdColor2" format="color"/> <!-- 纸风车第三个叶子的颜色 -->
    <attr name="wdColor3" format="color"/> <!-- 纸风车第四个叶子的颜色 -->
    <attr name="wdCenterDotRadius" format="dimension"/> <!-- 中心圆的半径 -->
    <attr name="wdCenterDotColor" format="color"/> <!-- 中心圆的填充色 -->
    <attr name="wdRotateDegrees" format="integer"/> <!-- 纸风车旋转角度 -->
  </declare-styleable>
```
可以看到,自定义属性这部分和普通的`View`自定义属性是一样的。name和自定义drawable的类名相同就行了,Folivora就可以在layout文件中为这些drawable的自定义属性提供属性的自动提示了

2. 创建自定义的`WindmillDrawable`,继承自`Drawable`, 提供一个`public WindmillDrawable(Context ctx, AttributeSet attrs)`的构造方法,在这个构造方法里就可以获取自定义的属性, 代码如下:
```java
public WindmillDrawable(Context ctx, AttributeSet attrs) {
  TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
  int count = a.getIndexCount();
  for (int i = 0; i < count; i++) {
    int index = a.getIndex(i);
    switch (index) {
      case R.styleable.WindmillDrawable_wdSize:
        mSize = a.getDimensionPixelSize(index, mSize);
        break;
      case R.styleable.WindmillDrawable_wdColor0:
        mColors[0] = a.getColor(index, mColors[0]);
        break;
      case R.styleable.WindmillDrawable_wdColor1:
        mColors[1] = a.getColor(index, mColors[1]);
        break;
      ...
      default://no-op unexpected attr index
        break;
    }
  }
  a.recycle();
}
```
这部分代码其实和自定义`View`的属性获取没有什么区别,主要就是给drawable添加一个构造方法,具体绘制代码就不贴了,如果想要查看具体细节,可以点击[这里](https://github.com/Cricin/Folivora/blob/master/sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java)查看源码

3. 在layout文件中使用自定义drawable,Folivora提供了`drawableName`属性,使用该属性指定需要使用的drawable:
```xml
<View
  andorid:layout_width="120dp"
  android:layout_height="120dp"
  app:drawableName="cn.cricin.folivora.sample.drawable.WindmillDrawable"
  app:wdColor0="@color/blue_light"
  app:wdColor1="@color/green_dark"
  app:wdColor2="@color/green_light"
  app:wdColor3="@color/purple"
  app:wdRotateDegrees="45"/>
```
运行之后的效果:

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_custom_drawable.png"></img>


到这里,Folivora就会为该`View`设置我们指定的drawable了,有人可能就会问了,drawable名字这么长,写起来会不会太复杂了,不用担心,当你敲出drawableName的时候,Folivora会为你自动提示可用的drawable名字的,并且该drawable的自定义属性也会有自动提示。

> 如果我的自定义drawable没有上面指定的构造方法,并且我没办法直接修改该drawable的源码来添加这个构造方法该怎么办呢?

Folivora考虑到了这一点,有些drawable的源码我们没法修改,但是它总会有向外提供设置属性的方法吧?所以,我们提供了一个`DrawableFactory`接口,假设`WindmillDrawable`只有一个无参的构造方法,但是提供了设置各种属性的方法,我们需要让Folivora支持`WindmillDrawable`,可以这样做:
```java
Folivora.addDrawableFactory(new Folivora.DrawableFactory() {
  @Override
  public Drawable newDrawable(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
    WindmillDrawable d = new WindmillDrawable();
    d.setColor0(a.getColor(R.styleable.WindmillDrawable_wdColor0, Color.BLACK));
    d.setRotateDegrees(a.getInt(R.styleable.WindmillDrawable_wdRotateDegrees, 0));
    ...
    a.recycle();
    return d;
  }

  @Override
  public Class<? extends Drawable> drawableClass() {
    return WindmillDrawable.class;
  }
});
```
> 自定义Drawable请注意,如果你的drawable需要获取其他drawable,建议使用`Folivora.getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex)`方法获取,这样可以支持获取内嵌的`shape`,当然如果你不需要支持内嵌的`shape`,可以不用这样做。

### 使用Drawable缓存

在之前的版本中,Folivora会根据view tag中的属性创建drawable,每次都会创建一个新的drawable实例,很浪费资源,现在Folivora支持了drawable的缓存功能(LruCache,大小为128), 使用缓存非常简单,只需要添加`app:drawableId`属性,为drawable指定一个id(string类型,不是android的id类型)即可。Folivora在为view设置drawable的时候,如果drawable在缓存中,会直接从缓存中取。这就带来了一个便利,如果在一个layout文件中,一个drawable被多次使用,只需要在第一次使用的地方编写drawable定义就行了,其他的地方可以直接使用drawableId引用该drawable。

```xml
<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

    <View
      android:layout_width="100dp"
      android:layout_height="40dp"
      app:drawableId="shape_rounded_6dp"
      app:drawableType="shape"
      app:shapeCornerRadius="6dp"
      app:shapeSolidColor="@color/blue_light"/>

    <View
      android:layout_width="100dp"
      android:layout_height="40dp"
      app:drawableId="shape_rounded_6dp"/>

</LinearLayout>
```

建议为需要复用的drawable和经常使用的layout文件中的drawable设置`drawableId`, 以提升性能。

### 下载示例APK
[点击下载](https://raw.githubusercontent.com/Cricin/Folivora/master/sample.apk)

### 编辑layout文件时的预览

> 预览效果

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/studio_preview.gif"></img>

依赖了Folivora之后,默认是可以直接预览的,如果没有效果,尝试build一下你的项目。

### Folivora支持的属性列表

##### 通用属性

属性 | 取值| 描述
 ---|--- | --- |
app:setAs|background(default) &#124; src &#124; foreground| 设置view背景或者ImageView的src或者view前景
app:drawableType|shape &#124; layer_list &#124; selector &#124; ripple &#124; clip &#124; scale &#124; animation &#124; level_list|drawable类型
app:drawableName|string|自定义drawable的class全名
app:drawableId|string|用于缓存的drawable唯一id

##### shape属性

属性 | 取值| 描述
 ---|--- | --- |
app:shapeType|rectangle(default)&#124;oval&#124;line&#124;ring|形状
app:shapeSolidSize|dimension|宽高
app:shapeSolidWidth|dimension|宽
app:shapeSolidHeight|dimension|高
app:shapeSolidColor|color|填充色
app:shapeSolidColor|color|边框填充色
app:shapeStokeWidth|dimension|边框厚度
app:shapeStokeDashWidth|dimension|边框线宽
app:shapeStokeDashGap|dimension|边框线间距
app:shapeCornerRadius|dimension|角半径
app:shapeCornerRadiusTopLeft|dimension|左上角半径
app:shapeCornerRadiusTopRight|dimension|右上角半径
app:shapeCornerRadiusBottomLeft|dimension|坐下角半径
app:shapeCornerRadiusBottomRight|dimension|右下角半径
app:shapeGradientType|linear &#124; radial &#124; sweep|渐变类型
app:shapeGradientAngle|tb &#124; tr_bl &#124; rl &#124; br_tl &#124; bt &#124; bl_tr &#124; lr &#124; tl_br|渐变角度
app:shapeGradientStartColor|color|渐变起始颜色
app:shapeGradientCenterColor|color|渐变中间颜色
app:shapeGradientEndColor|color|渐变结束颜色
app:shapeGradientRadius|dimension|渐变半径
app:shapeGradientCenterX|float|渐变中点x轴位置
app:shapeGradientCenterY|float|渐变中点y轴位置

##### selector属性

属性 | 取值| 描述
 ---|--- | --- |
app:selectorStateFirst|reference &#124; color|selector状态:第一个
app:selectorStateMiddle|reference &#124; color|selector状态:中间
app:selectorStateLast|reference &#124; color|selector状态:最后一个
app:selectorStateActive|reference &#124; color|selector状态:活动
app:selectorStateActivated|reference &#124; color|selector状态:激活的
app:selectorStateAccelerate|reference &#124; color|selector状态:加速的
app:selectorStateChecked|reference &#124; color|selector状态:勾选的
app:selectorStateCheckable|reference &#124; color|selector状态:可勾选的
app:selectorStateEnabled|reference &#124; color|selector状态:启用的
app:selectorStateFocused|reference &#124; color|selector状态:获得焦点
app:selectorStatePressed|reference &#124; color|selector状态:点击
app:selectorStateNormal|reference &#124; color|selector状态:正常状态

##### layerlist属性

属性 | 取值| 描述
 ---|--- | --- |
app:layerItem0Drawable| reference &#124; color| 最底层的drawable
app:layerItem0Insets|dimension|该drawable的margin
app:layerItem0Left|dimension| 该drawable的左margin
app:layerItem0Right|dimension|该drawable的右margin
app:layerItem0Top|dimension|该drawable的上margin
app:layerItem0Bottom|dimension|该drawable的下margin

...

layerlist支持最多5个drawable,替换相应的数字即可

##### ripple属性

属性 | 取值| 描述
 ---|--- | --- |
app:rippleColor|color|ripple点击时的涟漪色
app:rippleMask|reference &#124; color|ripple涟漪色的遮罩
app:rippleContent|reference &#124; color|ripple的内容背景

如果设备不支持Ripple效果(<Api21),可以给Folivora设置一个`RippleFallback`, 用来创建替代RippleDrawable的Drawable

##### levellist属性

属性 | 取值| 描述
 ---|--- | --- |
app:levelCurrentLevel|integer|当前的level
app:levelItem0Drawable|reference &#124; color|第一个item的drawable
app:levelItem1MinLevel|integer|该drawable的最小level
app:levelItem1MaxLevel|integer|该drawable的最大level

...

levellist支持最多5个drawable,替换相应的数字即可

##### clip属性

属性 | 取值| 描述
 ---|--- | --- |
app:clipDrawable|reference &#124; color|需要裁剪的drawable
app:clipGravity|同View的layout_gravity|裁剪位置
app:clipOrientation|vertical &#124; horizontal|裁剪的方向
app:clipLevel|integer|当前level

##### scale属性

属性 | 取值| 描述
 ---|--- | --- |
app:scaleDrawable|reference &#124; color|需要缩放的drawable
app:scaleGravity|同View的layout_gravity|缩放位置
app:scaleWidth|float[0,1] or -1()|宽度缩放比例
app:scaleHeight|float[0,1] or -1()|高度缩放比例
app:scaleLevel|integer[0,10000]|当前的level

##### inset属性

属性 | 取值| 描述
 ---|--- | --- |
app:insetDrawable|reference &#124; color|需要插入边距的drawable
app:insetAll|dimension|所有方向的边距
app:insetLeft|dimension|左边距
app:insetTop|dimension|上边距
app:insetRight|dimension|右边距
app:insetBottom|dimension|下边距

##### animation属性

属性 | 取值| 描述
 ---|--- | --- |
app:animAutoPlay|boolean|是否自动开始动画
app:animDuration|int(millisecond)|每一帧的持续时间
app:animOneShot|boolean|是否只播放一次
app:animFrame0|reference &#124; color|第0帧
app:animDuration0|int(millisecond)|第0帧持续时间

animation支持最多10帧,替换相应的数字即可


## License

Copyright 2019 Cricin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: README.md
================================================
English | [中文](https://github.com/Cricin/Folivora/blob/master/README-zh.md)

### Why Folivora
For most android develpers, it is usual to set `View`s background or `ImageView`s `src` by reference a drawable, which required to define a drawable.xml under drawable folder, but some drawable files may be only referenced once, or only to used as a round corner backgrond. more and more drawables may lead to develop and maintain hardly, is there a way to create and use drawables in layout.xml? yeah, Folivora can do this work for you.

### What does Folivora can do?
Folivora sets a View's background, foreground or ImageView's src in your layout.xml files, currently supported drawables are:

* shape (GradientDrawable)
* selector (StateListDrawable)
* ripple (RippleDrawable)
* layerlist (LayerListDrawable)
* levellist (LevelListDrawable)
* inset (InsetDrawable)
* clip (ClipDrawable)
* scale (ScaleDrawable)
* animation (AnimationDrawable)
* custom drawable **(newly supported)**

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview.gif" width="50%" height="50%"></img>

### Usage
 - **STEP1** :
gradle dependency, add below in your project's build.gradle
```groovy
  dependencies {
    implementation 'cn.cricin:folivora:0.1.0'
  }
```

 - **STEP2** :
write down the attribute provided by folivora, tell folivora how to create drawable, prefix of drawables folivora builtin supported are:

* shape       -> shape
* selectror   -> selector
* layer-list  -> layer
* level-list  -> level
* clip        -> clip
* scale       -> scale
* inset       -> inset
* ripple      -> ripple
* animation   -> anim

for example, all attributes prefix of a GradientDrawable is shape, like `shapeSolidColor`, `shapeCornerRadius`, IDE will gives you all available attributes after you write down `drawableType` and typed the drawable prefix.

> shape

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_shape.png"></img>

let's try to write down some code to introduce how folivora works with the first view above

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:text="shape1"
  android:gravity="center"
  android:textColor="@android:color/white"
  app:drawableType="shape"
  app:shapeCornerRadius="6dp"
  app:shapeSolidColor="@color/blue_light"/>
```

here are some other supported drawable usages:

> layerlist

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_layerlist.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:text="layerlist"
  android:gravity="center"
  android:textColor="@android:color/white"
  app:drawableType="layer_list"
  app:layerItem0Drawable="@color/blue_light"
  app:layerItem1Drawable="@color/blue_dark"
  app:layerItem1Insets="4dp"
  app:layerItem2Drawable="@color/blue_bright"
  app:layerItem2Insets="8dp"/>
```

> levellist

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_levellist.png"></img>

```xml
<!-- this level-list level is 95, levelItem1 matches -->
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="levellist"
  android:textColor="@android:color/white"
  app:drawableType="level_list"
  app:levelCurrentLevel="95"
  app:levelItem0Drawable="@color/green_dark"
  app:levelItem1Drawable="@color/blue_light"
  app:levelItem1MaxLevel="100"
  app:levelItem1MinLevel="90"/>
```

> selector

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_selector.gif"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="selector"
  app:drawableType="selector"
  app:selectorStateNormal="@color/blue_light"
  app:selectorStatePressed="@color/blue_dark"/>
```

since 0.0.7,Folivora added support about complicated state selector,use `app:selectorItemXStates` to set state flags,and use `app:selectorItemXDrawable` set corresponding drawable to the states(X can be 0,1,2,3,4),now we can use the new way to describe drawable above。

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="selector"
  app:drawableType="selector"
  app:selectorItem0States="pressed"
  app:selectorItem0Drawable="@color/blue_dark"
  app:selectorStateNormal="@color/blue_light"/>
```

Note:it is recommended to not mixed two selector definitions,just use the new way is better,which is ordered when add in selector by item index, constraint is only support 5 items for now, which is enough for usual selectors.

> ripple

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_ripple.gif"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:textColor="@android:color/white"
  android:gravity="center"
  android:text="ripple"
  app:drawableType="ripple"
  app:rippleColor="@android:color/white"
  app:rippleContent="@color/blue_light"/>
```

much cooler after used ripple drawable, but ripple effect is introduced in lollipop, if the device platform version is lower than lolipop, folivora provided a `RippleFallback` for you, you can provide a substitude drawable if ripple is unavailable, let's try a create a `selector` instead of `ripple`:
```java
Folivora.setRippleFallback(new RippleFallback()){
  @Override
  public Drawable onFallback(ColorStateList ripple, Drawable content, Drawable mask, Context ctx){
    StateListDrawable sld = new StateListDrawable();
    sld.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(ripple.getDefaultColor()));
    sld.addState(new int[0], content);
    return sld;
  }
}
```

> clip

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_clip.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="clip"
  android:textColor="@android:color/white"
  app:clipDrawable="@color/blue_light"
  app:clipLevel="6000"
  app:drawableType="clip"/>
```

> inset

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_inset.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="inset"
  android:textColor="@android:color/white"
  app:drawableType="inset"
  app:insetAll="4dp"
  app:insetDrawable="@color/blue_light"/>
```

> scale

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_scale.png"></img>

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="scale"
  android:textColor="@android:color/white"
  app:drawableType="scale"
  app:scaleDrawable="@color/blue_light"
  app:scaleGravity="center"
  app:scaleHeight="0.3"
  app:scaleWidth="0.3"/>
```

> animation

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_animation.gif"></img>

```xml
<TextView
  android:id="@+id/animation"
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="animation"
  android:textColor="@android:color/white"
  app:animAutoPlay="true"
  app:animDuration="300"
  app:animFrame0="@drawable/animation0"
  app:animFrame1="@drawable/animation1"
  app:animFrame2="@drawable/animation2"
  app:animFrame3="@drawable/animation3"
  app:animFrame4="@drawable/animation4"
  app:animFrame5="@drawable/animation5"
  app:animFrame6="@drawable/animation6"
  app:animFrame7="@drawable/animation7"
  app:animFrame8="@drawable/animation8"
  app:animFrame9="@drawable/animation9"
  app:drawableType="animation"/>
```

_Note: Popular IDE's (Android Studio, IntelliJ) will likely mark this as an error despite being correct. You may want to add `tools:ignore="MissingPrefix"` to either the View itself or its parent ViewGroup to avoid this. You'll need to add the tools namespace to have access to this "ignore" attribute. `xmlns:tools="
http://schemas.android.com/tools"`. See https://code.google.com/p/android/issues/detail?id=65176._

 - **STEP3** :
enable folivora in your app, there are two ways:

```java
public class MainActivity extends Activity {
  @Override
  protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(Folivora.wrap(newBase));
  }
}
```
or
```java
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Folivra.installViewFactory(this);
    setContentView(R.layout.your_layout_xml_name);
  }
}

```

#### Use nested shape

Folivora now support nest shape in drawable, except `animation`, all drawable's child drawable can use `@drawable/xxx`, a color, or one of shape/shape1/shape2/shape3/shape4, you can use this prefix combine with the shape attrs, let's define two round corner shape nested in selector:

```xml
<TextView
  android:layout_width="100dp"
  android:layout_height="40dp"
  android:gravity="center"
  android:text="selector"
  android:textColor="@android:color/white"
  app:drawableType="selector"
  app:selectorStateNormal="shape"
  app:shapeSolidColor="@color/blue_light"
  app:shapeCornerRadius="10dp"
  app:selectorStatePressed="shape1"
  app:shape1SolidColor="@color/blue_dark"
  app:shape1CornerRadius="10dp"/>
```

effect is:

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_shape_nested.gif"></img>

### Use custom drawable

since 0.0.4,Folivora support use custom drawable, makes it easyly to use custom drawables just like custom views,for example, let's write a `WindmillDrawable` which draws a paper windmill:

1. first, write down some attrs we needed for `WindmillDrawable`, just like the way of custom view:
```xml
<declare-styleable name="WindmillDrawable">
    <attr name="wdSize" format="dimension"/> <!-- default size -->
    <attr name="wdColor0" format="color"/> <!-- first leaf color -->
    <attr name="wdColor1" format="color"/> <!-- second leaf color -->
    <attr name="wdColor2" format="color"/> <!-- third leaf color -->
    <attr name="wdColor3" format="color"/> <!-- forth leaf color -->
    <attr name="wdCenterDotRadius" format="dimension"/> <!-- center dot radius -->
    <attr name="wdCenterDotColor" format="color"/> <!-- center dot color -->
    <attr name="wdRotateDegrees" format="integer"/> <!-- rotation degrees -->
  </declare-styleable>
```
Note: declare-styleable name must equals with the drawable's simple class name, so folivora will support code completion about the custom attrs.

2. Create a `WindmillDrawable`,extends `Drawable`, provide a `public WindmillDrawable(Context ctx, AttributeSet attrs)` constructor,you can retrieve custom attrs here, like this:
```java
public WindmillDrawable(Context ctx, AttributeSet attrs) {
  TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
  int count = a.getIndexCount();
  for (int i = 0; i < count; i++) {
    int index = a.getIndex(i);
    switch (index) {
      case R.styleable.WindmillDrawable_wdSize:
        mSize = a.getDimensionPixelSize(index, mSize);
        break;
      case R.styleable.WindmillDrawable_wdColor0:
        mColors[0] = a.getColor(index, mColors[0]);
        break;
      case R.styleable.WindmillDrawable_wdColor1:
        mColors[1] = a.getColor(index, mColors[1]);
        break;
      ...
      default://no-op unexpected attr index
        break;
    }
  }
  a.recycle();
}
```
this is samilar to costom `View`,the main purpose is to add a constructor that takes a `Context` and `AttributeSet` as parameter, other code is emitted here, for more details,[click](https://github.com/Cricin/Folivora/blob/master/sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java) to view source code

3. use `WindmillDrawable` in your layout files,Folivora provided a `drawableName` attr,you can declare the drawable name here:
```xml
<View
  andorid:layout_width="120dp"
  android:layout_height="120dp"
  app:drawableName="cn.cricin.folivora.sample.drawable.WindmillDrawable"
  app:wdColor0="@color/blue_light"
  app:wdColor1="@color/green_dark"
  app:wdColor2="@color/green_light"
  app:wdColor3="@color/purple"
  app:wdRotateDegrees="45"/>
```
at runtime, the drawable is created by folivora and get worked:

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/preview_custom_drawable.png"></img>

you may ask, the drawable's name is to long to remember, it's difficult to write down,don't worry at it,folivora will gives the candidate of custom drawables if you typed down drawableName attr, attrs about the specific drawable is also will have code completion support.

> Support of custom drawables do not have the constructor which recieves `Context` and `AttributeSet` as parameter

Folivora take concerned it, source code of some drawables is not permited to modify, so,we provided a `DrawableFactory` interface,assume `WindmillDrawable` only have a constructor takes no parameter,but provided some methods to modify it, to support `WindmillDrawable`,we can do this:
```java
Folivora.addDrawableFactory(new Folivora.DrawableFactory() {
  @Override
  public Drawable newDrawable(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WindmillDrawable);
    WindmillDrawable d = new WindmillDrawable();
    d.setColor0(a.getColor(R.styleable.WindmillDrawable_wdColor0, Color.BLACK));
    d.setRotateDegrees(a.getInt(R.styleable.WindmillDrawable_wdRotateDegrees, 0));
    ...
    a.recycle();
    return d;
  }

  @Override
  public Class<? extends Drawable> drawableClass() {
    return WindmillDrawable.class;
  }
});
```
> If you are using custom drawable,and your drawable contains other drawables, it is recommended to use `Folivora.getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex)` to get a drawable, this method will take care about nested shape creation, also you can do not follow this tip if you do not need nested shape support。

### Drawable caches

In previous releases,Folivora will create drawables according to attrs from view tag, a new instance is created for per view, which is waste resources, now Folivora supported drawable caching(LruCache,max = 128), usage is very simple,just add `app:drawableId` attr,set a id(string type,not android's id type) to drawable is ok。Folivora will lookup cache to find a cached drawable, which means,if in a layout.xml,a drawable should be referenced multi places, define it at first occurrence, then at other place, use the same `drawableId` to reference this drawable.

```xml
<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

    <TextView
      android:layout_width="100dp"
      android:layout_height="40dp"
      android:text="shape1"
      android:gravity="center"
      android:textColor="@android:color/white"
      app:drawableId="shape_rounded_6dp"
      app:drawableType="shape"
      app:shapeCornerRadius="6dp"
      app:shapeSolidColor="@color/blue_light"/>

    <TextView
      android:layout_width="100dp"
      android:layout_height="40dp"
      android:text="shape2"
      android:gravity="center"
      android:textColor="@android:color/white"
      app:drawableId="shape_rounded_6dp"/>

</LinearLayout>
```

It is recommended to set `drawableId` to drawable which is reusable or inside a frequently used layout files, which makes a better performance.

### Download Sample APK
[Click to download](https://raw.githubusercontent.com/Cricin/Folivora/master/sample.apk)


### Design time preview

> preview result

<img src="https://raw.githubusercontent.com/Cricin/Folivora/master/pics/studio_preview.gif"></img>

after you added folivora in gradle and sync project,preview would been enabled by default, if unavailable, try to build your project.

### Attrs Reference

##### Common Attrs

attr | value| desc
 ---|--- | --- |
app:setAs|background(default) &#124; src &#124; foreground| set drawable as backgrond or src or foreground
app:drawableType|shape &#124; layer_list &#124; selector &#124; ripple &#124; clip &#124; scale &#124; animation &#124; level_list|drawable type
app:drawableName|string|fq class name of custom drawable
app:drawableId|string|drawable unique id for cache use

##### Shape Attrs

attr | value | desc
 ---|--- | --- |
app:shapeType|rectangle(default)&#124;oval&#124;line&#124;ring
app:shapeSolidSize|dimension
app:shapeSolidWidth|dimension
app:shapeSolidHeight|dimension
app:shapeSolidColor|color
app:shapeStokeWidth|dimension
app:shapeStokeDashWidth|dimension
app:shapeStokeDashGap|dimension
app:shapeCornerRadius|dimension
app:shapeCornerRadiusTopLeft|dimension
app:shapeCornerRadiusTopRight|dimension
app:shapeCornerRadiusBottomLeft|dimension
app:shapeCornerRadiusBottomRight|dimension
app:shapeGradientType|linear &#124; radial &#124; sweep
app:shapeGradientAngle|tb &#124; tr_bl &#124; rl &#124; br_tl &#124; bt &#124; bl_tr &#124; lr &#124; tl_br|
app:shapeGradientStartColor|color
app:shapeGradientCenterColor|color
app:shapeGradientEndColor|color
app:shapeGradientRadius|dimension
app:shapeGradientCenterX|float(default 0.5)
app:shapeGradientCenterY|float(default 0.5)

##### Selector Attrs

attr | value| desc
 ---|--- | --- |
app:selectorStateFirst|reference &#124; color|
app:selectorStateMiddle|reference &#124; color|
app:selectorStateLast|reference &#124; color|
app:selectorStateActive|reference &#124; color|
app:selectorStateActivated|reference &#124; color|
app:selectorStateAccelerate|reference &#124; color|
app:selectorStateChecked|reference &#124; color|
app:selectorStateCheckable|reference &#124; color|
app:selectorStateEnabled|reference &#124; color|
app:selectorStateFocused|reference &#124; color|
app:selectorStatePressed|reference &#124; color|
app:selectorStateNormal|reference &#124; color|

##### LayerList Attrs

attr | value| desc
 ---|--- | --- |
app:layerItem0Drawable| reference &#124; color| drawable innermost
app:layerItem0Insets|dimension|margin for drawable
app:layerItem0Left|dimension| left margin
app:layerItem0Right|dimension|right margin
app:layerItem0Top|dimension|top margin
app:layerItem0Bottom|dimension|bottom margin

...

layerlist supports at most 5 children drawables, just substitute the digit

##### Ripple Attrs

attr | value| desc
 ---|--- | --- |
app:rippleColor|color|ripple color when touched
app:rippleMask|reference &#124; color|mask for ripple
app:rippleContent|reference &#124; color|content for ripple

##### LevelList Attrs

attr | value| desc
 ---|--- | --- |
app:levelCurrentLevel|integer|current level
app:levelItem0Drawable|reference &#124; color|drawable for item0
app:levelItem1MinLevel|integer|min level for item0
app:levelItem1MaxLevel|integer|max level for item0

...

levellist supports at most 5 children drawables, just substitute the digit

##### Clip Attrs

attr | value| desc
 ---|--- | --- |
app:clipDrawable|reference &#124; color|drawable to be clipped
app:clipGravity|same as View's layout_gravity|gravity to clip
app:clipOrientation|vertical &#124; horizontal|clip orientation
app:clipLevel|integer|current level(used to clip the drawable)

##### Scale Attrs

attr | value| desc
 ---|--- | --- |
app:scaleDrawable|reference &#124; color|drawable to be scaled
app:scaleGravity|same as View's layout_gravity|gravity to scale
app:scaleWidth|float[0,1] or -1()|scale ratio for width
app:scaleHeight|float[0,1] or -1()|scale ratio for height
app:scaleLevel|integer[0,10000]|current level(used to scale the drawable)

##### Inset Attrs

attr | value| desc
 ---|--- | --- |
app:insetDrawable|reference &#124; color|drawable to be inseted
app:insetAll|dimension|all inset
app:insetLeft|dimension|inset of left
app:insetTop|dimension|inset of top
app:insetRight|dimension|inset of right
app:insetBottom|dimension|inset of bottom

##### Animation Attrs

attr | value| desc
 ---|--- | --- |
app:animAutoPlay|boolean|play animation automaticly
app:animDuration|int(millisecond)|displayed duration per frame
app:animOneShot|boolean|play just once
app:animFrame0|reference &#124; color|first frame's drawable
app:animDuration0|int(millisecond)|first frame displayed duration

animation supports at most 10 frames, just substitute the digit


## License

Copyright 2019 Cricin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: android_release_aar.gradle
================================================
// ./gradlew clean build generateRelease
apply plugin: 'maven'

def groupId = project.PUBLISH_GROUP_ID
def artifactId = project.PUBLISH_ARTIFACT_ID
def version = project.PUBLISH_VERSION

def localReleaseDest = "${buildDir}/release/${version}"

task androidJavadocs(type: Javadoc) {
  failOnError = false
  source = android.sourceSets.main.java.srcDirs
  ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
  classpath += files(ext.androidJar)
}

task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
  classifier = 'javadoc'
  from androidJavadocs.destinationDir
}

task androidSourcesJar(type: Jar) {
  classifier = 'sources'
  from android.sourceSets.main.java.srcDirs
}

uploadArchives {
  repositories.mavenDeployer {
    pom.groupId = groupId
    pom.artifactId = artifactId
    pom.version = version
    // Add other pom properties here if you want (developer details / licenses)
    repository(url: "file://${localReleaseDest}")
  }
}

task zipRelease(type: Zip) {
  from localReleaseDest
  destinationDir buildDir
  archiveName "release-${version}.zip"
}

task generateRelease {
  doLast {
    println "Release ${version} can be found at ${localReleaseDest}/"
    println "Release ${version} zipped can be found ${buildDir}/release-${version}.zip"
  }
}

generateRelease.dependsOn(uploadArchives)
generateRelease.dependsOn(zipRelease)


artifacts {
  archives androidSourcesJar
  archives androidJavadocsJar
}

================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
  repositories {
    google()
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.6.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

allprojects {
  repositories {
    google()
    jcenter()
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
}


================================================
FILE: folivora/build.gradle
================================================
apply plugin: 'com.android.library'

def verName = '0.1.0'

android {
  compileSdkVersion 29
  defaultConfig {
    minSdkVersion 16
    targetSdkVersion 29
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
  lintChecks project(':lint')
  lintPublish project(':lint')
}

ext {
  PUBLISH_GROUP_ID = 'cn.cricin'
  PUBLISH_ARTIFACT_ID = 'folivora'
  PUBLISH_VERSION = verName
}
apply from: rootProject.file('android_release_aar.gradle')

================================================
FILE: folivora/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest package="cn.cricin.folivora"/>

================================================
FILE: folivora/src/main/java/cn/cricin/folivora/DrawableParser.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ScaleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.StateSet;
import android.view.Gravity;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static cn.cricin.folivora.Folivora.TAG;
import static cn.cricin.folivora.Folivora.getDrawable;

/**
 * A DrawableParser take responsibility of drawable parsing, Folivora
 * will find best match DrawableParser to parse a drawable instance
 * for view. each subclass handles one or more drawable parsing when
 * a view want a drawable to decorate self.
 */
public interface DrawableParser {

  /**
   * Entry point for subclass to accomplish drawable parsing task
   * @param request current parsing request
   * @return a parsed drawable instance, or null
   */
  Drawable parse(ParseRequest request);

  /**
   * Create a new GradientDrawable(shape).
   * attrs:
   * <p>
   * app:shapeType                    enum
   * app:shapeSolidSize               dimension
   * app:shapeSolidWidth              dimension
   * app:shapeSolidHeight             dimension
   * app:shapeSolidColor              color
   * <p>
   * app:shapeStrokeWidth             dimension
   * app:shapeStrokeColor             color
   * app:shapeStrokeDashGap           dimension
   * app:shapeStrokeDashWidth         dimension
   * <p>
   * app:shapeGradientType            enum
   * app:shapeGradientRadius          dimension
   * app:shapeGradientCenterX         dimension
   * app:shapeGradientCenterY         dimension
   * app:shapeGradientStartColor      color
   * app:shapeGradientCenterColor     color
   * app:shapeGradientEndColor        color
   * app:shapeGradientAngle           enum
   * <p>
   * app:shapeCornerRadius            dimension
   * app:shapeCornerRadiusTopLeft     dimension
   * app:shapeCornerRadiusTopRight    dimension
   * app:shapeCornerRadiusBottomLeft  dimension
   * app:shapeCornerRadiusBottomRight dimension
   */
  class GradientDrawableParser implements DrawableParser {

    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      final ShapeAttrs shapeAttrs = request.shapeAttrs();

      GradientDrawable gd = new GradientDrawable();
      TypedArray a = ctx.obtainStyledAttributes(attrs, shapeAttrs.mAttrStyleable);
      gd.setShape(a.getInt(shapeAttrs.mShapeType, GradientDrawable.RECTANGLE));

      final int size = a.getDimensionPixelSize(shapeAttrs.mShapeSolidSize, -1);
      gd.setSize(a.getDimensionPixelSize(shapeAttrs.mShapeSolidWidth, size),
        a.getDimensionPixelSize(shapeAttrs.mShapeSolidHeight, size));

      gd.setGradientType(a.getInt(shapeAttrs.mShapeGradientType, GradientDrawable.LINEAR_GRADIENT));
      gd.setGradientRadius(a.getDimension(shapeAttrs.mShapeGradientRadius, 0));
      gd.setGradientCenter(a.getFloat(shapeAttrs.mShapeGradientCenterX, 0.5F),
        a.getFloat(shapeAttrs.mShapeGradientCenterY, 0.5F));
      int[] gradientColors;
      final int gradientStartColor = a.getColor(shapeAttrs.mShapeGradientStartColor, 0);
      final int gradientEndColor = a.getColor(shapeAttrs.mShapeGradientEndColor, 0);
      final int gradientCenterColor = a.getColor(shapeAttrs.mShapeGradientCenterColor, 0);
      if (a.hasValue(shapeAttrs.mShapeGradientCenterColor)) {
        gradientColors = new int[]{gradientStartColor, gradientCenterColor, gradientEndColor};
      } else {
        gradientColors = new int[]{gradientStartColor, gradientEndColor};
      }
      gd.setColors(gradientColors);
      final int orientationIndex = a.getInt(shapeAttrs.mShapeGradientAngle, 0);
      gd.setOrientation(GradientDrawable.Orientation.values()[orientationIndex]);

      if (a.hasValue(shapeAttrs.mShapeSolidColor)) {
        gd.setColor(a.getColor(shapeAttrs.mShapeSolidColor, Color.WHITE));
      }

      gd.setStroke(
        a.getDimensionPixelSize(shapeAttrs.mShapeStrokeWidth, -1),
        a.getColor(shapeAttrs.mShapeStrokeColor, Color.WHITE),
        a.getDimensionPixelSize(shapeAttrs.mShapeStrokeDashGap, 0),
        a.getDimensionPixelSize(shapeAttrs.mShapeStrokeDashWidth, 0)
      );
      final float radius = a.getDimension(shapeAttrs.mShapeCornerRadius, 0);
      gd.setCornerRadii(new float[]{
        a.getDimension(shapeAttrs.mShapeCornerRadiusTopLeft, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusTopLeft, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusTopRight, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusTopRight, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusBottomRight, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusBottomRight, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusBottomLeft, radius),
        a.getDimension(shapeAttrs.mShapeCornerRadiusBottomLeft, radius),
      });
      a.recycle();
      return gd;
    }
  }

  /**
   * Create a new StateListDrawable, only support single state match.
   * attrs:
   * <p>
   * app:selectorStateFirst          drawable
   * app:selectorStateMiddle         drawable
   * app:selectorStateLast           drawable
   * app:selectorStateActive         drawable
   * app:selectorStateActivate       drawable
   * app:selectorStateAccelerate     drawable
   * app:selectorStateChecked        drawable
   * app:selectorStateCheckable      drawable
   * app:selectorStateEnabled        drawable
   * app:selectorStateFocused        drawable
   * app:selectorStatePressed        drawable
   * app:selectorStateNormal         drawable
   * app:selectorStateSelected       drawable
   * app:selectorStateSingle         drawable
   * app:selectorStateHovered        drawable
   * app:selectorStateWindowFocused  drawable
   *
   * note that if you want use more complicated state combination, use
   * <p>
   * selectorItemXXX instead.
   * app:selectorItemXStates         flags
   * app:selectorItemXDrawable       drawable
   * ...
   */
  class StateListDrawableParser implements DrawableParser {
    // Single state constants of view, keep sync with Folivora_Selector attrs
    private static final int[] STATE_FIRST = {android.R.attr.state_first};
    private static final int[] STATE_MIDDLE = {android.R.attr.state_middle};
    private static final int[] STATE_LAST = {android.R.attr.state_last};
    private static final int[] STATE_ACTIVE = {android.R.attr.state_active};
    private static final int[] STATE_ACTIVATED = {android.R.attr.state_activated};
    private static final int[] STATE_ACCELERATE = {android.R.attr.state_accelerated};
    private static final int[] STATE_CHECKED = {android.R.attr.state_checked};
    private static final int[] STATE_CHECKABLE = {android.R.attr.state_checkable};
    private static final int[] STATE_ENABLED = {android.R.attr.state_enabled};
    private static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
    private static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
    private static final int[] STATE_SELECTED = {android.R.attr.state_selected};
    private static final int[] STATE_SINGLE = {android.R.attr.state_single};
    private static final int[] STATE_HOVERED = {android.R.attr.state_hovered};
    private static final int[] STATE_WINDOW_FOCUSED = {android.R.attr.state_window_focused};
    // Should we support these state?
    //private static final int[] STATE_DRAG_HOVERED = {android.R.attr.state_drag_hovered};
    //private static final int[] STATE_DRAG_CAN_ACCEPT = {android.R.attr.state_drag_can_accept};
    private static final int[] STATE_NORMAL = {};

    // State flags
    private static final int FIRST = 1;
    private static final int FIRST_NOT = 1 << 1;
    private static final int MIDDLE = 1 << 2;
    private static final int MIDDLE_NOT = 1 << 3;
    private static final int LAST = 1 << 4;
    private static final int LAST_NOT = 1 << 5;
    private static final int ACTIVE = 1 << 6;
    private static final int ACTIVE_NOT = 1 << 7;
    private static final int ACTIVATED = 1 << 8;
    private static final int ACTIVATED_NOT = 1 << 9;
    private static final int ACCELERATE = 1 << 10;
    private static final int ACCELERATE_NOT = 1 << 11;
    private static final int CHECKED = 1 << 12;
    private static final int CHECKED_NOT = 1 << 13;
    private static final int CHECKABLE = 1 << 14;
    private static final int CHECKABLE_NOT = 1 << 15;
    private static final int ENABLED = 1 << 16;
    private static final int ENABLED_NOT = 1 << 17;
    private static final int FOCUSED = 1 << 18;
    private static final int FOCUSED_NOT = 1 << 19;
    private static final int PRESSED = 1 << 20;
    private static final int PRESSED_NOT = 1 << 21;
    private static final int SELECTED = 1 << 22;
    private static final int SELECTED_NOT = 1 << 23;
    private static final int SINGLE = 1 << 24;
    private static final int SINGLE_NOT = 1 << 25;
    private static final int HOVERED = 1 << 26;
    private static final int HOVERED_NOT = 1 << 27;
    private static final int WINDOW_FOCUSED = 1 << 28;
    private static final int WINDOW_FOCUSED_NOT = 1 << 29;
    private static final int[] TEMP_STATE_SET = new int[15];

    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      StateListDrawable d = new StateListDrawable();
      Drawable temp;
      int[] states;
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Selector);
      states = parseStateSet(a.getInt(R.styleable.Folivora_Selector_selectorItem0States, 0));
      if (states != null && (temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorItem0Drawable)) != null) {
        d.addState(states, temp);
      }
      states = parseStateSet(a.getInt(R.styleable.Folivora_Selector_selectorItem1States, 0));
      if (states != null && (temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorItem1Drawable)) != null) {
        d.addState(states, temp);
      }
      states = parseStateSet(a.getInt(R.styleable.Folivora_Selector_selectorItem2States, 0));
      if (states != null && (temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorItem2Drawable)) != null) {
        d.addState(states, temp);
      }
      states = parseStateSet(a.getInt(R.styleable.Folivora_Selector_selectorItem3States, 0));
      if (states != null && (temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorItem3Drawable)) != null) {
        d.addState(states, temp);
      }
      states = parseStateSet(a.getInt(R.styleable.Folivora_Selector_selectorItem4States, 0));
      if (states != null && (temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorItem4Drawable)) != null) {
        d.addState(states, temp);
      }
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateFirst);
      if (temp != null) d.addState(STATE_FIRST, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateMiddle);
      if (temp != null) d.addState(STATE_MIDDLE, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateLast);
      if (temp != null) d.addState(STATE_LAST, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateActive);
      if (temp != null) d.addState(STATE_ACTIVE, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateActivated);
      if (temp != null) d.addState(STATE_ACTIVATED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateAccelerate);
      if (temp != null) d.addState(STATE_ACCELERATE, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateChecked);
      if (temp != null) d.addState(STATE_CHECKED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateCheckable);
      if (temp != null) d.addState(STATE_CHECKABLE, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateEnabled);
      if (temp != null) d.addState(STATE_ENABLED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateFocused);
      if (temp != null) d.addState(STATE_FOCUSED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStatePressed);
      if (temp != null) d.addState(STATE_PRESSED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateSelected);
      if (temp != null) d.addState(STATE_SELECTED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateSingle);
      if (temp != null) d.addState(STATE_SINGLE, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateHovered);
      if (temp != null) d.addState(STATE_HOVERED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateWindowFocused);
      if (temp != null) d.addState(STATE_WINDOW_FOCUSED, temp);
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Selector_selectorStateNormal);
      if (temp != null) d.addState(STATE_NORMAL, temp);
      a.recycle();
      return d;
    }

    /**
     * Parse state sets from the stateFlags
     *
     * @param stateFlags the flags which states combined
     * @return state set or null if absent
     */
    private static int[] parseStateSet(int stateFlags) {
      if (stateFlags == 0) return null;
      int index = 0;
      if ((stateFlags & FIRST) == FIRST) {
        TEMP_STATE_SET[index++] = android.R.attr.state_first;
      }
      if ((stateFlags & FIRST_NOT) == FIRST_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_first;
      }
      if ((stateFlags & MIDDLE) == MIDDLE) {
        TEMP_STATE_SET[index++] = android.R.attr.state_middle;
      }
      if ((stateFlags & MIDDLE_NOT) == MIDDLE_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_middle;
      }
      if ((stateFlags & LAST) == LAST) {
        TEMP_STATE_SET[index++] = android.R.attr.state_last;
      }
      if ((stateFlags & LAST_NOT) == LAST_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_last;
      }
      if ((stateFlags & ACTIVE) == ACTIVE) {
        TEMP_STATE_SET[index++] = android.R.attr.state_active;
      }
      if ((stateFlags & ACTIVE_NOT) == ACTIVE_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_active;
      }
      if ((stateFlags & ACTIVATED) == ACTIVATED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_activated;
      }
      if ((stateFlags & ACTIVATED_NOT) == ACTIVATED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_activated;
      }
      if ((stateFlags & ACCELERATE) == ACCELERATE) {
        TEMP_STATE_SET[index++] = android.R.attr.state_accelerated;
      }
      if ((stateFlags & ACCELERATE_NOT) == ACCELERATE_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_accelerated;
      }
      if ((stateFlags & CHECKED) == CHECKED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_checked;
      }
      if ((stateFlags & CHECKED_NOT) == CHECKED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_checked;
      }
      if ((stateFlags & CHECKABLE) == CHECKABLE) {
        TEMP_STATE_SET[index++] = android.R.attr.state_checkable;
      }
      if ((stateFlags & CHECKABLE_NOT) == CHECKABLE_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_checkable;
      }
      if ((stateFlags & ENABLED) == ENABLED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_enabled;
      }
      if ((stateFlags & ENABLED_NOT) == ENABLED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_enabled;
      }
      if ((stateFlags & FOCUSED) == FOCUSED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_focused;
      }
      if ((stateFlags & FOCUSED_NOT) == FOCUSED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_focused;
      }
      if ((stateFlags & PRESSED) == PRESSED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_pressed;
      }
      if ((stateFlags & PRESSED_NOT) == PRESSED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_pressed;
      }
      if ((stateFlags & SELECTED) == SELECTED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_selected;
      }
      if ((stateFlags & SELECTED_NOT) == SELECTED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_selected;
      }
      if ((stateFlags & SINGLE) == SINGLE) {
        TEMP_STATE_SET[index++] = android.R.attr.state_single;
      }
      if ((stateFlags & SINGLE_NOT) == SINGLE_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_single;
      }
      if ((stateFlags & HOVERED) == HOVERED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_hovered;
      }
      if ((stateFlags & HOVERED_NOT) == HOVERED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_hovered;
      }
      if ((stateFlags & WINDOW_FOCUSED) == WINDOW_FOCUSED) {
        TEMP_STATE_SET[index++] = android.R.attr.state_window_focused;
      }
      if ((stateFlags & WINDOW_FOCUSED_NOT) == WINDOW_FOCUSED_NOT) {
        TEMP_STATE_SET[index++] = -android.R.attr.state_window_focused;
      }
      if (index == 0) return null;
      return StateSet.trimStateSet(TEMP_STATE_SET, index);
    }
  }

  /**
   * Create a new LayerDrawable, currently we only support 5 children drawables.
   * attrs:
   * <p>
   * app:layerItem0Drawable       drawable
   * app:layerItem0Insets         dimension
   * app:layerItem0Left           dimension
   * app:layerItem0Top            dimension
   * app:layerItem0Right          dimension
   * app:layerItem0Bottom         dimension
   * <p>
   * app:layerItem1Drawable       drawable
   * app:layerItem1Insets         dimension
   * app:layerItem1Left           dimension
   * app:layerItem1Top            dimension
   * app:layerItem1Right          dimension
   * app:layerItem1Bottom         dimension
   * <p>
   * app:layerItem2Drawable       drawable
   * app:layerItem2Insets         dimension
   * app:layerItem2Left           dimension
   * app:layerItem2Top            dimension
   * app:layerItem2Right          dimension
   * app:layerItem2Bottom         dimension
   * <p>
   * app:layerItem3Drawable       drawable
   * app:layerItem3Insets         dimension
   * app:layerItem3Left           dimension
   * app:layerItem3Top            dimension
   * app:layerItem3Right          dimension
   * app:layerItem3Bottom         dimension
   * <p>
   * app:layerItem4Drawable       drawable
   * app:layerItem4Insets         dimension
   * app:layerItem4Left           dimension
   * app:layerItem4Top            dimension
   * app:layerItem4Right          dimension
   * app:layerItem4Bottom         dimension
   */
  class LayerDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Layer);
      List<Drawable> childDrawables = new ArrayList<>(5);
      List<Rect> childInsets = new ArrayList<>(5);

      Drawable temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem0Drawable);
      if (temp != null) {
        childDrawables.add(temp);
        int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Insets, 0);
        childInsets.add(new Rect(
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Left, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Top, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Right, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem0Bottom, insets)
        ));
      }
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem1Drawable);
      if (temp != null) {
        childDrawables.add(temp);
        int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Insets, 0);
        childInsets.add(new Rect(
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Left, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Top, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Right, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem1Bottom, insets)
        ));
      }
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem2Drawable);
      if (temp != null) {
        childDrawables.add(temp);
        int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Insets, 0);
        childInsets.add(new Rect(
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Left, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Top, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Right, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem2Bottom, insets)
        ));
      }
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem3Drawable);
      if (temp != null) {
        childDrawables.add(temp);
        int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Insets, 0);
        childInsets.add(new Rect(
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Left, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Top, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Right, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem3Bottom, insets)
        ));
      }
      temp = getDrawable(ctx, a, attrs, R.styleable.Folivora_Layer_layerItem4Drawable);
      if (temp != null) {
        childDrawables.add(temp);
        int insets = a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Insets, 0);
        childInsets.add(new Rect(
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Left, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Top, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Right, insets),
          a.getDimensionPixelSize(R.styleable.Folivora_Layer_layerItem4Bottom, insets)
        ));
      }
      a.recycle();
      LayerDrawable d = new LayerDrawable(childDrawables.toArray(new Drawable[0]));
      for (int i = 0; i < childInsets.size(); i++) {
        Rect inset = childInsets.get(i);
        d.setLayerInset(i, inset.left, inset.top, inset.right, inset.bottom);
      }
      return d;
    }
  }

  /**
   * Create a new RippleDrawable, if current platform does not support,
   * we will try to create a substitute from {@link RippleFallback} rippleFallback.
   * attrs:
   * <p>
   * app:rippleColor              color
   * app:rippleContent            drawable
   * app:rippleMask               drawable
   */
  class RippleDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      final RippleFallback fallback = request.rippleFallback();

      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Ripple);
      ColorStateList color;
      Drawable content;
      Drawable mask;
      try {
        color = a.getColorStateList(R.styleable.Folivora_Ripple_rippleColor);
        if (color == null) {
          throw new IllegalStateException("rippleColor not set");
        }
        content = getDrawable(ctx, a, attrs, R.styleable.Folivora_Ripple_rippleContent);
        mask = getDrawable(ctx, a, attrs, R.styleable.Folivora_Ripple_rippleMask);
      } finally {
        a.recycle();
      }

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        return new RippleDrawable(color, content, mask);
      } else if (fallback != null) {
        return fallback.onFallback(color, content, mask, ctx);
      } else {
        Log.w(TAG, "RippleDrawable is not available in current platform");
        return null;
      }
    }
  }

  /**
   * Create a new LevelListDrawable, currently we only support 5 children drawables.
   * attrs:
   * <p>
   * app:levelCurrentLevel        int
   * app:levelItem0Drawable       drawable
   * app:levelItem0MinLevel       int
   * app:levelItem0MaxLevel       int
   * app:levelItem1Drawable       drawable
   * app:levelItem1MinLevel       int
   * app:levelItem1MaxLevel       int
   * app:levelItem2Drawable       drawable
   * app:levelItem2MinLevel       int
   * app:levelItem2MaxLevel       int
   * app:levelItem3Drawable       drawable
   * app:levelItem3MinLevel       int
   * app:levelItem3MaxLevel       int
   * app:levelItem4Drawable       drawable
   * app:levelItem4MinLevel       int
   * app:levelItem4MaxLevel       int
   */
  class LevelListDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      LevelListDrawable lld = new LevelListDrawable();
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Level);
      if (a.hasValue(R.styleable.Folivora_Level_levelItem0Drawable)) {
        lld.addLevel(
          a.getInt(R.styleable.Folivora_Level_levelItem0MinLevel, 0),
          a.getInt(R.styleable.Folivora_Level_levelItem0MaxLevel, 0),
          getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem0Drawable)
        );
      }
      if (a.hasValue(R.styleable.Folivora_Level_levelItem1Drawable)) {
        lld.addLevel(
          a.getInt(R.styleable.Folivora_Level_levelItem1MinLevel, 0),
          a.getInt(R.styleable.Folivora_Level_levelItem1MaxLevel, 0),
          getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem1Drawable)
        );
      }
      if (a.hasValue(R.styleable.Folivora_Level_levelItem2Drawable)) {
        lld.addLevel(
          a.getInt(R.styleable.Folivora_Level_levelItem2MinLevel, 0),
          a.getInt(R.styleable.Folivora_Level_levelItem2MaxLevel, 0),
          getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem2Drawable)
        );
      }
      if (a.hasValue(R.styleable.Folivora_Level_levelItem3Drawable)) {
        lld.addLevel(
          a.getInt(R.styleable.Folivora_Level_levelItem3MinLevel, 0),
          a.getInt(R.styleable.Folivora_Level_levelItem3MaxLevel, 0),
          getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem3Drawable)
        );
      }
      if (a.hasValue(R.styleable.Folivora_Level_levelItem4Drawable)) {
        lld.addLevel(
          a.getInt(R.styleable.Folivora_Level_levelItem4MinLevel, 0),
          a.getInt(R.styleable.Folivora_Level_levelItem4MaxLevel, 0),
          getDrawable(ctx, a, attrs, R.styleable.Folivora_Level_levelItem4Drawable)
        );
      }
      lld.setLevel(a.getInt(R.styleable.Folivora_Level_levelCurrentLevel, 0));
      a.recycle();
      return lld;
    }
  }

  /**
   * Create a new ClipDrawable.
   * attrs:
   * <p>
   * app:clipDrawable             drawable
   * app:clipGravity              enum
   * app:clipOrientation          enum
   * app:clipLevel                int(10000 means no clip)
   */
  class ClipDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Clip);
      final Drawable child = getDrawable(ctx, a, attrs, R.styleable.Folivora_Clip_clipDrawable);
      final int clipGravity = a.getInt(R.styleable.Folivora_Clip_clipGravity, Gravity.START);
      final int clipOrientation = a.getInt(R.styleable.Folivora_Clip_clipOrientation, ClipDrawable.HORIZONTAL);

      ClipDrawable cd = new ClipDrawable(child, clipGravity, clipOrientation);
      cd.setLevel(a.getInt(R.styleable.Folivora_Clip_clipLevel, 10000/*no clip*/));
      a.recycle();
      return cd;
    }
  }

  /**
   * Create a new InsetDrawable, inset by fraction is not support, since it is an new api.
   * attrs:
   * <p>
   * app:insetDrawable            drawable
   * app:insetAll                 dimension
   * app:insetLeft                dimension
   * app:insetTop                 dimension
   * app:insetRight               dimension
   * app:insetBottom              dimension
   */
  class InsetDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Inset);
      int insetAll = a.getDimensionPixelSize(R.styleable.Folivora_Inset_insetAll, 0);
      int[] ints = {
        R.styleable.Folivora_Inset_insetLeft,
        R.styleable.Folivora_Inset_insetTop,
        R.styleable.Folivora_Inset_insetRight,
        R.styleable.Folivora_Inset_insetBottom
      };
      for (int i = 0; i < ints.length; i++) {
        ints[i] = a.getDimensionPixelSize(ints[i], insetAll);
      }
      final Drawable child = getDrawable(ctx, a, attrs, R.styleable.Folivora_Inset_insetDrawable);
      a.recycle();
      return new InsetDrawable(child, ints[0], ints[1], ints[2], ints[3]);
    }
  }

  /**
   * Create a new ScaleDrawable.
   * attrs:
   * <p>
   * app:scaleDrawable            drawable
   * app:scaleGravity             enum
   * app:scaleWidth               float
   * app:scaleHeight              float
   * app:scaleLevel               int
   */
  class ScaleDrawableParser implements DrawableParser {
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Scale);
      ScaleDrawable sd = new ScaleDrawable(
        getDrawable(ctx, a, attrs, R.styleable.Folivora_Scale_scaleDrawable),
        a.getInt(R.styleable.Folivora_Scale_scaleGravity, Gravity.START),
        a.getFloat(R.styleable.Folivora_Scale_scaleWidth, -1F),
        a.getFloat(R.styleable.Folivora_Scale_scaleHeight, -1F)
      );
      sd.setLevel(a.getInt(R.styleable.Folivora_Scale_scaleLevel, 1));
      a.recycle();
      return sd;
    }
  }

  /**
   * Create a new AnimationDrawable, currently we only support 10 frames.
   * attrs:
   * <p>
   * app:animAutoPlay             boolean
   * app:animDuration             int(millisecond)
   * app:animOneShot              boolean
   * <p>
   * app:animFrame0               drawable
   * app:animDuration0            int(millisecond)
   * app:animFrame1               drawable
   * app:animDuration1            int(millisecond)
   * app:animFrame2               drawable
   * app:animDuration2            int(millisecond)
   * app:animFrame3               drawable
   * app:animDuration3            int(millisecond)
   * app:animFrame4               drawable
   * app:animDuration4            int(millisecond)
   * app:animFrame5               drawable
   * app:animDuration5            int(millisecond)
   * app:animFrame6               drawable
   * app:animDuration6            int(millisecond)
   * app:animFrame7               drawable
   * app:animDuration7            int(millisecond)
   * app:animFrame8               drawable
   * app:animDuration8            int(millisecond)
   * app:animFrame9               drawable
   * app:animDuration9            int(millisecond)
   */
  class AnimationDrawableParser implements DrawableParser {
    @SuppressWarnings("ConstantConditions")
    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      AnimationDrawable ad;
      TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora_Animation);
      final boolean autoPlay = a.getBoolean(R.styleable.Folivora_Animation_animAutoPlay, false);
      if (autoPlay) {
        // Workaround for android bug, animation drawable does not played
        // normally when calling start() on activity's onCreate() method.
        ad = new AnimationDrawable() {
          boolean autoPlayed;

          @Override
          protected void onBoundsChange(Rect bounds) {
            super.onBoundsChange(bounds);
            if (!autoPlayed) {
              if (isOneShot()) {
                Log.i(TAG, "Auto play and oneshot both enabled, you could not see the animation");
              }
              this.start();
              autoPlayed = true;
            }
          }
        };
      } else {
        ad = new AnimationDrawable();
      }
      ad.setOneShot(a.getBoolean(R.styleable.Folivora_Animation_animOneShot, false));
      final int frameDuration = a.getInt(R.styleable.Folivora_Animation_animDuration, -1);

      if (a.hasValue(R.styleable.Folivora_Animation_animFrame0)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame0),
          a.getInt(R.styleable.Folivora_Animation_animDuration0, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame1)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame1),
          a.getInt(R.styleable.Folivora_Animation_animDuration1, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame2)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame2),
          a.getInt(R.styleable.Folivora_Animation_animDuration2, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame3)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame3),
          a.getInt(R.styleable.Folivora_Animation_animDuration3, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame4)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame4),
          a.getInt(R.styleable.Folivora_Animation_animDuration4, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame5)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame5),
          a.getInt(R.styleable.Folivora_Animation_animDuration5, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame6)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame6),
          a.getInt(R.styleable.Folivora_Animation_animDuration6, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame7)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame7),
          a.getInt(R.styleable.Folivora_Animation_animDuration7, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame8)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame8),
          a.getInt(R.styleable.Folivora_Animation_animDuration8, frameDuration));
      }
      if (a.hasValue(R.styleable.Folivora_Animation_animFrame9)) {
        ad.addFrame(a.getDrawable(R.styleable.Folivora_Animation_animFrame9),
          a.getInt(R.styleable.Folivora_Animation_animDuration9, frameDuration));
      }
      a.recycle();
      return ad;
    }
  }

  /**
   * Try to create a custom drawable from the given class name, note
   * that the custom drawable class must have a public constructor
   * that takes a {@link Context} context and a {@link AttributeSet}
   * attrs as parameters
   */
  class ReflectiveDrawableParser implements DrawableParser {
    // Stuffs for create custom drawable reflectively
    private static Set<String> sFailedNames = new HashSet<>();
    private static Class[] sConstructorSignature = {Context.class, AttributeSet.class};
    private static Object[] sConstructorArgs = new Object[2];
    private static Map<String, Constructor<? extends Drawable>> sConstructorCache = new HashMap<>();

    @Override
    public Drawable parse(ParseRequest request) {
      final Context ctx = request.context();
      final AttributeSet attrs = request.attrs();
      final String drawableName = request.drawableClassName();
      if (sFailedNames.contains(drawableName)) return null;
      if (drawableName.indexOf('.') == -1) return null;
      Constructor<? extends Drawable> constructor = sConstructorCache.get(drawableName);

      try {
        if (constructor == null) {
          Class<? extends Drawable> clazz = ctx.getClassLoader().loadClass(drawableName)
            .asSubclass(Drawable.class);
          constructor = clazz.getConstructor(sConstructorSignature);
          constructor.setAccessible(true);
          sConstructorCache.put(drawableName, constructor);
        }
        sConstructorArgs[0] = ctx;
        sConstructorArgs[1] = attrs;
        return constructor.newInstance(sConstructorArgs);
      } catch (ClassNotFoundException cnfe) {
        sFailedNames.add(drawableName);
        Log.w(TAG, "drawable class [" + drawableName
          + "] not found, Folivora will never try to load it any more");
      } catch (NoSuchMethodException nsme) {
        sFailedNames.add(drawableName);
        final String classSimpleName = drawableName.substring(drawableName.lastIndexOf('.') + 1);
        final String msg = "constructor " + classSimpleName + "(Context context, AttributeSet attrs)"
          + " does not exists in drawable class [" + drawableName + "], Folivora will never try to" +
          " load it any more";
        Log.w(TAG, msg);
      } catch (IllegalAccessException iae) {
        throw new AssertionError(iae);//never happen
      } catch (Exception e) {
        Log.w(TAG, "exception occurred instantiating drawable [" + drawableName + "]", e);
      } finally {
        sConstructorArgs[0] = null;
        sConstructorArgs[1] = null;
      }
      return null;
    }
  }
}

================================================
FILE: folivora/src/main/java/cn/cricin/folivora/Folivora.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.LruCache;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Folivora support sets drawable directly in your layout.xml files, no need
 * to create XXX.xml in drawable directory. just write down attributes we
 * provided in your layout.xml, folivora will take care of with this attrs
 * and create suitable drawable's for view.
 * <p>
 * Folivora is light weight, you would use {@link #wrap(Context)} wrap()
 * or {@link #installViewFactory(Context)} installViewFactory() to enable
 * folivora functions
 *
 * @see #wrap(Context)
 * @see #installViewFactory(Context)
 * @see #setRippleFallback(RippleFallback)
 * @see #getDrawable(Context, TypedArray, AttributeSet, int)
 * @see #addOnViewCreatedListener(OnViewCreatedListener)
 */
public final class Folivora {
  static final String TAG = "Folivora";

  // Drawable type enums, keep sync with app:drawableType
  private static final int DRAWABLE_TYPE_SHAPE = 0;
  private static final int DRAWABLE_TYPE_SELECTOR = 1;
  private static final int DRAWABLE_TYPE_LAYER = 2;
  private static final int DRAWABLE_TYPE_RIPPLE = 3;
  private static final int DRAWABLE_TYPE_LEVEL = 4;
  private static final int DRAWABLE_TYPE_CLIP = 5;
  private static final int DRAWABLE_TYPE_INSET = 6;
  private static final int DRAWABLE_TYPE_SCALE = 7;
  private static final int DRAWABLE_TYPE_ANIMATION = 8;

  // Set as enums, keep sync with app:setAs
  private static final int SET_AS_BACKGROUND = 0;
  private static final int SET_AS_SRC = 1;
  private static final int SET_AS_FOREGROUND = 2;

  // Exposed apis
  private static RippleFallback sRippleFallback;
  private static List<OnViewCreatedListener> sOnViewCreatedListeners;
  private static Map<String, DrawableParser> sDrawableParsers = new HashMap<>();
  private static DrawableParser sReflectiveDrawableParser = new DrawableParser.ReflectiveDrawableParser();
  private static SparseArray<String> sSystemDrawableNames = new SparseArray<>();

  static {
    sDrawableParsers.put("android.graphics.drawable.GradientDrawable", new DrawableParser.GradientDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.StateListDrawable", new DrawableParser.StateListDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.LayerDrawable", new DrawableParser.LayerDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.RippleDrawable", new DrawableParser.RippleDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.LevelListDrawable", new DrawableParser.LevelListDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.ClipDrawable", new DrawableParser.ClipDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.InsetDrawable", new DrawableParser.InsetDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.ScaleDrawable", new DrawableParser.ScaleDrawableParser());
    sDrawableParsers.put("android.graphics.drawable.AnimationDrawable", new DrawableParser.AnimationDrawableParser());

    sSystemDrawableNames.put(DRAWABLE_TYPE_SHAPE, "android.graphics.drawable.GradientDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_SELECTOR, "android.graphics.drawable.StateListDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_LAYER, "android.graphics.drawable.LayerDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_RIPPLE, "android.graphics.drawable.RippleDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_LEVEL, "android.graphics.drawable.LevelListDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_CLIP, "android.graphics.drawable.ClipDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_INSET, "android.graphics.drawable.InsetDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_SCALE, "android.graphics.drawable.ScaleDrawable");
    sSystemDrawableNames.put(DRAWABLE_TYPE_ANIMATION, "android.graphics.drawable.AnimationDrawable");

  }

  // Cached drawables with it's ids
  private static LruCache<String, Drawable> sDrawableCache = new LruCache<>(128);
  // Cache is enabled at runtime, but at design time, this should be disabled for work properly
  @SuppressWarnings("FieldCanBeLocal") // This is accessed by layout editor
  private static boolean sDrawableCacheEnabled = true;

  /**
   * Try to get a child drawable, if the attrIndex pointing to a specific drawable,
   * then load it in normal way, if the attrIndex pointing a enum(shape index), try
   * to create it from the given attrs
   *
   * @param ctx       current context
   * @param a         caller's typed array
   * @param attrs     attributes from view tag
   * @param attrIndex attribute index in the typed array
   * @return a drawable, or a newly created GradientDrawable from attrs, or null
   */
  @SuppressWarnings("WeakerAccess")
  public static Drawable getDrawable(Context ctx, TypedArray a, AttributeSet attrs, int attrIndex) {
    if (!a.hasValue(attrIndex)) return null;
    Drawable result = null;
    ShapeAttrs shapeAttrs = ShapeAttrs.forIndex(a.getInt(attrIndex, -1));
    if (shapeAttrs != null) {
      final String className = "android.graphics.drawable.GradientDrawable";
      DrawableParser parser = sDrawableParsers.get(className);
      ParseRequest request = new ParseRequest(ctx, attrs, sRippleFallback, shapeAttrs, className);
      if (parser != null) {
        result = parser.parse(request);
      }
    }

    if (result == null) {
      result = a.getDrawable(attrIndex);
    }
    return result;
  }

  /**
   * Create a drawable to the specific view with attrs, this method is
   * used by folivora internally, but in order to support preview for
   * the views folivora not stubbed, this method becomes publicly
   *
   * @param view  view of drawable attached
   * @param attrs attributes from view tag
   */
  static void applyDrawableToView(View view, AttributeSet attrs) {
    final Context ctx = view.getContext();
    // Step1 extract attrs
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.Folivora);
    int drawableType = a.getInt(R.styleable.Folivora_drawableType, -1);
    String drawableId = a.getString(R.styleable.Folivora_drawableId);
    String drawableName = a.getString(R.styleable.Folivora_drawableName);
    int setAs = a.getInt(R.styleable.Folivora_setAs, SET_AS_BACKGROUND);
    a.recycle();
    if (drawableType < 0 && drawableId == null && drawableName == null) return;
    // Step2 lookup cached if available
    Drawable cached = null;
    Drawable d = null;
    if (drawableId != null) {
      cached = sDrawableCache.get(drawableId);
      if (cached != null && cached.getConstantState() != null) {
        cached = cached.getConstantState().newDrawable();
      }
    }
    // Step3 try to create a new drawable and cached it
    if (!sDrawableCacheEnabled || cached == null) {
      d = createDrawable(ctx, attrs, drawableType, drawableName);
      if (d != null && d.getConstantState() != null && drawableId != null) {
        sDrawableCache.put(drawableId, d);
      }
    }
    d = d == null ? cached : d;
    if (d == null) return;
    // Step4 set drawable to view
    if (setAs == SET_AS_BACKGROUND) {
      view.setBackground(d);
    } else if (setAs == SET_AS_SRC && view instanceof ImageView) {
      ((ImageView) view).setImageDrawable(d);
    } else if (setAs == SET_AS_FOREGROUND) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        view.setForeground(d);
      } else if (view instanceof FrameLayout) {
        //noinspection RedundantCast
        ((FrameLayout) view).setForeground(d);
      } else {
        Log.w(TAG, "Folivora can not set foreground to [" + view.getClass()
          + "], Current device platform is lower than MarshMallow");
      }
    }
  }

  private static Drawable createDrawable(Context ctx, AttributeSet attrs, int drawableType, String drawableName) {
    String realDrawableName = null;
    if (drawableType >= 0) {
      realDrawableName = sSystemDrawableNames.get(drawableType);
    }
    if (realDrawableName == null) {
      realDrawableName = drawableName;
    }
    if (realDrawableName == null) return null;
    DrawableParser parser = sDrawableParsers.get(realDrawableName);
    if (parser == null && !realDrawableName.startsWith("android.graphics.drawable")) {
      parser = sReflectiveDrawableParser;
    }
    if (parser == null) return null;
    ParseRequest request = new ParseRequest(ctx, attrs, sRippleFallback, ShapeAttrs.forIndex(0), realDrawableName);
    return parser.parse(request);
  }

  /**
   * Install Folivora's ViewFactory to current context. note that if
   * you are using AppCompatActivity, this method should called after
   * your activity's super.onCreate() method, since AppCompatDelegate
   * will install a {@link LayoutInflater.Factory2} factory2 to this
   * context.
   *
   * @param ctx context to enable folivora support
   */
  public static void installViewFactory(Context ctx) {
    LayoutInflater inflater = LayoutInflater.from(ctx);
    LayoutInflater.Factory2 factory2 = inflater.getFactory2();
    if (factory2 instanceof FolivoraViewFactory) return;
    FolivoraViewFactory viewFactory = new FolivoraViewFactory();
    viewFactory.mFactory2 = factory2;
    if (factory2 != null) {
      FolivoraViewFactory.forceSetFactory2(inflater, viewFactory);
    } else {
      inflater.setFactory2(viewFactory);
    }
  }

  /**
   * Wraps the given context, replace the {@link LayoutInflater} inflater
   * to folivora's implementation, this method does nothing if the given
   * context is already been wrapped.
   *
   * @param newBase new base context
   * @return a wrapped context
   */
  public static Context wrap(final Context newBase) {
    final LayoutInflater inflater = LayoutInflater.from(newBase);
    if (inflater instanceof FolivoraInflater) return newBase;
    return new ContextWrapper(newBase) {
      private FolivoraInflater mInflater;

      @Override
      public Object getSystemService(String name) {
        if (LAYOUT_INFLATER_SERVICE.equals(name)) {
          if (mInflater == null) {
            mInflater = new FolivoraInflater(newBase, inflater);
          }
          return mInflater;
        }
        return super.getSystemService(name);
      }
    };
  }

  /**
   * Set a fallback to create substitute drawable when the {@link RippleDrawable}
   * RippleDrawable is not available in current device.
   *
   * @param fallback a fallback to create drawable
   */
  public static void setRippleFallback(RippleFallback fallback) {
    sRippleFallback = fallback;
  }

  public static void registerDrawableParser(Class<? extends Drawable> drawableClass, DrawableParser parser) {
    final String className = drawableClass.getCanonicalName();
    sDrawableParsers.put(className, parser);
  }

  /**
   * Add a {@link OnViewCreatedListener} listener to folivora, folivora
   * will notify these listeners when a view is created. this listener
   * allows you do some extra customization about the inflated views.
   *
   * @param l listener to register
   */
  public static void addOnViewCreatedListener(OnViewCreatedListener l) {
    if (sOnViewCreatedListeners == null) {
      sOnViewCreatedListeners = new ArrayList<>();
    }
    sOnViewCreatedListeners.add(l);
  }

  static void dispatchViewCreated(View view, AttributeSet attrs) {
    if (sOnViewCreatedListeners != null) {
      for (OnViewCreatedListener l : sOnViewCreatedListeners) {
        l.onViewCreated(view, attrs);
      }
    }
  }

  private Folivora() {}
}


================================================
FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraInflater.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.xmlpull.v1.XmlPullParser;

/**
 * A LayoutInflater implementation which delegate all view creation
 * to {@link FolivoraViewFactory}.
 */
final class FolivoraInflater extends LayoutInflater {
  private static final String[] sClassPrefixList = {
    "android.widget.",
    "android.webkit.",
    "android.app."
  };

  FolivoraInflater(Context newContext, LayoutInflater original) {
    super(original, newContext);
  }

  @Override
  public LayoutInflater cloneInContext(Context newContext) {
    return new FolivoraInflater(newContext, this);
  }

  @Override
  public void setFactory(Factory factory) {
    FolivoraViewFactory f = (FolivoraViewFactory) getFactory2();
    if (f == null) {
      super.setFactory2(f = new FolivoraViewFactory());
    }
    f.mFactory = factory;
  }

  @Override
  public void setFactory2(Factory2 factory2) {
    FolivoraViewFactory f = (FolivoraViewFactory) getFactory2();
    if (f == null) {
      super.setFactory2(f = new FolivoraViewFactory());
    }
    f.mFactory2 = factory2;
  }

  @Override
  public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    Factory2 factory2 = getFactory2();
    if (factory2 == null) {
      super.setFactory2(new FolivoraViewFactory());
    }
    return super.inflate(parser, root, attachToRoot);
  }

  /** fallback if FolivoraViewFactory could not create views properly */
  @Override
  protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
    for (String prefix : sClassPrefixList) {
      try {
        View view = createView(name, prefix, attrs);
        if (view != null) {
          return view;
        }
      } catch (ClassNotFoundException e) {
        // In this case we want to let the base class take a crack
        // at it.
      }
    }
    return super.onCreateView(name, attrs);
  }
}


================================================
FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraViewFactory.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * A view factory takes responsibility of view creation, if the view
 * is created, folivora will create a drawable for it if available.
 */
final class FolivoraViewFactory implements LayoutInflater.Factory2 {
  private static final String[] sClassPrefixList = {
    "android.widget.",
    "android.webkit.",
    "android.app.",
    "android.view."
  };

  private static final Class<?>[] sConstructorSignature = new Class[]{
    Context.class, AttributeSet.class};
  private static Object[] sConstructorArgs = new Object[2];
  private static Map<String, Constructor<? extends View>> sConstructorMap = new HashMap<>();

  LayoutInflater.Factory2 mFactory2;
  LayoutInflater.Factory mFactory;

  @Override
  public View onCreateView(String name, Context context, AttributeSet attrs) {
    return onCreateView(null, name, context, attrs);
  }

  @Override
  public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    View view = null;
    if (mFactory2 != null) {
      view = mFactory2.onCreateView(parent, name, context, attrs);
    }
    if (view == null && mFactory != null) {
      view = mFactory.onCreateView(name, context, attrs);
    }
    if (view == null && name.endsWith("ViewStub")) return null;//fix NPE when creating ViewStub

    if (view == null && name.indexOf('.') != -1) {
      view = createView(name, context, attrs);
    }

    if (view == null) {
      for (String prefix : sClassPrefixList) {
        view = createView(prefix + name, context, attrs);
        if (view != null) break;
      }
    }
    if (view != null) {
      Folivora.applyDrawableToView(view, attrs);
      Folivora.dispatchViewCreated(view, attrs);
    }
    return view;
  }

  private static View createView(String name, Context ctx, AttributeSet attrs) {
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    try {
      if (constructor == null) {
        // Class not found in the cache, see if it's real, and try to add it
        Class<? extends View> clazz = ctx.getClassLoader().loadClass(name).asSubclass(View.class);

        constructor = clazz.getConstructor(sConstructorSignature);
        sConstructorMap.put(name, constructor);
      }
      constructor.setAccessible(true);
      sConstructorArgs[0] = ctx;
      sConstructorArgs[1] = attrs;
      return constructor.newInstance(sConstructorArgs);
    } catch (Exception e) {
      // We do not want to catch these, lets return null and let the actual LayoutInflater
      // try
      return null;
    } finally {
      sConstructorArgs[0] = null;
      sConstructorArgs[1] = null;
    }
  }

  private static LayoutInflater getLayoutInflater(Context context) {
    return LayoutInflater.from(context);
  }

  private static boolean sCheckedField;
  private static Field sLayoutInflaterFactory2Field;

  static void forceSetFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
    if (!sCheckedField) {
      try {
        //noinspection JavaReflectionMemberAccess
        sLayoutInflaterFactory2Field = LayoutInflater.class.getDeclaredField("mFactory2");
        sLayoutInflaterFactory2Field.setAccessible(true);
      } catch (NoSuchFieldException e) {
        Log.e(Folivora.TAG, "forceSetFactory2 Could not find field 'mFactory2' on class "
          + inflater.getClass().getName() + "; Folivora will not available.", e);
      }
      sCheckedField = true;
    }
    if (sLayoutInflaterFactory2Field != null) {
      try {
        sLayoutInflaterFactory2Field.set(inflater, factory);
      } catch (Exception e) {
        Log.e(Folivora.TAG, "forceSetFactory2 could not set the Factory2 on LayoutInflater "
          + inflater + "; Folivora will not available.", e);
      }
    }
  }

}


================================================
FILE: folivora/src/main/java/cn/cricin/folivora/OnViewCreatedListener.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.util.AttributeSet;
import android.view.View;

/**
 * A listener notified when a view is been created. you can
 * do some customization on the view based on the attrs. eg,
 * change text or typeface of TextView or change src of ImageView
 */
public interface OnViewCreatedListener {
  void onViewCreated(View view, AttributeSet attrs);
}

================================================
FILE: folivora/src/main/java/cn/cricin/folivora/ParseRequest.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.util.AttributeSet;

/**
 * A ParseRequest holding all information of drawable parsing task
 * each field may be used by different DrawableParsers.
 */
public final class ParseRequest {
  private final Context mContext;
  private final AttributeSet mAttrs;
  private final RippleFallback mRippleFallback;
  private final ShapeAttrs mShapeAttrs;
  private final String mDrawableClassName;

  /*package*/ParseRequest(Context context,
               AttributeSet attrs,
               RippleFallback fallback,
               ShapeAttrs shapeAttrs,
               String drawableClassName) {
    this.mContext = context;
    this.mAttrs = attrs;
    this.mRippleFallback = fallback;
    this.mShapeAttrs = shapeAttrs;
    this.mDrawableClassName = drawableClassName;
  }

  /**
   * @return current inflation context
   */
  public Context context() {
    return mContext;
  }

  /**
   * @return attribute retrieved from view tag
   */
  public AttributeSet attrs() {
    return mAttrs;
  }

  /**
   * @return a fallback for RippleDrawable
   */
  public RippleFallback rippleFallback() {
    return mRippleFallback;
  }

  /**
   * @return attribute information of a shape at different indexes, used by GradientDrawableParser
   */
  public ShapeAttrs shapeAttrs() {
    return mShapeAttrs;
  }

  /**
   * @return full qualified class name of drawable to be inflated
   */
  public String drawableClassName() {
    return mDrawableClassName;
  }
}

================================================
FILE: folivora/src/main/java/cn/cricin/folivora/RippleFallback.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Build;

/**
 * This class is designed for device platform lowers than
 * {@link Build.VERSION_CODES#LOLLIPOP} lollipop, which RippleDrawable
 * is unavailable, you can create substitution drawable here
 */
public interface RippleFallback {
  /**
   * Called when the view want a RippleDrawable, but it is unavailable in
   * current device
   *
   * @param color   ripple color, nonnull
   * @param content content of ripple, nullable
   * @param mask    ripple mask, nullable
   * @param ctx     current context
   * @return a substitute drawable, or null
   */
  Drawable onFallback(ColorStateList color, Drawable content,
                      Drawable mask, Context ctx);
}

================================================
FILE: folivora/src/main/java/cn/cricin/folivora/ShapeAttrs.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora;

/**
 * ShapeAttrs represents for a set of shape xml attribute indexes,
 * so we can refactor shape creating method to reduce boilerplate code
 */
final class ShapeAttrs {
  int[] mAttrStyleable;
  int mShapeType;
  int mShapeSolidSize;
  int mShapeSolidWidth;
  int mShapeSolidHeight;
  int mShapeGradientType;
  int mShapeGradientRadius;
  int mShapeGradientCenterX;
  int mShapeGradientCenterY;
  int mShapeGradientStartColor;
  int mShapeGradientCenterColor;
  int mShapeGradientEndColor;
  int mShapeGradientAngle;
  int mShapeSolidColor;
  int mShapeStrokeWidth;
  int mShapeStrokeColor;
  int mShapeStrokeDashGap;
  int mShapeStrokeDashWidth;
  int mShapeCornerRadius;
  int mShapeCornerRadiusTopLeft;
  int mShapeCornerRadiusTopRight;
  int mShapeCornerRadiusBottomLeft;
  int mShapeCornerRadiusBottomRight;

  private ShapeAttrs(
    int[] attrStyleable,
    int shapeType,
    int shapeSolidSize,
    int shapeSolidWidth,
    int shapeSolidHeight,
    int shapeGradientType,
    int shapeGradientRadius,
    int shapeGradientCenterX,
    int shapeGradientCenterY,
    int shapeGradientStartColor,
    int shapeGradientCenterColor,
    int shapeGradientEndColor,
    int shapeGradientAngle,
    int shapeSolidColor,
    int shapeStrokeWidth,
    int shapeStrokeColor,
    int shapeStrokeDashGap,
    int shapeStrokeDashWidth,
    int shapeCornerRadius,
    int shapeCornerRadiusTopLeft,
    int shapeCornerRadiusTopRight,
    int shapeCornerRadiusBottomLeft,
    int shapeCornerRadiusBottomRight
  ) {
    this.mAttrStyleable = attrStyleable;
    this.mShapeType = shapeType;
    this.mShapeSolidSize = shapeSolidSize;
    this.mShapeSolidWidth = shapeSolidWidth;
    this.mShapeSolidHeight = shapeSolidHeight;
    this.mShapeGradientType = shapeGradientType;
    this.mShapeGradientRadius = shapeGradientRadius;
    this.mShapeGradientCenterX = shapeGradientCenterX;
    this.mShapeGradientCenterY = shapeGradientCenterY;
    this.mShapeGradientStartColor = shapeGradientStartColor;
    this.mShapeGradientCenterColor = shapeGradientCenterColor;
    this.mShapeGradientEndColor = shapeGradientEndColor;
    this.mShapeGradientAngle = shapeGradientAngle;
    this.mShapeSolidColor = shapeSolidColor;
    this.mShapeStrokeWidth = shapeStrokeWidth;
    this.mShapeStrokeColor = shapeStrokeColor;
    this.mShapeStrokeDashGap = shapeStrokeDashGap;
    this.mShapeStrokeDashWidth = shapeStrokeDashWidth;
    this.mShapeCornerRadius = shapeCornerRadius;
    this.mShapeCornerRadiusTopLeft = shapeCornerRadiusTopLeft;
    this.mShapeCornerRadiusTopRight = shapeCornerRadiusTopRight;
    this.mShapeCornerRadiusBottomLeft = shapeCornerRadiusBottomLeft;
    this.mShapeCornerRadiusBottomRight = shapeCornerRadiusBottomRight;
  }

  private static final ShapeAttrs[] SHAPE_ATTRS_ARRAY = {
    new ShapeAttrs(
      R.styleable.Folivora_Shape,
      R.styleable.Folivora_Shape_shapeType,
      R.styleable.Folivora_Shape_shapeSolidSize,
      R.styleable.Folivora_Shape_shapeSolidWidth,
      R.styleable.Folivora_Shape_shapeSolidHeight,
      R.styleable.Folivora_Shape_shapeGradientType,
      R.styleable.Folivora_Shape_shapeGradientRadius,
      R.styleable.Folivora_Shape_shapeGradientCenterX,
      R.styleable.Folivora_Shape_shapeGradientCenterY,
      R.styleable.Folivora_Shape_shapeGradientStartColor,
      R.styleable.Folivora_Shape_shapeGradientEndColor,
      R.styleable.Folivora_Shape_shapeGradientCenterColor,
      R.styleable.Folivora_Shape_shapeGradientAngle,
      R.styleable.Folivora_Shape_shapeSolidColor,
      R.styleable.Folivora_Shape_shapeStrokeWidth,
      R.styleable.Folivora_Shape_shapeStrokeColor,
      R.styleable.Folivora_Shape_shapeStokeDashGap,
      R.styleable.Folivora_Shape_shapeStokeDashWidth,
      R.styleable.Folivora_Shape_shapeCornerRadius,
      R.styleable.Folivora_Shape_shapeCornerRadiusTopLeft,
      R.styleable.Folivora_Shape_shapeCornerRadiusTopRight,
      R.styleable.Folivora_Shape_shapeCornerRadiusBottomRight,
      R.styleable.Folivora_Shape_shapeCornerRadiusBottomLeft
    ),
    new ShapeAttrs(
      R.styleable.Folivora_Shape1,
      R.styleable.Folivora_Shape1_shape1Type,
      R.styleable.Folivora_Shape1_shape1SolidSize,
      R.styleable.Folivora_Shape1_shape1SolidWidth,
      R.styleable.Folivora_Shape1_shape1SolidHeight,
      R.styleable.Folivora_Shape1_shape1GradientType,
      R.styleable.Folivora_Shape1_shape1GradientRadius,
      R.styleable.Folivora_Shape1_shape1GradientCenterX,
      R.styleable.Folivora_Shape1_shape1GradientCenterY,
      R.styleable.Folivora_Shape1_shape1GradientStartColor,
      R.styleable.Folivora_Shape1_shape1GradientEndColor,
      R.styleable.Folivora_Shape1_shape1GradientCenterColor,
      R.styleable.Folivora_Shape1_shape1GradientAngle,
      R.styleable.Folivora_Shape1_shape1SolidColor,
      R.styleable.Folivora_Shape1_shape1StrokeWidth,
      R.styleable.Folivora_Shape1_shape1StrokeColor,
      R.styleable.Folivora_Shape1_shape1StokeDashGap,
      R.styleable.Folivora_Shape1_shape1StokeDashWidth,
      R.styleable.Folivora_Shape1_shape1CornerRadius,
      R.styleable.Folivora_Shape1_shape1CornerRadiusTopLeft,
      R.styleable.Folivora_Shape1_shape1CornerRadiusTopRight,
      R.styleable.Folivora_Shape1_shape1CornerRadiusBottomRight,
      R.styleable.Folivora_Shape1_shape1CornerRadiusBottomLeft
    ),
    new ShapeAttrs(
      R.styleable.Folivora_Shape2,
      R.styleable.Folivora_Shape2_shape2Type,
      R.styleable.Folivora_Shape2_shape2SolidSize,
      R.styleable.Folivora_Shape2_shape2SolidWidth,
      R.styleable.Folivora_Shape2_shape2SolidHeight,
      R.styleable.Folivora_Shape2_shape2GradientType,
      R.styleable.Folivora_Shape2_shape2GradientRadius,
      R.styleable.Folivora_Shape2_shape2GradientCenterX,
      R.styleable.Folivora_Shape2_shape2GradientCenterY,
      R.styleable.Folivora_Shape2_shape2GradientStartColor,
      R.styleable.Folivora_Shape2_shape2GradientEndColor,
      R.styleable.Folivora_Shape2_shape2GradientCenterColor,
      R.styleable.Folivora_Shape2_shape2GradientAngle,
      R.styleable.Folivora_Shape2_shape2SolidColor,
      R.styleable.Folivora_Shape2_shape2StrokeWidth,
      R.styleable.Folivora_Shape2_shape2StrokeColor,
      R.styleable.Folivora_Shape2_shape2StokeDashGap,
      R.styleable.Folivora_Shape2_shape2StokeDashWidth,
      R.styleable.Folivora_Shape2_shape2CornerRadius,
      R.styleable.Folivora_Shape2_shape2CornerRadiusTopLeft,
      R.styleable.Folivora_Shape2_shape2CornerRadiusTopRight,
      R.styleable.Folivora_Shape2_shape2CornerRadiusBottomRight,
      R.styleable.Folivora_Shape2_shape2CornerRadiusBottomLeft
    ),
    new ShapeAttrs(
      R.styleable.Folivora_Shape3,
      R.styleable.Folivora_Shape3_shape3Type,
      R.styleable.Folivora_Shape3_shape3SolidSize,
      R.styleable.Folivora_Shape3_shape3SolidWidth,
      R.styleable.Folivora_Shape3_shape3SolidHeight,
      R.styleable.Folivora_Shape3_shape3GradientType,
      R.styleable.Folivora_Shape3_shape3GradientRadius,
      R.styleable.Folivora_Shape3_shape3GradientCenterX,
      R.styleable.Folivora_Shape3_shape3GradientCenterY,
      R.styleable.Folivora_Shape3_shape3GradientStartColor,
      R.styleable.Folivora_Shape3_shape3GradientEndColor,
      R.styleable.Folivora_Shape3_shape3GradientCenterColor,
      R.styleable.Folivora_Shape3_shape3GradientAngle,
      R.styleable.Folivora_Shape3_shape3SolidColor,
      R.styleable.Folivora_Shape3_shape3StrokeWidth,
      R.styleable.Folivora_Shape3_shape3StrokeColor,
      R.styleable.Folivora_Shape3_shape3StokeDashGap,
      R.styleable.Folivora_Shape3_shape3StokeDashWidth,
      R.styleable.Folivora_Shape3_shape3CornerRadius,
      R.styleable.Folivora_Shape3_shape3CornerRadiusTopLeft,
      R.styleable.Folivora_Shape3_shape3CornerRadiusTopRight,
      R.styleable.Folivora_Shape3_shape3CornerRadiusBottomRight,
      R.styleable.Folivora_Shape3_shape3CornerRadiusBottomLeft
    ),
    new ShapeAttrs(
      R.styleable.Folivora_Shape4,
      R.styleable.Folivora_Shape4_shape4Type,
      R.styleable.Folivora_Shape4_shape4SolidSize,
      R.styleable.Folivora_Shape4_shape4SolidWidth,
      R.styleable.Folivora_Shape4_shape4SolidHeight,
      R.styleable.Folivora_Shape4_shape4GradientType,
      R.styleable.Folivora_Shape4_shape4GradientRadius,
      R.styleable.Folivora_Shape4_shape4GradientCenterX,
      R.styleable.Folivora_Shape4_shape4GradientCenterY,
      R.styleable.Folivora_Shape4_shape4GradientStartColor,
      R.styleable.Folivora_Shape4_shape4GradientEndColor,
      R.styleable.Folivora_Shape4_shape4GradientCenterColor,
      R.styleable.Folivora_Shape4_shape4GradientAngle,
      R.styleable.Folivora_Shape4_shape4SolidColor,
      R.styleable.Folivora_Shape4_shape4StrokeWidth,
      R.styleable.Folivora_Shape4_shape4StrokeColor,
      R.styleable.Folivora_Shape4_shape4StokeDashGap,
      R.styleable.Folivora_Shape4_shape4StokeDashWidth,
      R.styleable.Folivora_Shape4_shape4CornerRadius,
      R.styleable.Folivora_Shape4_shape4CornerRadiusTopLeft,
      R.styleable.Folivora_Shape4_shape4CornerRadiusTopRight,
      R.styleable.Folivora_Shape4_shape4CornerRadiusBottomRight,
      R.styleable.Folivora_Shape4_shape4CornerRadiusBottomLeft
    )
  };

  static ShapeAttrs forIndex(int index) {
    if (index < 0 || index > 4) {
      return null;
    } else {
      return SHAPE_ATTRS_ARRAY[index];
    }
  }
}

================================================
FILE: folivora/src/main/res/values/attrs.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!--
  * Copyright (C) 2019 Cricin
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *         http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
-->

<resources>

  <!--shape-->
  <declare-styleable name="Folivora_Shape">
    <attr name="shapeType" format="enum">
      <enum name="rectangle" value="0"/>
      <enum name="oval" value="1"/>
      <enum name="line" value="2"/>
      <enum name="ring" value="3"/>
    </attr>

    <attr name="shapeSolidSize" format="dimension"/>
    <attr name="shapeSolidWidth" format="dimension"/>
    <attr name="shapeSolidHeight" format="dimension"/>
    <attr name="shapeSolidColor" format="color"/>

    <attr name="shapeStrokeWidth" format="dimension"/>
    <attr name="shapeStrokeColor" format="color"/>
    <attr name="shapeStokeDashWidth" format="dimension"/>
    <attr name="shapeStokeDashGap" format="dimension"/>

    <attr name="shapeCornerRadius" format="dimension"/>
    <attr name="shapeCornerRadiusTopLeft" format="dimension"/>
    <attr name="shapeCornerRadiusTopRight" format="dimension"/>
    <attr name="shapeCornerRadiusBottomLeft" format="dimension"/>
    <attr name="shapeCornerRadiusBottomRight" format="dimension"/>

    <attr name="shapeGradientType" format="enum">
      <enum name="linear" value="0"/>
      <enum name="radial" value="1"/>
      <enum name="sweep" value="2"/>
    </attr>
    <attr name="shapeGradientAngle" format="enum">
      <enum name="tb" value="0"/>
      <enum name="tr_bl" value="1"/>
      <enum name="rl" value="2"/>
      <enum name="br_tl" value="3"/>
      <enum name="bt" value="4"/>
      <enum name="bl_tr" value="5"/>
      <enum name="lr" value="6"/>
      <enum name="tl_br" value="7"/>

    </attr>
    <attr name="shapeGradientStartColor" format="color"/>
    <attr name="shapeGradientCenterColor" format="color"/>
    <attr name="shapeGradientEndColor" format="color"/>
    <attr name="shapeGradientRadius" format="dimension"/>
    <attr name="shapeGradientCenterX" format="float"/>
    <attr name="shapeGradientCenterY" format="float"/>

  </declare-styleable>

  <!--shape1-->
  <declare-styleable name="Folivora_Shape1">
    <attr name="shape1Type" format="enum">
      <enum name="rectangle" value="0"/>
      <enum name="oval" value="1"/>
      <enum name="line" value="2"/>
      <enum name="ring" value="3"/>
    </attr>

    <attr name="shape1SolidSize" format="dimension"/>
    <attr name="shape1SolidWidth" format="dimension"/>
    <attr name="shape1SolidHeight" format="dimension"/>
    <attr name="shape1SolidColor" format="color"/>

    <attr name="shape1StrokeWidth" format="dimension"/>
    <attr name="shape1StrokeColor" format="color"/>
    <attr name="shape1StokeDashWidth" format="dimension"/>
    <attr name="shape1StokeDashGap" format="dimension"/>

    <attr name="shape1CornerRadius" format="dimension"/>
    <attr name="shape1CornerRadiusTopLeft" format="dimension"/>
    <attr name="shape1CornerRadiusTopRight" format="dimension"/>
    <attr name="shape1CornerRadiusBottomLeft" format="dimension"/>
    <attr name="shape1CornerRadiusBottomRight" format="dimension"/>

    <attr name="shape1GradientType" format="enum">
      <enum name="linear" value="0"/>
      <enum name="radial" value="1"/>
      <enum name="sweep" value="2"/>
    </attr>
    <attr name="shape1GradientAngle" format="enum">
      <enum name="tb" value="0"/>
      <enum name="tr_bl" value="1"/>
      <enum name="rl" value="2"/>
      <enum name="br_tl" value="3"/>
      <enum name="bt" value="4"/>
      <enum name="bl_tr" value="5"/>
      <enum name="lr" value="6"/>
      <enum name="tl_br" value="7"/>

    </attr>
    <attr name="shape1GradientStartColor" format="color"/>
    <attr name="shape1GradientCenterColor" format="color"/>
    <attr name="shape1GradientEndColor" format="color"/>
    <attr name="shape1GradientRadius" format="dimension"/>
    <attr name="shape1GradientCenterX" format="float"/>
    <attr name="shape1GradientCenterY" format="float"/>

  </declare-styleable>

  <!--shape2-->
  <declare-styleable name="Folivora_Shape2">
    <attr name="shape2Type" format="enum">
      <enum name="rectangle" value="0"/>
      <enum name="oval" value="1"/>
      <enum name="line" value="2"/>
      <enum name="ring" value="3"/>
    </attr>

    <attr name="shape2SolidSize" format="dimension"/>
    <attr name="shape2SolidWidth" format="dimension"/>
    <attr name="shape2SolidHeight" format="dimension"/>
    <attr name="shape2SolidColor" format="color"/>

    <attr name="shape2StrokeWidth" format="dimension"/>
    <attr name="shape2StrokeColor" format="color"/>
    <attr name="shape2StokeDashWidth" format="dimension"/>
    <attr name="shape2StokeDashGap" format="dimension"/>

    <attr name="shape2CornerRadius" format="dimension"/>
    <attr name="shape2CornerRadiusTopLeft" format="dimension"/>
    <attr name="shape2CornerRadiusTopRight" format="dimension"/>
    <attr name="shape2CornerRadiusBottomLeft" format="dimension"/>
    <attr name="shape2CornerRadiusBottomRight" format="dimension"/>

    <attr name="shape2GradientType" format="enum">
      <enum name="linear" value="0"/>
      <enum name="radial" value="1"/>
      <enum name="sweep" value="2"/>
    </attr>
    <attr name="shape2GradientAngle" format="enum">
      <enum name="tb" value="0"/>
      <enum name="tr_bl" value="1"/>
      <enum name="rl" value="2"/>
      <enum name="br_tl" value="3"/>
      <enum name="bt" value="4"/>
      <enum name="bl_tr" value="5"/>
      <enum name="lr" value="6"/>
      <enum name="tl_br" value="7"/>

    </attr>
    <attr name="shape2GradientStartColor" format="color"/>
    <attr name="shape2GradientCenterColor" format="color"/>
    <attr name="shape2GradientEndColor" format="color"/>
    <attr name="shape2GradientRadius" format="dimension"/>
    <attr name="shape2GradientCenterX" format="float"/>
    <attr name="shape2GradientCenterY" format="float"/>

  </declare-styleable>

  <!--shape3-->
  <declare-styleable name="Folivora_Shape3">
    <attr name="shape3Type" format="enum">
      <enum name="rectangle" value="0"/>
      <enum name="oval" value="1"/>
      <enum name="line" value="2"/>
      <enum name="ring" value="3"/>
    </attr>

    <attr name="shape3SolidSize" format="dimension"/>
    <attr name="shape3SolidWidth" format="dimension"/>
    <attr name="shape3SolidHeight" format="dimension"/>
    <attr name="shape3SolidColor" format="color"/>

    <attr name="shape3StrokeWidth" format="dimension"/>
    <attr name="shape3StrokeColor" format="color"/>
    <attr name="shape3StokeDashWidth" format="dimension"/>
    <attr name="shape3StokeDashGap" format="dimension"/>

    <attr name="shape3CornerRadius" format="dimension"/>
    <attr name="shape3CornerRadiusTopLeft" format="dimension"/>
    <attr name="shape3CornerRadiusTopRight" format="dimension"/>
    <attr name="shape3CornerRadiusBottomLeft" format="dimension"/>
    <attr name="shape3CornerRadiusBottomRight" format="dimension"/>

    <attr name="shape3GradientType" format="enum">
      <enum name="linear" value="0"/>
      <enum name="radial" value="1"/>
      <enum name="sweep" value="2"/>
    </attr>
    <attr name="shape3GradientAngle" format="enum">
      <enum name="tb" value="0"/>
      <enum name="tr_bl" value="1"/>
      <enum name="rl" value="2"/>
      <enum name="br_tl" value="3"/>
      <enum name="bt" value="4"/>
      <enum name="bl_tr" value="5"/>
      <enum name="lr" value="6"/>
      <enum name="tl_br" value="7"/>

    </attr>
    <attr name="shape3GradientStartColor" format="color"/>
    <attr name="shape3GradientCenterColor" format="color"/>
    <attr name="shape3GradientEndColor" format="color"/>
    <attr name="shape3GradientRadius" format="dimension"/>
    <attr name="shape3GradientCenterX" format="float"/>
    <attr name="shape3GradientCenterY" format="float"/>

  </declare-styleable>

  <!--shape4-->
  <declare-styleable name="Folivora_Shape4">
    <attr name="shape4Type" format="enum">
      <enum name="rectangle" value="0"/>
      <enum name="oval" value="1"/>
      <enum name="line" value="2"/>
      <enum name="ring" value="3"/>
    </attr>

    <attr name="shape4SolidSize" format="dimension"/>
    <attr name="shape4SolidWidth" format="dimension"/>
    <attr name="shape4SolidHeight" format="dimension"/>
    <attr name="shape4SolidColor" format="color"/>

    <attr name="shape4StrokeWidth" format="dimension"/>
    <attr name="shape4StrokeColor" format="color"/>
    <attr name="shape4StokeDashWidth" format="dimension"/>
    <attr name="shape4StokeDashGap" format="dimension"/>

    <attr name="shape4CornerRadius" format="dimension"/>
    <attr name="shape4CornerRadiusTopLeft" format="dimension"/>
    <attr name="shape4CornerRadiusTopRight" format="dimension"/>
    <attr name="shape4CornerRadiusBottomLeft" format="dimension"/>
    <attr name="shape4CornerRadiusBottomRight" format="dimension"/>

    <attr name="shape4GradientType" format="enum">
      <enum name="linear" value="0"/>
      <enum name="radial" value="1"/>
      <enum name="sweep" value="2"/>
    </attr>
    <attr name="shape4GradientAngle" format="enum">
      <enum name="tb" value="0"/>
      <enum name="tr_bl" value="1"/>
      <enum name="rl" value="2"/>
      <enum name="br_tl" value="3"/>
      <enum name="bt" value="4"/>
      <enum name="bl_tr" value="5"/>
      <enum name="lr" value="6"/>
      <enum name="tl_br" value="7"/>

    </attr>
    <attr name="shape4GradientStartColor" format="color"/>
    <attr name="shape4GradientCenterColor" format="color"/>
    <attr name="shape4GradientEndColor" format="color"/>
    <attr name="shape4GradientRadius" format="dimension"/>
    <attr name="shape4GradientCenterX" format="float"/>
    <attr name="shape4GradientCenterY" format="float"/>

  </declare-styleable>

  <!--selector-->
  <declare-styleable name="Folivora_Selector">
    <attr name="selectorStateFirst" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateMiddle" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateLast" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateActive" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateActivated" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateAccelerate" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateChecked" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateCheckable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateEnabled" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateFocused" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStatePressed" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateSelected" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateSingle" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateHovered" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateWindowFocused" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorStateNormal" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorItem0States" format="flags">
      <flag name="first" value="0x1"/>
      <flag name="firstNot" value="0x2"/>
      <flag name="middle" value="0x4"/>
      <flag name="middleNot" value="0x8"/>
      <flag name="last" value="0x10"/>
      <flag name="lastNot" value="0x20"/>
      <flag name="active" value="0x40"/>
      <flag name="activeNot" value="0x80"/>
      <flag name="activated" value="0x100"/>
      <flag name="activatedNot" value="0x200"/>
      <flag name="accelerate" value="0x400"/>
      <flag name="accelerateNot" value="0x800"/>
      <flag name="checked" value="0x1000"/>
      <flag name="checkedNot" value="0x2000"/>
      <flag name="checkable" value="0x4000"/>
      <flag name="checkableNot" value="0x8000"/>
      <flag name="enabled" value="0x10000"/>
      <flag name="enableNot" value="0x20000"/>
      <flag name="focused" value="0x40000"/>
      <flag name="focusedNot" value="0x80000"/>
      <flag name="pressed" value="0x100000"/>
      <flag name="pressedNot" value="0x200000"/>
      <flag name="selected" value="0x400000"/>
      <flag name="selectedNot" value="0x800000"/>
      <flag name="single" value="0x1000000"/>
      <flag name="singleNot" value="0x2000000"/>
      <flag name="hovered" value="0x4000000"/>
      <flag name="hoveredNot" value="0x8000000"/>
      <flag name="windowFocused" value="0x10000000"/>
      <flag name="windowFocusedNot" value="0x20000000"/>
    </attr>
    <attr name="selectorItem0Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorItem1States" format="flags">
      <flag name="first" value="0x1"/>
      <flag name="firstNot" value="0x2"/>
      <flag name="middle" value="0x4"/>
      <flag name="middleNot" value="0x8"/>
      <flag name="last" value="0x10"/>
      <flag name="lastNot" value="0x20"/>
      <flag name="active" value="0x40"/>
      <flag name="activeNot" value="0x80"/>
      <flag name="activated" value="0x100"/>
      <flag name="activatedNot" value="0x200"/>
      <flag name="accelerate" value="0x400"/>
      <flag name="accelerateNot" value="0x800"/>
      <flag name="checked" value="0x1000"/>
      <flag name="checkedNot" value="0x2000"/>
      <flag name="checkable" value="0x4000"/>
      <flag name="checkableNot" value="0x8000"/>
      <flag name="enabled" value="0x10000"/>
      <flag name="enableNot" value="0x20000"/>
      <flag name="focused" value="0x40000"/>
      <flag name="focusedNot" value="0x80000"/>
      <flag name="pressed" value="0x100000"/>
      <flag name="pressedNot" value="0x200000"/>
      <flag name="selected" value="0x400000"/>
      <flag name="selectedNot" value="0x800000"/>
      <flag name="single" value="0x1000000"/>
      <flag name="singleNot" value="0x2000000"/>
      <flag name="hovered" value="0x4000000"/>
      <flag name="hoveredNot" value="0x8000000"/>
      <flag name="windowFocused" value="0x10000000"/>
      <flag name="windowFocusedNot" value="0x20000000"/>
    </attr>
    <attr name="selectorItem1Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorItem2States" format="flags">
      <flag name="first" value="0x1"/>
      <flag name="firstNot" value="0x2"/>
      <flag name="middle" value="0x4"/>
      <flag name="middleNot" value="0x8"/>
      <flag name="last" value="0x10"/>
      <flag name="lastNot" value="0x20"/>
      <flag name="active" value="0x40"/>
      <flag name="activeNot" value="0x80"/>
      <flag name="activated" value="0x100"/>
      <flag name="activatedNot" value="0x200"/>
      <flag name="accelerate" value="0x400"/>
      <flag name="accelerateNot" value="0x800"/>
      <flag name="checked" value="0x1000"/>
      <flag name="checkedNot" value="0x2000"/>
      <flag name="checkable" value="0x4000"/>
      <flag name="checkableNot" value="0x8000"/>
      <flag name="enabled" value="0x10000"/>
      <flag name="enableNot" value="0x20000"/>
      <flag name="focused" value="0x40000"/>
      <flag name="focusedNot" value="0x80000"/>
      <flag name="pressed" value="0x100000"/>
      <flag name="pressedNot" value="0x200000"/>
      <flag name="selected" value="0x400000"/>
      <flag name="selectedNot" value="0x800000"/>
      <flag name="single" value="0x1000000"/>
      <flag name="singleNot" value="0x2000000"/>
      <flag name="hovered" value="0x4000000"/>
      <flag name="hoveredNot" value="0x8000000"/>
      <flag name="windowFocused" value="0x10000000"/>
      <flag name="windowFocusedNot" value="0x20000000"/>
    </attr>
    <attr name="selectorItem2Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorItem3States" format="flags">
      <flag name="first" value="0x1"/>
      <flag name="firstNot" value="0x2"/>
      <flag name="middle" value="0x4"/>
      <flag name="middleNot" value="0x8"/>
      <flag name="last" value="0x10"/>
      <flag name="lastNot" value="0x20"/>
      <flag name="active" value="0x40"/>
      <flag name="activeNot" value="0x80"/>
      <flag name="activated" value="0x100"/>
      <flag name="activatedNot" value="0x200"/>
      <flag name="accelerate" value="0x400"/>
      <flag name="accelerateNot" value="0x800"/>
      <flag name="checked" value="0x1000"/>
      <flag name="checkedNot" value="0x2000"/>
      <flag name="checkable" value="0x4000"/>
      <flag name="checkableNot" value="0x8000"/>
      <flag name="enabled" value="0x10000"/>
      <flag name="enableNot" value="0x20000"/>
      <flag name="focused" value="0x40000"/>
      <flag name="focusedNot" value="0x80000"/>
      <flag name="pressed" value="0x100000"/>
      <flag name="pressedNot" value="0x200000"/>
      <flag name="selected" value="0x400000"/>
      <flag name="selectedNot" value="0x800000"/>
      <flag name="single" value="0x1000000"/>
      <flag name="singleNot" value="0x2000000"/>
      <flag name="hovered" value="0x4000000"/>
      <flag name="hoveredNot" value="0x8000000"/>
      <flag name="windowFocused" value="0x10000000"/>
      <flag name="windowFocusedNot" value="0x20000000"/>
    </attr>
    <attr name="selectorItem3Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="selectorItem4States" format="flags">
      <flag name="first" value="0x1"/>
      <flag name="firstNot" value="0x2"/>
      <flag name="middle" value="0x4"/>
      <flag name="middleNot" value="0x8"/>
      <flag name="last" value="0x10"/>
      <flag name="lastNot" value="0x20"/>
      <flag name="active" value="0x40"/>
      <flag name="activeNot" value="0x80"/>
      <flag name="activated" value="0x100"/>
      <flag name="activatedNot" value="0x200"/>
      <flag name="accelerate" value="0x400"/>
      <flag name="accelerateNot" value="0x800"/>
      <flag name="checked" value="0x1000"/>
      <flag name="checkedNot" value="0x2000"/>
      <flag name="checkable" value="0x4000"/>
      <flag name="checkableNot" value="0x8000"/>
      <flag name="enabled" value="0x10000"/>
      <flag name="enableNot" value="0x20000"/>
      <flag name="focused" value="0x40000"/>
      <flag name="focusedNot" value="0x80000"/>
      <flag name="pressed" value="0x100000"/>
      <flag name="pressedNot" value="0x200000"/>
      <flag name="selected" value="0x400000"/>
      <flag name="selectedNot" value="0x800000"/>
      <flag name="single" value="0x1000000"/>
      <flag name="singleNot" value="0x2000000"/>
      <flag name="hovered" value="0x4000000"/>
      <flag name="hoveredNot" value="0x8000000"/>
      <flag name="windowFocused" value="0x10000000"/>
      <flag name="windowFocusedNot" value="0x20000000"/>
    </attr>
    <attr name="selectorItem4Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
  </declare-styleable>

  <!--layer-list-->
  <declare-styleable name="Folivora_Layer">
    <attr name="layerItem0Insets" format="dimension"/>
    <attr name="layerItem0Left" format="dimension"/>
    <attr name="layerItem0Top" format="dimension"/>
    <attr name="layerItem0Right" format="dimension"/>
    <attr name="layerItem0Bottom" format="dimension"/>
    <attr name="layerItem0Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>

    <attr name="layerItem1Insets" format="dimension"/>
    <attr name="layerItem1Left" format="dimension"/>
    <attr name="layerItem1Top" format="dimension"/>
    <attr name="layerItem1Right" format="dimension"/>
    <attr name="layerItem1Bottom" format="dimension"/>
    <attr name="layerItem1Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>

    <attr name="layerItem2Insets" format="dimension"/>
    <attr name="layerItem2Left" format="dimension"/>
    <attr name="layerItem2Top" format="dimension"/>
    <attr name="layerItem2Right" format="dimension"/>
    <attr name="layerItem2Bottom" format="dimension"/>
    <attr name="layerItem2Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>

    <attr name="layerItem3Insets" format="dimension"/>
    <attr name="layerItem3Left" format="dimension"/>
    <attr name="layerItem3Top" format="dimension"/>
    <attr name="layerItem3Right" format="dimension"/>
    <attr name="layerItem3Bottom" format="dimension"/>
    <attr name="layerItem3Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>

    <attr name="layerItem4Insets" format="dimension"/>
    <attr name="layerItem4Left" format="dimension"/>
    <attr name="layerItem4Top" format="dimension"/>
    <attr name="layerItem4Right" format="dimension"/>
    <attr name="layerItem4Bottom" format="dimension"/>
    <attr name="layerItem4Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
  </declare-styleable>

  <!--ripple only worked on Lollipop or higher-->
  <declare-styleable name="Folivora_Ripple">
    <attr name="rippleColor" format="color"/>
    <attr name="rippleMask" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="rippleContent" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
  </declare-styleable>

  <declare-styleable name="Folivora">
    <attr name="setAs" format="enum">
      <enum name="background" value="0"/>
      <enum name="src" value="1"/>
      <enum name="foreground" value="2"/>
    </attr>
    <attr name="drawableType" format="enum">
      <enum name="shape" value="0"/>
      <enum name="selector" value="1"/>
      <enum name="layer_list" value="2"/>
      <enum name="ripple" value="3"/>
      <enum name="level_list" value="4"/>
      <enum name="clip" value="5"/>
      <enum name="inset" value="6"/>
      <enum name="scale" value="7"/>
      <enum name="animation" value="8"/>
    </attr>
    <attr name="drawableName" format="string"/>
    <attr name="drawableId" format="string"/>
  </declare-styleable>

  <!--clip-->
  <declare-styleable name="Folivora_Clip">
    <attr name="clipOrientation" format="enum">
      <enum name="horizontal" value="1"/>
      <enum name="vertical" value="2"/>
    </attr>
    <attr name="clipDrawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="clipLevel" format="integer"/>
    <!-- Keep sync with android.view.Gravity -->
    <attr name="clipGravity" format="flags">
      <!-- Push object to the top of its container, not changing its size. -->
      <flag name="top" value="0x30" />
      <!-- Push object to the bottom of its container, not changing its size. -->
      <flag name="bottom" value="0x50" />
      <!-- Push object to the left of its container, not changing its size. -->
      <flag name="left" value="0x03" />
      <!-- Push object to the right of its container, not changing its size. -->
      <flag name="right" value="0x05" />
      <!-- Place object in the vertical center of its container, not changing its size. -->
      <flag name="center_vertical" value="0x10" />
      <!-- Grow the vertical size of the object if needed so it completely fills its container. -->
      <flag name="fill_vertical" value="0x70" />
      <!-- Place object in the horizontal center of its container, not changing its size. -->
      <flag name="center_horizontal" value="0x01" />
      <!-- Grow the horizontal size of the object if needed so it completely fills its container. -->
      <flag name="fill_horizontal" value="0x07" />
      <!-- Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. -->
      <flag name="center" value="0x11" />
      <!-- Grow the horizontal and vertical size of the object if needed so it completely fills its container. -->
      <flag name="fill" value="0x77" />
      <!-- Additional option that can be set to have the top and/or bottom edges of
           the child clipped to its container's bounds.
           The clip will be based on the vertical gravity: a top gravity will clip the bottom
           edge, a bottom gravity will clip the top edge, and neither will clip both edges. -->
      <flag name="clip_vertical" value="0x80" />
      <!-- Additional option that can be set to have the left and/or right edges of
           the child clipped to its container's bounds.
           The clip will be based on the horizontal gravity: a left gravity will clip the right
           edge, a right gravity will clip the left edge, and neither will clip both edges. -->
      <flag name="clip_horizontal" value="0x08" />
      <!-- Push object to the beginning of its container, not changing its size. -->
      <flag name="start" value="0x00800003" />
      <!-- Push object to the end of its container, not changing its size. -->
      <flag name="end" value="0x00800005" />
    </attr>
  </declare-styleable>

  <!--inset-->
  <declare-styleable name="Folivora_Inset">
    <attr name="insetDrawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="insetAll" format="dimension|fraction"/>
    <attr name="insetLeft" format="dimension|fraction"/>
    <attr name="insetTop" format="dimension|fraction"/>
    <attr name="insetRight" format="dimension|fraction"/>
    <attr name="insetBottom" format="dimension|fraction"/>
  </declare-styleable>

  <!--scale-->
  <declare-styleable name="Folivora_Scale">
    <attr name="scaleLevel" format="integer"/>
    <attr name="scaleDrawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <!-- Keep sync with android.view.Gravity -->
    <attr name="scaleGravity" format="flags">

      <!-- Push object to the top of its container, not changing its size. -->
      <flag name="top" value="0x30" />
      <!-- Push object to the bottom of its container, not changing its size. -->
      <flag name="bottom" value="0x50" />
      <!-- Push object to the left of its container, not changing its size. -->
      <flag name="left" value="0x03" />
      <!-- Push object to the right of its container, not changing its size. -->
      <flag name="right" value="0x05" />
      <!-- Place object in the vertical center of its container, not changing its size. -->
      <flag name="center_vertical" value="0x10" />
      <!-- Grow the vertical size of the object if needed so it completely fills its container. -->
      <flag name="fill_vertical" value="0x70" />
      <!-- Place object in the horizontal center of its container, not changing its size. -->
      <flag name="center_horizontal" value="0x01" />
      <!-- Grow the horizontal size of the object if needed so it completely fills its container. -->
      <flag name="fill_horizontal" value="0x07" />
      <!-- Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. -->
      <flag name="center" value="0x11" />
      <!-- Grow the horizontal and vertical size of the object if needed so it completely fills its container. -->
      <flag name="fill" value="0x77" />
      <!-- Additional option that can be set to have the top and/or bottom edges of
           the child clipped to its container's bounds.
           The clip will be based on the vertical gravity: a top gravity will clip the bottom
           edge, a bottom gravity will clip the top edge, and neither will clip both edges. -->
      <flag name="clip_vertical" value="0x80" />
      <!-- Additional option that can be set to have the left and/or right edges of
           the child clipped to its container's bounds.
           The clip will be based on the horizontal gravity: a left gravity will clip the right
           edge, a right gravity will clip the left edge, and neither will clip both edges. -->
      <flag name="clip_horizontal" value="0x08" />
      <!-- Push object to the beginning of its container, not changing its size. -->
      <flag name="start" value="0x00800003" />
      <!-- Push object to the end of its container, not changing its size. -->
      <flag name="end" value="0x00800005" />

    </attr>
    <attr name="scaleWidth" format="float"/>
    <attr name="scaleHeight" format="float"/>
  </declare-styleable>

  <!--animation-->
  <declare-styleable name="Folivora_Animation">
    <attr name="animAutoPlay" format="boolean"/>
    <attr name="animOneShot" format="boolean"/>
    <attr name="animFrame0" format="reference|color"/>
    <attr name="animFrame1" format="reference|color"/>
    <attr name="animFrame2" format="reference|color"/>
    <attr name="animFrame3" format="reference|color"/>
    <attr name="animFrame4" format="reference|color"/>
    <attr name="animFrame5" format="reference|color"/>
    <attr name="animFrame6" format="reference|color"/>
    <attr name="animFrame7" format="reference|color"/>
    <attr name="animFrame8" format="reference|color"/>
    <attr name="animFrame9" format="reference|color"/>

    <attr name="animDuration" format="integer"/>
    <attr name="animDuration0" format="integer"/>
    <attr name="animDuration1" format="integer"/>
    <attr name="animDuration2" format="integer"/>
    <attr name="animDuration3" format="integer"/>
    <attr name="animDuration4" format="integer"/>
    <attr name="animDuration5" format="integer"/>
    <attr name="animDuration6" format="integer"/>
    <attr name="animDuration7" format="integer"/>
    <attr name="animDuration8" format="integer"/>
    <attr name="animDuration9" format="integer"/>

  </declare-styleable>

  <!--level-->
  <declare-styleable name="Folivora_Level">
    <attr name="levelCurrentLevel" format="integer"/>
    <attr name="levelItem0Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="levelItem0MinLevel" format="integer"/>
    <attr name="levelItem0MaxLevel" format="integer"/>
    <attr name="levelItem1Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="levelItem1MinLevel" format="integer"/>
    <attr name="levelItem1MaxLevel" format="integer"/>
    <attr name="levelItem2Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="levelItem2MinLevel" format="integer"/>
    <attr name="levelItem2MaxLevel" format="integer"/>
    <attr name="levelItem3Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="levelItem3MinLevel" format="integer"/>
    <attr name="levelItem3MaxLevel" format="integer"/>
    <attr name="levelItem4Drawable" format="reference|color|enum">
      <enum name="shape" value="0"/>
      <enum name="shape1" value="1"/>
      <enum name="shape2" value="2"/>
      <enum name="shape3" value="3"/>
      <enum name="shape4" value="4"/>
    </attr>
    <attr name="levelItem4MinLevel" format="integer"/>
    <attr name="levelItem4MaxLevel" format="integer"/>
  </declare-styleable>


</resources>

================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sat Mar 21 17:57:59 CST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip

================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.useAndroidX=true

================================================
FILE: gradlew
================================================
#!/usr/bin/env sh

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    echo "$*"
}

die () {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
  cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"


================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: lint/build.gradle
================================================
apply plugin: 'java'

def ideInstallationDir = new File('d:/android/studio')
def androidPluginLibPath = 'plugins/android/lib'
def lintVersion = '26.2.0-alpha06'

configurations.all {
  transitive = false
}

dependencies {
  compileOnly "com.android.tools.lint:lint-api:$lintVersion"
  compileOnly "com.android.tools.lint:lint-checks:$lintVersion"
  compileOnly "com.android.tools.lint:lint:$lintVersion"
  compileOnly "com.android.tools.external.org-jetbrains:uast:$lintVersion"
  compileOnly "com.android.tools.external.com-intellij:intellij-core:$lintVersion"
  compileOnly 'com.android.tools:common:26.6.1'
  compileOnly 'com.android.tools.layoutlib:layoutlib-api:26.6.1'
  if (ideInstallationDir.exists() && ideInstallationDir.isDirectory()) {
     ["${androidPluginLibPath}/android.jar",
     'lib/openapi.jar',
     'lib/platform-api.jar',
     'lib/idea.jar'
    ].each { lib ->
       def file = new File(ideInstallationDir, lib)
       if(!file.exists()) throw new Exception("file $file does not exist")
      compileOnly files(file)
    }
    def legacyLayoutLib = new File("${androidPluginLibPath}/layoutlib.jar")
    def layoutLib = new File(ideInstallationDir, "plugins/android-layoutlib/lib/layoutlib.jar")
    if (legacyLayoutLib.exists()) {
      compileOnly files(legacyLayoutLib)
    } else if(layoutLib.exists()) {
      compileOnly files(layoutLib)
    } else {
      throw new Exception("layoutlib does not exist")
    }
  } else {
    throw new GradleException('Invalid ide installation dir')
  }
}

jar {
  manifest {
    attributes("Lint-Registry-v2": "cn.cricin.folivora.lint.FolivoraIssueRegistry")
    attributes("Lint-Registry": "cn.cricin.folivora.lint.FolivoraIssueRegistry")
  }
  archiveName('folivora-lint.jar')
}

task installLint(type: Copy) {
  setGroup('install')
  def jarTask = tasks.findByName('jar')
  dependsOn(jarTask)
  from(jarTask.outputs.files)
  into(new File(new File(System.getProperty("user.home")), '.android/lint/'))
}

task uninstallLint() {
  setGroup('install')
  doFirst {
    File lintLibDir = new File(new File(System.getProperty("user.home")), '.android/lint')
    def folivoraLintJar = new File(lintLibDir, 'folivora-lint.jar')
    if (folivoraLintJar.exists()) {
      folivoraLintJar.delete()
    }
  }
}

================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/AndroidFacetCompat.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora.dom;

import com.android.tools.idea.model.AndroidModel;
import com.intellij.openapi.util.Pair;

import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.resourceManagers.LocalResourceManager;
import org.jetbrains.android.resourceManagers.ModuleResourceManagers;
import org.jetbrains.android.resourceManagers.ResourceManager;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Since the API of AndroidFacet class changed so frequently
 * in different version of Android Studio, a compat utility
 * is needed for those API changes.
 */
final class AndroidFacetCompat {
  private static boolean sModuleResourceManagerExists = true;

  static ResourceManager getAppResourceManager(AndroidFacet facet) {
    ResourceManager manager = null;
    if (sModuleResourceManagerExists) {
      try {
        manager = ModuleResourceManagers.getInstance(facet).getResourceManager(null);
      } catch (Throwable ignore) {
        sModuleResourceManagerExists = false;
      }
    }
    if (!sModuleResourceManagerExists) {
      manager = LocalResourceManager.getInstance(facet.getModule());
    }
    return manager;
  }

  /**
   * Added for android studio 3.0
   */
  static boolean isAppProject(AndroidFacet facet) {
    Boolean value = invoke(AndroidFacet.class, "isAppProject", facet, null, null, new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        return facet.getConfiguration().isAppProject();
      }
    });
    return value != null && value;
  }

  /**
   * Added for android studio 4.0 canary release
   */
  static boolean requiresAndroidModel(AndroidFacet facet) {
    Boolean value = invoke(AndroidModel.class, "isRequired", null, new Class[]{AndroidFacet.class}, new Object[]{facet}, new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        return facet.requiresAndroidModel();
      }
    });
    return value != null && value;
  }

  /**
   * Added for android studio 4.0 canary release
   */
  static Manifest getManifest(AndroidFacet facet) {
    return invoke(AndroidFacet.class, "getManifest", facet, null, null, new Callable<Manifest>() {
      @Override
      public Manifest call() throws Exception {
        return Manifest.getMainManifest(facet);
      }
    });
  }

  private static Map<Pair<Class<?>, String>, Method> sInvokableMethods = new HashMap<>();

  @SuppressWarnings("unchecked")
  private static <R> R invoke(Class<?> clazz, String methodName, Object receiver, Class<?>[] argClasses, Object[] args, Callable<R> c) {
    final Pair<Class<?>, String> pair = Pair.create(clazz, methodName);
    Method method = sInvokableMethods.get(pair);
    if (method != null) {
      try {
        return (R) method.invoke(receiver, args);
      } catch (Throwable ignore) {
      }
    }
    try {
      return c.call();
    } catch (Throwable ignore) {
    }
    try {
      method = clazz.getDeclaredMethod(methodName, argClasses);
      Object result = method.invoke(receiver, args);
      sInvokableMethods.put(pair, method);
      return (R) result;
    } catch (Throwable ignore) {
    }
    return null;
  }

  private AndroidFacetCompat() {
  }
}

================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/DrawableIdConverter.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora.dom;

import com.android.SdkConstants;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.xml.ConvertContext;
import com.intellij.util.xml.ResolvingConverter;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * This converter keeps track app:drawableId values used
 * in project, and gives cached candidates when use drawableId
 */
public class DrawableIdConverter extends ResolvingConverter<String> {

  @NotNull
  @Override
  public Collection<? extends String> getVariants(ConvertContext convertContext) {
    if (convertContext == null) return Collections.emptyList();
    XmlFile file = convertContext.getFile();
    final Set<String> drawableIds = new HashSet<>();
    file.accept(new PsiRecursiveElementVisitor() {
      @Override
      public void visitElement(PsiElement element) {
        super.visitElement(element);
        if (element instanceof XmlTag) {
          String drawableId = ((XmlTag) element).getAttributeValue("drawableId", SdkConstants.AUTO_URI);
          if(drawableId != null && !drawableId.isEmpty()) {
            drawableIds.add(drawableId);
          }
        }
      }
    });
    return new ArrayList<>(drawableIds);
  }

  @Nullable
  @Override
  public String fromString(@Nullable String s, ConvertContext convertContext) {
    return s;
  }

  @Nullable
  @Override
  public String toString(@Nullable String s, ConvertContext convertContext) {
    return s;
  }

}


================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraAttrProcessing.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora.dom;

import com.android.SdkConstants;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.xml.Converter;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.XmlName;
import com.intellij.util.xml.reflect.DomExtension;

import org.jetbrains.android.dom.AndroidDomElement;
import org.jetbrains.android.dom.AndroidDomUtil;
import org.jetbrains.android.dom.AttributeProcessingUtil;
import org.jetbrains.android.dom.attrs.AttributeDefinition;
import org.jetbrains.android.dom.attrs.AttributeDefinitions;
import org.jetbrains.android.dom.attrs.StyleableDefinition;
import org.jetbrains.android.dom.attrs.ToolsAttributeUtil;
import org.jetbrains.android.dom.converters.CompositeConverter;
import org.jetbrains.android.dom.converters.PackageClassConverter;
import org.jetbrains.android.dom.converters.ResourceReferenceConverter;
import org.jetbrains.android.dom.layout.DataBindingElement;
import org.jetbrains.android.dom.layout.LayoutElement;
import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.resourceManagers.ResourceManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * Process folivora attr's to the current dom element
 */
final class FolivoraAttrProcessing {
  /**
   * If this attr name exists in xml tag, it's value is treated as
   * declare styleables, folivora will also register these attributes
   * to current xml tag.
   */
  private static final String EXTRA_STYLEABLE_ATTR_NAME = "extraStyleables";
  /**
   * This converter is used to find custom drawable classes in current project
   */
  private static final PackageClassConverter DRAWABLE_CLASS_CONVERTER =
    new PackageClassConverter("android.graphics.drawable.Drawable");
  private static final DrawableIdConverter DRAWABLE_ID_CONVERTER = new DrawableIdConverter();
  private static final HashMap<String, String> TYPE_TO_STYLEABLE = new HashMap<>();
  private static final HashMap<String, String> SHAPE_TO_STYLEABLE = new HashMap<>();

  static {
    TYPE_TO_STYLEABLE.put("shape", "Folivora_Shape");
    TYPE_TO_STYLEABLE.put("selector", "Folivora_Selector");
    TYPE_TO_STYLEABLE.put("layer_list", "Folivora_Layer");
    TYPE_TO_STYLEABLE.put("ripple", "Folivora_Ripple");
    TYPE_TO_STYLEABLE.put("level_list", "Folivora_Level");
    TYPE_TO_STYLEABLE.put("clip", "Folivora_Clip");
    TYPE_TO_STYLEABLE.put("inset", "Folivora_Inset");
    TYPE_TO_STYLEABLE.put("scale", "Folivora_Scale");
    TYPE_TO_STYLEABLE.put("animation", "Folivora_Animation");

    SHAPE_TO_STYLEABLE.put("shape", "Folivora_Shape");
    SHAPE_TO_STYLEABLE.put("shape1", "Folivora_Shape1");
    SHAPE_TO_STYLEABLE.put("shape2", "Folivora_Shape2");
    SHAPE_TO_STYLEABLE.put("shape3", "Folivora_Shape3");
    SHAPE_TO_STYLEABLE.put("shape4", "Folivora_Shape4");
  }

  static void registerFolivoraAttributes(AndroidFacet facet,
                                         AndroidDomElement element,
                                         AttributeProcessingUtil.AttributeProcessor callback) {
    if (!(element instanceof LayoutElement)) return;
    if (element instanceof DataBindingElement) return;
    XmlTag tag = element.getXmlTag();
    if (tag == null) return;
    if (isInvalidTagName(tag.getName())) return;
    List<String> styleableNames = getStyleablesToRegister(tag.getAttributes());
    for (String styleableName : styleableNames) {
      if (styleableName != null && styleableName.length() > 0) {
        registerAttributes(facet, element, styleableName, callback);
      }
    }
  }

  private static List<String> getStyleablesToRegister(XmlAttribute[] attrs) {
    List<String> styleableNames = new ArrayList<>(6);
    styleableNames.add("Folivora");
    String drawableType = null;
    String drawableName = null;
    for (XmlAttribute attr : attrs) {
      String attrName = attr.getLocalName();
      String attrValue = attr.getValue();
      if ("drawableType".equals(attrName)) {
        drawableType = attrValue;
      } else if ("drawableName".equals(attrName)) {
        drawableName = attrValue;
      } else if (EXTRA_STYLEABLE_ATTR_NAME.equals(attrName) && attrValue != null) {
        if (attrValue.indexOf(',') != -1) {
          styleableNames.addAll(Arrays.asList(attrValue.split(",")));
        } else {
          styleableNames.add(attrValue);
        }
      }
    }
    if (drawableType == null && drawableName == null) return styleableNames;
    if (drawableType != null) styleableNames.add(TYPE_TO_STYLEABLE.get(drawableType));
    if (drawableName != null) styleableNames.add(getSimpleClassName(drawableName));

    // process nested shapes
    String styleable;
    for (XmlAttribute attr : attrs) {
      String attrName = attr.getLocalName();
      String attrValue = attr.getValue();
      if (attrName.startsWith("shape1")
        || attrName.startsWith("shape2")
        || attrName.startsWith("shape3")
        || attrName.startsWith("shape4")) continue;
      styleable = SHAPE_TO_STYLEABLE.get(attrValue);
      if (styleable == null) continue;
      if (drawableType != null && attrName.startsWith(drawableType)) {
        styleableNames.add(styleable);
      } else if (drawableName != null) {
        // if is custom drawable, we don't know whether this drawable
        // need nested shapes, so register nested shape anyway
        styleableNames.add(styleable);
      }
    }
    return styleableNames;
  }

  private static String getSimpleClassName(String className) {
    if (className == null) return null;
    int dotIndex = className.lastIndexOf('.');
    if (dotIndex == -1 || dotIndex + 1 >= className.length()) return null;
    return className.substring(dotIndex + 1);
  }

  private static boolean isInvalidTagName(String tagName) {
    return "layout".equals(tagName)
      || "fragment".equals(tagName)
      || "include".equals(tagName)
      || "requestFocus".equals(tagName)
      || "merge".equals(tagName);
  }

  private static void registerAttributes(/*NotNull*/ AndroidFacet facet,
    /*NotNull*/ DomElement element,
    /*NotNull*/ String styleableName,
    /*NotNull*/ AttributeProcessingUtil.AttributeProcessor callback) {

    ResourceManager manager = AndroidFacetCompat.getAppResourceManager(facet);
    if (manager == null) {
      return;
    }

    AttributeDefinitions attrDefs = manager.getAttributeDefinitions();
    if (attrDefs == null) {
      return;
    }

    String namespace = getNamespaceUriByResourcePackage(facet, null);
    StyleableDefinition styleable = attrDefs.getStyleableByName(styleableName);
    if (styleable != null) {
      registerStyleableAttributes(element, styleable, namespace, callback);
    }
    // It's a good idea to add a warning when styleable not found, to make sure that code doesn't
    // try to use attributes that don't exist. However, current AndroidDomExtender code relies on
    // a lot of "heuristics" that fail quite a lot (like adding a bunch of suffixes to short
    // class names)
    // TODO: add a warning when rest of the code of AndroidDomExtender is cleaned up
  }

  /*Nullable*/
  private static String getNamespaceUriByResourcePackage(/*NotNull*/ AndroidFacet facet,
    /*Nullable*/ String resPackage) {
    if (resPackage == null) {
      if (!AndroidFacetCompat.isAppProject(facet)|| AndroidFacetCompat.requiresAndroidModel(facet)) {
        return SdkConstants.AUTO_URI;
      }
      Manifest manifest = AndroidFacetCompat.getManifest(facet);
      if (manifest != null) {
        String aPackage = manifest.getPackage().getValue();
        if (aPackage != null && !aPackage.isEmpty()) {
          return SdkConstants.URI_PREFIX + aPackage;
        }
      }
    } else if (resPackage.equals(SdkConstants.ANDROID_NS_NAME)) {
      return SdkConstants.ANDROID_URI;
    }
    return null;
  }

  private static void registerStyleableAttributes(
    /*NotNull*/ DomElement element,
    /*NotNull*/ StyleableDefinition styleable,
    /*Nullable*/ String namespaceUri,
    /*NotNull*/ AttributeProcessingUtil.AttributeProcessor callback) {
    for (AttributeDefinition attrDef : styleable.getAttributes()) {
      registerAttribute(attrDef, styleable.getName(), namespaceUri, element, callback);
    }
  }

  private static void registerAttribute(
    AttributeDefinition attrDef,
    String parentStyleableName,
    String namespaceKey,
    DomElement element,
    AttributeProcessingUtil.AttributeProcessor callback) {
    String name = attrDef.getName();
    if (!SdkConstants.ANDROID_URI.equals(namespaceKey) && name.startsWith(SdkConstants.ANDROID_NS_NAME_PREFIX)) {
      name = name.substring(SdkConstants.ANDROID_NS_NAME_PREFIX.length());
      namespaceKey = SdkConstants.ANDROID_URI;
    }

    XmlName xmlName = new XmlName(name, namespaceKey);
    DomExtension extension = callback.processAttribute(xmlName, attrDef, parentStyleableName);
    if (extension != null) {
      Converter converter = AndroidDomUtil.getSpecificConverter(xmlName, element);
      if ("drawableName".equals(name)) {
        converter = DRAWABLE_CLASS_CONVERTER;
      }
      if ("drawableId".equals(name)) {
        converter = DRAWABLE_ID_CONVERTER;
      }
      if (converter == null) {
        if (SdkConstants.TOOLS_URI.equals(namespaceKey)) {
          converter = ToolsAttributeUtil.getConverter(attrDef);
        } else {
          converter = AndroidDomUtil.getConverter(attrDef);
        }
      }

      if (converter != null) {
        extension.setConverter(converter, mustBeSoft(converter, attrDef.getFormats()));
      }
    }
  }

  private static boolean mustBeSoft(Converter converter, Collection formats) {
    if (!(converter instanceof CompositeConverter)
      && !(converter instanceof ResourceReferenceConverter)) {
      return formats.size() > 1;
    } else {
      return false;
    }
  }

  private FolivoraAttrProcessing() {}
}


================================================
FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraDomExtender.java
================================================
/*
 * Copyright (C) 2019 Cricin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.cricin.folivora.dom;

import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.reflect.DomExtender;
import com.intellij.util.xml.reflect.DomExtenderEP;
import com.intellij.util.xml.reflect.DomExtensionsRegistrar;

import org.jetbrains.android.dom.AndroidDomElement;
import org.jetbrains.android.dom.AttributeProcessingUtil;
import org.jetbrains.android.dom.resources.ResourceValue;
import org.jetbrains.android.facet.AndroidFacet;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Set;

import javax.annotation.Nonnull;

@SuppressWarnings("unchecked")
public final class FolivoraDomExtender extends DomExtender<AndroidDomElement> {
  private static HashMap<Object, Class> sValueClasses = new HashMap<>();

  static {
    try {
      Class legacyAttributeFormatClass = Class.forName("org.jetbrains.android.dom.attrs.AttributeFormat");
      sValueClasses.put(Enum.valueOf(legacyAttributeFormatClass, "Boolean"), boolean.class);
      sValueClasses.put(Enum.valueOf(legacyAttributeFormatClass, "Reference"), ResourceValue.class);
      sValueClasses.put(Enum.valueOf(legacyAttributeFormatClass, "Dimension"), ResourceValue.class);
      sValueClasses.put(Enum.valueOf(legacyAttributeFormatClass, "Color"), ResourceValue.class);
    } catch (ClassNotFoundException ignore) {
    }
    try {
      Class.forName("com.android.ide.common.rendering.api.AttributeFormat");
      sValueClasses.put(com.android.ide.common.rendering.api.AttributeFormat.BOOLEAN, boolean.class);
      sValueClasses.put(com.android.ide.common.rendering.api.AttributeFormat.REFERENCE, ResourceValue.class);
      sValueClasses.put(com.android.ide.common.rendering.api.AttributeFormat.DIMENSION, ResourceValue.class);
      sValueClasses.put(com.android.ide.common.rendering.api.AttributeFormat.COLOR, ResourceValue.class);
    } catch (ClassNotFoundException ignore) {
    }
  }

  @Override
  public boolean supportsStubs() {
    return false;
  }

  private static Class getValueClass(Object format) {
    Class cls = sValueClasses.get(format);
    return cls == null ? String.class : cls;
  }

  @Override
  public void registerExtensions(@Nonnull AndroidDomElement element,
                                 @Nonnull final DomExtensionsRegistrar registrar) {
    final AndroidFacet facet = AndroidFacet.getInstance(element);

    if (
Download .txt
gitextract_92jzfoma/

├── .gitignore
├── LICENSE
├── README-zh.md
├── README.md
├── android_release_aar.gradle
├── build.gradle
├── folivora/
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── cn/
│           │       └── cricin/
│           │           └── folivora/
│           │               ├── DrawableParser.java
│           │               ├── Folivora.java
│           │               ├── FolivoraInflater.java
│           │               ├── FolivoraViewFactory.java
│           │               ├── OnViewCreatedListener.java
│           │               ├── ParseRequest.java
│           │               ├── RippleFallback.java
│           │               └── ShapeAttrs.java
│           └── res/
│               └── values/
│                   └── attrs.xml
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── lint/
│   ├── build.gradle
│   └── src/
│       └── main/
│           └── java/
│               └── cn/
│                   └── cricin/
│                       └── folivora/
│                           ├── dom/
│                           │   ├── AndroidFacetCompat.java
│                           │   ├── DrawableIdConverter.java
│                           │   ├── FolivoraAttrProcessing.java
│                           │   └── FolivoraDomExtender.java
│                           ├── lint/
│                           │   ├── FolivoraIssueRegistry.java
│                           │   ├── InstalledBeforeSuperDetector.java
│                           │   ├── InternalFolivoraApiDetector.java
│                           │   └── PreferStubViewDetector.java
│                           └── preview/
│                               ├── FolivoraPreview.java
│                               └── ViewFactory.java
├── sample/
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── cn/
│           │       └── cricin/
│           │           └── folivora/
│           │               └── sample/
│           │                   ├── MainActivity.java
│           │                   └── drawable/
│           │                       ├── AlphaBackgroundDrawable.java
│           │                       ├── UmbrellaDrawable.java
│           │                       └── WindmillDrawable.java
│           └── res/
│               ├── layout/
│               │   └── activity_main.xml
│               └── values/
│                   ├── attrs.xml
│                   ├── colors.xml
│                   ├── strings.xml
│                   └── styles.xml
└── settings.gradle
Download .txt
SYMBOL INDEX (157 symbols across 22 files)

FILE: folivora/src/main/java/cn/cricin/folivora/DrawableParser.java
  type DrawableParser (line 57) | public interface DrawableParser {
    method parse (line 64) | Drawable parse(ParseRequest request);
    class GradientDrawableParser (line 96) | class GradientDrawableParser implements DrawableParser {
      method parse (line 98) | @Override
    class StateListDrawableParser (line 183) | class StateListDrawableParser implements DrawableParser {
      method parse (line 238) | @Override
      method parseStateSet (line 308) | private static int[] parseStateSet(int stateFlags) {
    class LayerDrawableParser (line 445) | class LayerDrawableParser implements DrawableParser {
      method parse (line 446) | @Override
    class RippleDrawableParser (line 528) | class RippleDrawableParser implements DrawableParser {
      method parse (line 529) | @Override
    class LevelListDrawableParser (line 582) | class LevelListDrawableParser implements DrawableParser {
      method parse (line 583) | @Override
    class ClipDrawableParser (line 639) | class ClipDrawableParser implements DrawableParser {
      method parse (line 640) | @Override
    class InsetDrawableParser (line 667) | class InsetDrawableParser implements DrawableParser {
      method parse (line 668) | @Override
    class ScaleDrawableParser (line 699) | class ScaleDrawableParser implements DrawableParser {
      method parse (line 700) | @Override
    class AnimationDrawableParser (line 746) | class AnimationDrawableParser implements DrawableParser {
      method parse (line 747) | @SuppressWarnings("ConstantConditions")
    class ReflectiveDrawableParser (line 830) | class ReflectiveDrawableParser implements DrawableParser {
      method parse (line 837) | @Override

FILE: folivora/src/main/java/cn/cricin/folivora/Folivora.java
  class Folivora (line 55) | public final class Folivora {
    method getDrawable (line 121) | @SuppressWarnings("WeakerAccess")
    method applyDrawableToView (line 149) | static void applyDrawableToView(View view, AttributeSet attrs) {
    method createDrawable (line 195) | private static Drawable createDrawable(Context ctx, AttributeSet attrs...
    method installViewFactory (line 222) | public static void installViewFactory(Context ctx) {
    method wrap (line 243) | public static Context wrap(final Context newBase) {
    method setRippleFallback (line 268) | public static void setRippleFallback(RippleFallback fallback) {
    method registerDrawableParser (line 272) | public static void registerDrawableParser(Class<? extends Drawable> dr...
    method addOnViewCreatedListener (line 284) | public static void addOnViewCreatedListener(OnViewCreatedListener l) {
    method dispatchViewCreated (line 291) | static void dispatchViewCreated(View view, AttributeSet attrs) {
    method Folivora (line 299) | private Folivora() {}

FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraInflater.java
  class FolivoraInflater (line 31) | final class FolivoraInflater extends LayoutInflater {
    method FolivoraInflater (line 38) | FolivoraInflater(Context newContext, LayoutInflater original) {
    method cloneInContext (line 42) | @Override
    method setFactory (line 47) | @Override
    method setFactory2 (line 56) | @Override
    method inflate (line 65) | @Override
    method onCreateView (line 75) | @Override

FILE: folivora/src/main/java/cn/cricin/folivora/FolivoraViewFactory.java
  class FolivoraViewFactory (line 34) | final class FolivoraViewFactory implements LayoutInflater.Factory2 {
    method onCreateView (line 50) | @Override
    method onCreateView (line 55) | @Override
    method createView (line 83) | private static View createView(String name, Context ctx, AttributeSet ...
    method getLayoutInflater (line 107) | private static LayoutInflater getLayoutInflater(Context context) {
    method forceSetFactory2 (line 114) | static void forceSetFactory2(LayoutInflater inflater, LayoutInflater.F...

FILE: folivora/src/main/java/cn/cricin/folivora/OnViewCreatedListener.java
  type OnViewCreatedListener (line 27) | public interface OnViewCreatedListener {
    method onViewCreated (line 28) | void onViewCreated(View view, AttributeSet attrs);

FILE: folivora/src/main/java/cn/cricin/folivora/ParseRequest.java
  class ParseRequest (line 26) | public final class ParseRequest {
    method ParseRequest (line 33) | ParseRequest(Context context,
    method context (line 48) | public Context context() {
    method attrs (line 55) | public AttributeSet attrs() {
    method rippleFallback (line 62) | public RippleFallback rippleFallback() {
    method shapeAttrs (line 69) | public ShapeAttrs shapeAttrs() {
    method drawableClassName (line 76) | public String drawableClassName() {

FILE: folivora/src/main/java/cn/cricin/folivora/RippleFallback.java
  type RippleFallback (line 29) | public interface RippleFallback {
    method onFallback (line 40) | Drawable onFallback(ColorStateList color, Drawable content,

FILE: folivora/src/main/java/cn/cricin/folivora/ShapeAttrs.java
  class ShapeAttrs (line 23) | final class ShapeAttrs {
    method ShapeAttrs (line 48) | private ShapeAttrs(
    method forIndex (line 226) | static ShapeAttrs forIndex(int index) {

FILE: lint/src/main/java/cn/cricin/folivora/dom/AndroidFacetCompat.java
  class AndroidFacetCompat (line 38) | final class AndroidFacetCompat {
    method getAppResourceManager (line 41) | static ResourceManager getAppResourceManager(AndroidFacet facet) {
    method isAppProject (line 59) | static boolean isAppProject(AndroidFacet facet) {
    method requiresAndroidModel (line 72) | static boolean requiresAndroidModel(AndroidFacet facet) {
    method getManifest (line 85) | static Manifest getManifest(AndroidFacet facet) {
    method invoke (line 96) | @SuppressWarnings("unchecked")
    method AndroidFacetCompat (line 120) | private AndroidFacetCompat() {

FILE: lint/src/main/java/cn/cricin/folivora/dom/DrawableIdConverter.java
  class DrawableIdConverter (line 40) | public class DrawableIdConverter extends ResolvingConverter<String> {
    method getVariants (line 42) | @NotNull
    method fromString (line 63) | @Nullable
    method toString (line 69) | @Nullable

FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraAttrProcessing.java
  class FolivoraAttrProcessing (line 52) | final class FolivoraAttrProcessing {
    method registerFolivoraAttributes (line 86) | static void registerFolivoraAttributes(AndroidFacet facet,
    method getStyleablesToRegister (line 102) | private static List<String> getStyleablesToRegister(XmlAttribute[] att...
    method getSimpleClassName (line 148) | private static String getSimpleClassName(String className) {
    method isInvalidTagName (line 155) | private static boolean isInvalidTagName(String tagName) {
    method registerAttributes (line 163) | private static void registerAttributes(/*NotNull*/ AndroidFacet facet,
    method getNamespaceUriByResourcePackage (line 191) | private static String getNamespaceUriByResourcePackage(/*NotNull*/ And...
    method registerStyleableAttributes (line 210) | private static void registerStyleableAttributes(
    method registerAttribute (line 220) | private static void registerAttribute(
    method mustBeSoft (line 256) | private static boolean mustBeSoft(Converter converter, Collection form...
    method FolivoraAttrProcessing (line 265) | private FolivoraAttrProcessing() {}

FILE: lint/src/main/java/cn/cricin/folivora/dom/FolivoraDomExtender.java
  class FolivoraDomExtender (line 37) | @SuppressWarnings("unchecked")
    method supportsStubs (line 60) | @Override
    method getValueClass (line 65) | private static Class getValueClass(Object format) {
    method registerExtensions (line 70) | @Override
    method install (line 94) | public static void install() {

FILE: lint/src/main/java/cn/cricin/folivora/lint/FolivoraIssueRegistry.java
  class FolivoraIssueRegistry (line 29) | @SuppressWarnings("unused")
    method installStudioPlugins (line 36) | private static void installStudioPlugins() {
    method getIssues (line 54) | @Override
    method getApi (line 61) | @Override

FILE: lint/src/main/java/cn/cricin/folivora/lint/InstalledBeforeSuperDetector.java
  class InstalledBeforeSuperDetector (line 40) | public final class InstalledBeforeSuperDetector extends Detector impleme...
    method getApplicableMethodNames (line 58) | @Nullable
    method visitMethod (line 64) | @Override
    class SuperOnCreateFinder (line 100) | private static class SuperOnCreateFinder extends AbstractUastVisitor {
      method SuperOnCreateFinder (line 108) | private SuperOnCreateFinder(UCallExpression target) {
      method visitCallExpression (line 112) | @Override
      method isSuperOnCreateCalled (line 129) | boolean isSuperOnCreateCalled() {

FILE: lint/src/main/java/cn/cricin/folivora/lint/InternalFolivoraApiDetector.java
  class InternalFolivoraApiDetector (line 43) | @Deprecated
    method getApplicableMethodNames (line 64) | @Nullable
    method visitMethod (line 70) | @Override
    method report (line 110) | private void report(JavaContext context, UCallExpression call) {

FILE: lint/src/main/java/cn/cricin/folivora/lint/PreferStubViewDetector.java
  class PreferStubViewDetector (line 39) | @Deprecated
    method getApplicableAttributes (line 58) | @Override
    method appliesTo (line 63) | @Override
    method visitAttribute (line 68) | @Override

FILE: lint/src/main/java/cn/cricin/folivora/preview/FolivoraPreview.java
  class FolivoraPreview (line 40) | @SuppressWarnings("unchecked")
    method install (line 47) | public static void install() {
    method tryHookConstructorMap (line 72) | private static void tryHookConstructorMap() {
    method getUnsafe (line 112) | private static Unsafe getUnsafe(){
    method installViewFactoryIfNeeded (line 126) | private static void installViewFactoryIfNeeded() {
    method peekContexts (line 136) | private static Collection<BridgeContext> peekContexts() {
    class MyHashMap (line 147) | static class MyHashMap<K,V> extends HashMap<K,V>{
      method MyHashMap (line 148) | MyHashMap(Map<? extends K, ? extends V> map) {
      method get (line 152) | @Override

FILE: lint/src/main/java/cn/cricin/folivora/preview/ViewFactory.java
  class ViewFactory (line 39) | final class ViewFactory implements LayoutInflater.Factory2 {
    method ViewFactory (line 63) | ViewFactory(LayoutInflater inflater, LayoutlibCallback layoutlibCallba...
    method getContext (line 72) | private BridgeContext getContext() {
    method onCreateView (line 76) | @Override
    method applyDrawableToView (line 116) | private void applyDrawableToView(View view, AttributeSet attrs) {
    method loadCustomView (line 140) | private View loadCustomView(String name, AttributeSet attrs) {
    method onCreateView (line 166) | @Override

FILE: sample/src/main/java/cn/cricin/folivora/sample/MainActivity.java
  class MainActivity (line 39) | public class MainActivity extends Activity {
    method attachBaseContext (line 41) | @Override
    method onCreate (line 46) | @Override

FILE: sample/src/main/java/cn/cricin/folivora/sample/drawable/AlphaBackgroundDrawable.java
  class AlphaBackgroundDrawable (line 37) | @SuppressWarnings("WeakerAccess, unused")
    method AlphaBackgroundDrawable (line 45) | public AlphaBackgroundDrawable(Context ctx) {
    method AlphaBackgroundDrawable (line 52) | public AlphaBackgroundDrawable(Context ctx, AttributeSet attrs) {
    method initPaint (line 63) | @SuppressWarnings("SuspiciousNameCombination")
    method draw (line 83) | @Override
    method setAlpha (line 91) | @Override
    method setColorFilter (line 96) | @Override
    method getOpacity (line 101) | @Override

FILE: sample/src/main/java/cn/cricin/folivora/sample/drawable/UmbrellaDrawable.java
  class UmbrellaDrawable (line 36) | @SuppressWarnings("unused")
    method UmbrellaDrawable (line 50) | public UmbrellaDrawable() {
    method draw (line 58) | @Override
    method onBoundsChange (line 74) | @Override
    method createShader (line 86) | private void createShader() {
    method setColor1 (line 94) | public void setColor1(int color) {
    method setColor2 (line 102) | public void setColor2(int color) {
    method setBackgroundColor (line 110) | public void setBackgroundColor(int color) {
    method getColor1 (line 117) | public int getColor1() {
    method getColor2 (line 121) | public int getColor2() {
    method getBackgroundColor (line 125) | public int getBackgroundColor() {
    method setAlpha (line 130) | @Override
    method setColorFilter (line 135) | @Override
    method getOpacity (line 140) | @Override

FILE: sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java
  class WindmillDrawable (line 36) | @SuppressWarnings("WeakerAccess, unused")
    method WindmillDrawable (line 49) | public WindmillDrawable(Context ctx) {
    method WindmillDrawable (line 59) | public WindmillDrawable(Context ctx, AttributeSet attrs) {
    method draw (line 97) | @Override
    method setAlpha (line 116) | @Override
    method setColorFilter (line 121) | @Override
    method getOpacity (line 126) | @Override
    method getIntrinsicWidth (line 131) | @Override
    method getIntrinsicHeight (line 136) | @Override
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (273K chars).
[
  {
    "path": ".gitignore",
    "chars": 1036,
    "preview": "# Built application files\n*.apk\n*.ap_\n\n# Files for the ART/Dalvik VM\n*.dex\n\n# Java class files\n*.class\n\n# Generated file"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README-zh.md",
    "chars": 18072,
    "preview": "### 为什么需要Folivora\n对于android开发者来说,在layout文件中引用drawable来设置`View`的背景或者`ImageView`的`src`是很常见的事情,需要我们在drawable文件夹下写好xml文件就可以应"
  },
  {
    "path": "README.md",
    "chars": 20968,
    "preview": "English | [中文](https://github.com/Cricin/Folivora/blob/master/README-zh.md)\n\n### Why Folivora\nFor most android develpers"
  },
  {
    "path": "android_release_aar.gradle",
    "chars": 1470,
    "preview": "// ./gradlew clean build generateRelease\napply plugin: 'maven'\n\ndef groupId = project.PUBLISH_GROUP_ID\ndef artifactId = "
  },
  {
    "path": "build.gradle",
    "chars": 490,
    "preview": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n  rep"
  },
  {
    "path": "folivora/build.gradle",
    "chars": 558,
    "preview": "apply plugin: 'com.android.library'\n\ndef verName = '0.1.0'\n\nandroid {\n  compileSdkVersion 29\n  defaultConfig {\n    minSd"
  },
  {
    "path": "folivora/src/main/AndroidManifest.xml",
    "chars": 79,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest package=\"cn.cricin.folivora\"/>"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/DrawableParser.java",
    "chars": 39568,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/Folivora.java",
    "chars": 12580,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/FolivoraInflater.java",
    "chars": 2646,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/FolivoraViewFactory.java",
    "chars": 4635,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/OnViewCreatedListener.java",
    "chars": 979,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/ParseRequest.java",
    "chars": 2121,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/RippleFallback.java",
    "chars": 1441,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/java/cn/cricin/folivora/ShapeAttrs.java",
    "chars": 10009,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "folivora/src/main/res/values/attrs.xml",
    "chars": 37517,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n  * Copyright (C) 2019 Cricin\n  *\n  * Licensed under the Apache License, Ver"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 231,
    "preview": "#Sat Mar 21 17:57:59 CST 2020\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
  },
  {
    "path": "gradle.properties",
    "chars": 750,
    "preview": "# Project-wide Gradle settings.\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will ov"
  },
  {
    "path": "gradlew",
    "chars": 5296,
    "preview": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up"
  },
  {
    "path": "gradlew.bat",
    "chars": 2176,
    "preview": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem "
  },
  {
    "path": "lint/build.gradle",
    "chars": 2267,
    "preview": "apply plugin: 'java'\n\ndef ideInstallationDir = new File('d:/android/studio')\ndef androidPluginLibPath = 'plugins/android"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/dom/AndroidFacetCompat.java",
    "chars": 3928,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/dom/DrawableIdConverter.java",
    "chars": 2344,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/dom/FolivoraAttrProcessing.java",
    "chars": 10609,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/dom/FolivoraDomExtender.java",
    "chars": 4808,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/lint/FolivoraIssueRegistry.java",
    "chars": 1769,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/lint/InstalledBeforeSuperDetector.java",
    "chars": 5118,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/lint/InternalFolivoraApiDetector.java",
    "chars": 4188,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/lint/PreferStubViewDetector.java",
    "chars": 2963,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/preview/FolivoraPreview.java",
    "chars": 5251,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "lint/src/main/java/cn/cricin/folivora/preview/ViewFactory.java",
    "chars": 6169,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "sample/build.gradle",
    "chars": 644,
    "preview": "apply plugin: 'com.android.application'\n\nandroid {\n  compileSdkVersion 29\n  defaultConfig {\n    applicationId \"cn.cricin"
  },
  {
    "path": "sample/src/main/AndroidManifest.xml",
    "chars": 679,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n  xmlns:android=\"http://schemas.android.com/apk/res/android\"\n  xmlns:to"
  },
  {
    "path": "sample/src/main/java/cn/cricin/folivora/sample/MainActivity.java",
    "chars": 3438,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "sample/src/main/java/cn/cricin/folivora/sample/drawable/AlphaBackgroundDrawable.java",
    "chars": 3817,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "sample/src/main/java/cn/cricin/folivora/sample/drawable/UmbrellaDrawable.java",
    "chars": 3691,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "sample/src/main/java/cn/cricin/folivora/sample/drawable/WindmillDrawable.java",
    "chars": 4545,
    "preview": "/*\n * Copyright (C) 2019 Cricin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use"
  },
  {
    "path": "sample/src/main/res/layout/activity_main.xml",
    "chars": 11778,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--\n  * Copyright (C) 2019 Cricin\n  *\n  * Licensed under the Apache License, Vers"
  },
  {
    "path": "sample/src/main/res/values/attrs.xml",
    "chars": 946,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n  <declare-styleable name=\"WindmillDrawable\">\n    <attr name=\"wdSize\""
  },
  {
    "path": "sample/src/main/res/values/colors.xml",
    "chars": 689,
    "preview": "<resources>\n  <color name=\"colorPrimary\">#008577</color>\n  <color name=\"colorPrimaryDark\">#00574B</color>\n  <color name="
  },
  {
    "path": "sample/src/main/res/values/strings.xml",
    "chars": 76,
    "preview": "<resources>\n  <string name=\"app_name\">Folivora-Sample</string>\n</resources>\n"
  },
  {
    "path": "sample/src/main/res/values/styles.xml",
    "chars": 89,
    "preview": "<resources>\n\n  <!-- Base application theme. -->\n  <style name=\"AppTheme\"/>\n\n</resources>\n"
  },
  {
    "path": "settings.gradle",
    "chars": 53,
    "preview": "include ':sample'\ninclude ':folivora'\ninclude ':lint'"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the Cricin/Folivora GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (247.9 KB), approximately 65.5k tokens, and a symbol index with 157 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!