[
  {
    "path": ".gitignore",
    "content": "bin/\ngen/\nbuild/\nlocal.properties\nThumbs.db\n.DS_Store\n.idea\n.gradle\n*.iml\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# MultiStateAnimation\n\nAndroid library to create complex multi-state animations.\n\n![Demo animation](docs/images/demo_1.gif)\n\n## Overview\n\nA class that allows for complex multi-state animations using Android's\n`AnimationDrawable`. It supports both oneshot and looped animation sections.\nTransitions between sections can be defined, and will play automatically when\nmoving between the defined states. State transitions can be queued\nasynchronously, and the library will take car of smoothly starting the next\nanimation once the current section is complete.\n\n## Installation\n\nAdd the following dependency to your gradle build file:\n```gradle\n    dependencies {  \n        compile 'com.getkeepsafe.android.multistateanimation:library:1.1.1'\n    }\n```\n## Usage\nEach animation consists of a series of states. A state has some metadata and a list\nof frames to draw. A state can also define transitions from other states. A\ntransition is a list of frames that will be played when moving directly from a\nspecified state to the state where the transition is defined.\n\nAn animation can be defined either with a JSON file included as a `raw` resource, \nor directly in Java code using builders.\n\n### Defining an animation with Java code\n\n```java\n\n    // The ID is used in code to specify a section to play\n    MultiStateAnimation.SectionBuilder firstSection = new MultiStateAnimation.SectionBuilder(\"first_section\")\n        // If true, this section will play once and stop. Otherwise it\n        // will loop indefinitely.\n        .setOneshot(false)\n        // The number of milliseconds that each frame of this section will\n        // play\n        .setFrameDuration(33)\n        // Each frame is the name of an image resource. They will be\n        // played in the order added.\n        .addFrame(R.drawable.first_section_01)\n        .addFrame(R.drawable.first_section_02);\n\n    // The frames of a transition will be played before playing\n    // the normal frames of this section when transitioning. In\n    // this case, the frames for this transition will play if\n    // \"first_section\" is playing when queueTransition(\"second_section\") \n    // is called\n    MultiStateAnimation.TransitionBuilder transitionFromFirst = new MultiStateAnimation.TransitionBuilder()\n        .setFrameDuration(33)\n        .addFrame(R.drawable.first_to_second_transition_001)\n        .addFrame(R.drawable.first_to_second_transition_002)\n        .addFrame(R.drawable.first_to_second_transition_003);\n\n    // As a special case, a transition ID of \"\" is a transition\n    // from nothing. It will play if the associated section is the\n    // first to ever play.\n    MultiStateAnimation.TransitionBuilder transitionFromNothing = new MultiStateAnimation.TransitionBuilder()\n        .addFrame(R.drawable.nothing_to_second_001)\n        .addFrame(R.drawable.nothing_to_second_002);\n\n    // A section with a single frame and \"oneshot\" set to true is\n    // equivalent to a static image\n    MultiStateAnimation.SectionBuilder secondSection = new MultiStateAnimation.SectionBuilder(\"second_section\")\n        .setOneshot(true)\n        .addTransition(\"first_section\", transitionFromFirst)\n        .addTransition(\"\", transitionFromNothing)\n        .addFrame(R.drawable.second_section_01);\n\n    // Animation should be given an View that will be used to display the animation.\n    ImageView view = (ImageView) findViewById(R.id.animationImageView);\n    MultiStateAnimation animation = new MultiStateAnimation.Builder(view)\n        .addSection(startSection)\n        .addSection(loadingSection)\n        .addSection(endSection)\n        .build(context);\n\n```\n\n### Defining an animation using JSON\n\nAs an alternative to using Java code, you can instead define animations using a JSON file stored as a raw resource. The following JSON file defines the same animation as the above Java code.\n\n```javascript\n\n    {\n        \"first_section\": { \n            \"oneshot\": false, \n            \"frame_duration\": 33, \n            \"frames\": [\n                \"first_section_1\",\n                \"first_section_2\"\n            ],\n    \n        }\n    \n        \"second_section\": {\n            \"oneshot\": true,\n            \"frames\": [\n                \"second_section_01\"\n            ],\n            \"transitions_from\": {\n                \"first_section\": {\n                    \"frame_duration\": 33,\n                    \"frames\": [\n                            \"first_to_second_transition_001\",\n                            \"first_to_second_transition_002\",\n                            \"first_to_second_transition_003\"\n                    ]\n                }\n                \"\": {\n                    \"frames\": [\n                        \"nothing_to_second_001\",\n                        \"nothing_to_second_002\"\n                    ]\n                }\n            }\n        }\n    }\n\n```\n\nThen a `MultiStateAnimationOjbect` can be created in Java:\n\n```java\n\n    ImageView view = (ImageView) findViewById(R.id.animationImageView);\n    MultiStateAnimation animationSeries = MultiStateAnimation.fromJsonResource(context, view, R.raw.sample_animation);\n\n```\n\n#### Generating JSON animation files automatically\n\nIncluded in the repo is a [Python 3 script](scripts/generate_animation_json.py) that can assist in generating the JSON for an animation. To use it, place the frames for each section of the animation in a separate folder, the pass those folders to the script.\n\nFor example, to generate the JSON file above, create a folder structure like this:\n```bash\n    .\n    ├── first_section\n    │   ├── first_section_1.png\n    │   └── first_section_2.png\n    ├── first_to_second_transition\n    │   ├── first_to_second_transition_001.png\n    │   ├── first_to_second_transition_002.png\n    │   └── first_to_second_transition_003.png\n    ├── nothing_to_second_transition\n    │   ├── nothing_to_second_001.png\n    │   └── nothing_to_second_002.png\n    └── second_section\n        └── second_section_01.png\n```\nThese folders can be located anywhere in your filesystem. To generate the JSON file, run the script with the folders as arguments:\n```bash\n    python generate_animation_json.py first_section/ second_section/ first_to_second_transition/ nothing_to_second_transition/ --output=sample_animation.json\n```\nThe script will ask a series of questions about each section, and save the resulting json file to `sample_animation.json`. You can run `python generate_animation_json.py --help` to see a full list of arguments\n\n### Playing animations\n\nOnce the animation object is created via one of the above methods, you can use `queueTransition` and `transitionNow` \nfrom the GUI thread to start playing the animations.\n\n```java\n\n    animationSeries.queueTransition(\"first_section\");\n    \n```\n\n## Sample application\n\nSee the [main Activity](samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java) and the [json animation definition](samples/res/raw/sample_animation.json)\n in the [sample application](samples/) for an example.\n\n## Java API\n\nCheck out [the Javadocs](http://keepsafe.github.io/MultiStateAnimation/) for more API details.\n\n## License\n\n    Copyright 2016 KeepSafe Inc.\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n"
  },
  {
    "path": "build.gradle",
    "content": "buildscript {\n    repositories {\n        mavenCentral()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:1.2.3'\n    }\n}\n\nallprojects {\n    repositories {\n        mavenCentral()\n    }\n}\n"
  },
  {
    "path": "gradle/gradle-mvn-push.gradle",
    "content": "/*\n * Copyright 2013 Chris Banes\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\napply plugin: 'maven'\napply plugin: 'signing'\n\ndef isReleaseBuild() {\n    return VERSION_NAME.contains(\"SNAPSHOT\") == false\n}\n\ndef getReleaseRepositoryUrl() {\n    return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL\n            : \"https://oss.sonatype.org/service/local/staging/deploy/maven2/\"\n}\n\ndef getSnapshotRepositoryUrl() {\n    return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL\n            : \"https://oss.sonatype.org/content/repositories/snapshots/\"\n}\n\ndef getRepositoryUsername() {\n    return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : \"\"\n}\n\ndef getRepositoryPassword() {\n    return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : \"\"\n}\n\nafterEvaluate { project ->\n    uploadArchives {\n        repositories {\n            mavenDeployer {\n                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }\n\n                pom.groupId = GROUP\n                pom.artifactId = POM_ARTIFACT_ID\n                pom.version = VERSION_NAME\n\n                repository(url: getReleaseRepositoryUrl()) {\n                    authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())\n                }\n                snapshotRepository(url: getSnapshotRepositoryUrl()) {\n                    authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())\n                }\n\n                pom.project {\n                    name POM_NAME\n                    packaging POM_PACKAGING\n                    description POM_DESCRIPTION\n                    url POM_URL\n\n                    scm {\n                        url POM_SCM_URL\n                        connection POM_SCM_CONNECTION\n                        developerConnection POM_SCM_DEV_CONNECTION\n                    }\n\n                    licenses {\n                        license {\n                            name POM_LICENCE_NAME\n                            url POM_LICENCE_URL\n                            distribution POM_LICENCE_DIST\n                        }\n                    }\n\n                    developers {\n                        developer {\n                            id POM_DEVELOPER_ID\n                            name POM_DEVELOPER_NAME\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    signing {\n        required { isReleaseBuild() && gradle.taskGraph.hasTask(\"uploadArchives\") }\n        sign configurations.archives\n    }\n\n    task androidJavadocs(type: Javadoc) {\n        source = android.sourceSets.main.java.srcDirs\n        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))\n    }\n\n    task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {\n        classifier = 'javadoc'\n        from androidJavadocs.destinationDir\n    }\n\n    task androidSourcesJar(type: Jar) {\n        classifier = 'sources'\n        from android.sourceSets.main.java.sourceFiles\n    }\n\n    artifacts {\n        archives androidSourcesJar\n        archives androidJavadocsJar\n    }\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Wed Apr 10 15:27:10 PDT 2013\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "VERSION_NAME=1.1.1\nVERSION_CODE=3\nGROUP=com.getkeepsafe.android.multistateanimation\n\nPOM_ARTIFACT_ID=MultiStateAnimation\nPOM_NAME=MultiStateAnimation\nPOM_PACKAGING=aar\n\nPOM_DESCRIPTION=An Android library to create complex animations.\nPOM_INCEPTION_YEAR=2015\n\nPOM_URL=https://github.com/KeepSafe/MultiStateAnimation\nPOM_SCM_URL=https://github.com/KeepSafe/MultiStateAnimation\nPOM_SCM_CONNECTION=scm:git:git://github.com/KeepSafe/MultiStateAnimation.git\nPOM_SCM_DEV_CONNECTION=scm:git:git@github.com:KeepSafe/MultiStateAnimation.git\n\nPOM_LICENCE_NAME=Apache License 2.0\nPOM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt\nPOM_LICENCE_DIST=repo\n\nPOM_DEVELOPER_ID=keepsafe\nPOM_DEVELOPER_NAME=KeepSafe Software, Inc.\n"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# For Cygwin, ensure paths are in UNIX format before anything is touched.\nif $cygwin ; then\n    [ -n \"$JAVA_HOME\" ] && JAVA_HOME=`cygpath --unix \"$JAVA_HOME\"`\nfi\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >&-\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >&-\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windowz variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\ngoto execute\r\n\r\n:4NT_args\r\n@rem Get arguments from the 4NT Shell from JP Software\r\nset CMD_LINE_ARGS=%$\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "library/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "library/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest package=\"com.getkeepsafe.android.multistateanimation\">\n</manifest>\n"
  },
  {
    "path": "library/build.gradle",
    "content": "apply plugin: 'com.android.library'\n\ngroup = GROUP\nversion = VERSION_NAME\n\nrepositories {\n    mavenCentral()\n}\n\nandroid {\n    compileSdkVersion 22\n    buildToolsVersion '22.0.1'\n\n    defaultConfig {\n        minSdkVersion 1\n        targetSdkVersion 22\n        versionCode 3\n        versionName '1.1.1'\n    }\n\n    sourceSets {\n        main {\n            manifest.srcFile 'AndroidManifest.xml'\n            res.srcDirs = ['res']\n        }\n    }\n\n    lintOptions {\n        abortOnError false\n    }\n}\n\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n}\n\nandroid.libraryVariants.all { variant ->\n    task(\"generate${variant.name.capitalize()}Javadoc\", type: Javadoc) {\n        // title = ''\n        // description = ''\n        source = variant.javaCompile.source\n        classpath = files(variant.javaCompile.classpath.files, project.android.getBootClasspath())\n        options {\n            links \"http://docs.oracle.com/javase/7/docs/api/\"\n            linksOffline \"http://d.android.com/reference\",\"${android.sdkDirectory}/docs/reference\"\n        }\n        exclude '**/BuildConfig.java'\n        exclude '**/R.java'\n    }\n}\n\napply from: file('../gradle/gradle-mvn-push.gradle')\n"
  },
  {
    "path": "library/gradle.properties",
    "content": "POM_NAME=MultiStateAnimation\nPOM_ARTIFACT_ID=library\nPOM_PACKAGING=aar\n"
  },
  {
    "path": "library/src/main/java/com/getkeepsafe/android/multistateanimation/MultiStateAnimation.java",
    "content": "package com.getkeepsafe.android.multistateanimation;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport android.graphics.drawable.AnimationDrawable;\nimport android.os.Build;\nimport android.view.View;\n\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Animates a series of separate AnimationDrawables on the background of a single View.\n * The view to animate is passed in the constructor. Animations are added with addSection, or they\n * can be defined in a JSON resource and passed to fromJsonResource. To start an animation,\n * call transitionNow or queueTransition.\n *\n * @author AJ Alt\n */\npublic class MultiStateAnimation implements NotifyingAnimationDrawable.OnAnimationFinishedListener {\n    public static final int DEFAULT_FRAME_DURATION = 33;\n    public static final boolean DEFAULT_ONESHOT_STATUS = true;\n\n    /**\n     * Cache to prevent duplicate json reads; map of resource id -> builder.\n     */\n    private static final Map<Integer, Builder> mBuilderCache = new HashMap<>();\n\n    /**\n     * A class that creates an AnimationDrawable from a list of frames.\n     */\n    private static class AnimationDrawableLoader {\n        private int mFrameDuration;\n        private boolean mIsOneShot;\n        private int[] mFrameIds;\n        private Context mContext;\n\n        public AnimationDrawableLoader(Context context) {\n            mContext = context;\n        }\n\n        public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, String[] frameNames) {\n            mContext = context;\n            mFrameDuration = frameDuration;\n            mIsOneShot = isOneShot;\n            mFrameIds = new int[frameNames.length];\n\n            for (int i = 0; i < frameNames.length; i++) {\n                mFrameIds[i] = getDrawableResourceId(mContext, frameNames[i]);\n            }\n        }\n\n        public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, int[] frameIds) {\n            mContext = context;\n            mFrameDuration = frameDuration;\n            mIsOneShot = isOneShot;\n            mFrameIds = frameIds;\n        }\n\n        public NotifyingAnimationDrawable load() {\n            NotifyingAnimationDrawable d = new NotifyingAnimationDrawable();\n            d.setOneShot(mIsOneShot);\n\n            // XXX: AnimationDrawable has a bug that causes it to be unresponsive\n            // if exactly one frame is added. A workaround is to add the same frame\n            // twice if there's only one.\n            if (mFrameIds.length == 1) {\n                for (int i = 0; i < 2; i++) {\n                    d.addFrame(mContext.getResources().getDrawable(mFrameIds[0]), mFrameDuration);\n                }\n                d.setOneShot(true);\n            } else {\n                for (int resid : mFrameIds) {\n                    d.addFrame(mContext.getResources().getDrawable(resid), mFrameDuration);\n                }\n            }\n            return d;\n        }\n\n        /**\n         * Returns the duration of this animation.\n         *\n         * @return int number of milliseconds that the animation will play.\n         */\n        public int totalDuration() {\n            return mFrameDuration * mFrameIds.length;\n        }\n    }\n\n    /**\n     * A class that holds loaders for a single animation section and transitions to that section.\n     */\n    private static class AnimationSection {\n        private String mId;\n        private AnimationDrawableLoader mLoader;\n        private Map<String, AnimationDrawableLoader> mTransitions;\n\n        public AnimationSection(String id, AnimationDrawableLoader loader, Map<String, AnimationDrawableLoader> transitions) {\n            mId = id;\n            mLoader = loader;\n            mTransitions = transitions;\n        }\n\n        /**\n         * @param id     The id of this section.\n         * @param loader A loader for this section's primary animation.\n         */\n        public AnimationSection(String id, AnimationDrawableLoader loader) {\n            this(id, loader, new HashMap<String, AnimationDrawableLoader>());\n        }\n\n        public String getId() {\n            return mId;\n        }\n\n        /**\n         * Creates the primary animation drawable for this section.\n         */\n        public NotifyingAnimationDrawable loadDrawable() {\n            return mLoader.load();\n        }\n\n        /**\n         * @param fromId The id of the section to transition from.\n         * @return The transition animation for fromId if one has been added, or null.\n         */\n        public NotifyingAnimationDrawable getTransition(String fromId) {\n            if (mTransitions.containsKey(fromId)) {\n                return mTransitions.get(fromId).load();\n            }\n            return null;\n        }\n\n        /**\n         * @param fromId The Id of the section that will be transitioned from.\n         * @param loader The loader for this transition animation.\n         */\n        public void addTransition(String fromId, AnimationDrawableLoader loader) {\n            mTransitions.put(fromId, loader);\n        }\n\n        /**\n         * Calculates the total duration if the animation, including the transition.\n         *\n         * @param fromId If a transition exists from this id, the duration will include the transition duration.\n         * @return int number of milliseconds.\n         */\n        public int getDuration(String fromId) {\n            int total = mLoader.totalDuration();\n            AnimationDrawableLoader loader = mTransitions.get(fromId);\n            if (loader != null) {\n                total += loader.totalDuration();\n            }\n            return total;\n        }\n\n        /**\n         * Calculates the duration of the animation, excluding any transition.\n         *\n         * @return int number of milliseconds.\n         */\n        public int getDuration() {\n            return getDuration(null);\n        }\n    }\n\n\n    public interface AnimationSeriesListener {\n        /**\n         * Called when a playing animation finishes and before the drawable is replaced.\n         */\n        void onAnimationFinished();\n\n        /**\n         * Called after a new animation has been created, but before the animation has started.\n         * The new animation can be accessed through getCurrentDrawable.\n         */\n        void onAnimationStarting();\n    }\n\n    private WeakReference<AnimationSeriesListener> mListener = new WeakReference<AnimationSeriesListener>(null);\n    private AnimationSection mCurrentSection;\n\n    /**\n     * The id of the animation that will be started as soon as the current animation\n     * finishes, or null if no animation is queued.\n     */\n    private String mQueuedSectionId;\n    private NotifyingAnimationDrawable mCurrentDrawable;\n\n    /**\n     * The id of the previous section if a transition is currently playing, or null\n     * id no transition is playing.\n     */\n    private String mTransitioningFromId;\n    private View mView;\n\n    /**\n     * An array of resource IDs corresponding to animations that can be played.\n     */\n    private Map<String, AnimationSection> mSectionsById;\n\n    /**\n     * Create a new instance and automatically set animations as the background of the given view.\n     *\n     * @param view If not null, animations will be set as the background of this view.\n     */\n    public MultiStateAnimation(View view) {\n        mSectionsById = new HashMap<>();\n        mView = view;\n    }\n\n    /**\n     * Create an instance without giving a view to hold the animations.\n     * <p/>\n     * Note that due to a limitation in AnimationDrawable, you must set\n     * created animations as the image or background of a View in an\n     * onAnimationStarting listener, otherwise the animation will not\n     * advance.\n     *\n     * @see com.getkeepsafe.android.multistateanimation.MultiStateAnimation.AnimationSeriesListener#onAnimationStarting()\n     */\n    public MultiStateAnimation() {\n        this(null);\n    }\n\n    /**\n     * Load the id for a drawable resource from its name\n     */\n    private static int getDrawableResourceId(Context context, String name) {\n        return context.getResources().getIdentifier(name, \"drawable\", context.getPackageName());\n    }\n\n    /**\n     * Convert a JSONArray containing only strings to a String[].\n     *\n     * @param jsonArray the array to convert.\n     * @return a String[] with the contents of the JSONArray.\n     * @throws org.json.JSONException\n     */\n    private static String[] jsonArrayToArray(JSONArray jsonArray) throws JSONException {\n        String[] array = new String[jsonArray.length()];\n        for (int i = 0; i < array.length; i++) {\n            array[i] = jsonArray.getString(i);\n        }\n        return array;\n    }\n\n    /**\n     * Convert a List of Integers to an int[]\n     *\n     * @param list the List to convert\n     * @return an int[] with the same values as the list\n     */\n    private static int[] integerListToArray(List<Integer> list) {\n        int[] array = new int[list.size()];\n\n        for (int i = 0; i < list.size(); i++) {\n            array[i] = list.get(i);\n        }\n        return array;\n    }\n\n    /**\n     * A Builder for a transition from one section to another.\n     * <p/>\n     * It's possible to use the same transition between more than one set of sections.\n     */\n    public static class TransitionBuilder {\n        private List<Integer> mFrames = new ArrayList<>();\n        private int mFrameDuration = DEFAULT_FRAME_DURATION;\n\n        /**\n         * Add a frame to the transition animation.\n         *\n         * @param imageResource The resource id of a image drawable.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public TransitionBuilder addFrame(int imageResource) {\n            mFrames.add(imageResource);\n            return this;\n        }\n\n        /**\n         * Set the duration that each frame in this section will play.\n         *\n         * @param frameDuration The number of milliseconds that each frame will be displayed.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public TransitionBuilder setFrameDuration(int frameDuration) {\n            mFrameDuration = frameDuration;\n            return this;\n        }\n\n        private AnimationDrawableLoader build(Context context) {\n            return new AnimationDrawableLoader(context, mFrameDuration, true, integerListToArray(mFrames));\n        }\n    }\n\n    /**\n     * A builder for an animation section.\n     */\n    public static class SectionBuilder {\n        private String mId;\n        private List<Integer> mFrames = new ArrayList<>();\n        private boolean mIsOneshot = DEFAULT_ONESHOT_STATUS;\n        private int mFrameDuration = DEFAULT_FRAME_DURATION;\n        private Map<String, TransitionBuilder> mTransitions = new HashMap<>();\n\n        /**\n         * A constructor that takes the ID of this section.\n         *\n         * @param id The ID of the section\n         */\n        public SectionBuilder(String id) {\n            mId = id;\n        }\n\n        /**\n         * Add a frame to the section animation.\n         *\n         * @param imageResource The resource id of a image drawable.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public SectionBuilder addFrame(int imageResource) {\n            mFrames.add(imageResource);\n            return this;\n        }\n\n        /**\n         * Set that oneshot status of this section.\n         *\n         * @param isOneshot If true, the animation for this section will pause playing on the final frame.\n         *                  If false, the animation for this section will loop until a new section is transitioned to.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public SectionBuilder setOneshot(boolean isOneshot) {\n            mIsOneshot = isOneshot;\n            return this;\n        }\n\n        /**\n         * Set the duration that each frame in this section will play.\n         *\n         * @param frameDuration The number of milliseconds that each frame will be displayed\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public SectionBuilder setFrameDuration(int frameDuration) {\n            mFrameDuration = frameDuration;\n            return this;\n        }\n\n        /**\n         * Add an animation that will play when transitioning to this section.\n         *\n         * @param fromId     A section name. When a transition is queued from the named section to this one, this transition will play.\n         * @param transition The transition that will play.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public SectionBuilder addTransition(String fromId, TransitionBuilder transition) {\n            mTransitions.put(fromId, transition);\n            return this;\n        }\n\n        private AnimationSection build(Context context) {\n            AnimationDrawableLoader loader = new AnimationDrawableLoader(context, mFrameDuration, mIsOneshot, integerListToArray(mFrames));\n            AnimationSection section = new AnimationSection(mId, loader);\n\n            for (Map.Entry<String, TransitionBuilder> entry : mTransitions.entrySet()) {\n                loader = entry.getValue().build(context);\n                section.addTransition(entry.getKey(), loader);\n            }\n\n            return section;\n        }\n    }\n\n    /**\n     * A builder for manually constructing a MultiStateAnimation.\n     */\n    public static class Builder {\n        List<SectionBuilder> mSections = new ArrayList<>();\n        View mView = null;\n\n        /**\n         * Set a view to attach this animation to.\n         *\n         * The background of the view will contain the animation.\n         * @param view The view that will hold the animation.\n         */\n        public Builder(View view) {\n            mView = view;\n        }\n\n        /**\n         * Add an animation section.\n         * @param section The section to add.\n         * @return This Builder object to allow for chaining of calls to set methods\n         */\n        public Builder addSection(SectionBuilder section) {\n            mSections.add(section);\n            return this;\n        }\n\n        /**\n         * Construct a MultiStateAnimation.\n         * @param context A context used to load resources.\n         * @return A new MultiStateAnimation.\n         */\n        public MultiStateAnimation build(Context context) {\n            MultiStateAnimation animation = new MultiStateAnimation(mView);\n            for (SectionBuilder section : mSections) {\n                animation.addSection(section.build(context));\n            }\n            return animation;\n        }\n    }\n\n    /**\n     * Creates a new MultiStateAnimation object from a json string.\n     * <p/>\n     * The document must have the following structure:\n     * <pre>\n     *  {\n     *      \"first_section\": {\n     *          \"oneshot\": false,\n     *          \"frame_duration\": 33,\n     *          \"frames\": [\n     *              \"frame_01\",\n     *              \"frame_02\"\n     *          ],\n     *\n     *      }\n     *      \"second_section\": {\n     *          \"oneshot\": true,\n     *          \"frames\": [\n     *              \"other_frame_01\"\n     *          ],\n     *          \"transitions_from\": {\n     *              \"first_section\": {\n     *                  \"frame_duration\": 33,\n     *                  \"frames\": [\n     *                          \"first_to_second_transition_001\",\n     *                          \"first_to_second_transition_002\"\n     *                  ]\n     *              }\n     *              \"\": {\n     *                  \"frames\": [\n     *                      \"nothing_to_second_001\",\n     *                      \"nothing_to_second_002\"\n     *                  ]\n     *              }\n     *          }\n     *      }\n     *  }\n     * </pre>\n     * The key for each entry is the ID of the state.\n     * <dl>\n     * <dt>\"oneshot\"</dt>\n     * <dd>If false, the animation will play in a loop instead of stopping at the last\n     * frame.</dd>\n     * <dt>\"frame_duration\"</dt><dd>The number of milliseconds that each frame in the \"frame\"\n     * list will play. It defaults to 33 (30fps) if not given.</dd>\n     * <dt>\"frames\"</dt><dd>A list of string resource ID names that must correspond to a\n     * drawable resource.</dd>\n     * <dt>\"transitions_from\"</dt><dd>Optional, and is a set of animations that play when transitioning to\n     * the current state from another given state. A transition will play when the ID of the\n     * current state matches the transition's key and the state is transitioning to the state\n     * in which the transition is defined.</dd>\n     * </dl>\n     *\n     * @param context The application Context.\n     * @param view    If not null, animations will be set as the background of this view.\n     * @param resid   The resource ID the the raw json document.\n     * @return A new MultiStateAnimation.\n     * @throws RuntimeException\n     */\n    public static MultiStateAnimation fromJsonResource(Context context, View view, int resid) {\n        // Use the cached builder, if one exists.\n        if (mBuilderCache.containsKey(resid)) {\n            return mBuilderCache.get(resid).build(context);\n        }\n\n        // Read the resource into a string\n        BufferedReader r = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resid)));\n        StringBuilder stringBuilder = new StringBuilder();\n        String line;\n        try {\n            while ((line = r.readLine()) != null) {\n                stringBuilder.append(line);\n            }\n        } catch (IOException ignored) {\n            throw new RuntimeException(\"Cannot Read JSON sync animation Resource\");\n        }\n\n        // Parse\n        Builder animationBuilder = new Builder(view);\n        try {\n            JSONObject root = new JSONObject(stringBuilder.toString());\n\n            // The root is a an object with keys that are sequence IDs\n            for (Iterator<String> iter = root.keys(); iter.hasNext(); ) {\n                String sectionId = iter.next();\n                JSONObject obj = root.getJSONObject(sectionId);\n                int frameDuration = obj.optInt(\"frame_duration\", DEFAULT_FRAME_DURATION);\n                boolean isOneShot = obj.optBoolean(\"oneshot\", DEFAULT_ONESHOT_STATUS);\n                JSONArray frames = obj.getJSONArray(\"frames\");\n\n                SectionBuilder sectionBuilder = new SectionBuilder(sectionId)\n                        .setFrameDuration(frameDuration)\n                        .setOneshot(isOneShot);\n\n                for (String frame : jsonArrayToArray(frames)) {\n                    sectionBuilder.addFrame(getDrawableResourceId(context, frame));\n                }\n\n                JSONObject transitions_from;\n                if (obj.has(\"transitions_from\")) {\n                    transitions_from = obj.getJSONObject(\"transitions_from\");\n                } else {\n                    transitions_from = new JSONObject();\n                }\n\n                // The optional \"transitions\" entry is another list of objects\n                for (Iterator<String> transition_iter = transitions_from.keys(); transition_iter.hasNext(); ) {\n                    String from = transition_iter.next();\n\n                    JSONObject t_obj = transitions_from.getJSONObject(from);\n                    frameDuration = t_obj.optInt(\"frame_duration\", DEFAULT_FRAME_DURATION);\n                    frames = t_obj.getJSONArray(\"frames\");\n                    TransitionBuilder transitionBuilder = new TransitionBuilder()\n                            .setFrameDuration(frameDuration);\n                    for (String frame : jsonArrayToArray(frames)) {\n                        transitionBuilder.addFrame(getDrawableResourceId(context, frame));\n                    }\n                    sectionBuilder.addTransition(from, transitionBuilder);\n                }\n                animationBuilder.addSection(sectionBuilder);\n            }\n        } catch (JSONException ignored) {\n            throw new RuntimeException(\"Invalid sync animation JSON file format.\");\n        }\n\n        mBuilderCache.put(resid, animationBuilder);\n        return animationBuilder.build(context);\n    }\n\n    /**\n     * Create a MultiStateAnimation from a JSON resource without a connected View.\n     *\n     * @param context the Application context.\n     * @param resid   The resource ID the the raw json document.\n     * @return A new MultiStateAnimation instance.\n     * @throws RuntimeException\n     */\n    public static MultiStateAnimation fromJsonResource(Context context, int resid)  {\n        return MultiStateAnimation.fromJsonResource(context, null, resid);\n    }\n\n    /**\n     * Add an animation section to this series.\n     *\n     * @param section the section to add.\n     */\n    private void addSection(AnimationSection section) {\n        mSectionsById.put(section.getId(), section);\n    }\n\n    /**\n     * Returns the registered listener, if one exists.\n     */\n    public AnimationSeriesListener getSeriesAnimationFinishedListener() {\n        return mListener.get();\n    }\n\n    /**\n     * Registers a listener that will be called when a running animation finishes. If the\n     * animation is continuous, the listener will be called every time the last frame of the\n     * animation is played.\n     *\n     * @param listener The listener to register.\n     */\n    public void setSeriesAnimationFinishedListener(AnimationSeriesListener listener) {\n        this.mListener = new WeakReference<AnimationSeriesListener>(listener);\n    }\n\n    /**\n     * Calculates the total duration of the current animation section, including the transition\n     * if applicable. If the the animation is not a oneshot, the total will be for a single loop.\n     *\n     * @return The total animation duration, or 0 if no animation is playing.\n     */\n    public int currentSectionDuration() {\n        if (mCurrentSection == null) return 0;\n        return mCurrentSection.getDuration(mTransitioningFromId);\n    }\n\n    /**\n     * Returns the currently playing animation. If no animation has played since this object was\n     * created or since a call to {@link #clearAnimation()}, null is returned.\n     */\n    public AnimationDrawable getCurrentDrawable() {\n        return mCurrentDrawable;\n    }\n\n    /**\n     * Return the ID of the current section if one is playing, or null otherwise.\n     */\n    public String getCurrentSectionId() {\n        return mCurrentSection == null ? null : mCurrentSection.getId();\n    }\n\n    /**\n     * If the currently playing animation is a transition, return the ID of the\n     * section that is being transitioned from. Otherwise return null.\n     */\n    public String getTransitioningFromId() {\n        return mTransitioningFromId;\n    }\n\n    /**\n     * Play an animation drawable.\n     *\n     * @param drawable The drawable to play.\n     */\n    @TargetApi(16)\n    private void playDrawable(NotifyingAnimationDrawable drawable) {\n        mCurrentDrawable = drawable;\n        mCurrentDrawable.setAnimationFinishedListener(this);\n\n        AnimationSeriesListener listener = mListener.get();\n        if (listener != null) {\n            listener.onAnimationStarting();\n        }\n\n        if (mView != null) {\n            if (Build.VERSION.SDK_INT >= 16) {\n                mView.setBackground(mCurrentDrawable);\n            } else {\n                mView.setBackgroundDrawable(mCurrentDrawable);\n            }\n        }\n        mCurrentDrawable.start();\n    }\n\n    /**\n     * Queues a section to start as soon as the current animation finishes.\n     * If no animation is playing, the queued animation will be started immediately.\n     * Queueing a transition to the currently playing section has no effect.\n     *\n     * @param id The name of the section that will be queued.\n     */\n    public void queueTransition(String id) {\n        if (id.equals(getCurrentSectionId())) return;\n        if (mCurrentSection == null ||\n                mCurrentDrawable != null &&\n                        mCurrentDrawable.isOneShot() &&\n                        mCurrentDrawable.isFinished()) {\n            transitionNow(id);\n        } else {\n            mQueuedSectionId = id;\n        }\n    }\n\n    /**\n     * Starts a specific section without waiting for the current animation to finish.\n     * If there is a defined transition from the current section to the new one, the\n     * transition will be played, followed immediately by the regular section animation.\n     * Transitioning to the currently playing section will restart the animation.\n     *\n     * @param id The name of the section that will be played.\n     */\n    public void transitionNow(String id) {\n        AnimationSection newSection = mSectionsById.get(id);\n        if (newSection == null) {\n            throw new IllegalArgumentException(\"transitionNow called with invalid id: \" + id);\n        }\n\n        // If the section has a transition from the old section, play the\n        // transition before the main animation.\n        NotifyingAnimationDrawable transition = mCurrentSection == null ?\n                newSection.getTransition(\"\") :\n                newSection.getTransition(mCurrentSection.getId());\n        if (transition != null) {\n            mCurrentDrawable = transition;\n            mTransitioningFromId = mCurrentSection == null ? \"\" : mCurrentSection.getId();\n        } else {\n            mCurrentDrawable = newSection.loadDrawable();\n            mTransitioningFromId = null;\n        }\n        mCurrentSection = newSection;\n        mQueuedSectionId = null;\n\n        playDrawable(mCurrentDrawable);\n    }\n\n    /**\n     * Clear any currently playing animation. This will cause a \"\" transition to\n     * be played before the next queued section, if one was defined.\n     */\n    public void clearAnimation() {\n        if (mCurrentDrawable != null) {\n            mCurrentDrawable.stop();\n        }\n        if (mView != null) {\n            mView.setBackgroundResource(0);\n        }\n        mCurrentDrawable = null;\n        mCurrentSection = null;\n        mQueuedSectionId = null;\n        mTransitioningFromId = null;\n    }\n\n    /**\n     * Callback that is run when a playing animation finishes.\n     */\n    @Override\n    public void onAnimationFinished() {\n        AnimationSeriesListener listener = mListener.get();\n        if (listener != null) {\n            listener.onAnimationFinished();\n        }\n        if (mTransitioningFromId != null) {\n            mTransitioningFromId = null;\n            playDrawable(mCurrentSection.loadDrawable());\n        } else if (mQueuedSectionId != null) {\n            transitionNow(mQueuedSectionId);\n        }\n    }\n}\n"
  },
  {
    "path": "library/src/main/java/com/getkeepsafe/android/multistateanimation/NotifyingAnimationDrawable.java",
    "content": "package com.getkeepsafe.android.multistateanimation;\n\nimport android.graphics.drawable.AnimationDrawable;\n\nimport java.lang.ref.WeakReference;\n\n/**\n * Extends AnimationDrawable to signal an event when the animation finishes.\n * This class behaves identically to a normal AnimationDrawable, but contains a method for\n * registering a callback that is called whenever the final frame of the animation is played.\n * If the animation is continuous, the callback will be called repeatedly while the animation\n * is running.\n *\n * @author AJ Alt\n */\npublic class NotifyingAnimationDrawable extends AnimationDrawable {\n    public interface OnAnimationFinishedListener {\n        void onAnimationFinished();\n    }\n\n    private boolean mFinished = false;\n    private WeakReference<OnAnimationFinishedListener> mListener = new WeakReference<OnAnimationFinishedListener>(null);\n\n    /**\n     * @param drawable The frames data from animation will be copied into this instance. The animation object will be unchanged.\n     */\n    public NotifyingAnimationDrawable(AnimationDrawable drawable) {\n        for (int i = 0; i < drawable.getNumberOfFrames(); i++) {\n            addFrame(drawable.getFrame(i), drawable.getDuration(i));\n        }\n        setOneShot(drawable.isOneShot());\n    }\n\n    public NotifyingAnimationDrawable() {\n        super();\n    }\n\n    /**\n     * @return The registered animation listener, or null if none exists.\n     */\n    public OnAnimationFinishedListener getAnimationFinishedListener() {\n        return mListener.get();\n    }\n\n    /**\n     * Sets a listener that will be called when the last frame of the animation is rendered.\n     * If the animation is continuous, the listener will be called repeatedly while the animation\n     * is running.\n     *\n     * @param listener The listener to register.\n     */\n    public void setAnimationFinishedListener(OnAnimationFinishedListener listener) {\n        this.mListener = new WeakReference<OnAnimationFinishedListener>(listener);\n    }\n\n    /**\n     * Indicates whether the animation has ever finished.\n     */\n    public boolean isFinished() {\n        return mFinished;\n    }\n\n    @Override\n    public boolean selectDrawable(int idx) {\n        boolean result = super.selectDrawable(idx);\n\n        if (idx != 0 && idx == getNumberOfFrames() - 1) {\n            if (!mFinished || !isOneShot()) {\n                mFinished = true;\n                OnAnimationFinishedListener listener = mListener.get();\n                if (listener != null) {\n                    listener.onAnimationFinished();\n                }\n            }\n        }\n\n        return result;\n    }\n}"
  },
  {
    "path": "samples/.gitignore",
    "content": "/build\n/src/version/\n"
  },
  {
    "path": "samples/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.getkeepsafe.android.multistateanimation.samples\">\n\n    <android:uses-permission\n        android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"\n        android:maxSdkVersion=\"18\" />\n    <android:uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />\n    <android:uses-permission\n        android:name=\"android.permission.READ_EXTERNAL_STORAGE\"\n        android:maxSdkVersion=\"18\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\">\n        <activity\n            android:name=\"com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity\"\n            android:label=\"@string/title_activity_three_state_sample\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>\n"
  },
  {
    "path": "samples/build.gradle",
    "content": "buildscript {\n    repositories {\n        mavenCentral()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:1.2.3'\n    }\n}\n\napply plugin: 'com.android.application'\n\nrepositories {\n    mavenCentral()\n}\n\ndependencies {\n    compile project(':library')\n}\n\nandroid {\n    compileSdkVersion 22\n    buildToolsVersion \"22.0.1\"\n\n    defaultConfig {\n        minSdkVersion 1\n        targetSdkVersion 22\n        applicationId \"com.getkeepsafe.android.multistateanimation.samples\"\n        versionCode 3\n        versionName \"1.1.1\"\n    }\n\n    sourceSets {\n        main {\n            manifest.srcFile 'AndroidManifest.xml'\n            res.srcDirs = ['res']\n            assets.srcDirs = ['assets']\n        }\n    }\n\n    lintOptions {\n        abortOnError false\n    }\n}\n"
  },
  {
    "path": "samples/res/layout/activity_three_state_sample.xml",
    "content": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n                xmlns:tools=\"http://schemas.android.com/tools\"\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"match_parent\"\n                android:paddingBottom=\"@dimen/activity_vertical_margin\"\n                android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n                android:paddingRight=\"@dimen/activity_horizontal_margin\"\n                android:paddingTop=\"@dimen/activity_vertical_margin\"\n                tools:context=\"com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity\">\n\n    <ImageView\n        android:id=\"@+id/animationImageView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_above=\"@+id/current_state_textview\"\n        android:layout_toLeftOf=\"@+id/next_state_btn\"\n        android:layout_toStartOf=\"@+id/next_state_btn\"\n        tools:src=\"@drawable/loading_animation_end_023\"/>\n\n\n    <ImageView\n        android:id=\"@+id/animationImageView2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_above=\"@+id/current_state_textview\"\n        android:layout_toEndOf=\"@+id/next_state_btn\"\n        android:layout_toRightOf=\"@+id/next_state_btn\"\n        tools:src=\"@drawable/pending_animation_099\"/>\n\n    <TextView\n        android:id=\"@+id/current_state_textview\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_above=\"@+id/next_state_btn\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_marginTop=\"45dp\"/>\n\n\n    <Button\n        android:id=\"@+id/next_state_btn\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_marginTop=\"45dp\"\n        android:onClick=\"onNextStateBtnClick\"\n        android:text=\"@string/next_state_btn_text\"/>\n\n</RelativeLayout>\n"
  },
  {
    "path": "samples/res/menu/menu_three_state_sample.xml",
    "content": "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n    xmlns:tools=\"http://schemas.android.com/tools\"\r\n    tools:context=\"com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity\">\r\n    <item android:id=\"@+id/action_settings\" android:title=\"@string/action_settings\"\r\n        android:orderInCategory=\"100\" android:showAsAction=\"never\" />\r\n</menu>\r\n"
  },
  {
    "path": "samples/res/raw/sample_animation.json",
    "content": "{\n    \"pending\": {\n        \"oneshot\": true,\n        \"frames\": [\n            \"loading_animation_start_000\"\n        ]\n    },\n    \"loading\": {\n        \"frame_duration\": 33,\n        \"oneshot\": false,\n        \"transitions_from\": {\n            \"pending\": {\n                \"frame_duration\": 33,\n                \"frames\": [\n                    \"loading_animation_start_000\",\n                    \"loading_animation_start_001\",\n                    \"loading_animation_start_002\",\n                    \"loading_animation_start_003\",\n                    \"loading_animation_start_004\",\n                    \"loading_animation_start_005\",\n                    \"loading_animation_start_006\",\n                    \"loading_animation_start_007\",\n                    \"loading_animation_start_008\",\n                    \"loading_animation_start_009\",\n                    \"loading_animation_start_010\",\n                    \"loading_animation_start_011\",\n                    \"loading_animation_start_012\",\n                    \"loading_animation_start_013\",\n                    \"loading_animation_start_014\",\n                    \"loading_animation_start_015\",\n                    \"loading_animation_start_016\",\n                    \"loading_animation_start_017\",\n                    \"loading_animation_start_018\",\n                    \"loading_animation_start_019\",\n                    \"loading_animation_start_020\",\n                    \"loading_animation_start_021\",\n                    \"loading_animation_start_022\",\n                    \"loading_animation_start_023\",\n                    \"loading_animation_start_024\"\n                ]\n            }\n        },\n        \"frames\": [\n            \"loading_animation_work_000\",\n            \"loading_animation_work_001\",\n            \"loading_animation_work_002\",\n            \"loading_animation_work_003\",\n            \"loading_animation_work_004\",\n            \"loading_animation_work_005\",\n            \"loading_animation_work_006\",\n            \"loading_animation_work_007\",\n            \"loading_animation_work_008\",\n            \"loading_animation_work_009\",\n            \"loading_animation_work_010\",\n            \"loading_animation_work_011\",\n            \"loading_animation_work_012\",\n            \"loading_animation_work_013\",\n            \"loading_animation_work_014\"\n        ]\n    },\n    \"finished\": {\n        \"oneshot\": true,\n        \"transitions_from\": {\n            \"loading\": {\n                \"frame_duration\": 33,\n                \"frames\": [\n                    \"loading_animation_end_000\",\n                    \"loading_animation_end_001\",\n                    \"loading_animation_end_002\",\n                    \"loading_animation_end_003\",\n                    \"loading_animation_end_004\",\n                    \"loading_animation_end_005\",\n                    \"loading_animation_end_006\",\n                    \"loading_animation_end_007\",\n                    \"loading_animation_end_008\",\n                    \"loading_animation_end_009\",\n                    \"loading_animation_end_010\",\n                    \"loading_animation_end_011\",\n                    \"loading_animation_end_012\",\n                    \"loading_animation_end_013\",\n                    \"loading_animation_end_014\",\n                    \"loading_animation_end_015\",\n                    \"loading_animation_end_016\",\n                    \"loading_animation_end_017\",\n                    \"loading_animation_end_018\",\n                    \"loading_animation_end_019\",\n                    \"loading_animation_end_020\",\n                    \"loading_animation_end_021\",\n                    \"loading_animation_end_022\",\n                    \"loading_animation_end_023\"\n                ]\n            }\n        },\n        \"frames\": [\n            \"loading_animation_end_023\"    \n        ]\n    }\n}\n"
  },
  {
    "path": "samples/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<resources>\r\n    <color name=\"bg_blue\">#3F99D6</color>\r\n</resources>"
  },
  {
    "path": "samples/res/values/dimens.xml",
    "content": "<resources>\r\n    <!-- Default screen margins, per the Android Design guidelines. -->\r\n    <dimen name=\"activity_horizontal_margin\">16dp</dimen>\r\n    <dimen name=\"activity_vertical_margin\">16dp</dimen>\r\n</resources>\r\n"
  },
  {
    "path": "samples/res/values/strings.xml",
    "content": "<resources>\n\n    <string name=\"title_activity_three_state_sample\">ThreeStateSampleActivity</string>\n    <string name=\"app_name\">Sample App</string>\n\n    <string name=\"hello_world\">Hello world!</string>\n    <string name=\"action_settings\">Settings</string>\n    <string name=\"next_state_btn_text\">Next State</string>\n</resources>\n"
  },
  {
    "path": "samples/res/values/styles.xml",
    "content": "<resources>\n    <style name=\"AppTheme\" parent=\"android:Theme.Light\">\n        <item name=\"android:windowBackground\">@color/bg_blue</item>\n    </style>\n</resources>\n"
  },
  {
    "path": "samples/res/values-w820dp/dimens.xml",
    "content": "<resources>\r\n    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r\n         (such as screen margins) for screens with more than 820dp of available width. This\r\n         would include 7\" and 10\" devices in landscape (~960dp and ~1280dp respectively). -->\r\n    <dimen name=\"activity_horizontal_margin\">64dp</dimen>\r\n</resources>\r\n"
  },
  {
    "path": "samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java",
    "content": "package com.getkeepsafe.android.multistateanimation.samples;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\n\nimport com.getkeepsafe.android.multistateanimation.MultiStateAnimation;\n\n\npublic class ThreeStateSampleActivity extends Activity implements MultiStateAnimation.AnimationSeriesListener {\n    private MultiStateAnimation mAnimation1;\n    private MultiStateAnimation mAnimation2;\n    private TextView mCurrentStateTextView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_three_state_sample);\n        mCurrentStateTextView = (TextView) findViewById(R.id.current_state_textview);\n        mCurrentStateTextView.setText(\"Not started\");\n\n        ImageView animationView1 = (ImageView) findViewById(R.id.animationImageView1);\n        mAnimation1 = MultiStateAnimation.fromJsonResource(this, animationView1, R.raw.sample_animation);\n        mAnimation1.setSeriesAnimationFinishedListener(this);\n\n        ImageView animationView2 = (ImageView) findViewById(R.id.animationImageView2);\n        mAnimation2 = makeAnimation2(animationView2);\n        mAnimation2.setSeriesAnimationFinishedListener(this);\n\n        mAnimation1.transitionNow(\"pending\");\n        mAnimation2.transitionNow(\"pending\");\n    }\n\n    public void onNextStateBtnClick(View view) {\n        if (mAnimation1.getCurrentSectionId() == null) {\n            mAnimation1.transitionNow(\"pending\");\n            mAnimation2.transitionNow(\"pending\");\n            return;\n        }\n        switch (mAnimation1.getCurrentSectionId()) {\n            case \"pending\":\n                mAnimation1.queueTransition(\"loading\");\n                mAnimation2.queueTransition(\"loading\");\n                break;\n            case \"loading\":\n                mAnimation1.queueTransition(\"finished\");\n                mAnimation2.queueTransition(\"finished\");\n                break;\n            case \"finished\":\n                mAnimation1.queueTransition(\"pending\");\n                mAnimation2.queueTransition(\"pending\");\n                break;\n        }\n    }\n\n    @Override\n    public void onAnimationFinished() {\n        if (mAnimation1.getCurrentDrawable().isOneShot()) {\n            mCurrentStateTextView.setText(\"Showing: \" + mAnimation1.getCurrentSectionId());\n        }\n    }\n\n    @Override\n    public void onAnimationStarting() {\n        if (mAnimation1.getTransitioningFromId() != null) {\n            mCurrentStateTextView.setText(\"Transitioning to: \" + mAnimation1.getCurrentSectionId());\n        } else if (!mAnimation1.getCurrentDrawable().isOneShot()) {\n            mCurrentStateTextView.setText(\"Current state: \" + mAnimation1.getCurrentSectionId());\n        }\n    }\n\n    private MultiStateAnimation makeAnimation2(View view) {\n        MultiStateAnimation.SectionBuilder startSection = new MultiStateAnimation.SectionBuilder(\"pending\")\n                .setOneshot(true)\n                .addFrame(R.drawable.pending_animation_000);\n\n        MultiStateAnimation.TransitionBuilder endTransition = new MultiStateAnimation.TransitionBuilder()\n                .setFrameDuration(33)\n                .addFrame(R.drawable.pending_animation_091)\n                .addFrame(R.drawable.pending_animation_092)\n                .addFrame(R.drawable.pending_animation_093)\n                .addFrame(R.drawable.pending_animation_094)\n                .addFrame(R.drawable.pending_animation_095)\n                .addFrame(R.drawable.pending_animation_096)\n                .addFrame(R.drawable.pending_animation_097)\n                .addFrame(R.drawable.pending_animation_098);\n\n        MultiStateAnimation.SectionBuilder endSection = new MultiStateAnimation.SectionBuilder(\"finished\")\n                .setOneshot(true)\n                .addTransition(\"working\", endTransition)\n                .addFrame(R.drawable.pending_animation_099);\n\n        MultiStateAnimation.SectionBuilder loadingSection = new MultiStateAnimation.SectionBuilder(\"loading\")\n                .setOneshot(false)\n                .setFrameDuration(33)\n                .addFrame(R.drawable.pending_animation_001)\n                .addFrame(R.drawable.pending_animation_002)\n                .addFrame(R.drawable.pending_animation_003)\n                .addFrame(R.drawable.pending_animation_004)\n                .addFrame(R.drawable.pending_animation_005)\n                .addFrame(R.drawable.pending_animation_006)\n                .addFrame(R.drawable.pending_animation_007)\n                .addFrame(R.drawable.pending_animation_008)\n                .addFrame(R.drawable.pending_animation_009)\n                .addFrame(R.drawable.pending_animation_010)\n                .addFrame(R.drawable.pending_animation_011)\n                .addFrame(R.drawable.pending_animation_012)\n                .addFrame(R.drawable.pending_animation_013)\n                .addFrame(R.drawable.pending_animation_014)\n                .addFrame(R.drawable.pending_animation_015)\n                .addFrame(R.drawable.pending_animation_016)\n                .addFrame(R.drawable.pending_animation_017)\n                .addFrame(R.drawable.pending_animation_018)\n                .addFrame(R.drawable.pending_animation_019)\n                .addFrame(R.drawable.pending_animation_020)\n                .addFrame(R.drawable.pending_animation_021)\n                .addFrame(R.drawable.pending_animation_022)\n                .addFrame(R.drawable.pending_animation_023)\n                .addFrame(R.drawable.pending_animation_024)\n                .addFrame(R.drawable.pending_animation_025)\n                .addFrame(R.drawable.pending_animation_026)\n                .addFrame(R.drawable.pending_animation_027)\n                .addFrame(R.drawable.pending_animation_028)\n                .addFrame(R.drawable.pending_animation_029)\n                .addFrame(R.drawable.pending_animation_030)\n                .addFrame(R.drawable.pending_animation_031)\n                .addFrame(R.drawable.pending_animation_032)\n                .addFrame(R.drawable.pending_animation_033)\n                .addFrame(R.drawable.pending_animation_034)\n                .addFrame(R.drawable.pending_animation_035)\n                .addFrame(R.drawable.pending_animation_036)\n                .addFrame(R.drawable.pending_animation_037)\n                .addFrame(R.drawable.pending_animation_038)\n                .addFrame(R.drawable.pending_animation_039)\n                .addFrame(R.drawable.pending_animation_040)\n                .addFrame(R.drawable.pending_animation_041)\n                .addFrame(R.drawable.pending_animation_042)\n                .addFrame(R.drawable.pending_animation_043)\n                .addFrame(R.drawable.pending_animation_044)\n                .addFrame(R.drawable.pending_animation_045)\n                .addFrame(R.drawable.pending_animation_046)\n                .addFrame(R.drawable.pending_animation_047)\n                .addFrame(R.drawable.pending_animation_048)\n                .addFrame(R.drawable.pending_animation_049)\n                .addFrame(R.drawable.pending_animation_050)\n                .addFrame(R.drawable.pending_animation_051)\n                .addFrame(R.drawable.pending_animation_052)\n                .addFrame(R.drawable.pending_animation_053)\n                .addFrame(R.drawable.pending_animation_054)\n                .addFrame(R.drawable.pending_animation_055)\n                .addFrame(R.drawable.pending_animation_056)\n                .addFrame(R.drawable.pending_animation_057)\n                .addFrame(R.drawable.pending_animation_058)\n                .addFrame(R.drawable.pending_animation_059)\n                .addFrame(R.drawable.pending_animation_060)\n                .addFrame(R.drawable.pending_animation_061)\n                .addFrame(R.drawable.pending_animation_062)\n                .addFrame(R.drawable.pending_animation_063)\n                .addFrame(R.drawable.pending_animation_064)\n                .addFrame(R.drawable.pending_animation_065)\n                .addFrame(R.drawable.pending_animation_066)\n                .addFrame(R.drawable.pending_animation_067)\n                .addFrame(R.drawable.pending_animation_068)\n                .addFrame(R.drawable.pending_animation_069)\n                .addFrame(R.drawable.pending_animation_070)\n                .addFrame(R.drawable.pending_animation_071)\n                .addFrame(R.drawable.pending_animation_072)\n                .addFrame(R.drawable.pending_animation_073)\n                .addFrame(R.drawable.pending_animation_074)\n                .addFrame(R.drawable.pending_animation_075)\n                .addFrame(R.drawable.pending_animation_076)\n                .addFrame(R.drawable.pending_animation_077)\n                .addFrame(R.drawable.pending_animation_078)\n                .addFrame(R.drawable.pending_animation_079)\n                .addFrame(R.drawable.pending_animation_080)\n                .addFrame(R.drawable.pending_animation_081)\n                .addFrame(R.drawable.pending_animation_082)\n                .addFrame(R.drawable.pending_animation_083)\n                .addFrame(R.drawable.pending_animation_084)\n                .addFrame(R.drawable.pending_animation_085)\n                .addFrame(R.drawable.pending_animation_086)\n                .addFrame(R.drawable.pending_animation_087)\n                .addFrame(R.drawable.pending_animation_088)\n                .addFrame(R.drawable.pending_animation_089)\n                .addFrame(R.drawable.pending_animation_090);\n\n        return new MultiStateAnimation.Builder(view)\n                .addSection(startSection)\n                .addSection(loadingSection)\n                .addSection(endSection)\n                .build(this);\n    }\n}\n"
  },
  {
    "path": "scripts/generate_animation_json.py",
    "content": "#!/usr/bin/env python3\nimport argparse\nimport collections\nimport json\nimport pathlib\nimport re\nimport sys\n\nclass Spec(collections.OrderedDict):\n    \"\"\"An ordered defaultdict(dict).\"\"\"\n    def __missing__(self, key):\n        self[key] = ret = {}\n        return ret\n\n\n# A list of image filetypes used to filter out hidden files etc. from section\n# directories\nVALID_EXTENSITONS = {'.png', '.gif', '.bmp', '.jpg', '.jpeg'}\n\ndef answer_to_bool(answer):\n    \"\"\"Convert a string to a boolean.\"\"\"\n    a = answer.lower()\n    if any(w.startswith(a) for w in ('yes', 'true', '1')):\n        return True\n    elif any(w.startswith(a) for w in ('no', 'false', '0')):\n        return False\n\ndef get_answer(question, allow_empty=False):\n    \"\"\"Ask the user a question until they enter input.\"\"\"\n    ans = ''\n    while not ans:\n        ans = input(question.strip() + ' ')\n        if allow_empty: \n            break\n    return ans.strip()\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description='Generate an animation specification file.'\n        'e.x.\\n`%(prog)s 01-start-image/  02-working/  03-end-transition/  04-end-image/`',\n        epilog='''The arguments to this program are a series of directories.\n        Each directory must contain the frames of a section of an overall\n        animation. Frames can be any image file, but the names of the files\n        must consist only of letters, numbers, and underscores. The program\n        will ask a series of questions about each directory to generate the\n        final specification. Each section must be given an ID, which does not\n        have to match the directory name.''')\n    parser.add_argument('directories', metavar='DIRS', nargs='+', type=pathlib.Path,\n                       help='Directories of animation sequence. Each directory '\n                       'should contain all of the frames for one section.')\n    parser.add_argument('-d', '--frame-duration', type=int, default=33, metavar='INT',\n                        help='Milliseconds per frame of the animation '\n                        '(16 = 60fps, 33 = 30fps) [default: %(default)s]')\n    parser.add_argument('-o', '--output', metavar='FILE', type=pathlib.Path,\n                        help='If given, write output to %(metavar)s isntead of stdout.')\n\n    args = parser.parse_args()\n\n    spec = Spec()\n\n    for path in args.directories:\n        if not path.is_dir():\n            print('Directory %s does not exist' % dirname)\n            sys.exit(1)\n\n        print('Working on directory %s...' % path)\n\n        # The frames are the file names in the directory without path or extenstions\n        frames = [f.stem for f in path.iterdir() if f.suffix in VALID_EXTENSITONS]\n        for frame in frames:\n            if re.search(r'^\\w+$', frame) is None:\n                print('ERROR: filename %s is not valid. Filenames must consist '\n                      'only of letters, numbers and underscores' % frame)\n                sys.exit(1)\n\n        if len(frames) > 1:\n            if answer_to_bool(get_answer('Are these frames a transition [y/n]?')):\n                from_id = get_answer(\n                    'What is the ID that these frames are a transition FROM '\n                    '(leave empty for initial transition)?', allow_empty=True)\n                section_id = get_answer('What is the ID that these frames are a transition TO?')\n                # Create the section if it doesn't exist yet.\n                spec[section_id].setdefault('transitions_from', {})[from_id] = {\n                    'frame_duration': args.frame_duration,\n                    'frames': frames\n                }\n                print()\n                continue\n            \n        section_id = get_answer('What is the name of this section?')\n\n        # Single-frame sections are automatically oneshot with default duration.\n        if len(frames) == 1:\n            oneshot = True\n        else:\n            spec[section_id]['frame_duration'] = args.frame_duration\n            oneshot = answer_to_bool(get_answer('Is this section a oneshot [y/n]?'))\n\n        spec[section_id]['oneshot'] = oneshot\n        spec[section_id]['frames'] = frames\n\n        print()\n\n    if args.output:\n        with open(args.output, 'w') as f:\n            json.dump(spec, f, indent=4)\n    else:\n        print(json.dumps(spec, indent=4))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':library', ':samples'\n"
  }
]