Full Code of KeepSafe/MultiStateAnimation for AI

master 7dbd2d19437a cached
30 files
84.0 KB
19.2k tokens
73 symbols
1 requests
Download .txt
Repository: KeepSafe/MultiStateAnimation
Branch: master
Commit: 7dbd2d19437a
Files: 30
Total size: 84.0 KB

Directory structure:
gitextract_u5l7ysds/

├── .gitignore
├── LICENSE.txt
├── README.md
├── build.gradle
├── gradle/
│   ├── gradle-mvn-push.gradle
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── library/
│   ├── .gitignore
│   ├── AndroidManifest.xml
│   ├── build.gradle
│   ├── gradle.properties
│   └── src/
│       └── main/
│           └── java/
│               └── com/
│                   └── getkeepsafe/
│                       └── android/
│                           └── multistateanimation/
│                               ├── MultiStateAnimation.java
│                               └── NotifyingAnimationDrawable.java
├── samples/
│   ├── .gitignore
│   ├── AndroidManifest.xml
│   ├── build.gradle
│   ├── res/
│   │   ├── layout/
│   │   │   └── activity_three_state_sample.xml
│   │   ├── menu/
│   │   │   └── menu_three_state_sample.xml
│   │   ├── raw/
│   │   │   └── sample_animation.json
│   │   ├── values/
│   │   │   ├── colors.xml
│   │   │   ├── dimens.xml
│   │   │   ├── strings.xml
│   │   │   └── styles.xml
│   │   └── values-w820dp/
│   │       └── dimens.xml
│   └── src/
│       └── main/
│           └── java/
│               └── com/
│                   └── getkeepsafe/
│                       └── android/
│                           └── multistateanimation/
│                               └── samples/
│                                   └── ThreeStateSampleActivity.java
├── scripts/
│   └── generate_animation_json.py
└── settings.gradle

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

================================================
FILE: .gitignore
================================================
bin/
gen/
build/
local.properties
Thumbs.db
.DS_Store
.idea
.gradle
*.iml


================================================
FILE: LICENSE.txt
================================================

                                 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.md
================================================
# MultiStateAnimation

Android library to create complex multi-state animations.

![Demo animation](docs/images/demo_1.gif)

## Overview

A class that allows for complex multi-state animations using Android's
`AnimationDrawable`. It supports both oneshot and looped animation sections.
Transitions between sections can be defined, and will play automatically when
moving between the defined states. State transitions can be queued
asynchronously, and the library will take car of smoothly starting the next
animation once the current section is complete.

## Installation

Add the following dependency to your gradle build file:
```gradle
    dependencies {  
        compile 'com.getkeepsafe.android.multistateanimation:library:1.1.1'
    }
```
## Usage
Each animation consists of a series of states. A state has some metadata and a list
of frames to draw. A state can also define transitions from other states. A
transition is a list of frames that will be played when moving directly from a
specified state to the state where the transition is defined.

An animation can be defined either with a JSON file included as a `raw` resource, 
or directly in Java code using builders.

### Defining an animation with Java code

```java

    // The ID is used in code to specify a section to play
    MultiStateAnimation.SectionBuilder firstSection = new MultiStateAnimation.SectionBuilder("first_section")
        // If true, this section will play once and stop. Otherwise it
        // will loop indefinitely.
        .setOneshot(false)
        // The number of milliseconds that each frame of this section will
        // play
        .setFrameDuration(33)
        // Each frame is the name of an image resource. They will be
        // played in the order added.
        .addFrame(R.drawable.first_section_01)
        .addFrame(R.drawable.first_section_02);

    // The frames of a transition will be played before playing
    // the normal frames of this section when transitioning. In
    // this case, the frames for this transition will play if
    // "first_section" is playing when queueTransition("second_section") 
    // is called
    MultiStateAnimation.TransitionBuilder transitionFromFirst = new MultiStateAnimation.TransitionBuilder()
        .setFrameDuration(33)
        .addFrame(R.drawable.first_to_second_transition_001)
        .addFrame(R.drawable.first_to_second_transition_002)
        .addFrame(R.drawable.first_to_second_transition_003);

    // As a special case, a transition ID of "" is a transition
    // from nothing. It will play if the associated section is the
    // first to ever play.
    MultiStateAnimation.TransitionBuilder transitionFromNothing = new MultiStateAnimation.TransitionBuilder()
        .addFrame(R.drawable.nothing_to_second_001)
        .addFrame(R.drawable.nothing_to_second_002);

    // A section with a single frame and "oneshot" set to true is
    // equivalent to a static image
    MultiStateAnimation.SectionBuilder secondSection = new MultiStateAnimation.SectionBuilder("second_section")
        .setOneshot(true)
        .addTransition("first_section", transitionFromFirst)
        .addTransition("", transitionFromNothing)
        .addFrame(R.drawable.second_section_01);

    // Animation should be given an View that will be used to display the animation.
    ImageView view = (ImageView) findViewById(R.id.animationImageView);
    MultiStateAnimation animation = new MultiStateAnimation.Builder(view)
        .addSection(startSection)
        .addSection(loadingSection)
        .addSection(endSection)
        .build(context);

```

### Defining an animation using JSON

As 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.

```javascript

    {
        "first_section": { 
            "oneshot": false, 
            "frame_duration": 33, 
            "frames": [
                "first_section_1",
                "first_section_2"
            ],
    
        }
    
        "second_section": {
            "oneshot": true,
            "frames": [
                "second_section_01"
            ],
            "transitions_from": {
                "first_section": {
                    "frame_duration": 33,
                    "frames": [
                            "first_to_second_transition_001",
                            "first_to_second_transition_002",
                            "first_to_second_transition_003"
                    ]
                }
                "": {
                    "frames": [
                        "nothing_to_second_001",
                        "nothing_to_second_002"
                    ]
                }
            }
        }
    }

```

Then a `MultiStateAnimationOjbect` can be created in Java:

```java

    ImageView view = (ImageView) findViewById(R.id.animationImageView);
    MultiStateAnimation animationSeries = MultiStateAnimation.fromJsonResource(context, view, R.raw.sample_animation);

```

#### Generating JSON animation files automatically

Included 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.

For example, to generate the JSON file above, create a folder structure like this:
```bash
    .
    ├── first_section
    │   ├── first_section_1.png
    │   └── first_section_2.png
    ├── first_to_second_transition
    │   ├── first_to_second_transition_001.png
    │   ├── first_to_second_transition_002.png
    │   └── first_to_second_transition_003.png
    ├── nothing_to_second_transition
    │   ├── nothing_to_second_001.png
    │   └── nothing_to_second_002.png
    └── second_section
        └── second_section_01.png
```
These folders can be located anywhere in your filesystem. To generate the JSON file, run the script with the folders as arguments:
```bash
    python generate_animation_json.py first_section/ second_section/ first_to_second_transition/ nothing_to_second_transition/ --output=sample_animation.json
```
The 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

### Playing animations

Once the animation object is created via one of the above methods, you can use `queueTransition` and `transitionNow` 
from the GUI thread to start playing the animations.

```java

    animationSeries.queueTransition("first_section");
    
```

## Sample application

See 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)
 in the [sample application](samples/) for an example.

## Java API

Check out [the Javadocs](http://keepsafe.github.io/MultiStateAnimation/) for more API details.

## License

    Copyright 2016 KeepSafe Inc.

    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: build.gradle
================================================
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}


================================================
FILE: gradle/gradle-mvn-push.gradle
================================================
/*
 * Copyright 2013 Chris Banes
 *
 * 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.
 */

apply plugin: 'maven'
apply plugin: 'signing'

def isReleaseBuild() {
    return VERSION_NAME.contains("SNAPSHOT") == false
}

def getReleaseRepositoryUrl() {
    return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
            : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}

def getSnapshotRepositoryUrl() {
    return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
            : "https://oss.sonatype.org/content/repositories/snapshots/"
}

def getRepositoryUsername() {
    return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
}

def getRepositoryPassword() {
    return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
}

afterEvaluate { project ->
    uploadArchives {
        repositories {
            mavenDeployer {
                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

                pom.groupId = GROUP
                pom.artifactId = POM_ARTIFACT_ID
                pom.version = VERSION_NAME

                repository(url: getReleaseRepositoryUrl()) {
                    authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
                }
                snapshotRepository(url: getSnapshotRepositoryUrl()) {
                    authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
                }

                pom.project {
                    name POM_NAME
                    packaging POM_PACKAGING
                    description POM_DESCRIPTION
                    url POM_URL

                    scm {
                        url POM_SCM_URL
                        connection POM_SCM_CONNECTION
                        developerConnection POM_SCM_DEV_CONNECTION
                    }

                    licenses {
                        license {
                            name POM_LICENCE_NAME
                            url POM_LICENCE_URL
                            distribution POM_LICENCE_DIST
                        }
                    }

                    developers {
                        developer {
                            id POM_DEVELOPER_ID
                            name POM_DEVELOPER_NAME
                        }
                    }
                }
            }
        }
    }

    signing {
        required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
        sign configurations.archives
    }

    task androidJavadocs(type: Javadoc) {
        source = android.sourceSets.main.java.srcDirs
        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    }

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

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

    artifacts {
        archives androidSourcesJar
        archives androidJavadocsJar
    }
}


================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip


================================================
FILE: gradle.properties
================================================
VERSION_NAME=1.1.1
VERSION_CODE=3
GROUP=com.getkeepsafe.android.multistateanimation

POM_ARTIFACT_ID=MultiStateAnimation
POM_NAME=MultiStateAnimation
POM_PACKAGING=aar

POM_DESCRIPTION=An Android library to create complex animations.
POM_INCEPTION_YEAR=2015

POM_URL=https://github.com/KeepSafe/MultiStateAnimation
POM_SCM_URL=https://github.com/KeepSafe/MultiStateAnimation
POM_SCM_CONNECTION=scm:git:git://github.com/KeepSafe/MultiStateAnimation.git
POM_SCM_DEV_CONNECTION=scm:git:git@github.com:KeepSafe/MultiStateAnimation.git

POM_LICENCE_NAME=Apache License 2.0
POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo

POM_DEVELOPER_ID=keepsafe
POM_DEVELOPER_NAME=KeepSafe Software, Inc.


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

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

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

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

# 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
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

# 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\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-

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" ] ; 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"`

    # 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

# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
    JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"


================================================
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

@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=

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

@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 Windowz variants

if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_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=%*
goto execute

:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
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: library/.gitignore
================================================
/build


================================================
FILE: library/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.getkeepsafe.android.multistateanimation">
</manifest>


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

group = GROUP
version = VERSION_NAME

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.1'

    defaultConfig {
        minSdkVersion 1
        targetSdkVersion 22
        versionCode 3
        versionName '1.1.1'
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            res.srcDirs = ['res']
        }
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

android.libraryVariants.all { variant ->
    task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
        // title = ''
        // description = ''
        source = variant.javaCompile.source
        classpath = files(variant.javaCompile.classpath.files, project.android.getBootClasspath())
        options {
            links "http://docs.oracle.com/javase/7/docs/api/"
            linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference"
        }
        exclude '**/BuildConfig.java'
        exclude '**/R.java'
    }
}

apply from: file('../gradle/gradle-mvn-push.gradle')


================================================
FILE: library/gradle.properties
================================================
POM_NAME=MultiStateAnimation
POM_ARTIFACT_ID=library
POM_PACKAGING=aar


================================================
FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/MultiStateAnimation.java
================================================
package com.getkeepsafe.android.multistateanimation;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.view.View;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Animates a series of separate AnimationDrawables on the background of a single View.
 * The view to animate is passed in the constructor. Animations are added with addSection, or they
 * can be defined in a JSON resource and passed to fromJsonResource. To start an animation,
 * call transitionNow or queueTransition.
 *
 * @author AJ Alt
 */
public class MultiStateAnimation implements NotifyingAnimationDrawable.OnAnimationFinishedListener {
    public static final int DEFAULT_FRAME_DURATION = 33;
    public static final boolean DEFAULT_ONESHOT_STATUS = true;

    /**
     * Cache to prevent duplicate json reads; map of resource id -> builder.
     */
    private static final Map<Integer, Builder> mBuilderCache = new HashMap<>();

    /**
     * A class that creates an AnimationDrawable from a list of frames.
     */
    private static class AnimationDrawableLoader {
        private int mFrameDuration;
        private boolean mIsOneShot;
        private int[] mFrameIds;
        private Context mContext;

        public AnimationDrawableLoader(Context context) {
            mContext = context;
        }

        public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, String[] frameNames) {
            mContext = context;
            mFrameDuration = frameDuration;
            mIsOneShot = isOneShot;
            mFrameIds = new int[frameNames.length];

            for (int i = 0; i < frameNames.length; i++) {
                mFrameIds[i] = getDrawableResourceId(mContext, frameNames[i]);
            }
        }

        public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, int[] frameIds) {
            mContext = context;
            mFrameDuration = frameDuration;
            mIsOneShot = isOneShot;
            mFrameIds = frameIds;
        }

        public NotifyingAnimationDrawable load() {
            NotifyingAnimationDrawable d = new NotifyingAnimationDrawable();
            d.setOneShot(mIsOneShot);

            // XXX: AnimationDrawable has a bug that causes it to be unresponsive
            // if exactly one frame is added. A workaround is to add the same frame
            // twice if there's only one.
            if (mFrameIds.length == 1) {
                for (int i = 0; i < 2; i++) {
                    d.addFrame(mContext.getResources().getDrawable(mFrameIds[0]), mFrameDuration);
                }
                d.setOneShot(true);
            } else {
                for (int resid : mFrameIds) {
                    d.addFrame(mContext.getResources().getDrawable(resid), mFrameDuration);
                }
            }
            return d;
        }

        /**
         * Returns the duration of this animation.
         *
         * @return int number of milliseconds that the animation will play.
         */
        public int totalDuration() {
            return mFrameDuration * mFrameIds.length;
        }
    }

    /**
     * A class that holds loaders for a single animation section and transitions to that section.
     */
    private static class AnimationSection {
        private String mId;
        private AnimationDrawableLoader mLoader;
        private Map<String, AnimationDrawableLoader> mTransitions;

        public AnimationSection(String id, AnimationDrawableLoader loader, Map<String, AnimationDrawableLoader> transitions) {
            mId = id;
            mLoader = loader;
            mTransitions = transitions;
        }

        /**
         * @param id     The id of this section.
         * @param loader A loader for this section's primary animation.
         */
        public AnimationSection(String id, AnimationDrawableLoader loader) {
            this(id, loader, new HashMap<String, AnimationDrawableLoader>());
        }

        public String getId() {
            return mId;
        }

        /**
         * Creates the primary animation drawable for this section.
         */
        public NotifyingAnimationDrawable loadDrawable() {
            return mLoader.load();
        }

        /**
         * @param fromId The id of the section to transition from.
         * @return The transition animation for fromId if one has been added, or null.
         */
        public NotifyingAnimationDrawable getTransition(String fromId) {
            if (mTransitions.containsKey(fromId)) {
                return mTransitions.get(fromId).load();
            }
            return null;
        }

        /**
         * @param fromId The Id of the section that will be transitioned from.
         * @param loader The loader for this transition animation.
         */
        public void addTransition(String fromId, AnimationDrawableLoader loader) {
            mTransitions.put(fromId, loader);
        }

        /**
         * Calculates the total duration if the animation, including the transition.
         *
         * @param fromId If a transition exists from this id, the duration will include the transition duration.
         * @return int number of milliseconds.
         */
        public int getDuration(String fromId) {
            int total = mLoader.totalDuration();
            AnimationDrawableLoader loader = mTransitions.get(fromId);
            if (loader != null) {
                total += loader.totalDuration();
            }
            return total;
        }

        /**
         * Calculates the duration of the animation, excluding any transition.
         *
         * @return int number of milliseconds.
         */
        public int getDuration() {
            return getDuration(null);
        }
    }


    public interface AnimationSeriesListener {
        /**
         * Called when a playing animation finishes and before the drawable is replaced.
         */
        void onAnimationFinished();

        /**
         * Called after a new animation has been created, but before the animation has started.
         * The new animation can be accessed through getCurrentDrawable.
         */
        void onAnimationStarting();
    }

    private WeakReference<AnimationSeriesListener> mListener = new WeakReference<AnimationSeriesListener>(null);
    private AnimationSection mCurrentSection;

    /**
     * The id of the animation that will be started as soon as the current animation
     * finishes, or null if no animation is queued.
     */
    private String mQueuedSectionId;
    private NotifyingAnimationDrawable mCurrentDrawable;

    /**
     * The id of the previous section if a transition is currently playing, or null
     * id no transition is playing.
     */
    private String mTransitioningFromId;
    private View mView;

    /**
     * An array of resource IDs corresponding to animations that can be played.
     */
    private Map<String, AnimationSection> mSectionsById;

    /**
     * Create a new instance and automatically set animations as the background of the given view.
     *
     * @param view If not null, animations will be set as the background of this view.
     */
    public MultiStateAnimation(View view) {
        mSectionsById = new HashMap<>();
        mView = view;
    }

    /**
     * Create an instance without giving a view to hold the animations.
     * <p/>
     * Note that due to a limitation in AnimationDrawable, you must set
     * created animations as the image or background of a View in an
     * onAnimationStarting listener, otherwise the animation will not
     * advance.
     *
     * @see com.getkeepsafe.android.multistateanimation.MultiStateAnimation.AnimationSeriesListener#onAnimationStarting()
     */
    public MultiStateAnimation() {
        this(null);
    }

    /**
     * Load the id for a drawable resource from its name
     */
    private static int getDrawableResourceId(Context context, String name) {
        return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
    }

    /**
     * Convert a JSONArray containing only strings to a String[].
     *
     * @param jsonArray the array to convert.
     * @return a String[] with the contents of the JSONArray.
     * @throws org.json.JSONException
     */
    private static String[] jsonArrayToArray(JSONArray jsonArray) throws JSONException {
        String[] array = new String[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getString(i);
        }
        return array;
    }

    /**
     * Convert a List of Integers to an int[]
     *
     * @param list the List to convert
     * @return an int[] with the same values as the list
     */
    private static int[] integerListToArray(List<Integer> list) {
        int[] array = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    /**
     * A Builder for a transition from one section to another.
     * <p/>
     * It's possible to use the same transition between more than one set of sections.
     */
    public static class TransitionBuilder {
        private List<Integer> mFrames = new ArrayList<>();
        private int mFrameDuration = DEFAULT_FRAME_DURATION;

        /**
         * Add a frame to the transition animation.
         *
         * @param imageResource The resource id of a image drawable.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public TransitionBuilder addFrame(int imageResource) {
            mFrames.add(imageResource);
            return this;
        }

        /**
         * Set the duration that each frame in this section will play.
         *
         * @param frameDuration The number of milliseconds that each frame will be displayed.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public TransitionBuilder setFrameDuration(int frameDuration) {
            mFrameDuration = frameDuration;
            return this;
        }

        private AnimationDrawableLoader build(Context context) {
            return new AnimationDrawableLoader(context, mFrameDuration, true, integerListToArray(mFrames));
        }
    }

    /**
     * A builder for an animation section.
     */
    public static class SectionBuilder {
        private String mId;
        private List<Integer> mFrames = new ArrayList<>();
        private boolean mIsOneshot = DEFAULT_ONESHOT_STATUS;
        private int mFrameDuration = DEFAULT_FRAME_DURATION;
        private Map<String, TransitionBuilder> mTransitions = new HashMap<>();

        /**
         * A constructor that takes the ID of this section.
         *
         * @param id The ID of the section
         */
        public SectionBuilder(String id) {
            mId = id;
        }

        /**
         * Add a frame to the section animation.
         *
         * @param imageResource The resource id of a image drawable.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public SectionBuilder addFrame(int imageResource) {
            mFrames.add(imageResource);
            return this;
        }

        /**
         * Set that oneshot status of this section.
         *
         * @param isOneshot If true, the animation for this section will pause playing on the final frame.
         *                  If false, the animation for this section will loop until a new section is transitioned to.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public SectionBuilder setOneshot(boolean isOneshot) {
            mIsOneshot = isOneshot;
            return this;
        }

        /**
         * Set the duration that each frame in this section will play.
         *
         * @param frameDuration The number of milliseconds that each frame will be displayed
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public SectionBuilder setFrameDuration(int frameDuration) {
            mFrameDuration = frameDuration;
            return this;
        }

        /**
         * Add an animation that will play when transitioning to this section.
         *
         * @param fromId     A section name. When a transition is queued from the named section to this one, this transition will play.
         * @param transition The transition that will play.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public SectionBuilder addTransition(String fromId, TransitionBuilder transition) {
            mTransitions.put(fromId, transition);
            return this;
        }

        private AnimationSection build(Context context) {
            AnimationDrawableLoader loader = new AnimationDrawableLoader(context, mFrameDuration, mIsOneshot, integerListToArray(mFrames));
            AnimationSection section = new AnimationSection(mId, loader);

            for (Map.Entry<String, TransitionBuilder> entry : mTransitions.entrySet()) {
                loader = entry.getValue().build(context);
                section.addTransition(entry.getKey(), loader);
            }

            return section;
        }
    }

    /**
     * A builder for manually constructing a MultiStateAnimation.
     */
    public static class Builder {
        List<SectionBuilder> mSections = new ArrayList<>();
        View mView = null;

        /**
         * Set a view to attach this animation to.
         *
         * The background of the view will contain the animation.
         * @param view The view that will hold the animation.
         */
        public Builder(View view) {
            mView = view;
        }

        /**
         * Add an animation section.
         * @param section The section to add.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder addSection(SectionBuilder section) {
            mSections.add(section);
            return this;
        }

        /**
         * Construct a MultiStateAnimation.
         * @param context A context used to load resources.
         * @return A new MultiStateAnimation.
         */
        public MultiStateAnimation build(Context context) {
            MultiStateAnimation animation = new MultiStateAnimation(mView);
            for (SectionBuilder section : mSections) {
                animation.addSection(section.build(context));
            }
            return animation;
        }
    }

    /**
     * Creates a new MultiStateAnimation object from a json string.
     * <p/>
     * The document must have the following structure:
     * <pre>
     *  {
     *      "first_section": {
     *          "oneshot": false,
     *          "frame_duration": 33,
     *          "frames": [
     *              "frame_01",
     *              "frame_02"
     *          ],
     *
     *      }
     *      "second_section": {
     *          "oneshot": true,
     *          "frames": [
     *              "other_frame_01"
     *          ],
     *          "transitions_from": {
     *              "first_section": {
     *                  "frame_duration": 33,
     *                  "frames": [
     *                          "first_to_second_transition_001",
     *                          "first_to_second_transition_002"
     *                  ]
     *              }
     *              "": {
     *                  "frames": [
     *                      "nothing_to_second_001",
     *                      "nothing_to_second_002"
     *                  ]
     *              }
     *          }
     *      }
     *  }
     * </pre>
     * The key for each entry is the ID of the state.
     * <dl>
     * <dt>"oneshot"</dt>
     * <dd>If false, the animation will play in a loop instead of stopping at the last
     * frame.</dd>
     * <dt>"frame_duration"</dt><dd>The number of milliseconds that each frame in the "frame"
     * list will play. It defaults to 33 (30fps) if not given.</dd>
     * <dt>"frames"</dt><dd>A list of string resource ID names that must correspond to a
     * drawable resource.</dd>
     * <dt>"transitions_from"</dt><dd>Optional, and is a set of animations that play when transitioning to
     * the current state from another given state. A transition will play when the ID of the
     * current state matches the transition's key and the state is transitioning to the state
     * in which the transition is defined.</dd>
     * </dl>
     *
     * @param context The application Context.
     * @param view    If not null, animations will be set as the background of this view.
     * @param resid   The resource ID the the raw json document.
     * @return A new MultiStateAnimation.
     * @throws RuntimeException
     */
    public static MultiStateAnimation fromJsonResource(Context context, View view, int resid) {
        // Use the cached builder, if one exists.
        if (mBuilderCache.containsKey(resid)) {
            return mBuilderCache.get(resid).build(context);
        }

        // Read the resource into a string
        BufferedReader r = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resid)));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        try {
            while ((line = r.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException ignored) {
            throw new RuntimeException("Cannot Read JSON sync animation Resource");
        }

        // Parse
        Builder animationBuilder = new Builder(view);
        try {
            JSONObject root = new JSONObject(stringBuilder.toString());

            // The root is a an object with keys that are sequence IDs
            for (Iterator<String> iter = root.keys(); iter.hasNext(); ) {
                String sectionId = iter.next();
                JSONObject obj = root.getJSONObject(sectionId);
                int frameDuration = obj.optInt("frame_duration", DEFAULT_FRAME_DURATION);
                boolean isOneShot = obj.optBoolean("oneshot", DEFAULT_ONESHOT_STATUS);
                JSONArray frames = obj.getJSONArray("frames");

                SectionBuilder sectionBuilder = new SectionBuilder(sectionId)
                        .setFrameDuration(frameDuration)
                        .setOneshot(isOneShot);

                for (String frame : jsonArrayToArray(frames)) {
                    sectionBuilder.addFrame(getDrawableResourceId(context, frame));
                }

                JSONObject transitions_from;
                if (obj.has("transitions_from")) {
                    transitions_from = obj.getJSONObject("transitions_from");
                } else {
                    transitions_from = new JSONObject();
                }

                // The optional "transitions" entry is another list of objects
                for (Iterator<String> transition_iter = transitions_from.keys(); transition_iter.hasNext(); ) {
                    String from = transition_iter.next();

                    JSONObject t_obj = transitions_from.getJSONObject(from);
                    frameDuration = t_obj.optInt("frame_duration", DEFAULT_FRAME_DURATION);
                    frames = t_obj.getJSONArray("frames");
                    TransitionBuilder transitionBuilder = new TransitionBuilder()
                            .setFrameDuration(frameDuration);
                    for (String frame : jsonArrayToArray(frames)) {
                        transitionBuilder.addFrame(getDrawableResourceId(context, frame));
                    }
                    sectionBuilder.addTransition(from, transitionBuilder);
                }
                animationBuilder.addSection(sectionBuilder);
            }
        } catch (JSONException ignored) {
            throw new RuntimeException("Invalid sync animation JSON file format.");
        }

        mBuilderCache.put(resid, animationBuilder);
        return animationBuilder.build(context);
    }

    /**
     * Create a MultiStateAnimation from a JSON resource without a connected View.
     *
     * @param context the Application context.
     * @param resid   The resource ID the the raw json document.
     * @return A new MultiStateAnimation instance.
     * @throws RuntimeException
     */
    public static MultiStateAnimation fromJsonResource(Context context, int resid)  {
        return MultiStateAnimation.fromJsonResource(context, null, resid);
    }

    /**
     * Add an animation section to this series.
     *
     * @param section the section to add.
     */
    private void addSection(AnimationSection section) {
        mSectionsById.put(section.getId(), section);
    }

    /**
     * Returns the registered listener, if one exists.
     */
    public AnimationSeriesListener getSeriesAnimationFinishedListener() {
        return mListener.get();
    }

    /**
     * Registers a listener that will be called when a running animation finishes. If the
     * animation is continuous, the listener will be called every time the last frame of the
     * animation is played.
     *
     * @param listener The listener to register.
     */
    public void setSeriesAnimationFinishedListener(AnimationSeriesListener listener) {
        this.mListener = new WeakReference<AnimationSeriesListener>(listener);
    }

    /**
     * Calculates the total duration of the current animation section, including the transition
     * if applicable. If the the animation is not a oneshot, the total will be for a single loop.
     *
     * @return The total animation duration, or 0 if no animation is playing.
     */
    public int currentSectionDuration() {
        if (mCurrentSection == null) return 0;
        return mCurrentSection.getDuration(mTransitioningFromId);
    }

    /**
     * Returns the currently playing animation. If no animation has played since this object was
     * created or since a call to {@link #clearAnimation()}, null is returned.
     */
    public AnimationDrawable getCurrentDrawable() {
        return mCurrentDrawable;
    }

    /**
     * Return the ID of the current section if one is playing, or null otherwise.
     */
    public String getCurrentSectionId() {
        return mCurrentSection == null ? null : mCurrentSection.getId();
    }

    /**
     * If the currently playing animation is a transition, return the ID of the
     * section that is being transitioned from. Otherwise return null.
     */
    public String getTransitioningFromId() {
        return mTransitioningFromId;
    }

    /**
     * Play an animation drawable.
     *
     * @param drawable The drawable to play.
     */
    @TargetApi(16)
    private void playDrawable(NotifyingAnimationDrawable drawable) {
        mCurrentDrawable = drawable;
        mCurrentDrawable.setAnimationFinishedListener(this);

        AnimationSeriesListener listener = mListener.get();
        if (listener != null) {
            listener.onAnimationStarting();
        }

        if (mView != null) {
            if (Build.VERSION.SDK_INT >= 16) {
                mView.setBackground(mCurrentDrawable);
            } else {
                mView.setBackgroundDrawable(mCurrentDrawable);
            }
        }
        mCurrentDrawable.start();
    }

    /**
     * Queues a section to start as soon as the current animation finishes.
     * If no animation is playing, the queued animation will be started immediately.
     * Queueing a transition to the currently playing section has no effect.
     *
     * @param id The name of the section that will be queued.
     */
    public void queueTransition(String id) {
        if (id.equals(getCurrentSectionId())) return;
        if (mCurrentSection == null ||
                mCurrentDrawable != null &&
                        mCurrentDrawable.isOneShot() &&
                        mCurrentDrawable.isFinished()) {
            transitionNow(id);
        } else {
            mQueuedSectionId = id;
        }
    }

    /**
     * Starts a specific section without waiting for the current animation to finish.
     * If there is a defined transition from the current section to the new one, the
     * transition will be played, followed immediately by the regular section animation.
     * Transitioning to the currently playing section will restart the animation.
     *
     * @param id The name of the section that will be played.
     */
    public void transitionNow(String id) {
        AnimationSection newSection = mSectionsById.get(id);
        if (newSection == null) {
            throw new IllegalArgumentException("transitionNow called with invalid id: " + id);
        }

        // If the section has a transition from the old section, play the
        // transition before the main animation.
        NotifyingAnimationDrawable transition = mCurrentSection == null ?
                newSection.getTransition("") :
                newSection.getTransition(mCurrentSection.getId());
        if (transition != null) {
            mCurrentDrawable = transition;
            mTransitioningFromId = mCurrentSection == null ? "" : mCurrentSection.getId();
        } else {
            mCurrentDrawable = newSection.loadDrawable();
            mTransitioningFromId = null;
        }
        mCurrentSection = newSection;
        mQueuedSectionId = null;

        playDrawable(mCurrentDrawable);
    }

    /**
     * Clear any currently playing animation. This will cause a "" transition to
     * be played before the next queued section, if one was defined.
     */
    public void clearAnimation() {
        if (mCurrentDrawable != null) {
            mCurrentDrawable.stop();
        }
        if (mView != null) {
            mView.setBackgroundResource(0);
        }
        mCurrentDrawable = null;
        mCurrentSection = null;
        mQueuedSectionId = null;
        mTransitioningFromId = null;
    }

    /**
     * Callback that is run when a playing animation finishes.
     */
    @Override
    public void onAnimationFinished() {
        AnimationSeriesListener listener = mListener.get();
        if (listener != null) {
            listener.onAnimationFinished();
        }
        if (mTransitioningFromId != null) {
            mTransitioningFromId = null;
            playDrawable(mCurrentSection.loadDrawable());
        } else if (mQueuedSectionId != null) {
            transitionNow(mQueuedSectionId);
        }
    }
}


================================================
FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/NotifyingAnimationDrawable.java
================================================
package com.getkeepsafe.android.multistateanimation;

import android.graphics.drawable.AnimationDrawable;

import java.lang.ref.WeakReference;

/**
 * Extends AnimationDrawable to signal an event when the animation finishes.
 * This class behaves identically to a normal AnimationDrawable, but contains a method for
 * registering a callback that is called whenever the final frame of the animation is played.
 * If the animation is continuous, the callback will be called repeatedly while the animation
 * is running.
 *
 * @author AJ Alt
 */
public class NotifyingAnimationDrawable extends AnimationDrawable {
    public interface OnAnimationFinishedListener {
        void onAnimationFinished();
    }

    private boolean mFinished = false;
    private WeakReference<OnAnimationFinishedListener> mListener = new WeakReference<OnAnimationFinishedListener>(null);

    /**
     * @param drawable The frames data from animation will be copied into this instance. The animation object will be unchanged.
     */
    public NotifyingAnimationDrawable(AnimationDrawable drawable) {
        for (int i = 0; i < drawable.getNumberOfFrames(); i++) {
            addFrame(drawable.getFrame(i), drawable.getDuration(i));
        }
        setOneShot(drawable.isOneShot());
    }

    public NotifyingAnimationDrawable() {
        super();
    }

    /**
     * @return The registered animation listener, or null if none exists.
     */
    public OnAnimationFinishedListener getAnimationFinishedListener() {
        return mListener.get();
    }

    /**
     * Sets a listener that will be called when the last frame of the animation is rendered.
     * If the animation is continuous, the listener will be called repeatedly while the animation
     * is running.
     *
     * @param listener The listener to register.
     */
    public void setAnimationFinishedListener(OnAnimationFinishedListener listener) {
        this.mListener = new WeakReference<OnAnimationFinishedListener>(listener);
    }

    /**
     * Indicates whether the animation has ever finished.
     */
    public boolean isFinished() {
        return mFinished;
    }

    @Override
    public boolean selectDrawable(int idx) {
        boolean result = super.selectDrawable(idx);

        if (idx != 0 && idx == getNumberOfFrames() - 1) {
            if (!mFinished || !isOneShot()) {
                mFinished = true;
                OnAnimationFinishedListener listener = mListener.get();
                if (listener != null) {
                    listener.onAnimationFinished();
                }
            }
        }

        return result;
    }
}

================================================
FILE: samples/.gitignore
================================================
/build
/src/version/


================================================
FILE: samples/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.getkeepsafe.android.multistateanimation.samples">

    <android:uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="18" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity"
            android:label="@string/title_activity_three_state_sample">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


================================================
FILE: samples/build.gradle
================================================
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

dependencies {
    compile project(':library')
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        minSdkVersion 1
        targetSdkVersion 22
        applicationId "com.getkeepsafe.android.multistateanimation.samples"
        versionCode 3
        versionName "1.1.1"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }

    lintOptions {
        abortOnError false
    }
}


================================================
FILE: samples/res/layout/activity_three_state_sample.xml
================================================
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context="com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity">

    <ImageView
        android:id="@+id/animationImageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/current_state_textview"
        android:layout_toLeftOf="@+id/next_state_btn"
        android:layout_toStartOf="@+id/next_state_btn"
        tools:src="@drawable/loading_animation_end_023"/>


    <ImageView
        android:id="@+id/animationImageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/current_state_textview"
        android:layout_toEndOf="@+id/next_state_btn"
        android:layout_toRightOf="@+id/next_state_btn"
        tools:src="@drawable/pending_animation_099"/>

    <TextView
        android:id="@+id/current_state_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/next_state_btn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"/>


    <Button
        android:id="@+id/next_state_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:onClick="onNextStateBtnClick"
        android:text="@string/next_state_btn_text"/>

</RelativeLayout>


================================================
FILE: samples/res/menu/menu_three_state_sample.xml
================================================
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.getkeepsafe.android.multistateanimation.samples.ThreeStateSampleActivity">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" android:showAsAction="never" />
</menu>


================================================
FILE: samples/res/raw/sample_animation.json
================================================
{
    "pending": {
        "oneshot": true,
        "frames": [
            "loading_animation_start_000"
        ]
    },
    "loading": {
        "frame_duration": 33,
        "oneshot": false,
        "transitions_from": {
            "pending": {
                "frame_duration": 33,
                "frames": [
                    "loading_animation_start_000",
                    "loading_animation_start_001",
                    "loading_animation_start_002",
                    "loading_animation_start_003",
                    "loading_animation_start_004",
                    "loading_animation_start_005",
                    "loading_animation_start_006",
                    "loading_animation_start_007",
                    "loading_animation_start_008",
                    "loading_animation_start_009",
                    "loading_animation_start_010",
                    "loading_animation_start_011",
                    "loading_animation_start_012",
                    "loading_animation_start_013",
                    "loading_animation_start_014",
                    "loading_animation_start_015",
                    "loading_animation_start_016",
                    "loading_animation_start_017",
                    "loading_animation_start_018",
                    "loading_animation_start_019",
                    "loading_animation_start_020",
                    "loading_animation_start_021",
                    "loading_animation_start_022",
                    "loading_animation_start_023",
                    "loading_animation_start_024"
                ]
            }
        },
        "frames": [
            "loading_animation_work_000",
            "loading_animation_work_001",
            "loading_animation_work_002",
            "loading_animation_work_003",
            "loading_animation_work_004",
            "loading_animation_work_005",
            "loading_animation_work_006",
            "loading_animation_work_007",
            "loading_animation_work_008",
            "loading_animation_work_009",
            "loading_animation_work_010",
            "loading_animation_work_011",
            "loading_animation_work_012",
            "loading_animation_work_013",
            "loading_animation_work_014"
        ]
    },
    "finished": {
        "oneshot": true,
        "transitions_from": {
            "loading": {
                "frame_duration": 33,
                "frames": [
                    "loading_animation_end_000",
                    "loading_animation_end_001",
                    "loading_animation_end_002",
                    "loading_animation_end_003",
                    "loading_animation_end_004",
                    "loading_animation_end_005",
                    "loading_animation_end_006",
                    "loading_animation_end_007",
                    "loading_animation_end_008",
                    "loading_animation_end_009",
                    "loading_animation_end_010",
                    "loading_animation_end_011",
                    "loading_animation_end_012",
                    "loading_animation_end_013",
                    "loading_animation_end_014",
                    "loading_animation_end_015",
                    "loading_animation_end_016",
                    "loading_animation_end_017",
                    "loading_animation_end_018",
                    "loading_animation_end_019",
                    "loading_animation_end_020",
                    "loading_animation_end_021",
                    "loading_animation_end_022",
                    "loading_animation_end_023"
                ]
            }
        },
        "frames": [
            "loading_animation_end_023"    
        ]
    }
}


================================================
FILE: samples/res/values/colors.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="bg_blue">#3F99D6</color>
</resources>

================================================
FILE: samples/res/values/dimens.xml
================================================
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>


================================================
FILE: samples/res/values/strings.xml
================================================
<resources>

    <string name="title_activity_three_state_sample">ThreeStateSampleActivity</string>
    <string name="app_name">Sample App</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="next_state_btn_text">Next State</string>
</resources>


================================================
FILE: samples/res/values/styles.xml
================================================
<resources>
    <style name="AppTheme" parent="android:Theme.Light">
        <item name="android:windowBackground">@color/bg_blue</item>
    </style>
</resources>


================================================
FILE: samples/res/values-w820dp/dimens.xml
================================================
<resources>
    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
    <dimen name="activity_horizontal_margin">64dp</dimen>
</resources>


================================================
FILE: samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java
================================================
package com.getkeepsafe.android.multistateanimation.samples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.getkeepsafe.android.multistateanimation.MultiStateAnimation;


public class ThreeStateSampleActivity extends Activity implements MultiStateAnimation.AnimationSeriesListener {
    private MultiStateAnimation mAnimation1;
    private MultiStateAnimation mAnimation2;
    private TextView mCurrentStateTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three_state_sample);
        mCurrentStateTextView = (TextView) findViewById(R.id.current_state_textview);
        mCurrentStateTextView.setText("Not started");

        ImageView animationView1 = (ImageView) findViewById(R.id.animationImageView1);
        mAnimation1 = MultiStateAnimation.fromJsonResource(this, animationView1, R.raw.sample_animation);
        mAnimation1.setSeriesAnimationFinishedListener(this);

        ImageView animationView2 = (ImageView) findViewById(R.id.animationImageView2);
        mAnimation2 = makeAnimation2(animationView2);
        mAnimation2.setSeriesAnimationFinishedListener(this);

        mAnimation1.transitionNow("pending");
        mAnimation2.transitionNow("pending");
    }

    public void onNextStateBtnClick(View view) {
        if (mAnimation1.getCurrentSectionId() == null) {
            mAnimation1.transitionNow("pending");
            mAnimation2.transitionNow("pending");
            return;
        }
        switch (mAnimation1.getCurrentSectionId()) {
            case "pending":
                mAnimation1.queueTransition("loading");
                mAnimation2.queueTransition("loading");
                break;
            case "loading":
                mAnimation1.queueTransition("finished");
                mAnimation2.queueTransition("finished");
                break;
            case "finished":
                mAnimation1.queueTransition("pending");
                mAnimation2.queueTransition("pending");
                break;
        }
    }

    @Override
    public void onAnimationFinished() {
        if (mAnimation1.getCurrentDrawable().isOneShot()) {
            mCurrentStateTextView.setText("Showing: " + mAnimation1.getCurrentSectionId());
        }
    }

    @Override
    public void onAnimationStarting() {
        if (mAnimation1.getTransitioningFromId() != null) {
            mCurrentStateTextView.setText("Transitioning to: " + mAnimation1.getCurrentSectionId());
        } else if (!mAnimation1.getCurrentDrawable().isOneShot()) {
            mCurrentStateTextView.setText("Current state: " + mAnimation1.getCurrentSectionId());
        }
    }

    private MultiStateAnimation makeAnimation2(View view) {
        MultiStateAnimation.SectionBuilder startSection = new MultiStateAnimation.SectionBuilder("pending")
                .setOneshot(true)
                .addFrame(R.drawable.pending_animation_000);

        MultiStateAnimation.TransitionBuilder endTransition = new MultiStateAnimation.TransitionBuilder()
                .setFrameDuration(33)
                .addFrame(R.drawable.pending_animation_091)
                .addFrame(R.drawable.pending_animation_092)
                .addFrame(R.drawable.pending_animation_093)
                .addFrame(R.drawable.pending_animation_094)
                .addFrame(R.drawable.pending_animation_095)
                .addFrame(R.drawable.pending_animation_096)
                .addFrame(R.drawable.pending_animation_097)
                .addFrame(R.drawable.pending_animation_098);

        MultiStateAnimation.SectionBuilder endSection = new MultiStateAnimation.SectionBuilder("finished")
                .setOneshot(true)
                .addTransition("working", endTransition)
                .addFrame(R.drawable.pending_animation_099);

        MultiStateAnimation.SectionBuilder loadingSection = new MultiStateAnimation.SectionBuilder("loading")
                .setOneshot(false)
                .setFrameDuration(33)
                .addFrame(R.drawable.pending_animation_001)
                .addFrame(R.drawable.pending_animation_002)
                .addFrame(R.drawable.pending_animation_003)
                .addFrame(R.drawable.pending_animation_004)
                .addFrame(R.drawable.pending_animation_005)
                .addFrame(R.drawable.pending_animation_006)
                .addFrame(R.drawable.pending_animation_007)
                .addFrame(R.drawable.pending_animation_008)
                .addFrame(R.drawable.pending_animation_009)
                .addFrame(R.drawable.pending_animation_010)
                .addFrame(R.drawable.pending_animation_011)
                .addFrame(R.drawable.pending_animation_012)
                .addFrame(R.drawable.pending_animation_013)
                .addFrame(R.drawable.pending_animation_014)
                .addFrame(R.drawable.pending_animation_015)
                .addFrame(R.drawable.pending_animation_016)
                .addFrame(R.drawable.pending_animation_017)
                .addFrame(R.drawable.pending_animation_018)
                .addFrame(R.drawable.pending_animation_019)
                .addFrame(R.drawable.pending_animation_020)
                .addFrame(R.drawable.pending_animation_021)
                .addFrame(R.drawable.pending_animation_022)
                .addFrame(R.drawable.pending_animation_023)
                .addFrame(R.drawable.pending_animation_024)
                .addFrame(R.drawable.pending_animation_025)
                .addFrame(R.drawable.pending_animation_026)
                .addFrame(R.drawable.pending_animation_027)
                .addFrame(R.drawable.pending_animation_028)
                .addFrame(R.drawable.pending_animation_029)
                .addFrame(R.drawable.pending_animation_030)
                .addFrame(R.drawable.pending_animation_031)
                .addFrame(R.drawable.pending_animation_032)
                .addFrame(R.drawable.pending_animation_033)
                .addFrame(R.drawable.pending_animation_034)
                .addFrame(R.drawable.pending_animation_035)
                .addFrame(R.drawable.pending_animation_036)
                .addFrame(R.drawable.pending_animation_037)
                .addFrame(R.drawable.pending_animation_038)
                .addFrame(R.drawable.pending_animation_039)
                .addFrame(R.drawable.pending_animation_040)
                .addFrame(R.drawable.pending_animation_041)
                .addFrame(R.drawable.pending_animation_042)
                .addFrame(R.drawable.pending_animation_043)
                .addFrame(R.drawable.pending_animation_044)
                .addFrame(R.drawable.pending_animation_045)
                .addFrame(R.drawable.pending_animation_046)
                .addFrame(R.drawable.pending_animation_047)
                .addFrame(R.drawable.pending_animation_048)
                .addFrame(R.drawable.pending_animation_049)
                .addFrame(R.drawable.pending_animation_050)
                .addFrame(R.drawable.pending_animation_051)
                .addFrame(R.drawable.pending_animation_052)
                .addFrame(R.drawable.pending_animation_053)
                .addFrame(R.drawable.pending_animation_054)
                .addFrame(R.drawable.pending_animation_055)
                .addFrame(R.drawable.pending_animation_056)
                .addFrame(R.drawable.pending_animation_057)
                .addFrame(R.drawable.pending_animation_058)
                .addFrame(R.drawable.pending_animation_059)
                .addFrame(R.drawable.pending_animation_060)
                .addFrame(R.drawable.pending_animation_061)
                .addFrame(R.drawable.pending_animation_062)
                .addFrame(R.drawable.pending_animation_063)
                .addFrame(R.drawable.pending_animation_064)
                .addFrame(R.drawable.pending_animation_065)
                .addFrame(R.drawable.pending_animation_066)
                .addFrame(R.drawable.pending_animation_067)
                .addFrame(R.drawable.pending_animation_068)
                .addFrame(R.drawable.pending_animation_069)
                .addFrame(R.drawable.pending_animation_070)
                .addFrame(R.drawable.pending_animation_071)
                .addFrame(R.drawable.pending_animation_072)
                .addFrame(R.drawable.pending_animation_073)
                .addFrame(R.drawable.pending_animation_074)
                .addFrame(R.drawable.pending_animation_075)
                .addFrame(R.drawable.pending_animation_076)
                .addFrame(R.drawable.pending_animation_077)
                .addFrame(R.drawable.pending_animation_078)
                .addFrame(R.drawable.pending_animation_079)
                .addFrame(R.drawable.pending_animation_080)
                .addFrame(R.drawable.pending_animation_081)
                .addFrame(R.drawable.pending_animation_082)
                .addFrame(R.drawable.pending_animation_083)
                .addFrame(R.drawable.pending_animation_084)
                .addFrame(R.drawable.pending_animation_085)
                .addFrame(R.drawable.pending_animation_086)
                .addFrame(R.drawable.pending_animation_087)
                .addFrame(R.drawable.pending_animation_088)
                .addFrame(R.drawable.pending_animation_089)
                .addFrame(R.drawable.pending_animation_090);

        return new MultiStateAnimation.Builder(view)
                .addSection(startSection)
                .addSection(loadingSection)
                .addSection(endSection)
                .build(this);
    }
}


================================================
FILE: scripts/generate_animation_json.py
================================================
#!/usr/bin/env python3
import argparse
import collections
import json
import pathlib
import re
import sys

class Spec(collections.OrderedDict):
    """An ordered defaultdict(dict)."""
    def __missing__(self, key):
        self[key] = ret = {}
        return ret


# A list of image filetypes used to filter out hidden files etc. from section
# directories
VALID_EXTENSITONS = {'.png', '.gif', '.bmp', '.jpg', '.jpeg'}

def answer_to_bool(answer):
    """Convert a string to a boolean."""
    a = answer.lower()
    if any(w.startswith(a) for w in ('yes', 'true', '1')):
        return True
    elif any(w.startswith(a) for w in ('no', 'false', '0')):
        return False

def get_answer(question, allow_empty=False):
    """Ask the user a question until they enter input."""
    ans = ''
    while not ans:
        ans = input(question.strip() + ' ')
        if allow_empty: 
            break
    return ans.strip()

def main():
    parser = argparse.ArgumentParser(
        description='Generate an animation specification file.'
        'e.x.\n`%(prog)s 01-start-image/  02-working/  03-end-transition/  04-end-image/`',
        epilog='''The arguments to this program are a series of directories.
        Each directory must contain the frames of a section of an overall
        animation. Frames can be any image file, but the names of the files
        must consist only of letters, numbers, and underscores. The program
        will ask a series of questions about each directory to generate the
        final specification. Each section must be given an ID, which does not
        have to match the directory name.''')
    parser.add_argument('directories', metavar='DIRS', nargs='+', type=pathlib.Path,
                       help='Directories of animation sequence. Each directory '
                       'should contain all of the frames for one section.')
    parser.add_argument('-d', '--frame-duration', type=int, default=33, metavar='INT',
                        help='Milliseconds per frame of the animation '
                        '(16 = 60fps, 33 = 30fps) [default: %(default)s]')
    parser.add_argument('-o', '--output', metavar='FILE', type=pathlib.Path,
                        help='If given, write output to %(metavar)s isntead of stdout.')

    args = parser.parse_args()

    spec = Spec()

    for path in args.directories:
        if not path.is_dir():
            print('Directory %s does not exist' % dirname)
            sys.exit(1)

        print('Working on directory %s...' % path)

        # The frames are the file names in the directory without path or extenstions
        frames = [f.stem for f in path.iterdir() if f.suffix in VALID_EXTENSITONS]
        for frame in frames:
            if re.search(r'^\w+$', frame) is None:
                print('ERROR: filename %s is not valid. Filenames must consist '
                      'only of letters, numbers and underscores' % frame)
                sys.exit(1)

        if len(frames) > 1:
            if answer_to_bool(get_answer('Are these frames a transition [y/n]?')):
                from_id = get_answer(
                    'What is the ID that these frames are a transition FROM '
                    '(leave empty for initial transition)?', allow_empty=True)
                section_id = get_answer('What is the ID that these frames are a transition TO?')
                # Create the section if it doesn't exist yet.
                spec[section_id].setdefault('transitions_from', {})[from_id] = {
                    'frame_duration': args.frame_duration,
                    'frames': frames
                }
                print()
                continue
            
        section_id = get_answer('What is the name of this section?')

        # Single-frame sections are automatically oneshot with default duration.
        if len(frames) == 1:
            oneshot = True
        else:
            spec[section_id]['frame_duration'] = args.frame_duration
            oneshot = answer_to_bool(get_answer('Is this section a oneshot [y/n]?'))

        spec[section_id]['oneshot'] = oneshot
        spec[section_id]['frames'] = frames

        print()

    if args.output:
        with open(args.output, 'w') as f:
            json.dump(spec, f, indent=4)
    else:
        print(json.dumps(spec, indent=4))


if __name__ == '__main__':
    main()


================================================
FILE: settings.gradle
================================================
include ':library', ':samples'
Download .txt
gitextract_u5l7ysds/

├── .gitignore
├── LICENSE.txt
├── README.md
├── build.gradle
├── gradle/
│   ├── gradle-mvn-push.gradle
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── library/
│   ├── .gitignore
│   ├── AndroidManifest.xml
│   ├── build.gradle
│   ├── gradle.properties
│   └── src/
│       └── main/
│           └── java/
│               └── com/
│                   └── getkeepsafe/
│                       └── android/
│                           └── multistateanimation/
│                               ├── MultiStateAnimation.java
│                               └── NotifyingAnimationDrawable.java
├── samples/
│   ├── .gitignore
│   ├── AndroidManifest.xml
│   ├── build.gradle
│   ├── res/
│   │   ├── layout/
│   │   │   └── activity_three_state_sample.xml
│   │   ├── menu/
│   │   │   └── menu_three_state_sample.xml
│   │   ├── raw/
│   │   │   └── sample_animation.json
│   │   ├── values/
│   │   │   ├── colors.xml
│   │   │   ├── dimens.xml
│   │   │   ├── strings.xml
│   │   │   └── styles.xml
│   │   └── values-w820dp/
│   │       └── dimens.xml
│   └── src/
│       └── main/
│           └── java/
│               └── com/
│                   └── getkeepsafe/
│                       └── android/
│                           └── multistateanimation/
│                               └── samples/
│                                   └── ThreeStateSampleActivity.java
├── scripts/
│   └── generate_animation_json.py
└── settings.gradle
Download .txt
SYMBOL INDEX (73 symbols across 4 files)

FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/MultiStateAnimation.java
  class MultiStateAnimation (line 31) | public class MultiStateAnimation implements NotifyingAnimationDrawable.O...
    class AnimationDrawableLoader (line 43) | private static class AnimationDrawableLoader {
      method AnimationDrawableLoader (line 49) | public AnimationDrawableLoader(Context context) {
      method AnimationDrawableLoader (line 53) | public AnimationDrawableLoader(Context context, int frameDuration, b...
      method AnimationDrawableLoader (line 64) | public AnimationDrawableLoader(Context context, int frameDuration, b...
      method load (line 71) | public NotifyingAnimationDrawable load() {
      method totalDuration (line 96) | public int totalDuration() {
    class AnimationSection (line 104) | private static class AnimationSection {
      method AnimationSection (line 109) | public AnimationSection(String id, AnimationDrawableLoader loader, M...
      method AnimationSection (line 119) | public AnimationSection(String id, AnimationDrawableLoader loader) {
      method getId (line 123) | public String getId() {
      method loadDrawable (line 130) | public NotifyingAnimationDrawable loadDrawable() {
      method getTransition (line 138) | public NotifyingAnimationDrawable getTransition(String fromId) {
      method addTransition (line 149) | public void addTransition(String fromId, AnimationDrawableLoader loa...
      method getDuration (line 159) | public int getDuration(String fromId) {
      method getDuration (line 173) | public int getDuration() {
    type AnimationSeriesListener (line 179) | public interface AnimationSeriesListener {
      method onAnimationFinished (line 183) | void onAnimationFinished();
      method onAnimationStarting (line 189) | void onAnimationStarting();
    method MultiStateAnimation (line 219) | public MultiStateAnimation(View view) {
    method MultiStateAnimation (line 234) | public MultiStateAnimation() {
    method getDrawableResourceId (line 241) | private static int getDrawableResourceId(Context context, String name) {
    method jsonArrayToArray (line 252) | private static String[] jsonArrayToArray(JSONArray jsonArray) throws J...
    method integerListToArray (line 266) | private static int[] integerListToArray(List<Integer> list) {
    class TransitionBuilder (line 280) | public static class TransitionBuilder {
      method addFrame (line 290) | public TransitionBuilder addFrame(int imageResource) {
      method setFrameDuration (line 301) | public TransitionBuilder setFrameDuration(int frameDuration) {
      method build (line 306) | private AnimationDrawableLoader build(Context context) {
    class SectionBuilder (line 314) | public static class SectionBuilder {
      method SectionBuilder (line 326) | public SectionBuilder(String id) {
      method addFrame (line 336) | public SectionBuilder addFrame(int imageResource) {
      method setOneshot (line 348) | public SectionBuilder setOneshot(boolean isOneshot) {
      method setFrameDuration (line 359) | public SectionBuilder setFrameDuration(int frameDuration) {
      method addTransition (line 371) | public SectionBuilder addTransition(String fromId, TransitionBuilder...
      method build (line 376) | private AnimationSection build(Context context) {
    class Builder (line 392) | public static class Builder {
      method Builder (line 402) | public Builder(View view) {
      method addSection (line 411) | public Builder addSection(SectionBuilder section) {
      method build (line 421) | public MultiStateAnimation build(Context context) {
    method fromJsonResource (line 489) | public static MultiStateAnimation fromJsonResource(Context context, Vi...
    method fromJsonResource (line 567) | public static MultiStateAnimation fromJsonResource(Context context, in...
    method addSection (line 576) | private void addSection(AnimationSection section) {
    method getSeriesAnimationFinishedListener (line 583) | public AnimationSeriesListener getSeriesAnimationFinishedListener() {
    method setSeriesAnimationFinishedListener (line 594) | public void setSeriesAnimationFinishedListener(AnimationSeriesListener...
    method currentSectionDuration (line 604) | public int currentSectionDuration() {
    method getCurrentDrawable (line 613) | public AnimationDrawable getCurrentDrawable() {
    method getCurrentSectionId (line 620) | public String getCurrentSectionId() {
    method getTransitioningFromId (line 628) | public String getTransitioningFromId() {
    method playDrawable (line 637) | @TargetApi(16)
    method queueTransition (line 664) | public void queueTransition(String id) {
    method transitionNow (line 684) | public void transitionNow(String id) {
    method clearAnimation (line 712) | public void clearAnimation() {
    method onAnimationFinished (line 728) | @Override

FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/NotifyingAnimationDrawable.java
  class NotifyingAnimationDrawable (line 16) | public class NotifyingAnimationDrawable extends AnimationDrawable {
    type OnAnimationFinishedListener (line 17) | public interface OnAnimationFinishedListener {
      method onAnimationFinished (line 18) | void onAnimationFinished();
    method NotifyingAnimationDrawable (line 27) | public NotifyingAnimationDrawable(AnimationDrawable drawable) {
    method NotifyingAnimationDrawable (line 34) | public NotifyingAnimationDrawable() {
    method getAnimationFinishedListener (line 41) | public OnAnimationFinishedListener getAnimationFinishedListener() {
    method setAnimationFinishedListener (line 52) | public void setAnimationFinishedListener(OnAnimationFinishedListener l...
    method isFinished (line 59) | public boolean isFinished() {
    method selectDrawable (line 63) | @Override

FILE: samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java
  class ThreeStateSampleActivity (line 12) | public class ThreeStateSampleActivity extends Activity implements MultiS...
    method onCreate (line 17) | @Override
    method onNextStateBtnClick (line 36) | public void onNextStateBtnClick(View view) {
    method onAnimationFinished (line 58) | @Override
    method onAnimationStarting (line 65) | @Override
    method makeAnimation2 (line 74) | private MultiStateAnimation makeAnimation2(View view) {

FILE: scripts/generate_animation_json.py
  class Spec (line 9) | class Spec(collections.OrderedDict):
    method __missing__ (line 11) | def __missing__(self, key):
  function answer_to_bool (line 20) | def answer_to_bool(answer):
  function get_answer (line 28) | def get_answer(question, allow_empty=False):
  function main (line 37) | def main():
Condensed preview — 30 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (91K chars).
[
  {
    "path": ".gitignore",
    "chars": 74,
    "preview": "bin/\ngen/\nbuild/\nlocal.properties\nThumbs.db\n.DS_Store\n.idea\n.gradle\n*.iml\n"
  },
  {
    "path": "LICENSE.txt",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 7691,
    "preview": "# MultiStateAnimation\n\nAndroid library to create complex multi-state animations.\n\n![Demo animation](docs/images/demo_1.g"
  },
  {
    "path": "build.gradle",
    "chars": 211,
    "preview": "buildscript {\n    repositories {\n        mavenCentral()\n    }\n    dependencies {\n        classpath 'com.android.tools.bu"
  },
  {
    "path": "gradle/gradle-mvn-push.gradle",
    "chars": 3635,
    "preview": "/*\n * Copyright 2013 Chris Banes\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 232,
    "preview": "#Wed Apr 10 15:27:10 PDT 2013\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
  },
  {
    "path": "gradle.properties",
    "chars": 723,
    "preview": "VERSION_NAME=1.1.1\nVERSION_CODE=3\nGROUP=com.getkeepsafe.android.multistateanimation\n\nPOM_ARTIFACT_ID=MultiStateAnimation"
  },
  {
    "path": "gradlew",
    "chars": 5080,
    "preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start "
  },
  {
    "path": "gradlew.bat",
    "chars": 2404,
    "preview": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@r"
  },
  {
    "path": "library/.gitignore",
    "chars": 7,
    "preview": "/build\n"
  },
  {
    "path": "library/AndroidManifest.xml",
    "chars": 116,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest package=\"com.getkeepsafe.android.multistateanimation\">\n</manifest>\n"
  },
  {
    "path": "library/build.gradle",
    "chars": 1192,
    "preview": "apply plugin: 'com.android.library'\n\ngroup = GROUP\nversion = VERSION_NAME\n\nrepositories {\n    mavenCentral()\n}\n\nandroid "
  },
  {
    "path": "library/gradle.properties",
    "chars": 71,
    "preview": "POM_NAME=MultiStateAnimation\nPOM_ARTIFACT_ID=library\nPOM_PACKAGING=aar\n"
  },
  {
    "path": "library/src/main/java/com/getkeepsafe/android/multistateanimation/MultiStateAnimation.java",
    "chars": 27069,
    "preview": "package com.getkeepsafe.android.multistateanimation;\n\nimport android.annotation.TargetApi;\nimport android.content.Contex"
  },
  {
    "path": "library/src/main/java/com/getkeepsafe/android/multistateanimation/NotifyingAnimationDrawable.java",
    "chars": 2625,
    "preview": "package com.getkeepsafe.android.multistateanimation;\n\nimport android.graphics.drawable.AnimationDrawable;\n\nimport java.l"
  },
  {
    "path": "samples/.gitignore",
    "chars": 21,
    "preview": "/build\n/src/version/\n"
  },
  {
    "path": "samples/AndroidManifest.xml",
    "chars": 1150,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package="
  },
  {
    "path": "samples/build.gradle",
    "chars": 774,
    "preview": "buildscript {\n    repositories {\n        mavenCentral()\n    }\n    dependencies {\n        classpath 'com.android.tools.bu"
  },
  {
    "path": "samples/res/layout/activity_three_state_sample.xml",
    "chars": 2079,
    "preview": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n                xmlns:tools=\"http://schemas.a"
  },
  {
    "path": "samples/res/menu/menu_three_state_sample.xml",
    "chars": 382,
    "preview": "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n    xmlns:tools=\"http://schemas.android.com/tools\"\r\n  "
  },
  {
    "path": "samples/res/raw/sample_animation.json",
    "chars": 3764,
    "preview": "{\n    \"pending\": {\n        \"oneshot\": true,\n        \"frames\": [\n            \"loading_animation_start_000\"\n        ]\n    "
  },
  {
    "path": "samples/res/values/colors.xml",
    "chars": 108,
    "preview": "<?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",
    "chars": 216,
    "preview": "<resources>\r\n    <!-- Default screen margins, per the Android Design guidelines. -->\r\n    <dimen name=\"activity_horizont"
  },
  {
    "path": "samples/res/values/strings.xml",
    "chars": 327,
    "preview": "<resources>\n\n    <string name=\"title_activity_three_state_sample\">ThreeStateSampleActivity</string>\n    <string name=\"ap"
  },
  {
    "path": "samples/res/values/styles.xml",
    "chars": 163,
    "preview": "<resources>\n    <style name=\"AppTheme\" parent=\"android:Theme.Light\">\n        <item name=\"android:windowBackground\">@colo"
  },
  {
    "path": "samples/res/values-w820dp/dimens.xml",
    "chars": 364,
    "preview": "<resources>\r\n    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r\n         (such as"
  },
  {
    "path": "samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java",
    "chars": 9778,
    "preview": "package com.getkeepsafe.android.multistateanimation.samples;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimp"
  },
  {
    "path": "scripts/generate_animation_json.py",
    "chars": 4357,
    "preview": "#!/usr/bin/env python3\nimport argparse\nimport collections\nimport json\nimport pathlib\nimport re\nimport sys\n\nclass Spec(co"
  },
  {
    "path": "settings.gradle",
    "chars": 31,
    "preview": "include ':library', ':samples'\n"
  }
]

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

About this extraction

This page contains the full source code of the KeepSafe/MultiStateAnimation GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 30 files (84.0 KB), approximately 19.2k tokens, and a symbol index with 73 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!