├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── android-gif-drawable ├── .gitignore ├── Doxyfile ├── build.gradle ├── consumer-proguard-rules.pro ├── gradle-mvn-push.gradle ├── gradle.properties └── src │ ├── androidTest │ ├── AndroidManifest.xml │ ├── java │ │ └── pl │ │ │ └── droidsonroids │ │ │ └── gif │ │ │ ├── AllocationByteCountTest.java │ │ │ ├── ErrnoMessageTest.java │ │ │ └── InputStreamTest.java │ └── res │ │ └── raw │ │ └── test.gif │ ├── main │ ├── AndroidManifest.xml │ ├── c │ │ ├── Android.mk │ │ ├── Application.mk │ │ ├── bitmap.c │ │ ├── control.c │ │ ├── decoding.c │ │ ├── dispose.c │ │ ├── drawing.c │ │ ├── exception.c │ │ ├── gif.c │ │ ├── gif.h │ │ ├── giflib │ │ │ ├── dgif_lib.c │ │ │ ├── gif_lib.h │ │ │ ├── gif_lib_private.h │ │ │ ├── gifalloc.c │ │ │ └── openbsd-reallocarray.c │ │ ├── init.c │ │ ├── jni.c │ │ ├── memset.arm.S │ │ ├── memset32_neon.S │ │ ├── metadata.c │ │ ├── opengl.c │ │ ├── surface.c │ │ └── time.c │ ├── java │ │ └── pl │ │ │ └── droidsonroids │ │ │ └── gif │ │ │ ├── AnimationListener.java │ │ │ ├── ConditionVariable.java │ │ │ ├── GifAnimationMetaData.java │ │ │ ├── GifDecoder.java │ │ │ ├── GifDrawable.java │ │ │ ├── GifDrawableBuilder.java │ │ │ ├── GifError.java │ │ │ ├── GifIOException.java │ │ │ ├── GifImageButton.java │ │ │ ├── GifImageView.java │ │ │ ├── GifInfoHandle.java │ │ │ ├── GifOptions.java │ │ │ ├── GifRenderingExecutor.java │ │ │ ├── GifTexImage2D.java │ │ │ ├── GifTextView.java │ │ │ ├── GifTextureView.java │ │ │ ├── GifViewSavedState.java │ │ │ ├── GifViewUtils.java │ │ │ ├── InputSource.java │ │ │ ├── InvalidationHandler.java │ │ │ ├── LibraryLoader.java │ │ │ ├── MultiCallback.java │ │ │ ├── PlaceholderDrawingSurfaceTextureListener.java │ │ │ ├── ReLinker.java │ │ │ ├── RenderTask.java │ │ │ ├── SafeRunnable.java │ │ │ ├── annotations │ │ │ └── Beta.java │ │ │ ├── package-info.java │ │ │ └── transforms │ │ │ ├── CornerRadiusTransform.java │ │ │ ├── Transform.java │ │ │ └── package-info.java │ └── res │ │ └── values │ │ └── attrs.xml │ └── test │ ├── java │ └── pl │ │ └── droidsonroids │ │ └── gif │ │ ├── CallbackWeakReferenceTest.java │ │ ├── ConditionVariableTest.java │ │ ├── GifDrawableBuilderTest.java │ │ ├── GifOptionsTest.java │ │ ├── GifViewUtilsDensityTest.java │ │ ├── GifViewUtilsTest.java │ │ └── MultiCallbackTest.java │ └── resources │ └── pl │ └── droidsonroids │ └── gif │ └── robolectric.properties ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── .gitignore ├── README.md ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── Animated-Flag-Delaware.gif │ ├── Animated-Flag-Estonia.gif │ ├── Animated-Flag-Finland.gif │ ├── Animated-Flag-France.gif │ ├── Animated-Flag-Georgia.gif │ ├── Animated-Flag-Greece.gif │ ├── Animated-Flag-Hungary.gif │ ├── Animated-Flag-Uruguay.gif │ └── Animated-Flag-Virgin_Islands.gif │ ├── java │ └── pl │ │ └── droidsonroids │ │ └── gif │ │ └── sample │ │ ├── AboutFragment.java │ │ ├── AnimatedSelectorDrawableGenerator.java │ │ ├── AnimatedSelectorFragment.java │ │ ├── AnimationControlFragment.java │ │ ├── BaseFragment.java │ │ ├── GifLoadTask.java │ │ ├── GifSelectorDrawable.java │ │ ├── GifTexImage2DFragment.java │ │ ├── GifTextViewFragment.java │ │ ├── GifTextureFragment.java │ │ ├── HttpFragment.java │ │ ├── ImageSpanFragment.java │ │ ├── MainActivity.java │ │ ├── MainPagerAdapter.java │ │ ├── TexturePlaceholderFragment.java │ │ └── sources │ │ ├── GifSourceItemHolder.java │ │ ├── GifSourcesAdapter.java │ │ ├── GifSourcesFragment.java │ │ └── GifSourcesResolver.java │ └── res │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-nodpi │ ├── anim_flag_chile.gif │ ├── anim_flag_england.gif │ ├── anim_flag_greenland.gif │ ├── anim_flag_iceland.gif │ └── led7.gif │ ├── drawable-v24 │ └── selector.xml │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── drawable │ └── selector.xml │ ├── layout-v14 │ ├── http.xml │ └── texture.xml │ ├── layout │ ├── about.xml │ ├── activity_main.xml │ ├── animated_selector.xml │ ├── animation_control.xml │ ├── compound_drawables.xml │ ├── opengl.xml │ ├── source_item.xml │ └── texture.xml │ ├── raw │ └── anim_flag_hungary.gif │ └── values │ ├── arrays.xml │ └── strings.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Java class files 2 | *.class 3 | 4 | # Local configuration file (sdk path, etc) 5 | local.properties 6 | 7 | #IntelliJ IDEA 8 | .idea 9 | *.iml 10 | 11 | #Gradle 12 | .gradle 13 | build 14 | 15 | signing.properties 16 | 17 | .externalNativeBuild/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | env: 2 | global: 3 | - NDK_VERSION=r13b 4 | - MALLOC_ARENA_MAX=2 5 | 6 | sudo: true 7 | 8 | language: 9 | - android 10 | 11 | licenses: 12 | - 'android-sdk-preview-license-52d11cd2' 13 | - 'android-sdk-license-.+' 14 | - 'google-gdk-license-.+' 15 | 16 | android: 17 | components: 18 | - tools # to get the new `repository-11.xml` 19 | - tools # see https://github.com/travis-ci/travis-ci/issues/6040#issuecomment-219367943) 20 | - platform-tools 21 | - build-tools-25.0.2 22 | - android-25 23 | - android-24 24 | - extra-android-m2repository 25 | - sys-img-armeabi-v7a-android-24 26 | 27 | jdk: 28 | - oraclejdk8 29 | 30 | before_script: 31 | - echo n | android create avd --force --name test --target android-24 --abi armeabi-v7a --tag default 32 | - emulator -avd test -no-window -gpu off & 33 | - android-wait-for-emulator 34 | - adb shell wm dismiss-keyguard 35 | 36 | before_install: 37 | - wget http://dl.google.com/android/repository/android-ndk-$NDK_VERSION-linux-x86_64.zip 38 | - unzip android-ndk-$NDK_VERSION-linux-x86_64.zip > /dev/null 39 | - export ANDROID_NDK_HOME=`pwd`/android-ndk-$NDK_VERSION 40 | - export PATH=${PATH}:${ANDROID_NDK_HOME} 41 | 42 | script: 43 | - ./gradlew build connectedCheck :android-gif-drawable:jacocoTestReport 44 | 45 | after_failure: 46 | - cat android-gif-drawable/build/outputs/lint-results-debug.xml 47 | 48 | after_success: 49 | - bash <(curl -s https://codecov.io/bash) 50 | 51 | before_cache: 52 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 53 | 54 | cache: 55 | directories: 56 | - $HOME/.gradle/caches/ 57 | - $HOME/.gradle/wrapper/ 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | Copyright (c) 2016 Karol Wrótniak, Droids on Roids 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | 22 | SKIA: 23 | // Copyright (c) 2011 Google Inc. All rights reserved. 24 | // 25 | // Redistribution and use in source and binary forms, with or without 26 | // modification, are permitted provided that the following conditions are 27 | // met: 28 | // 29 | // * Redistributions of source code must retain the above copyright 30 | // notice, this list of conditions and the following disclaimer. 31 | // * Redistributions in binary form must reproduce the above 32 | // copyright notice, this list of conditions and the following disclaimer 33 | // in the documentation and/or other materials provided with the 34 | // distribution. 35 | // * Neither the name of Google Inc. nor the names of its 36 | // contributors may be used to endorse or promote products derived from 37 | // this software without specific prior written permission. 38 | // 39 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 40 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 41 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 42 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 43 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 44 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 45 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 46 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 47 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 48 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 49 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 50 | 51 | GIFLIB: 52 | The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond 53 | 54 | ReLinker: 55 | Copyright 2015 KeepSafe Software, Inc. 56 | 57 | Licensed under the Apache License, Version 2.0 (the "License"); 58 | you may not use this file except in compliance with the License. 59 | You may obtain a copy of the License at 60 | 61 | http://www.apache.org/licenses/LICENSE-2.0 62 | 63 | Unless required by applicable law or agreed to in writing, software 64 | distributed under the License is distributed on an "AS IS" BASIS, 65 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 66 | See the License for the specific language governing permissions and 67 | limitations under the License. 68 | 69 | memset.arm.S: 70 | Copyright (C) 2010 The Android Open Source Project 71 | 72 | Licensed under the Apache License, Version 2.0 (the "License"); 73 | you may not use this file except in compliance with the License. 74 | You may obtain a copy of the License at 75 | 76 | http://www.apache.org/licenses/LICENSE-2.0 77 | 78 | Unless required by applicable law or agreed to in writing, software 79 | distributed under the License is distributed on an "AS IS" BASIS, 80 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 81 | See the License for the specific language governing permissions and 82 | limitations under the License. 83 | 84 | memset32_neon.S: 85 | Copyright (c) 2009,2010, Code Aurora Forum. All rights reserved. 86 | Use of this source code is governed by a BSD-style license that can be 87 | found in the LICENSE file (SKIA section). 88 | -------------------------------------------------------------------------------- /android-gif-drawable/.gitignore: -------------------------------------------------------------------------------- 1 | CMakeLists.txt 2 | src/main/obj 3 | src/main/libs -------------------------------------------------------------------------------- /android-gif-drawable/Doxyfile: -------------------------------------------------------------------------------- 1 | PROJECT_NAME = android-gif-drawable 2 | RECURSIVE = YES 3 | INPUT = src/main/c 4 | OUTPUT_DIRECTORY = build/doxygen 5 | #JAVADOC_AUTOBRIEF = YES 6 | OPTIMIZE_OUTPUT_FOR_C = YES 7 | EXTRACT_ALL = YES 8 | EXTRACT_STATIC = YES 9 | HIDE_SCOPE_NAMES = YES 10 | FILE_PATTERNS = *.c \ 11 | *.h 12 | RECURSIVE = YES -------------------------------------------------------------------------------- /android-gif-drawable/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.jfrog.bintray' version '1.7.3' 3 | } 4 | 5 | apply plugin: 'com.android.library' 6 | apply plugin: 'jacoco-android' 7 | apply from: 'gradle-mvn-push.gradle' 8 | 9 | version = VERSION_NAME 10 | group = GROUP 11 | 12 | android { 13 | compileSdkVersion versions.compileSdk 14 | buildToolsVersion versions.buildTools 15 | 16 | compileOptions { 17 | sourceCompatibility JavaVersion.VERSION_1_7 18 | targetCompatibility JavaVersion.VERSION_1_7 19 | } 20 | 21 | defaultConfig { 22 | versionName project.version 23 | minSdkVersion versions.minSdk 24 | targetSdkVersion versions.targetSdk 25 | consumerProguardFiles 'consumer-proguard-rules.pro' 26 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' 27 | externalNativeBuild { 28 | ndkBuild { 29 | if (isDebugBuild()) { 30 | cFlags '-Wall', '-Weverything', '-std=c11', '-DDEBUG' 31 | arguments 'NDK_DEBUG=1' 32 | } else { 33 | cFlags '-std=c11', '-DNDEBUG', '-Os', '-g0', '-fvisibility=hidden' 34 | arguments 'NDK_DEBUG=0' 35 | } 36 | } 37 | } 38 | } 39 | externalNativeBuild { 40 | ndkBuild { 41 | path 'src/main/c/Android.mk' 42 | } 43 | } 44 | } 45 | 46 | dependencies { 47 | provided 'com.android.support:support-annotations:25.1.1' 48 | testCompile 'junit:junit:4.12' 49 | testCompile 'org.mockito:mockito-core:2.7.0' 50 | testCompile 'org.robolectric:robolectric:3.2.2' 51 | testCompile 'org.assertj:assertj-core:1.7.1' 52 | testCompile 'net.jodah:concurrentunit:0.4.2' 53 | testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1' 54 | androidTestCompile 'junit:junit:4.12' 55 | androidTestCompile 'org.assertj:assertj-core:1.7.1' 56 | androidTestCompile 'com.squareup.okhttp3:mockwebserver:3.5.0' 57 | androidTestCompile 'com.android.support:support-annotations:25.1.1' 58 | androidTestCompile 'com.android.support.test:runner:0.5' 59 | androidTestCompile 'com.android.support.test:rules:0.5' 60 | } 61 | 62 | jacocoAndroidUnitTestReport { 63 | html.enabled true 64 | xml.enabled true 65 | } 66 | 67 | bintray { 68 | user = POM_DEVELOPER_ID 69 | key = BINTRAY_API_KEY 70 | pkg { 71 | repo = 'maven' 72 | name = "$group:$POM_ARTIFACT_ID" 73 | licenses = ['MIT'] 74 | } 75 | configurations = ['archives'] 76 | } 77 | 78 | def isDebugBuild() { 79 | !gradle.startParameter.taskNames.contains("uploadArchives") && VERSION_NAME.contains("SNAPSHOT") 80 | } -------------------------------------------------------------------------------- /android-gif-drawable/consumer-proguard-rules.pro: -------------------------------------------------------------------------------- 1 | -keep public class pl.droidsonroids.gif.GifIOException{(int, java.lang.String);} 2 | -------------------------------------------------------------------------------- /android-gif-drawable/gradle-mvn-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | def isReleaseBuild() { 21 | return VERSION_NAME.contains("SNAPSHOT") == false 22 | } 23 | 24 | def getReleaseRepositoryUrl() { 25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 26 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 27 | } 28 | 29 | def getSnapshotRepositoryUrl() { 30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 31 | : "https://oss.sonatype.org/content/repositories/snapshots/" 32 | } 33 | 34 | def getRepositoryUsername() { 35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" 36 | } 37 | 38 | def getRepositoryPassword() { 39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" 40 | } 41 | 42 | afterEvaluate { project -> 43 | uploadArchives { 44 | repositories { 45 | mavenDeployer { 46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 47 | 48 | pom.groupId = GROUP 49 | pom.artifactId = POM_ARTIFACT_ID 50 | pom.version = VERSION_NAME 51 | 52 | repository(url: getReleaseRepositoryUrl()) { 53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 54 | } 55 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | 59 | pom.project { 60 | name POM_NAME 61 | packaging POM_PACKAGING 62 | description POM_DESCRIPTION 63 | url POM_URL 64 | 65 | scm { 66 | url POM_SCM_URL 67 | connection POM_SCM_CONNECTION 68 | developerConnection POM_SCM_DEV_CONNECTION 69 | } 70 | 71 | licenses { 72 | license { 73 | name POM_LICENCE_NAME 74 | url POM_LICENCE_URL 75 | distribution POM_LICENCE_DIST 76 | } 77 | } 78 | 79 | developers { 80 | developer { 81 | id POM_DEVELOPER_ID 82 | name POM_DEVELOPER_NAME 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | signing { 91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 92 | sign configurations.archives 93 | } 94 | 95 | task androidJavadocs(type: Javadoc) { 96 | android.libraryVariants.all { variant -> 97 | source = variant.javaCompile.source 98 | classpath = files(variant.javaCompile.classpath.files, android.getBootClasspath()) 99 | options { 100 | links "http://docs.oracle.com/javase/7/docs/api/" 101 | linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" 102 | } 103 | exclude '**/R.java' 104 | exclude '**/BuildConfig.java' 105 | } 106 | } 107 | 108 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 109 | classifier = 'javadoc' 110 | from androidJavadocs.destinationDir 111 | } 112 | 113 | task androidSourcesJar(type: Jar) { 114 | classifier = 'sources' 115 | from android.sourceSets.main.java.sourceFiles 116 | } 117 | 118 | artifacts { 119 | archives androidSourcesJar 120 | archives androidJavadocsJar 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /android-gif-drawable/gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=1.2.5 2 | GROUP=pl.droidsonroids.gif 3 | 4 | POM_DESCRIPTION=Views and Drawable for displaying animated GIFs for Android 5 | POM_URL=https://github.com/koral--/android-gif-drawable 6 | POM_SCM_URL=https://github.com/koral--/android-gif-drawable.git 7 | POM_SCM_CONNECTION=scm:git@github.com:koral--/android-gif-drawable.git 8 | POM_SCM_DEV_CONNECTION=scm:git@github.com:koral--/android-gif-drawable.git 9 | POM_LICENCE_NAME=The MIT License 10 | POM_LICENCE_URL=http://opensource.org/licenses/MIT 11 | POM_LICENCE_DIST=repo 12 | 13 | POM_DEVELOPER_ID=koral 14 | POM_NAME=Android GIF Drawable Library 15 | POM_ARTIFACT_ID=android-gif-drawable 16 | POM_PACKAGING=aar 17 | 18 | POM_DEVELOPER_NAME=Karol Wrótniak 19 | 20 | NATIVE_LIBRARY_NAME=pl_droidsonroids_gif 21 | BINTRAY_API_KEY= -------------------------------------------------------------------------------- /android-gif-drawable/src/androidTest/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android-gif-drawable/src/androidTest/java/pl/droidsonroids/gif/AllocationByteCountTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.res.Resources; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import pl.droidsonroids.gif.test.R; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | @RunWith(AndroidJUnit4.class) 15 | public class AllocationByteCountTest { 16 | 17 | @Test 18 | public void allocationByteCountIsConsistent() throws Exception { 19 | final Resources resources = InstrumentationRegistry.getContext().getResources(); 20 | final GifDrawable drawable = new GifDrawable(resources, R.raw.test); 21 | final GifAnimationMetaData metaData = new GifAnimationMetaData(resources, R.raw.test); 22 | 23 | assertThat(drawable.getFrameByteCount() + metaData.getAllocationByteCount()).isEqualTo(drawable.getAllocationByteCount()); 24 | assertThat(metaData.getDrawableAllocationByteCount(null, 1)).isEqualTo(drawable.getAllocationByteCount()); 25 | assertThat(metaData.getDrawableAllocationByteCount(drawable, 1)).isEqualTo(drawable.getAllocationByteCount()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /android-gif-drawable/src/androidTest/java/pl/droidsonroids/gif/ErrnoMessageTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.test.runner.AndroidJUnit4; 4 | 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.junit.rules.TemporaryFolder; 9 | import org.junit.runner.RunWith; 10 | 11 | import java.io.File; 12 | 13 | 14 | @RunWith(AndroidJUnit4.class) 15 | public class ErrnoMessageTest { 16 | 17 | @Rule 18 | public ExpectedException mExpectedException = ExpectedException.none(); 19 | @Rule 20 | public TemporaryFolder mTemporaryFolder = new TemporaryFolder(); 21 | 22 | @Test 23 | public void errnoMessageAppendedToOpenFailed() throws Exception { 24 | mExpectedException.expect(GifIOException.class); 25 | mExpectedException.expectMessage("GifError 101: Failed to open given input: No such file or directory"); 26 | final File nonExistentFile = new File(mTemporaryFolder.getRoot(), "non-existent"); 27 | new GifDrawable(nonExistentFile); 28 | } 29 | 30 | @Test 31 | public void errnoMessageAppendedToReadFailed() throws Exception { 32 | mExpectedException.expect(GifIOException.class); 33 | mExpectedException.expectMessage("GifError 102: Failed to read from given input: Is a directory"); 34 | new GifDrawable(mTemporaryFolder.getRoot()); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /android-gif-drawable/src/androidTest/java/pl/droidsonroids/gif/InputStreamTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.test.InstrumentationRegistry; 4 | import android.support.test.runner.AndroidJUnit4; 5 | 6 | import org.junit.Rule; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import java.io.BufferedInputStream; 11 | import java.io.InputStream; 12 | import java.net.URL; 13 | 14 | import okhttp3.mockwebserver.MockResponse; 15 | import okhttp3.mockwebserver.MockWebServer; 16 | import okio.Buffer; 17 | import pl.droidsonroids.gif.test.R; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | @RunWith(AndroidJUnit4.class) 22 | public class InputStreamTest { 23 | 24 | @Rule 25 | public MockWebServer mMockWebServer = new MockWebServer(); 26 | 27 | @Test 28 | public void gifDrawableCreatedFromInputStream() throws Exception { 29 | final InputStream originalStream = InstrumentationRegistry.getContext().getResources().openRawResource(R.raw.test); 30 | mMockWebServer.enqueue(new MockResponse().setChunkedBody(new Buffer().readFrom(originalStream), 1 << 8)); 31 | 32 | final URL url = new URL(mMockWebServer.url("/").toString()); 33 | final BufferedInputStream responseStream = new BufferedInputStream(url.openConnection().getInputStream(), 1 << 16); 34 | 35 | final GifDrawable gifDrawable = new GifDrawable(responseStream); 36 | assertThat(gifDrawable.getError()).isEqualTo(GifError.NO_ERROR); 37 | assertThat(gifDrawable.getIntrinsicWidth()).isEqualTo(278); 38 | assertThat(gifDrawable.getIntrinsicHeight()).isEqualTo(183); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /android-gif-drawable/src/androidTest/res/raw/test.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/android-gif-drawable/src/androidTest/res/raw/test.gif -------------------------------------------------------------------------------- /android-gif-drawable/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/Android.mk: -------------------------------------------------------------------------------- 1 | extra_ldlibs := 2 | 3 | ifeq ($(NDK_DEBUG),1) 4 | extra_ldlibs= -llog 5 | endif 6 | 7 | LOCAL_PATH := $(call my-dir) 8 | include $(CLEAR_VARS) 9 | 10 | LOCAL_MODULE := pl_droidsonroids_gif 11 | LOCAL_LDLIBS := -ljnigraphics -landroid -lGLESv2 $(extra_ldlibs) 12 | 13 | LOCAL_SRC_FILES := \ 14 | drawing.c \ 15 | gif.c \ 16 | metadata.c \ 17 | memset32_neon.S \ 18 | bitmap.c \ 19 | decoding.c \ 20 | exception.c \ 21 | time.c \ 22 | control.c \ 23 | memset.arm.S \ 24 | surface.c \ 25 | opengl.c \ 26 | jni.c \ 27 | init.c \ 28 | dispose.c \ 29 | giflib/dgif_lib.c \ 30 | giflib/gifalloc.c \ 31 | giflib/openbsd-reallocarray.c \ 32 | 33 | include $(BUILD_SHARED_LIBRARY) -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/Application.mk: -------------------------------------------------------------------------------- 1 | APP_ABI := all 2 | APP_PLATFORM := android-9 3 | 4 | ifeq ($(NDK_DEBUG),1) 5 | APP_OPTIM := debug 6 | else 7 | APP_OPTIM := release 8 | endif 9 | 10 | NDK_TOOLCHAIN_VERSION := clang -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/bitmap.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | #include 3 | 4 | int lockPixels(JNIEnv *env, jobject jbitmap, GifInfo *info, void **pixels) { 5 | AndroidBitmapInfo bitmapInfo; 6 | if (AndroidBitmap_getInfo(env, jbitmap, &bitmapInfo) == ANDROID_BITMAP_RESULT_SUCCESS) 7 | info->stride = bitmapInfo.width; 8 | else { 9 | throwException(env, RUNTIME_EXCEPTION_BARE, "Could not get bitmap info"); 10 | return -2; 11 | } 12 | 13 | const int lockPixelsResult = AndroidBitmap_lockPixels(env, jbitmap, pixels); 14 | if (lockPixelsResult == ANDROID_BITMAP_RESULT_SUCCESS) { 15 | return 0; 16 | } 17 | 18 | char *message; 19 | switch (lockPixelsResult) { 20 | case ANDROID_BITMAP_RESULT_ALLOCATION_FAILED: 21 | #ifdef DEBUG 22 | LOGE("bitmap lock allocation failed"); 23 | #endif 24 | return -1; //#122 workaround 25 | case ANDROID_BITMAP_RESULT_BAD_PARAMETER: 26 | message = "Lock pixels error, bad parameter"; 27 | break; 28 | case ANDROID_BITMAP_RESULT_JNI_EXCEPTION: 29 | message = "Lock pixels error, JNI exception"; 30 | break; 31 | default: 32 | message = "Lock pixels error"; 33 | } 34 | throwException(env, RUNTIME_EXCEPTION_BARE, message); 35 | return -2; 36 | } 37 | 38 | void unlockPixels(JNIEnv *env, jobject jbitmap) { 39 | const int unlockPixelsResult = AndroidBitmap_unlockPixels(env, jbitmap); 40 | if (unlockPixelsResult == ANDROID_BITMAP_RESULT_SUCCESS) { 41 | return; 42 | } 43 | char *message; 44 | switch (unlockPixelsResult) { 45 | case ANDROID_BITMAP_RESULT_BAD_PARAMETER: 46 | message = "Unlock pixels error, bad parameter"; 47 | break; 48 | case ANDROID_BITMAP_RESULT_JNI_EXCEPTION: 49 | message = "Unlock pixels error, JNI exception"; 50 | break; 51 | default: 52 | message = "Unlock pixels error"; 53 | } 54 | throwException(env, RUNTIME_EXCEPTION_BARE, message); 55 | } 56 | 57 | __unused JNIEXPORT jlong JNICALL 58 | Java_pl_droidsonroids_gif_GifInfoHandle_renderFrame(JNIEnv *env, jclass __unused handleClass, jlong gifInfo, jobject jbitmap) { 59 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 60 | if (info == NULL) 61 | return -1; 62 | 63 | long renderStartTime = getRealTime(); 64 | void *pixels; 65 | if (lockPixels(env, jbitmap, info, &pixels) != 0) { 66 | return 0; 67 | } 68 | DDGifSlurp(info, true, false); 69 | if (info->currentIndex == 0) { 70 | prepareCanvas(pixels, info); 71 | } 72 | const uint_fast32_t frameDuration = getBitmap(pixels, info); 73 | unlockPixels(env, jbitmap); 74 | return calculateInvalidationDelay(info, renderStartTime, frameDuration); 75 | } 76 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/control.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | bool reset(GifInfo *info) { 4 | if (info->rewindFunction(info) != 0) { 5 | return false; 6 | } 7 | info->nextStartTime = 0; 8 | info->currentLoop = 0; 9 | info->currentIndex = 0; 10 | info->lastFrameRemainder = -1; 11 | return true; 12 | } 13 | 14 | __unused JNIEXPORT jboolean JNICALL 15 | Java_pl_droidsonroids_gif_GifInfoHandle_reset(JNIEnv *__unused env, jclass __unused class, jlong gifInfo) { 16 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 17 | if (info != NULL && reset(info)) { 18 | return JNI_TRUE; 19 | } 20 | return JNI_FALSE; 21 | } 22 | 23 | __unused JNIEXPORT void JNICALL 24 | Java_pl_droidsonroids_gif_GifInfoHandle_setSpeedFactor(JNIEnv __unused *env, jclass __unused handleClass, 25 | jlong gifInfo, jfloat factor) { 26 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 27 | if (info == NULL) { 28 | return; 29 | } 30 | info->speedFactor = factor; 31 | } 32 | 33 | static uint_fast32_t seekBitmap(GifInfo *info, JNIEnv *env, jint desiredIndex, jobject jbitmap) { 34 | void *pixels; 35 | if (lockPixels(env, jbitmap, info, &pixels) != 0) { 36 | return 0; 37 | } 38 | uint_fast32_t duration = seek(info, (uint_fast32_t) desiredIndex, pixels); 39 | unlockPixels(env, jbitmap); 40 | return duration; 41 | } 42 | 43 | uint_fast32_t seek(GifInfo *info, uint_fast32_t desiredIndex, void *pixels) { 44 | GifFileType *const gifFilePtr = info->gifFilePtr; 45 | if (desiredIndex < info->currentIndex || info->currentIndex == 0) { 46 | if (!reset(info)) { 47 | gifFilePtr->Error = D_GIF_ERR_REWIND_FAILED; 48 | return 0; 49 | } 50 | prepareCanvas(pixels, info); 51 | } 52 | if (desiredIndex >= gifFilePtr->ImageCount) { 53 | desiredIndex = gifFilePtr->ImageCount - 1; 54 | } 55 | 56 | uint_fast32_t i; 57 | for (i = desiredIndex; i > info->currentIndex; i--) { 58 | const GifImageDesc imageDesc = info->gifFilePtr->SavedImages[i].ImageDesc; 59 | if (gifFilePtr->SWidth == imageDesc.Width && gifFilePtr->SHeight == imageDesc.Height) { 60 | const GraphicsControlBlock controlBlock = info->controlBlock[i]; 61 | if (controlBlock.TransparentColor == NO_TRANSPARENT_COLOR) { 62 | break; 63 | } else if (controlBlock.DisposalMode == DISPOSE_BACKGROUND) { 64 | break; 65 | } 66 | } 67 | } 68 | 69 | if (i > 0) { 70 | while (info->currentIndex < i - 1) { 71 | DDGifSlurp(info, false, true); 72 | ++info->currentIndex; 73 | } 74 | } 75 | 76 | do { 77 | DDGifSlurp(info, true, false); 78 | drawNextBitmap(pixels, info); 79 | } while (info->currentIndex++ < desiredIndex); 80 | --info->currentIndex; 81 | return getFrameDuration(info); 82 | } 83 | 84 | __unused JNIEXPORT void JNICALL 85 | Java_pl_droidsonroids_gif_GifInfoHandle_seekToTime(JNIEnv *env, jclass __unused handleClass, 86 | jlong gifInfo, jint desiredPos, jobject jbitmap) { 87 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 88 | if (info == NULL || info->gifFilePtr->ImageCount == 1) { 89 | return; 90 | } 91 | 92 | unsigned long sum = 0; 93 | unsigned int desiredIndex; 94 | for (desiredIndex = 0; desiredIndex < info->gifFilePtr->ImageCount - 1; desiredIndex++) { 95 | unsigned long newSum = sum + info->controlBlock[desiredIndex].DelayTime; 96 | if (newSum > (unsigned long) desiredPos) 97 | break; 98 | sum = newSum; 99 | } 100 | 101 | if (info->lastFrameRemainder != -1) { 102 | info->lastFrameRemainder = desiredPos - sum; 103 | if (desiredIndex == info->gifFilePtr->ImageCount - 1 && 104 | info->lastFrameRemainder > (long long) info->controlBlock[desiredIndex].DelayTime) 105 | info->lastFrameRemainder = info->controlBlock[desiredIndex].DelayTime; 106 | } 107 | seekBitmap(info, env, desiredIndex, jbitmap); 108 | 109 | info->nextStartTime = getRealTime() + (long) (info->lastFrameRemainder / info->speedFactor); 110 | } 111 | 112 | __unused JNIEXPORT void JNICALL 113 | Java_pl_droidsonroids_gif_GifInfoHandle_seekToFrame(JNIEnv *env, jclass __unused handleClass, 114 | jlong gifInfo, jint desiredIndex, jobject jbitmap) { 115 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 116 | if (info == NULL || info->gifFilePtr->ImageCount == 1) { 117 | return; 118 | } 119 | 120 | uint_fast32_t lastFrameDuration = seekBitmap(info, env, desiredIndex, jbitmap); 121 | 122 | info->nextStartTime = getRealTime() + (long) (lastFrameDuration / info->speedFactor); 123 | if (info->lastFrameRemainder != -1) 124 | info->lastFrameRemainder = 0; 125 | } 126 | 127 | __unused JNIEXPORT void JNICALL 128 | Java_pl_droidsonroids_gif_GifInfoHandle_saveRemainder(JNIEnv *__unused env, jclass __unused handleClass, 129 | jlong gifInfo) { 130 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 131 | if (info == NULL || info->lastFrameRemainder != -1 || info->currentIndex == info->gifFilePtr->ImageCount || 132 | info->gifFilePtr->ImageCount == 1) 133 | return; 134 | info->lastFrameRemainder = info->nextStartTime - getRealTime(); 135 | if (info->lastFrameRemainder < 0) 136 | info->lastFrameRemainder = 0; 137 | } 138 | 139 | __unused JNIEXPORT jlong JNICALL 140 | Java_pl_droidsonroids_gif_GifInfoHandle_restoreRemainder(JNIEnv *__unused env, 141 | jclass __unused handleClass, jlong gifInfo) { 142 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 143 | if (info == NULL || info->lastFrameRemainder == -1 || info->gifFilePtr->ImageCount == 1 || 144 | (info->loopCount > 0 && info->currentLoop == info->loopCount)) 145 | return -1; 146 | info->nextStartTime = getRealTime() + info->lastFrameRemainder; 147 | const long long remainder = info->lastFrameRemainder; 148 | info->lastFrameRemainder = -1; 149 | return remainder; 150 | } 151 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/dispose.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | __unused JNIEXPORT void JNICALL 4 | Java_pl_droidsonroids_gif_GifInfoHandle_free(JNIEnv *env, jclass __unused handleClass, jlong gifInfo) { 5 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 6 | if (info == NULL) { 7 | return; 8 | } 9 | if (info->destructor != NULL) { 10 | info->destructor(info, env); 11 | } 12 | if (info->rewindFunction == streamRewind) { 13 | StreamContainer *sc = info->gifFilePtr->UserData; 14 | static jmethodID closeMID = NULL; 15 | if (closeMID == NULL) { 16 | (*env)->GetMethodID(env, sc->streamCls, "close", "()V"); 17 | } 18 | if (closeMID != NULL) { 19 | (*env)->CallVoidMethod(env, sc->stream, closeMID); 20 | } 21 | if ((*env)->ExceptionCheck(env)) { 22 | (*env)->ExceptionClear(env); 23 | } 24 | 25 | (*env)->DeleteGlobalRef(env, sc->streamCls); 26 | (*env)->DeleteGlobalRef(env, sc->stream); 27 | 28 | if (sc->buffer != NULL) { 29 | (*env)->DeleteGlobalRef(env, sc->buffer); 30 | } 31 | 32 | free(sc); 33 | } 34 | else if (info->rewindFunction == fileRewind) { 35 | fclose(info->gifFilePtr->UserData); 36 | } 37 | else if (info->rewindFunction == byteArrayRewind) { 38 | ByteArrayContainer *bac = info->gifFilePtr->UserData; 39 | if (bac->buffer != NULL) { 40 | (*env)->DeleteGlobalRef(env, bac->buffer); 41 | } 42 | free(bac); 43 | } 44 | else if (info->rewindFunction == directByteBufferRewind) { 45 | free(info->gifFilePtr->UserData); 46 | } 47 | info->gifFilePtr->UserData = NULL; 48 | cleanUp(info); 49 | } 50 | 51 | void cleanUp(GifInfo *info) { 52 | free(info->backupPtr); 53 | info->backupPtr = NULL; 54 | free(info->controlBlock); 55 | info->controlBlock = NULL; 56 | free(info->rasterBits); 57 | info->rasterBits = NULL; 58 | free(info->comment); 59 | info->comment = NULL; 60 | 61 | DGifCloseFile(info->gifFilePtr); 62 | free(info); 63 | } 64 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/drawing.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | #if defined (__arm__) 4 | extern void arm_memset32(uint32_t* dst, uint32_t value, int count); 5 | #define MEMSET_ARGB(dst, value, count) arm_memset32(dst, value, (int) count) 6 | #elif defined (__ARM_ARCH_7A__) 7 | extern void memset32_neon(uint32_t* dst, uint32_t value, int count); 8 | #define MEMSET_ARGB(dst, value, count) memset32_neon(dst, value, (int) count) 9 | #else 10 | #define MEMSET_ARGB(dst, value, count) memset(dst, value, count * sizeof(argb)) 11 | #endif 12 | 13 | static inline void blitNormal(argb *bm, GifInfo *info, SavedImage *frame, ColorMapObject *cmap) { 14 | unsigned char *src = info->rasterBits; 15 | if (src == NULL) { 16 | return; 17 | } 18 | argb *dst = GET_ADDR(bm, info->stride, frame->ImageDesc.Left, frame->ImageDesc.Top); 19 | 20 | uint_fast16_t x, y = frame->ImageDesc.Height; 21 | const int_fast16_t transpIndex = info->controlBlock[info->currentIndex].TransparentColor; 22 | const GifWord frameWidth = frame->ImageDesc.Width; 23 | const GifWord padding = info->stride - frameWidth; 24 | if (info->isOpaque) { 25 | if (transpIndex == NO_TRANSPARENT_COLOR) { 26 | for (; y > 0; y--) { 27 | for (x = frameWidth; x > 0; x--, src++, dst++) { 28 | dst->rgb = cmap->Colors[*src]; 29 | } 30 | dst += padding; 31 | } 32 | } else { 33 | for (; y > 0; y--) { 34 | for (x = frameWidth; x > 0; x--, src++, dst++) { 35 | if (*src != transpIndex) { 36 | dst->rgb = cmap->Colors[*src]; 37 | } 38 | } 39 | dst += padding; 40 | } 41 | } 42 | } else { 43 | if (transpIndex == NO_TRANSPARENT_COLOR) { 44 | for (; y > 0; y--) { 45 | MEMSET_ARGB((uint32_t *) dst, UINT_MAX, frameWidth); 46 | for (x = frameWidth; x > 0; x--, src++, dst++) { 47 | dst->rgb = cmap->Colors[*src]; 48 | } 49 | dst += padding; 50 | } 51 | } else { 52 | for (; y > 0; y--) { 53 | for (x = frameWidth; x > 0; x--, src++, dst++) { 54 | if (*src != transpIndex) { 55 | dst->rgb = cmap->Colors[*src]; 56 | dst->alpha = 0xFF; 57 | } 58 | } 59 | dst += padding; 60 | } 61 | } 62 | } 63 | } 64 | 65 | static void drawFrame(argb *bm, GifInfo *info, SavedImage *frame) { 66 | ColorMapObject *cmap; 67 | if (frame->ImageDesc.ColorMap != NULL) 68 | cmap = frame->ImageDesc.ColorMap;// use local color table 69 | else if (info->gifFilePtr->SColorMap != NULL) 70 | cmap = info->gifFilePtr->SColorMap; 71 | else 72 | cmap = getDefColorMap(); 73 | 74 | blitNormal(bm, info, frame, cmap); 75 | } 76 | 77 | // return true if area of 'target' is completely covers area of 'covered' 78 | static bool checkIfCover(const SavedImage *target, const SavedImage *covered) { 79 | return target->ImageDesc.Left <= covered->ImageDesc.Left 80 | && covered->ImageDesc.Left + covered->ImageDesc.Width <= target->ImageDesc.Left + target->ImageDesc.Width 81 | && target->ImageDesc.Top <= covered->ImageDesc.Top 82 | && covered->ImageDesc.Top + covered->ImageDesc.Height 83 | <= target->ImageDesc.Top + target->ImageDesc.Height; 84 | } 85 | 86 | static inline void disposeFrameIfNeeded(argb *bm, GifInfo *info) { 87 | GifFileType *fGif = info->gifFilePtr; 88 | SavedImage *cur = &fGif->SavedImages[info->currentIndex - 1]; 89 | SavedImage *next = &fGif->SavedImages[info->currentIndex]; 90 | // We can skip disposal process if next frame is not transparent 91 | // and completely covers current area 92 | uint_fast8_t curDisposal = info->controlBlock[info->currentIndex - 1].DisposalMode; 93 | bool nextTrans = info->controlBlock[info->currentIndex].TransparentColor != NO_TRANSPARENT_COLOR; 94 | uint_fast8_t nextDisposal = info->controlBlock[info->currentIndex].DisposalMode; 95 | 96 | if ((curDisposal == DISPOSE_PREVIOUS || nextDisposal == DISPOSE_PREVIOUS) && info->backupPtr == NULL) { 97 | info->backupPtr = calloc(info->stride * fGif->SHeight, sizeof(argb)); 98 | if (!info->backupPtr) { 99 | info->gifFilePtr->Error = D_GIF_ERR_NOT_ENOUGH_MEM; //TODO throw OOME 100 | return; 101 | } 102 | } 103 | 104 | argb *backup = info->backupPtr; 105 | if (nextTrans || !checkIfCover(next, cur)) { 106 | if (curDisposal == DISPOSE_BACKGROUND || (info->currentIndex == 1 && curDisposal == DISPOSE_PREVIOUS)) {// restore to background (under this image) color 107 | uint32_t *dst = (uint32_t *) GET_ADDR(bm, info->stride, cur->ImageDesc.Left, cur->ImageDesc.Top); 108 | uint_fast16_t copyHeight = cur->ImageDesc.Height; 109 | for (; copyHeight > 0; copyHeight--) { 110 | MEMSET_ARGB(dst, 0, cur->ImageDesc.Width); 111 | dst += info->stride; 112 | } 113 | } else if (curDisposal == DISPOSE_PREVIOUS && nextDisposal == DISPOSE_PREVIOUS) {// restore to previous 114 | argb *tmp = bm; 115 | bm = backup; 116 | backup = tmp; 117 | } 118 | } 119 | 120 | // Save current image if next frame's disposal method == DISPOSE_PREVIOUS 121 | if (nextDisposal == DISPOSE_PREVIOUS) { 122 | memcpy(backup, bm, info->stride * fGif->SHeight * sizeof(argb)); 123 | } 124 | } 125 | 126 | void prepareCanvas(const argb *bm, GifInfo *info) { 127 | GifFileType *const gifFilePtr = info->gifFilePtr; 128 | if (gifFilePtr->SColorMap && info->controlBlock->TransparentColor == NO_TRANSPARENT_COLOR) { 129 | const GifColorType backgroundRGB = gifFilePtr->SColorMap->Colors[gifFilePtr->SBackGroundColor]; 130 | argb *pixel; 131 | for (pixel = (argb *) bm; pixel < bm + (info->stride * info->gifFilePtr->SHeight); pixel++) { 132 | pixel->alpha = 0xFF; 133 | pixel->rgb = backgroundRGB; 134 | } 135 | } else { 136 | MEMSET_ARGB((uint32_t *) bm, 0, info->stride * gifFilePtr->SHeight); 137 | } 138 | } 139 | 140 | void drawNextBitmap(argb *bm, GifInfo *info) { 141 | if (info->currentIndex > 0) { 142 | disposeFrameIfNeeded(bm, info); 143 | } 144 | drawFrame(bm, info, info->gifFilePtr->SavedImages + info->currentIndex); 145 | } 146 | 147 | uint_fast32_t getFrameDuration(GifInfo *info) { 148 | uint_fast32_t frameDuration = info->controlBlock[info->currentIndex].DelayTime; 149 | if (++info->currentIndex >= info->gifFilePtr->ImageCount) { 150 | if (info->loopCount == 0 || info->currentLoop + 1 < info->loopCount) { 151 | if (info->rewindFunction(info) != 0) 152 | return 0; 153 | else if (info->loopCount > 0) 154 | info->currentLoop++; 155 | info->currentIndex = 0; 156 | } else { 157 | info->currentLoop++; 158 | --info->currentIndex; 159 | frameDuration = 0; 160 | } 161 | } 162 | return frameDuration; 163 | } 164 | 165 | uint_fast32_t getBitmap(argb *bm, GifInfo *info) { 166 | drawNextBitmap(bm, info); 167 | return getFrameDuration(info); 168 | } 169 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/exception.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | #define RUNTIME_EXCEPTION_CLASS_NAME "java/lang/RuntimeException" 4 | #define OUT_OF_MEMORY_ERROR_CLASS_NAME "java/lang/OutOfMemoryError" 5 | #define NULL_POINTER_EXCEPTION_CLASS_NAME "java/lang/NullPointerException" 6 | 7 | inline void throwException(JNIEnv *env, enum Exception exception, char *message) { 8 | if ((*env)->ExceptionCheck(env) == JNI_TRUE) { 9 | return; 10 | } 11 | if (errno == ENOMEM) { 12 | exception = OUT_OF_MEMORY_ERROR; 13 | } 14 | 15 | const char *exceptionClassName; 16 | switch (exception) { 17 | case OUT_OF_MEMORY_ERROR: 18 | exceptionClassName = OUT_OF_MEMORY_ERROR_CLASS_NAME; 19 | break; 20 | case NULL_POINTER_EXCEPTION: 21 | exceptionClassName = NULL_POINTER_EXCEPTION_CLASS_NAME; 22 | break; 23 | case RUNTIME_EXCEPTION_ERRNO: 24 | exceptionClassName = RUNTIME_EXCEPTION_CLASS_NAME; 25 | char fullMessage[NL_TEXTMAX] = ""; 26 | strncat(fullMessage, message, NL_TEXTMAX); 27 | 28 | char errnoMessage[NL_TEXTMAX]; 29 | if (strerror_r(errno, errnoMessage, NL_TEXTMAX) == 0) { 30 | strncat(fullMessage, errnoMessage, NL_TEXTMAX); 31 | } 32 | message = fullMessage; 33 | break; 34 | default: 35 | exceptionClassName = RUNTIME_EXCEPTION_CLASS_NAME; 36 | } 37 | 38 | jclass exClass = (*env)->FindClass(env, exceptionClassName); 39 | if (exClass != NULL) { 40 | (*env)->ThrowNew(env, exClass, message); 41 | } 42 | } 43 | 44 | inline bool isSourceNull(void *ptr, JNIEnv *env) { 45 | if (ptr != NULL) { 46 | return false; 47 | } 48 | throwException(env, NULL_POINTER_EXCEPTION, "Input source is null"); 49 | return true; 50 | } 51 | 52 | void throwGifIOException(int gifErrorCode, JNIEnv *env, bool readErrno) { 53 | //nullchecks just to prevent segfaults, LinkageError will be thrown if GifIOException cannot be instantiated 54 | if ((*env)->ExceptionCheck(env) == JNI_TRUE) { 55 | return; 56 | } 57 | jclass exClass = (*env)->FindClass(env, "pl/droidsonroids/gif/GifIOException"); 58 | if (exClass == NULL) { 59 | return; 60 | } 61 | jmethodID mid = (*env)->GetMethodID(env, exClass, "", "(ILjava/lang/String;)V"); 62 | if (mid == NULL) { 63 | return; 64 | } 65 | jstring errnoJString = NULL; 66 | if (readErrno) { 67 | char errnoMessage[NL_TEXTMAX]; 68 | if (strerror_r(errno, errnoMessage, NL_TEXTMAX) == 0) { 69 | errnoJString = (*env)->NewStringUTF(env, errnoMessage); 70 | } 71 | } 72 | jobject exception = (*env)->NewObject(env, exClass, mid, gifErrorCode, errnoJString); 73 | if (exception != NULL) { 74 | (*env)->Throw(env, exception); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/gif.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define _GNU_SOURCE 1 4 | #ifdef __clang__ 5 | #pragma clang system_header 6 | #pragma clang diagnostic ignored "-Wgnu" 7 | #elif __GNUC__ 8 | #pragma GCC system_header 9 | #pragma GCC diagnostic ignored "-Wgnu" 10 | #endif 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "giflib/gif_lib.h" 30 | 31 | #ifdef DEBUG 32 | #include 33 | #define LOG_TAG "libgif" 34 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) 35 | #endif 36 | 37 | #define TEMP_FAILURE_RETRY(exp) ({ \ 38 | __typeof__(exp) _rc; \ 39 | do { \ 40 | _rc = (exp); \ 41 | } while (_rc == -1 && errno == EINTR); \ 42 | _rc; }) 43 | #define THROW_ON_NONZERO_RESULT(fun, message) if (fun !=0) throwException(env, RUNTIME_EXCEPTION_ERRNO, message) 44 | #define GET_ADDR(bm, width, left, top) bm + top * width + left 45 | 46 | #define OOME_MESSAGE "Failed to allocate native memory" 47 | #define DEFAULT_FRAME_DURATION_MS 100 48 | #define STREAM_BUFFER_SIZE 8192 49 | #define NULL_GIF_INFO (jlong) (intptr_t) NULL; 50 | 51 | /** 52 | * Some gif files are not strictly follow 89a. 53 | * DGifSlurp will return read head error or get record type error. 54 | * but the image still can display. so here should ignore the error. 55 | */ 56 | //#define STRICT_FORMAT_89A 57 | 58 | /** 59 | * Decoding error - no frames 60 | */ 61 | #define D_GIF_ERR_NO_FRAMES 1000 62 | /** 63 | * Decoding error - invalid GIF screen size 64 | */ 65 | #define D_GIF_ERR_INVALID_SCR_DIMS 1001 66 | /** 67 | * Decoding error - invalid frame size 68 | */ 69 | #define D_GIF_ERR_INVALID_IMG_DIMS 1002 70 | /** 71 | * Decoding error - frame size is greater that screen size 72 | */ 73 | #define D_GIF_ERR_IMG_NOT_CONFINED 1003 74 | /** 75 | * Decoding error - input source rewind failed 76 | */ 77 | #define D_GIF_ERR_REWIND_FAILED 1004 78 | /** 79 | * Decoding error - invalid and/or indirect byte buffer specified 80 | */ 81 | #define D_GIF_ERR_INVALID_BYTE_BUFFER 1005 82 | 83 | enum Exception { 84 | RUNTIME_EXCEPTION_ERRNO, RUNTIME_EXCEPTION_BARE, OUT_OF_MEMORY_ERROR, NULL_POINTER_EXCEPTION 85 | }; 86 | 87 | typedef struct { 88 | GifColorType rgb; 89 | uint8_t alpha; 90 | } argb; 91 | 92 | typedef struct GifInfo GifInfo; 93 | 94 | typedef int 95 | (*RewindFunc)(GifInfo *); 96 | 97 | struct GifInfo { 98 | void (*destructor)(GifInfo *, JNIEnv *); 99 | GifFileType *gifFilePtr; 100 | GifWord originalWidth, originalHeight; 101 | uint_fast16_t sampleSize; 102 | long long lastFrameRemainder; 103 | long long nextStartTime; 104 | uint_fast32_t currentIndex; 105 | GraphicsControlBlock *controlBlock; 106 | argb *backupPtr; 107 | long long startPos; 108 | unsigned char *rasterBits; 109 | uint_fast32_t rasterSize; 110 | char *comment; 111 | uint_fast16_t loopCount; 112 | uint_fast16_t currentLoop; 113 | RewindFunc rewindFunction; 114 | jfloat speedFactor; 115 | uint32_t stride; 116 | jlong sourceLength; 117 | bool isOpaque; 118 | void *frameBufferDescriptor; 119 | }; 120 | 121 | typedef struct { 122 | jobject stream; 123 | jclass streamCls; 124 | jmethodID readMID; 125 | jmethodID resetMID; 126 | jbyteArray buffer; 127 | jint bufferPosition; 128 | bool markCalled; 129 | } StreamContainer; 130 | 131 | typedef struct { 132 | uint_fast32_t position; 133 | jbyteArray buffer; 134 | unsigned int length; 135 | } ByteArrayContainer; 136 | 137 | typedef struct { 138 | jlong position; 139 | jbyte *bytes; 140 | jlong capacity; 141 | } DirectByteBufferContainer; 142 | 143 | typedef struct { 144 | GifFileType *GifFileIn; 145 | int Error; 146 | long long startPos; 147 | RewindFunc rewindFunc; 148 | jlong sourceLength; 149 | } GifSourceDescriptor; 150 | 151 | void DetachCurrentThread(); 152 | 153 | ColorMapObject *getDefColorMap(); 154 | 155 | /** 156 | * @return the real time, in ms 157 | */ 158 | long getRealTime(); 159 | 160 | /** 161 | * Frees dynamically allocated memory 162 | */ 163 | void cleanUp(GifInfo *info); 164 | 165 | void throwException(JNIEnv *env, enum Exception exception, char *message); 166 | 167 | bool isSourceNull(void *ptr, JNIEnv *env); 168 | 169 | static uint_fast8_t fileRead(GifFileType *gif, GifByteType *bytes, uint_fast8_t size); 170 | 171 | static uint_fast8_t directByteBufferRead(GifFileType *gif, GifByteType *bytes, uint_fast8_t size); 172 | 173 | static uint_fast8_t byteArrayRead(GifFileType *gif, GifByteType *bytes, uint_fast8_t size); 174 | 175 | static uint_fast8_t streamRead(GifFileType *gif, GifByteType *bytes, uint_fast8_t size); 176 | 177 | int fileRewind(GifInfo *info); 178 | 179 | int streamRewind(GifInfo *info); 180 | 181 | int byteArrayRewind(GifInfo *info); 182 | 183 | int directByteBufferRewind(GifInfo *info); 184 | 185 | static int getComment(GifByteType *Bytes, GifInfo *); 186 | 187 | static int readExtensions(int ExtFunction, GifByteType *ExtData, GifInfo *info); 188 | 189 | void DDGifSlurp(GifInfo *info, bool decode, bool exitAfterFrame); 190 | 191 | void throwGifIOException(int gifErrorCode, JNIEnv *env, bool readErrno); 192 | 193 | GifInfo *createGifInfo(GifSourceDescriptor *descriptor, JNIEnv *env); 194 | 195 | static inline void blitNormal(argb *bm, GifInfo *info, SavedImage *frame, ColorMapObject *cmap); 196 | 197 | static void drawFrame(argb *bm, GifInfo *info, SavedImage *frame); 198 | 199 | static bool checkIfCover(const SavedImage *target, const SavedImage *covered); 200 | 201 | static void disposeFrameIfNeeded(argb *bm, GifInfo *info); 202 | 203 | uint_fast32_t getBitmap(argb *bm, GifInfo *info); 204 | 205 | bool reset(GifInfo *info); 206 | 207 | int lockPixels(JNIEnv *env, jobject jbitmap, GifInfo *info, void **pixels); 208 | 209 | void unlockPixels(JNIEnv *env, jobject jbitmap); 210 | 211 | long long calculateInvalidationDelay(GifInfo *info, long renderStartTime, uint_fast32_t frameDuration); 212 | 213 | jint restoreSavedState(GifInfo *info, JNIEnv *env, jlongArray state, void *pixels); 214 | 215 | void prepareCanvas(const argb *bm, GifInfo *info); 216 | 217 | void drawNextBitmap(argb *bm, GifInfo *info); 218 | 219 | uint_fast32_t getFrameDuration(GifInfo *info); 220 | 221 | JNIEnv *getEnv(); 222 | 223 | uint_fast32_t seek(GifInfo *info, uint_fast32_t desiredIndex, void *pixels); 224 | 225 | void setGCBDefaults(GraphicsControlBlock *gcb); 226 | 227 | static GifInfo *createGifInfoFromFile(JNIEnv *env, FILE *file, const long sourceLength); 228 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/giflib/gif_lib_private.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | 3 | gif_lib_private.h - internal giflib routines and structures 4 | 5 | ****************************************************************************/ 6 | 7 | #ifndef _GIF_LIB_PRIVATE_H 8 | #define _GIF_LIB_PRIVATE_H 9 | 10 | #include "gif_lib.h" 11 | 12 | #define EXTENSION_INTRODUCER 0x21 13 | #define DESCRIPTOR_INTRODUCER 0x2c 14 | #define TERMINATOR_INTRODUCER 0x3b 15 | 16 | #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */ 17 | #define LZ_BITS 12 18 | 19 | #define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */ 20 | #define FIRST_CODE 4097 /* Impossible code, to signal first. */ 21 | #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */ 22 | 23 | //#define FILE_STATE_WRITE 0x01 24 | //#define FILE_STATE_SCREEN 0x02 25 | //#define FILE_STATE_IMAGE 0x04 26 | //#define FILE_STATE_READ 0x08 27 | 28 | //#define IS_READABLE(Private) (Private->FileState & FILE_STATE_READ) 29 | 30 | typedef struct GifFilePrivateType { 31 | GifWord //FileState, /*FileHandle,*/ /* Where all this data goes to! */ 32 | BitsPerPixel, /* Bits per pixel (Codes uses at least this + 1). */ 33 | ClearCode, /* The CLEAR LZ code. */ 34 | EOFCode, /* The EOF LZ code. */ 35 | RunningCode, /* The next code algorithm can generate. */ 36 | RunningBits, /* The number of bits required to represent RunningCode. */ 37 | MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */ 38 | LastCode, /* The code before the current code. */ 39 | // CrntCode, /* Current algorithm code. */ 40 | StackPtr, /* For character stack (see below). */ 41 | CrntShiftState; 42 | /* Number of bits in CrntShiftDWord. */ 43 | unsigned long CrntShiftDWord; 44 | /* For bytes decomposition into codes. */ 45 | uint_fast32_t PixelCount; 46 | /* Number of pixels in image. */ 47 | // FILE *File; 48 | /* File as stream. */ 49 | InputFunc Read; /* function to read gif input (TVT) */ 50 | // OutputFunc Write; /* function to write gif output (MRB) */ 51 | GifByteType Buf[256]; 52 | /* Compressed input is buffered here. */ 53 | GifByteType Stack[LZ_MAX_CODE]; 54 | /* Decoded pixels are stacked here. */ 55 | GifByteType Suffix[LZ_MAX_CODE + 1]; 56 | /* So we can trace the codes. */ 57 | GifPrefixType Prefix[LZ_MAX_CODE + 1]; 58 | // bool gif89; 59 | } GifFilePrivateType; 60 | 61 | #endif /* _GIF_LIB_PRIVATE_H */ 62 | 63 | /* end */ 64 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/giflib/gifalloc.c: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | 3 | GIF construction tools 4 | 5 | ****************************************************************************/ 6 | 7 | #include 8 | #include 9 | #include "gif_lib.h" 10 | 11 | //#define MAX(x, y) (((x) > (y)) ? (x) : (y)) 12 | 13 | /****************************************************************************** 14 | Miscellaneous utility functions 15 | ******************************************************************************/ 16 | 17 | /* return smallest bitfield size n will fit in */ 18 | //int 19 | //GifBitSize(int n) 20 | //{ 21 | // register int i; 22 | // 23 | // for (i = 1; i <= 8; i++) 24 | // if ((1 << i) >= n) 25 | // break; 26 | // return (i); 27 | //} 28 | 29 | /****************************************************************************** 30 | Color map object functions 31 | ******************************************************************************/ 32 | 33 | /* 34 | * Allocate a color map of given size; initialize with contents of 35 | * ColorMap if that pointer is non-NULL. 36 | */ 37 | ColorMapObject * 38 | GifMakeMapObject(uint_fast8_t BitsPerPixel, const GifColorType *ColorMap) { 39 | ColorMapObject *Object; 40 | 41 | /*** Our ColorCount has to be a power of two. Is it necessary to 42 | * make the user know that or should we automatically round up instead? */ 43 | // if (ColorCount != (1 << GifBitSize(ColorCount))) { 44 | // return ((ColorMapObject *) NULL); 45 | // } 46 | 47 | Object = (ColorMapObject *) malloc(sizeof(ColorMapObject)); 48 | if (Object == (ColorMapObject *) NULL) { 49 | return ((ColorMapObject *) NULL); 50 | } 51 | 52 | Object->Colors = (GifColorType *) calloc(256, sizeof(GifColorType)); 53 | if (Object->Colors == (GifColorType *) NULL) { 54 | free(Object); 55 | return ((ColorMapObject *) NULL); 56 | } 57 | 58 | Object->ColorCount = (uint_fast16_t) (1 << BitsPerPixel); 59 | Object->BitsPerPixel = BitsPerPixel; 60 | 61 | if (ColorMap != NULL) { 62 | memcpy((char *) Object->Colors, 63 | (char *) ColorMap, Object->ColorCount * sizeof(GifColorType)); 64 | } 65 | 66 | return (Object); 67 | } 68 | 69 | /******************************************************************************* 70 | Free a color map object 71 | *******************************************************************************/ 72 | void 73 | GifFreeMapObject(ColorMapObject *Object) { 74 | if (Object != NULL) { 75 | free(Object->Colors); 76 | free(Object); 77 | } 78 | } 79 | 80 | /****************************************************************************** 81 | Image block allocation functions 82 | ******************************************************************************/ 83 | 84 | void 85 | GifFreeSavedImages(GifFileType *GifFile) { 86 | SavedImage *sp; 87 | 88 | if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) { 89 | return; 90 | } 91 | for (sp = GifFile->SavedImages; 92 | sp < GifFile->SavedImages + GifFile->ImageCount; sp++) { 93 | if (sp->ImageDesc.ColorMap != NULL) { 94 | GifFreeMapObject(sp->ImageDesc.ColorMap); 95 | sp->ImageDesc.ColorMap = NULL; 96 | } 97 | 98 | // if (sp->RasterBits != NULL) 99 | // free((char *)sp->RasterBits); 100 | // 101 | // GifFreeExtensions(&sp->ExtensionBlockCount, &sp->ExtensionBlocks); 102 | } 103 | free((char *) GifFile->SavedImages); 104 | GifFile->SavedImages = NULL; 105 | } 106 | 107 | /* end */ 108 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/giflib/openbsd-reallocarray.c: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $ */ 2 | /* 3 | * Copyright (c) 2008 Otto Moerbeek 4 | * 5 | * Permission to use, copy, modify, and distribute this software for any 6 | * purpose with or without fee is hereby granted, provided that the above 7 | * copyright notice and this permission notice appear in all copies. 8 | * 9 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | /* 24 | * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 25 | * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 26 | */ 27 | #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 28 | 29 | void * 30 | reallocarray(void *optr, size_t nmemb, size_t size) { 31 | if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 32 | nmemb > 0 && SIZE_MAX / nmemb < size) { 33 | errno = ENOMEM; 34 | return NULL; 35 | } 36 | return realloc(optr, size * nmemb); 37 | } 38 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/init.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | GifInfo *createGifInfo(GifSourceDescriptor *descriptor, JNIEnv *env) { 4 | if (descriptor->startPos < 0) { 5 | descriptor->Error = D_GIF_ERR_NOT_READABLE; 6 | } 7 | if (descriptor->Error != 0 || descriptor->GifFileIn == NULL) { 8 | bool readErrno = descriptor->rewindFunc == fileRewind && (descriptor->Error == D_GIF_ERR_NOT_READABLE || descriptor->Error == D_GIF_ERR_READ_FAILED); 9 | throwGifIOException(descriptor->Error, env, readErrno); 10 | DGifCloseFile(descriptor->GifFileIn); 11 | return NULL; 12 | } 13 | 14 | GifInfo *info = malloc(sizeof(GifInfo)); 15 | if (info == NULL) { 16 | DGifCloseFile(descriptor->GifFileIn); 17 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 18 | return NULL; 19 | } 20 | info->controlBlock = malloc(sizeof(GraphicsControlBlock)); 21 | if (info->controlBlock == NULL) { 22 | DGifCloseFile(descriptor->GifFileIn); 23 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 24 | return NULL; 25 | } 26 | setGCBDefaults(info->controlBlock); 27 | info->destructor = NULL; 28 | info->gifFilePtr = descriptor->GifFileIn; 29 | info->startPos = descriptor->startPos; 30 | info->currentIndex = 0; 31 | info->nextStartTime = 0; 32 | info->lastFrameRemainder = -1; 33 | info->comment = NULL; 34 | info->loopCount = 1; 35 | info->currentLoop = 0; 36 | info->speedFactor = 1.0; 37 | info->sourceLength = descriptor->sourceLength; 38 | 39 | info->backupPtr = NULL; 40 | info->rewindFunction = descriptor->rewindFunc; 41 | info->frameBufferDescriptor = NULL; 42 | info->isOpaque = false; 43 | info->sampleSize = 1; 44 | 45 | DDGifSlurp(info, false, false); 46 | info->rasterBits = NULL; 47 | info->rasterSize = 0; 48 | info->originalHeight = info->gifFilePtr->SHeight; 49 | info->originalWidth = info->gifFilePtr->SWidth; 50 | 51 | if (descriptor->GifFileIn->SWidth < 1 || descriptor->GifFileIn->SHeight < 1) { 52 | DGifCloseFile(descriptor->GifFileIn); 53 | throwGifIOException(D_GIF_ERR_INVALID_SCR_DIMS, env, false); 54 | return NULL; 55 | } 56 | if (descriptor->GifFileIn->Error == D_GIF_ERR_NOT_ENOUGH_MEM) { 57 | cleanUp(info); 58 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 59 | return NULL; 60 | } 61 | #if defined(STRICT_FORMAT_89A) 62 | descriptor->Error = descriptor->GifFileIn->Error; 63 | #endif 64 | 65 | if (descriptor->GifFileIn->ImageCount == 0) { 66 | descriptor->Error = D_GIF_ERR_NO_FRAMES; 67 | } else if (descriptor->GifFileIn->Error == D_GIF_ERR_REWIND_FAILED) { 68 | descriptor->Error = D_GIF_ERR_REWIND_FAILED; 69 | } 70 | if (descriptor->Error != 0) { 71 | cleanUp(info); 72 | throwGifIOException(descriptor->Error, env, false); 73 | return NULL; 74 | } 75 | return info; 76 | } 77 | 78 | void setGCBDefaults(GraphicsControlBlock *gcb) { 79 | gcb->DelayTime = DEFAULT_FRAME_DURATION_MS; 80 | gcb->TransparentColor = NO_TRANSPARENT_COLOR; 81 | gcb->DisposalMode = DISPOSAL_UNSPECIFIED; 82 | } 83 | 84 | __unused JNIEXPORT void JNICALL 85 | Java_pl_droidsonroids_gif_GifInfoHandle_setOptions(__unused JNIEnv *env, jclass __unused class, jlong gifInfo, jchar sampleSize, jboolean isOpaque) { 86 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 87 | if (info == NULL) { 88 | return; 89 | } 90 | info->isOpaque = isOpaque == JNI_TRUE; 91 | info->sampleSize = (uint_fast16_t) sampleSize; 92 | info->gifFilePtr->SHeight /= info->sampleSize; 93 | info->gifFilePtr->SWidth /= info->sampleSize; 94 | if (info->gifFilePtr->SHeight == 0) { 95 | info->gifFilePtr->SHeight = 1; 96 | } 97 | if (info->gifFilePtr->SWidth == 0) { 98 | info->gifFilePtr->SWidth = 1; 99 | } 100 | 101 | SavedImage *sp; 102 | uint_fast32_t i; 103 | for (i = 0; i < info->gifFilePtr->ImageCount; i++) { 104 | sp = &info->gifFilePtr->SavedImages[i]; 105 | sp->ImageDesc.Width /= info->sampleSize; 106 | sp->ImageDesc.Height /= info->sampleSize; 107 | sp->ImageDesc.Left /= info->sampleSize; 108 | sp->ImageDesc.Top /= info->sampleSize; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/jni.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | /** 4 | * Global VM reference, initialized in JNI_OnLoad 5 | */ 6 | static JavaVM *g_jvm; 7 | static struct JavaVMAttachArgs attachArgs = {.version=JNI_VERSION_1_6, .group=NULL, .name="GifIOThread"}; 8 | static ColorMapObject *defaultCmap; 9 | 10 | JNIEnv *getEnv() { 11 | JNIEnv *env; 12 | if ((*g_jvm)->AttachCurrentThread(g_jvm, &env, &attachArgs) == JNI_OK) { 13 | return env; 14 | } 15 | return NULL; 16 | } 17 | 18 | void DetachCurrentThread() { 19 | (*g_jvm)->DetachCurrentThread(g_jvm); 20 | } 21 | 22 | __unused JNIEXPORT jint JNICALL 23 | JNI_OnLoad(JavaVM *vm, void *__unused reserved) { 24 | g_jvm = vm; 25 | JNIEnv *env; 26 | if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) { 27 | return JNI_ERR; 28 | } 29 | 30 | defaultCmap = GifMakeMapObject(8, NULL); 31 | if (defaultCmap != NULL) { 32 | uint_fast16_t iColor; 33 | for (iColor = 1; iColor < 256; iColor++) { 34 | defaultCmap->Colors[iColor].Red = (GifByteType) iColor; 35 | defaultCmap->Colors[iColor].Green = (GifByteType) iColor; 36 | defaultCmap->Colors[iColor].Blue = (GifByteType) iColor; 37 | } 38 | } else { 39 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 40 | } 41 | 42 | struct timespec ts; 43 | if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == -1) { 44 | //sanity check here instead of on each clock_gettime() call 45 | throwException(env, RUNTIME_EXCEPTION_BARE, "CLOCK_MONOTONIC_RAW is not present"); 46 | } 47 | return JNI_VERSION_1_6; 48 | } 49 | 50 | __unused JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *__unused vm, void *__unused reserved) { 51 | GifFreeMapObject(defaultCmap); 52 | } 53 | 54 | ColorMapObject *getDefColorMap() { 55 | return defaultCmap; 56 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/memset.arm.S: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* Changes: 18 | * 2010-08-11 Steve McIntyre 19 | * Added small changes to the two functions to make them work on the 20 | * specified number of 16- or 32-bit values rather than the original 21 | * code which was specified as a count of bytes. More verbose comments 22 | * to aid future maintenance. 23 | */ 24 | #ifdef __arm__ 25 | .text 26 | .align 4 27 | .syntax unified 28 | 29 | .global arm_memset32 30 | .hidden arm_memset32 31 | .type arm_memset32, %function 32 | 33 | /* 34 | * Optimized memset functions for ARM. 35 | * 36 | * void arm_memset32(uint32_t* dst, uint32_t value, int count); 37 | * 38 | */ 39 | arm_memset32: 40 | .fnstart 41 | push {lr} 42 | 43 | /* Multiply count by 4 - go from the number of 32-bit words to 44 | * the number of bytes desired. */ 45 | mov r2, r2, lsl #2 46 | 47 | .Lwork_32: 48 | /* Set up registers ready for writing them out. */ 49 | mov ip, r1 50 | mov lr, r1 51 | 52 | /* Try to align the destination to a cache line. Assume 32 53 | * byte (8 word) cache lines, it's the common case. */ 54 | rsb r3, r0, #0 55 | ands r3, r3, #0x1C 56 | beq .Laligned32 57 | cmp r3, r2 58 | andhi r3, r2, #0x1C 59 | sub r2, r2, r3 60 | 61 | /* (Optionally) write any unaligned leading bytes. 62 | * (0-28 bytes, length in r3) */ 63 | movs r3, r3, lsl #28 64 | stmiacs r0!, {r1, lr} 65 | stmiacs r0!, {r1, lr} 66 | stmiami r0!, {r1, lr} 67 | movs r3, r3, lsl #2 68 | strcs r1, [r0], #4 69 | 70 | /* Now quickly loop through the cache-aligned data. */ 71 | .Laligned32: 72 | mov r3, r1 73 | 1: subs r2, r2, #32 74 | stmiahs r0!, {r1,r3,ip,lr} 75 | stmiahs r0!, {r1,r3,ip,lr} 76 | bhs 1b 77 | add r2, r2, #32 78 | 79 | /* (Optionally) store any remaining trailing bytes. 80 | * (0-30 bytes, length in r2) */ 81 | movs r2, r2, lsl #28 82 | stmiacs r0!, {r1,r3,ip,lr} 83 | stmiami r0!, {r1,lr} 84 | movs r2, r2, lsl #2 85 | strcs r1, [r0], #4 86 | strhmi lr, [r0], #2 87 | 88 | .Lfinish: 89 | pop {pc} 90 | .fnend 91 | #endif 92 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/memset32_neon.S: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | * Copyright (c) 2009,2010, Code Aurora Forum. All rights reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license that can be 5 | * found in the LICENSE file. 6 | ***************************************************************************/ 7 | #ifdef __ARM_ARCH_7A__ 8 | .syntax unified 9 | .code 32 10 | .fpu neon 11 | .align 4 12 | .globl memset32_neon 13 | .hidden memset32_neon 14 | 15 | /* r0 = buffer, r1 = value, r2 = times to write */ 16 | memset32_neon: 17 | cmp r2, #1 18 | streq r1, [r0], #4 19 | bxeq lr 20 | 21 | cmp r2, #4 22 | bgt memset32_neon_start 23 | cmp r2, #0 24 | bxeq lr 25 | memset32_neon_small: 26 | str r1, [r0], #4 27 | subs r2, r2, #1 28 | bne memset32_neon_small 29 | bx lr 30 | memset32_neon_start: 31 | cmp r2, #16 32 | blt memset32_dropthru 33 | vdup.32 q0, r1 34 | vmov q1, q0 35 | cmp r2, #32 36 | blt memset32_16 37 | cmp r2, #64 38 | blt memset32_32 39 | cmp r2, #128 40 | blt memset32_64 41 | memset32_128: 42 | movs r12, r2, lsr #7 43 | memset32_loop128: 44 | subs r12, r12, #1 45 | vst1.64 {q0, q1}, [r0]! 46 | vst1.64 {q0, q1}, [r0]! 47 | vst1.64 {q0, q1}, [r0]! 48 | vst1.64 {q0, q1}, [r0]! 49 | vst1.64 {q0, q1}, [r0]! 50 | vst1.64 {q0, q1}, [r0]! 51 | vst1.64 {q0, q1}, [r0]! 52 | vst1.64 {q0, q1}, [r0]! 53 | vst1.64 {q0, q1}, [r0]! 54 | vst1.64 {q0, q1}, [r0]! 55 | vst1.64 {q0, q1}, [r0]! 56 | vst1.64 {q0, q1}, [r0]! 57 | vst1.64 {q0, q1}, [r0]! 58 | vst1.64 {q0, q1}, [r0]! 59 | vst1.64 {q0, q1}, [r0]! 60 | vst1.64 {q0, q1}, [r0]! 61 | bne memset32_loop128 62 | ands r2, r2, #0x7f 63 | bxeq lr 64 | memset32_64: 65 | movs r12, r2, lsr #6 66 | beq memset32_32 67 | vst1.64 {q0, q1}, [r0]! 68 | vst1.64 {q0, q1}, [r0]! 69 | vst1.64 {q0, q1}, [r0]! 70 | vst1.64 {q0, q1}, [r0]! 71 | vst1.64 {q0, q1}, [r0]! 72 | vst1.64 {q0, q1}, [r0]! 73 | vst1.64 {q0, q1}, [r0]! 74 | vst1.64 {q0, q1}, [r0]! 75 | ands r2, r2, #0x3f 76 | bxeq lr 77 | memset32_32: 78 | movs r12, r2, lsr #5 79 | beq memset32_16 80 | vst1.64 {q0, q1}, [r0]! 81 | vst1.64 {q0, q1}, [r0]! 82 | vst1.64 {q0, q1}, [r0]! 83 | vst1.64 {q0, q1}, [r0]! 84 | ands r2, r2, #0x1f 85 | bxeq lr 86 | memset32_16: 87 | movs r12, r2, lsr #4 88 | beq memset32_dropthru 89 | and r2, r2, #0xf 90 | vst1.64 {q0, q1}, [r0]! 91 | vst1.64 {q0, q1}, [r0]! 92 | memset32_dropthru: 93 | rsb r2, r2, #15 94 | add pc, pc, r2, lsl #2 95 | nop 96 | str r1, [r0, #56] 97 | str r1, [r0, #52] 98 | str r1, [r0, #48] 99 | str r1, [r0, #44] 100 | str r1, [r0, #40] 101 | str r1, [r0, #36] 102 | str r1, [r0, #32] 103 | str r1, [r0, #28] 104 | str r1, [r0, #24] 105 | str r1, [r0, #20] 106 | str r1, [r0, #16] 107 | str r1, [r0, #12] 108 | str r1, [r0, #8] 109 | str r1, [r0, #4] 110 | str r1, [r0, #0] 111 | bx lr 112 | 113 | .end 114 | #endif 115 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/opengl.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | #include 3 | 4 | typedef struct { 5 | struct pollfd eventPollFd; 6 | void *frameBuffer; 7 | pthread_mutex_t renderMutex; 8 | pthread_t slurpThread; 9 | } TexImageDescriptor; 10 | 11 | __unused JNIEXPORT void JNICALL 12 | Java_pl_droidsonroids_gif_GifInfoHandle_glTexImage2D(JNIEnv *__unused unused, jclass __unused handleClass, jlong gifInfo, jint target, jint level) { 13 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 14 | if (info == NULL || info->frameBufferDescriptor == NULL) { 15 | return; 16 | } 17 | const GLsizei width = (const GLsizei) info->gifFilePtr->SWidth; 18 | const GLsizei height = (const GLsizei) info->gifFilePtr->SHeight; 19 | TexImageDescriptor *descriptor = info->frameBufferDescriptor; 20 | void *const pixels = descriptor->frameBuffer; 21 | pthread_mutex_lock(&descriptor->renderMutex); 22 | glTexImage2D((GLenum) target, level, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 23 | pthread_mutex_unlock(&descriptor->renderMutex); 24 | } 25 | 26 | __unused JNIEXPORT void JNICALL 27 | Java_pl_droidsonroids_gif_GifInfoHandle_glTexSubImage2D(JNIEnv *__unused env, jclass __unused handleClass, jlong gifInfo, jint target, jint level) { 28 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 29 | if (info == NULL || info->frameBufferDescriptor == NULL) { 30 | return; 31 | } 32 | const GLsizei width = (const GLsizei) info->gifFilePtr->SWidth; 33 | const GLsizei height = (const GLsizei) info->gifFilePtr->SHeight; 34 | TexImageDescriptor *descriptor = info->frameBufferDescriptor; 35 | void *const pixels = descriptor->frameBuffer; 36 | pthread_mutex_lock(&descriptor->renderMutex); 37 | glTexSubImage2D((GLenum) target, level, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 38 | pthread_mutex_unlock(&descriptor->renderMutex); 39 | } 40 | 41 | static void *slurp(void *pVoidInfo) { 42 | GifInfo *info = pVoidInfo; 43 | while (1) { 44 | long renderStartTime = getRealTime(); 45 | DDGifSlurp(info, true, false); 46 | TexImageDescriptor *texImageDescriptor = info->frameBufferDescriptor; 47 | pthread_mutex_lock(&texImageDescriptor->renderMutex); 48 | if (info->currentIndex == 0) { 49 | prepareCanvas(texImageDescriptor->frameBuffer, info); 50 | } 51 | const uint_fast32_t frameDuration = getBitmap(texImageDescriptor->frameBuffer, info); 52 | pthread_mutex_unlock(&texImageDescriptor->renderMutex); 53 | 54 | const long long invalidationDelayMillis = calculateInvalidationDelay(info, renderStartTime, frameDuration); 55 | int pollResult = poll(&texImageDescriptor->eventPollFd, 1, (int) invalidationDelayMillis); 56 | eventfd_t eventValue; 57 | if (pollResult < 0) { 58 | throwException(getEnv(), RUNTIME_EXCEPTION_ERRNO, "Could not poll on eventfd "); 59 | break; 60 | } else if (pollResult > 0) { 61 | const int readResult = TEMP_FAILURE_RETRY(eventfd_read(texImageDescriptor->eventPollFd.fd, &eventValue)); 62 | if (readResult != 0) { 63 | throwException(getEnv(), RUNTIME_EXCEPTION_ERRNO, "Could not read from eventfd "); 64 | } 65 | break; 66 | } 67 | } 68 | DetachCurrentThread(); 69 | return NULL; 70 | } 71 | 72 | static void stopDecoderThread(JNIEnv *env, TexImageDescriptor *descriptor) { 73 | if (descriptor->eventPollFd.fd != -1) { 74 | const int writeResult = TEMP_FAILURE_RETRY(eventfd_write(descriptor->eventPollFd.fd, 1)); 75 | if (writeResult != 0) { 76 | throwException(env, RUNTIME_EXCEPTION_ERRNO, "Could not write to eventfd "); 77 | } 78 | errno = pthread_join(descriptor->slurpThread, NULL); 79 | THROW_ON_NONZERO_RESULT(errno, "Slurp thread join failed "); 80 | 81 | if (close(descriptor->eventPollFd.fd) != 0 && errno != EINTR) { 82 | throwException(env, RUNTIME_EXCEPTION_ERRNO, "Eventfd close failed "); 83 | } 84 | descriptor->eventPollFd.fd = -1; 85 | } 86 | } 87 | 88 | static void releaseTexImageDescriptor(GifInfo *info, JNIEnv *env) { 89 | TexImageDescriptor *descriptor = info->frameBufferDescriptor; 90 | stopDecoderThread(env, descriptor); 91 | info->frameBufferDescriptor = NULL; 92 | free(descriptor->frameBuffer); 93 | errno = pthread_mutex_destroy(&descriptor->renderMutex); 94 | THROW_ON_NONZERO_RESULT(errno, "Render mutex destroy failed "); 95 | free(descriptor); 96 | } 97 | 98 | __unused JNIEXPORT void JNICALL 99 | Java_pl_droidsonroids_gif_GifInfoHandle_initTexImageDescriptor(JNIEnv *env, jclass __unused handleClass, jlong gifInfo) { 100 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 101 | if (info == NULL) { 102 | return; 103 | } 104 | TexImageDescriptor *descriptor = malloc(sizeof(TexImageDescriptor)); 105 | if (!descriptor) { 106 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 107 | return; 108 | } 109 | descriptor->eventPollFd.fd = -1; 110 | const GifWord width = info->gifFilePtr->SWidth; 111 | const GifWord height = info->gifFilePtr->SHeight; 112 | descriptor->frameBuffer = malloc(width * height * sizeof(argb)); 113 | if (!descriptor->frameBuffer) { 114 | free(descriptor); 115 | throwException(env, OUT_OF_MEMORY_ERROR, OOME_MESSAGE); 116 | return; 117 | } 118 | info->stride = (uint32_t) width; 119 | info->frameBufferDescriptor = descriptor; 120 | errno = pthread_mutex_init(&descriptor->renderMutex, NULL); 121 | THROW_ON_NONZERO_RESULT(errno, "Render mutex initialization failed "); 122 | } 123 | 124 | __unused JNIEXPORT void JNICALL 125 | Java_pl_droidsonroids_gif_GifInfoHandle_startDecoderThread(JNIEnv *env, jclass __unused handleClass, jlong gifInfo) { 126 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 127 | if (info == NULL) { 128 | return; 129 | } 130 | TexImageDescriptor *descriptor = info->frameBufferDescriptor; 131 | if (descriptor->eventPollFd.fd != -1) { 132 | return; 133 | } 134 | 135 | descriptor->eventPollFd.events = POLL_IN; 136 | descriptor->eventPollFd.fd = eventfd(0, 0); 137 | if (descriptor->eventPollFd.fd == -1) { 138 | free(descriptor); 139 | throwException(env, RUNTIME_EXCEPTION_ERRNO, "Eventfd creation failed "); 140 | return; 141 | } 142 | info->frameBufferDescriptor = descriptor; 143 | info->destructor = releaseTexImageDescriptor; 144 | 145 | errno = pthread_create(&descriptor->slurpThread, NULL, slurp, info); 146 | THROW_ON_NONZERO_RESULT(errno, "Slurp thread creation failed "); 147 | } 148 | 149 | __unused JNIEXPORT void JNICALL 150 | Java_pl_droidsonroids_gif_GifInfoHandle_stopDecoderThread(JNIEnv *env, jclass __unused handleClass, jlong gifInfo) { 151 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 152 | if (info == NULL || info->frameBufferDescriptor == NULL) { 153 | return; 154 | } 155 | stopDecoderThread(env, info->frameBufferDescriptor); 156 | } 157 | 158 | __unused JNIEXPORT void JNICALL 159 | Java_pl_droidsonroids_gif_GifInfoHandle_seekToFrameGL(__unused JNIEnv *env, jclass __unused handleClass, jlong gifInfo, jint desiredIndex) { 160 | GifInfo *info = (GifInfo *) (intptr_t) gifInfo; 161 | if (info == NULL) { 162 | return; 163 | } 164 | TexImageDescriptor *descriptor = info->frameBufferDescriptor; 165 | seek(info, (uint_fast32_t) desiredIndex, descriptor->frameBuffer); 166 | } 167 | 168 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/c/time.c: -------------------------------------------------------------------------------- 1 | #include "gif.h" 2 | 3 | long long calculateInvalidationDelay(GifInfo *info, long renderStartTime, uint_fast32_t frameDuration) { 4 | if (frameDuration) { 5 | long long invalidationDelay = frameDuration; 6 | if (info->speedFactor != 1.0) { 7 | invalidationDelay /= info->speedFactor; 8 | } 9 | const long renderingTime = getRealTime() - renderStartTime; 10 | if (renderingTime >= invalidationDelay) { 11 | invalidationDelay = 0; 12 | } else { 13 | invalidationDelay -= renderingTime; 14 | } 15 | info->nextStartTime = renderStartTime + invalidationDelay; 16 | return invalidationDelay; 17 | } 18 | return -1; 19 | } 20 | 21 | long getRealTime() { 22 | struct timespec ts; //result not checked since CLOCK_MONOTONIC_RAW availability is checked in JNI_ONLoad 23 | clock_gettime(CLOCK_MONOTONIC_RAW, &ts); 24 | return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; 25 | } 26 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/AnimationListener.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | /** 4 | * Interface which can be used to run some code when particular animation event occurs. 5 | */ 6 | public interface AnimationListener { 7 | /** 8 | * Called when a single loop of the animation is completed. 9 | * 10 | * @param loopNumber 0-based number of the completed loop, 0 for infinite animations 11 | */ 12 | void onAnimationCompleted(int loopNumber); 13 | } 14 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/ConditionVariable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2006 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package pl.droidsonroids.gif; 18 | 19 | class ConditionVariable { 20 | private volatile boolean mCondition; 21 | 22 | synchronized void set(boolean state) { 23 | if (state) { 24 | open(); 25 | } else { 26 | close(); 27 | } 28 | } 29 | 30 | synchronized void open() { 31 | boolean old = mCondition; 32 | mCondition = true; 33 | if (!old) { 34 | this.notify(); 35 | } 36 | } 37 | 38 | synchronized void close() { 39 | mCondition = false; 40 | } 41 | 42 | synchronized void block() throws InterruptedException { 43 | while (!mCondition) { 44 | this.wait(); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifDecoder.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.Bitmap; 4 | import android.support.annotation.IntRange; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * GifDecoder allows lightweight access to GIF frames, without wrappers like Drawable or View. 12 | * {@link Bitmap} with size equal to or greater than size of the GIF is needed. 13 | * For access only metadata (size, number of frames etc.) without pixels see {@link GifAnimationMetaData}. 14 | */ 15 | public class GifDecoder { 16 | //TODO extract common container 17 | private final GifInfoHandle mGifInfoHandle; 18 | 19 | /** 20 | * Constructs new GifDecoder. 21 | * Equivalent of {@link #GifDecoder(InputSource, GifOptions)} with null {@code options} 22 | * @param inputSource source 23 | * @throws IOException when creation fails 24 | */ 25 | public GifDecoder(@NonNull final InputSource inputSource) throws IOException { 26 | this(inputSource, null); 27 | } 28 | 29 | /** 30 | * Constructs new GifDecoder 31 | * 32 | * @param inputSource source 33 | * @param options null-ok; options controlling subsampling and opacity 34 | * @throws IOException when creation fails 35 | */ 36 | public GifDecoder(@NonNull final InputSource inputSource, @Nullable final GifOptions options) throws IOException { 37 | mGifInfoHandle = inputSource.open(); 38 | if (options != null) { 39 | mGifInfoHandle.setOptions(options.inSampleSize, options.inIsOpaque); 40 | } 41 | } 42 | 43 | /** 44 | * See {@link GifDrawable#getComment()} 45 | * 46 | * @return GIF comment 47 | */ 48 | public String getComment() { 49 | return mGifInfoHandle.getComment(); 50 | } 51 | 52 | /** 53 | * See {@link GifDrawable#getLoopCount()} 54 | * 55 | * @return loop count, 0 means that animation is infinite 56 | */ 57 | public int getLoopCount() { 58 | return mGifInfoHandle.getLoopCount(); 59 | } 60 | 61 | /** 62 | * See {@link GifDrawable#getInputSourceByteCount()} 63 | * 64 | * @return number of bytes backed by input source or -1 if it is unknown 65 | */ 66 | public long getSourceLength() { 67 | return mGifInfoHandle.getSourceLength(); 68 | } 69 | 70 | /** 71 | * See {@link GifDrawable#seekTo(int)} 72 | * 73 | * @param position position to seek to in milliseconds 74 | * @param buffer the frame buffer 75 | * @throws IllegalArgumentException if {@code position < 0 }or {@code buffer} is recycled 76 | */ 77 | public void seekToTime(@IntRange(from = 0, to = Integer.MAX_VALUE) final int position, @NonNull final Bitmap buffer) { 78 | checkBuffer(buffer); 79 | mGifInfoHandle.seekToTime(position, buffer); 80 | } 81 | 82 | /** 83 | * See {@link GifDrawable#seekToFrame(int)} 84 | * 85 | * @param frameIndex position to seek to in milliseconds 86 | * @param buffer the frame buffer 87 | * @throws IllegalArgumentException if {@code frameIndex < 0} or {@code buffer} is recycled 88 | */ 89 | public void seekToFrame(@IntRange(from = 0, to = Integer.MAX_VALUE) final int frameIndex, @NonNull final Bitmap buffer) { 90 | checkBuffer(buffer); 91 | mGifInfoHandle.seekToFrame(frameIndex, buffer); 92 | } 93 | 94 | /** 95 | * See {@link GifDrawable#getAllocationByteCount()} 96 | * 97 | * @return possible size of the memory needed to store pixels of this object 98 | */ 99 | public long getAllocationByteCount() { 100 | return mGifInfoHandle.getAllocationByteCount(); 101 | } 102 | 103 | /** 104 | * See {@link GifDrawable#getFrameDuration(int)} 105 | * 106 | * @param index index of the frame 107 | * @return duration of the given frame in milliseconds 108 | * @throws IndexOutOfBoundsException if {@code index < 0 || index >= } 109 | */ 110 | public int getFrameDuration(@IntRange(from = 0) int index) { 111 | return mGifInfoHandle.getFrameDuration(index); 112 | } 113 | 114 | /** 115 | * See {@link GifDrawable#getDuration()} 116 | * 117 | * @return duration of of one loop the animation in milliseconds. Result is always multiple of 10. 118 | */ 119 | public int getDuration() { 120 | return mGifInfoHandle.getDuration(); 121 | } 122 | 123 | /** 124 | * @return width od the GIF canvas in pixels 125 | */ 126 | public int getWidth() { 127 | return mGifInfoHandle.getWidth(); 128 | } 129 | 130 | /** 131 | * @return height od the GIF canvas in pixels 132 | */ 133 | public int getHeight() { 134 | return mGifInfoHandle.getHeight(); 135 | } 136 | 137 | /** 138 | * @return number of frames in GIF, at least one 139 | */ 140 | public int getNumberOfFrames() { 141 | return mGifInfoHandle.getNumberOfFrames(); 142 | } 143 | 144 | /** 145 | * @return true if GIF is animated (has at least 2 frames and positive duration), false otherwise 146 | */ 147 | public boolean isAnimated() { 148 | return mGifInfoHandle.getNumberOfFrames() > 1 && getDuration() > 0; 149 | } 150 | 151 | /** 152 | * See {@link GifDrawable#recycle()} 153 | */ 154 | public void recycle() { 155 | mGifInfoHandle.recycle(); 156 | } 157 | 158 | private void checkBuffer(final Bitmap buffer) { 159 | if (buffer.isRecycled()) { 160 | throw new IllegalArgumentException("Bitmap is recycled"); 161 | } 162 | if (buffer.getWidth() < mGifInfoHandle.getWidth() || buffer.getHeight() < mGifInfoHandle.getHeight()) { 163 | throw new IllegalArgumentException("Bitmap ia too small, size must be greater than or equal to GIF size"); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifError.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import java.util.Locale; 6 | 7 | /** 8 | * Encapsulation of decoding errors occurring in native code. 9 | * Three digit codes are equal to GIFLib error codes. 10 | * 11 | * @author koral-- 12 | */ 13 | @SuppressWarnings("MagicNumber") //error code constants matching native ones 14 | public enum GifError { 15 | /** 16 | * Special value indicating lack of errors. 17 | */ 18 | NO_ERROR(0, "No error"), 19 | /** 20 | * Failed to open given input. 21 | */ 22 | OPEN_FAILED(101, "Failed to open given input"), 23 | /** 24 | * Failed to read from given input. 25 | */ 26 | READ_FAILED(102, "Failed to read from given input"), 27 | /** 28 | * Data is not in GIF format. 29 | */ 30 | NOT_GIF_FILE(103, "Data is not in GIF format"), 31 | /** 32 | * No screen descriptor detected. 33 | */ 34 | NO_SCRN_DSCR(104, "No screen descriptor detected"), 35 | /** 36 | * No image descriptor detected. 37 | */ 38 | NO_IMAG_DSCR(105, "No image descriptor detected"), 39 | /** 40 | * Neither global nor local color map found. 41 | */ 42 | NO_COLOR_MAP(106, "Neither global nor local color map found"), 43 | /** 44 | * Wrong record type detected. 45 | */ 46 | WRONG_RECORD(107, "Wrong record type detected"), 47 | /** 48 | * Number of pixels bigger than width * height. 49 | */ 50 | DATA_TOO_BIG(108, "Number of pixels bigger than width * height"), 51 | /** 52 | * Failed to allocate required memory. 53 | */ 54 | NOT_ENOUGH_MEM(109, "Failed to allocate required memory"), 55 | /** 56 | * Failed to close given input. 57 | */ 58 | CLOSE_FAILED(110, "Failed to close given input"), 59 | /** 60 | * Given file was not opened for read. 61 | */ 62 | NOT_READABLE(111, "Given file was not opened for read"), 63 | /** 64 | * Image is defective, decoding aborted. 65 | */ 66 | IMAGE_DEFECT(112, "Image is defective, decoding aborted"), 67 | /** 68 | * Image EOF detected before image complete. 69 | * EOF means GIF terminator, not the end of input source. 70 | */ 71 | EOF_TOO_SOON(113, "Image EOF detected before image complete"), 72 | /** 73 | * No frames found, at least one frame required. 74 | */ 75 | NO_FRAMES(1000, "No frames found, at least one frame required"), 76 | /** 77 | * Invalid screen size, dimensions must be positive. 78 | */ 79 | INVALID_SCR_DIMS(1001, "Invalid screen size, dimensions must be positive"), 80 | /** 81 | * Invalid image size, dimensions must be positive. 82 | * 83 | * @deprecated This error is no longer thrown. 84 | */ 85 | @Deprecated 86 | INVALID_IMG_DIMS(1002, "Invalid image size, dimensions must be positive"), 87 | /** 88 | * Image size exceeds screen size. Occurs only if input source changes after opening. 89 | * Otherwise canvas is extended. 90 | */ 91 | IMG_NOT_CONFINED(1003, "Image size exceeds screen size"), 92 | /** 93 | * Input source rewind has failed, animation is stopped. 94 | */ 95 | REWIND_FAILED(1004, "Input source rewind failed, animation stopped"), 96 | /** 97 | * Invalid and/or indirect byte buffer specified. 98 | */ 99 | INVALID_BYTE_BUFFER(1005, "Invalid and/or indirect byte buffer specified"), 100 | /** 101 | * Unknown error, should never appear 102 | */ 103 | UNKNOWN(-1, "Unknown error"); 104 | /** 105 | * Human readable description of the error. 106 | */ 107 | @NonNull 108 | public final String description; 109 | int errorCode; 110 | 111 | GifError(int code, @NonNull String description) { 112 | errorCode = code; 113 | this.description = description; 114 | } 115 | 116 | static GifError fromCode(int code) { 117 | for (GifError err : GifError.values()) 118 | if (err.errorCode == code) { 119 | return err; 120 | } 121 | GifError unk = UNKNOWN; 122 | unk.errorCode = code; 123 | return unk; 124 | } 125 | 126 | /** 127 | * @return error code 128 | */ 129 | public int getErrorCode() { 130 | return errorCode; 131 | } 132 | 133 | String getFormattedDescription() { 134 | return String.format(Locale.ENGLISH, "GifError %d: %s", errorCode, description); 135 | } 136 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifIOException.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Exception encapsulating {@link GifError}s. 9 | * 10 | * @author koral-- 11 | */ 12 | public class GifIOException extends IOException { 13 | private static final long serialVersionUID = 13038402904505L; 14 | /** 15 | * Reason which caused an exception 16 | */ 17 | @NonNull 18 | public final GifError reason; 19 | 20 | private final String mErrnoMessage; 21 | 22 | @Override 23 | public String getMessage() { 24 | if (mErrnoMessage == null) { 25 | return reason.getFormattedDescription(); 26 | } 27 | return reason.getFormattedDescription() + ": " + mErrnoMessage; 28 | } 29 | 30 | private GifIOException(int errorCode, String errnoMessage) { 31 | reason = GifError.fromCode(errorCode); 32 | mErrnoMessage = errnoMessage; 33 | } 34 | 35 | static GifIOException fromCode(final int nativeErrorCode) { 36 | if (nativeErrorCode == GifError.NO_ERROR.errorCode) { 37 | return null; 38 | } 39 | return new GifIOException(nativeErrorCode, null); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifImageButton.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.Context; 4 | import android.graphics.drawable.Drawable; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.os.Parcelable; 8 | import android.support.annotation.RequiresApi; 9 | import android.util.AttributeSet; 10 | import android.widget.ImageButton; 11 | 12 | /** 13 | * An {@link ImageButton} which tries treating background and src as {@link GifDrawable} 14 | * 15 | * @author koral-- 16 | */ 17 | public class GifImageButton extends ImageButton { 18 | 19 | private boolean mFreezesAnimation; 20 | 21 | /** 22 | * A corresponding superclass constructor wrapper. 23 | * 24 | * @param context 25 | * @see ImageButton#ImageButton(Context) 26 | */ 27 | public GifImageButton(Context context) { 28 | super(context); 29 | } 30 | 31 | /** 32 | * Like equivalent from superclass but also try to interpret src and background 33 | * attributes as {@link GifDrawable}. 34 | * 35 | * @param context 36 | * @param attrs 37 | * @see ImageButton#ImageButton(Context, AttributeSet) 38 | */ 39 | public GifImageButton(Context context, AttributeSet attrs) { 40 | super(context, attrs); 41 | postInit(GifViewUtils.initImageView(this, attrs, 0, 0)); 42 | } 43 | 44 | /** 45 | * Like equivalent from superclass but also try to interpret src and background 46 | * attributes as GIFs. 47 | * 48 | * @param context 49 | * @param attrs 50 | * @param defStyle 51 | * @see ImageButton#ImageButton(Context, AttributeSet, int) 52 | */ 53 | public GifImageButton(Context context, AttributeSet attrs, int defStyle) { 54 | super(context, attrs, defStyle); 55 | postInit(GifViewUtils.initImageView(this, attrs, defStyle, 0)); 56 | } 57 | 58 | /** 59 | * Like equivalent from superclass but also try to interpret src and background 60 | * attributes as GIFs. 61 | * 62 | * @param context 63 | * @param attrs 64 | * @param defStyle 65 | * @param defStyleRes 66 | * @see ImageButton#ImageButton(Context, AttributeSet, int, int) 67 | */ 68 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 69 | public GifImageButton(Context context, AttributeSet attrs, int defStyle, int defStyleRes) { 70 | super(context, attrs, defStyle, defStyleRes); 71 | postInit(GifViewUtils.initImageView(this, attrs, defStyle, defStyleRes)); 72 | } 73 | 74 | private void postInit(GifViewUtils.InitResult result) { 75 | mFreezesAnimation = result.mFreezesAnimation; 76 | if (result.mSourceResId > 0) { 77 | super.setImageResource(result.mSourceResId); 78 | } 79 | if (result.mBackgroundResId > 0) { 80 | super.setBackgroundResource(result.mBackgroundResId); 81 | } 82 | } 83 | 84 | /** 85 | * Sets the content of this GifImageView to the specified Uri. 86 | * If uri destination is not a GIF then {@link android.widget.ImageView#setImageURI(android.net.Uri)} 87 | * is called as fallback. 88 | * For supported URI schemes see: {@link android.content.ContentResolver#openAssetFileDescriptor(android.net.Uri, String)}. 89 | * 90 | * @param uri The Uri of an image 91 | */ 92 | @Override 93 | public void setImageURI(Uri uri) { 94 | if (!GifViewUtils.setGifImageUri(this, uri)) { 95 | super.setImageURI(uri); 96 | } 97 | } 98 | 99 | @Override 100 | public void setImageResource(int resId) { 101 | if (!GifViewUtils.setResource(this, true, resId)) { 102 | super.setImageResource(resId); 103 | } 104 | } 105 | 106 | @Override 107 | public void setBackgroundResource(int resId) { 108 | if (!GifViewUtils.setResource(this, false, resId)) { 109 | super.setBackgroundResource(resId); 110 | } 111 | } 112 | 113 | @Override 114 | public Parcelable onSaveInstanceState() { 115 | Drawable source = mFreezesAnimation ? getDrawable() : null; 116 | Drawable background = mFreezesAnimation ? getBackground() : null; 117 | return new GifViewSavedState(super.onSaveInstanceState(), source, background); 118 | } 119 | 120 | @Override 121 | public void onRestoreInstanceState(Parcelable state) { 122 | if (!(state instanceof GifViewSavedState)) { 123 | super.onRestoreInstanceState(state); 124 | return; 125 | } 126 | GifViewSavedState ss = (GifViewSavedState) state; 127 | super.onRestoreInstanceState(ss.getSuperState()); 128 | ss.restoreState(getDrawable(), 0); 129 | ss.restoreState(getBackground(), 1); 130 | } 131 | 132 | /** 133 | * Sets whether animation position is saved in {@link #onSaveInstanceState()} and restored 134 | * in {@link #onRestoreInstanceState(Parcelable)} 135 | * 136 | * @param freezesAnimation whether animation position is saved 137 | */ 138 | public void setFreezesAnimation(boolean freezesAnimation) { 139 | mFreezesAnimation = freezesAnimation; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifImageView.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.Context; 4 | import android.graphics.drawable.Drawable; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.os.Parcelable; 8 | import android.support.annotation.RequiresApi; 9 | import android.util.AttributeSet; 10 | import android.widget.ImageView; 11 | 12 | /** 13 | * An {@link ImageView} which tries treating background and src as {@link GifDrawable} 14 | * 15 | * @author koral-- 16 | */ 17 | public class GifImageView extends ImageView { 18 | 19 | private boolean mFreezesAnimation; 20 | 21 | /** 22 | * A corresponding superclass constructor wrapper. 23 | * 24 | * @param context 25 | * @see ImageView#ImageView(Context) 26 | */ 27 | public GifImageView(Context context) { 28 | super(context); 29 | } 30 | 31 | /** 32 | * Like equivalent from superclass but also try to interpret src and background 33 | * attributes as {@link GifDrawable}. 34 | * 35 | * @param context 36 | * @param attrs 37 | * @see ImageView#ImageView(Context, AttributeSet) 38 | */ 39 | public GifImageView(Context context, AttributeSet attrs) { 40 | super(context, attrs); 41 | postInit(GifViewUtils.initImageView(this, attrs, 0, 0)); 42 | } 43 | 44 | /** 45 | * Like equivalent from superclass but also try to interpret src and background 46 | * attributes as GIFs. 47 | * 48 | * @param context 49 | * @param attrs 50 | * @param defStyle 51 | * @see ImageView#ImageView(Context, AttributeSet, int) 52 | */ 53 | public GifImageView(Context context, AttributeSet attrs, int defStyle) { 54 | super(context, attrs, defStyle); 55 | postInit(GifViewUtils.initImageView(this, attrs, defStyle, 0)); 56 | } 57 | 58 | /** 59 | * Like equivalent from superclass but also try to interpret src and background 60 | * attributes as GIFs. 61 | * 62 | * @param context 63 | * @param attrs 64 | * @param defStyle 65 | * @param defStyleRes 66 | * @see ImageView#ImageView(Context, AttributeSet, int, int) 67 | */ 68 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 69 | public GifImageView(Context context, AttributeSet attrs, int defStyle, int defStyleRes) { 70 | super(context, attrs, defStyle, defStyleRes); 71 | postInit(GifViewUtils.initImageView(this, attrs, defStyle, defStyleRes)); 72 | } 73 | 74 | private void postInit(GifViewUtils.InitResult result) { 75 | mFreezesAnimation = result.mFreezesAnimation; 76 | if (result.mSourceResId > 0) { 77 | super.setImageResource(result.mSourceResId); 78 | } 79 | if (result.mBackgroundResId > 0) { 80 | super.setBackgroundResource(result.mBackgroundResId); 81 | } 82 | } 83 | 84 | /** 85 | * Sets the content of this GifImageView to the specified Uri. 86 | * If uri destination is not a GIF then {@link android.widget.ImageView#setImageURI(android.net.Uri)} 87 | * is called as fallback. 88 | * For supported URI schemes see: {@link android.content.ContentResolver#openAssetFileDescriptor(android.net.Uri, String)}. 89 | * 90 | * @param uri The Uri of an image 91 | */ 92 | @Override 93 | public void setImageURI(Uri uri) { 94 | if (!GifViewUtils.setGifImageUri(this, uri)) { 95 | super.setImageURI(uri); 96 | } 97 | } 98 | 99 | @Override 100 | public void setImageResource(int resId) { 101 | if (!GifViewUtils.setResource(this, true, resId)) { 102 | super.setImageResource(resId); 103 | } 104 | } 105 | 106 | @Override 107 | public void setBackgroundResource(int resId) { 108 | if (!GifViewUtils.setResource(this, false, resId)) { 109 | super.setBackgroundResource(resId); 110 | } 111 | } 112 | 113 | @Override 114 | public Parcelable onSaveInstanceState() { 115 | Drawable source = mFreezesAnimation ? getDrawable() : null; 116 | Drawable background = mFreezesAnimation ? getBackground() : null; 117 | return new GifViewSavedState(super.onSaveInstanceState(), source, background); 118 | } 119 | 120 | @Override 121 | public void onRestoreInstanceState(Parcelable state) { 122 | if (!(state instanceof GifViewSavedState)) { 123 | super.onRestoreInstanceState(state); 124 | return; 125 | } 126 | GifViewSavedState ss = (GifViewSavedState) state; 127 | super.onRestoreInstanceState(ss.getSuperState()); 128 | ss.restoreState(getDrawable(), 0); 129 | ss.restoreState(getBackground(), 1); 130 | } 131 | 132 | /** 133 | * Sets whether animation position is saved in {@link #onSaveInstanceState()} and restored 134 | * in {@link #onRestoreInstanceState(Parcelable)} 135 | * 136 | * @param freezesAnimation whether animation position is saved 137 | */ 138 | public void setFreezesAnimation(boolean freezesAnimation) { 139 | mFreezesAnimation = freezesAnimation; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifOptions.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.annotation.IntRange; 4 | import android.support.annotation.Nullable; 5 | 6 | import pl.droidsonroids.gif.annotations.Beta; 7 | 8 | /** 9 | * Options controlling various GIF parameters similar to 10 | * {@link android.graphics.BitmapFactory.Options} 11 | */ 12 | @Beta 13 | public class GifOptions { 14 | 15 | char inSampleSize; 16 | boolean inIsOpaque; 17 | 18 | public GifOptions() { 19 | reset(); 20 | } 21 | 22 | private void reset() { 23 | inSampleSize = 1; 24 | inIsOpaque = false; 25 | } 26 | 27 | /** 28 | * If set to a value {@code > 1}, requests the decoder to subsample the original 29 | * frames, returning a smaller frame buffer to save memory. The sample size is 30 | * the number of pixels in either dimension that correspond to a single 31 | * pixel in the decoded bitmap. For example, inSampleSize == 4 returns 32 | * an image that is 1/4 the width/height of the original, and 1/16 the 33 | * number of pixels. Values outside range {@code <1, 65635>} are treated as 1. 34 | * Unlike {@link android.graphics.BitmapFactory.Options#inSampleSize} 35 | * values which are not powers of 2 are also supported. 36 | * Default value is 1. 37 | * 38 | * @param inSampleSize the sample size 39 | */ 40 | public void setInSampleSize(@IntRange(from = 1, to = Character.MAX_VALUE) int inSampleSize) { 41 | if (inSampleSize < 1 || inSampleSize > Character.MAX_VALUE) { 42 | this.inSampleSize = 1; 43 | } else { 44 | this.inSampleSize = (char) inSampleSize; 45 | } 46 | } 47 | 48 | /** 49 | * Indicates whether the content is opaque. GIF that is known to be opaque can 50 | * take a faster drawing case than non-opaque one, since alpha channel processing may be skipped. 51 | *

52 | * Common usage is setting this to true when view where GIF is displayed is known to be non-transparent 53 | * and its background is irrelevant.In such case even if GIF contains transparent areas, 54 | * they will appear black. 55 | *

56 | * See also {@link GifTextureView#setOpaque(boolean)}. 57 | * Default value is {@code false}, which means that content can be transparent. 58 | * 59 | * @param inIsOpaque whether the content is opaque 60 | */ 61 | public void setInIsOpaque(boolean inIsOpaque) { 62 | this.inIsOpaque = inIsOpaque; 63 | } 64 | 65 | void setFrom(@Nullable GifOptions source) { 66 | if (source == null) { 67 | reset(); 68 | } else { 69 | inIsOpaque = source.inIsOpaque; 70 | inSampleSize = source.inSampleSize; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifRenderingExecutor.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import java.util.concurrent.ScheduledThreadPoolExecutor; 4 | 5 | /** 6 | * Default executor for rendering tasks - {@link java.util.concurrent.ScheduledThreadPoolExecutor} 7 | * with 1 worker thread and {@link java.util.concurrent.ThreadPoolExecutor.DiscardPolicy}. 8 | */ 9 | final class GifRenderingExecutor extends ScheduledThreadPoolExecutor { 10 | 11 | // Lazy initialization via inner-class holder 12 | private static final class InstanceHolder { 13 | private static final GifRenderingExecutor INSTANCE = new GifRenderingExecutor(); 14 | } 15 | 16 | static GifRenderingExecutor getInstance() { 17 | return InstanceHolder.INSTANCE; 18 | } 19 | 20 | private GifRenderingExecutor() { 21 | super(1, new DiscardPolicy()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifTexImage2D.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.support.annotation.IntRange; 4 | import android.support.annotation.Nullable; 5 | 6 | import java.io.IOException; 7 | import java.nio.Buffer; 8 | 9 | import pl.droidsonroids.gif.annotations.Beta; 10 | 11 | /** 12 | * Provides support for animated GIFs in OpenGL. 13 | * There are 2 possible usages: 14 | *

    15 | *
  1. Rendering GIF automatically according to its timing to internal frame buffer in the background thread, 16 | * and requesting frame to be copied to 2D texture when needed. See {@link #glTexImage2D(int, int)} and {@link #glTexImage2D(int, int)}
  2. 17 | *
  3. Manual frame advancing. See {@link #seekToFrame(int)} (int)}
  4. 18 | *
19 | */ 20 | @Beta 21 | public class GifTexImage2D { 22 | private final GifInfoHandle mGifInfoHandle; 23 | 24 | /** 25 | * Constructs new GifTexImage2D. 26 | * Decoder thread is initially stopped, use {@link #startDecoderThread()} to start it. 27 | * 28 | * @param inputSource source 29 | * @param options null-ok; options controlling parameters like subsampling and opacity 30 | * @throws IOException when creation fails 31 | */ 32 | public GifTexImage2D(final InputSource inputSource, @Nullable GifOptions options) throws IOException { 33 | if (options == null) { 34 | options = new GifOptions(); 35 | } 36 | mGifInfoHandle = inputSource.open(); 37 | mGifInfoHandle.setOptions(options.inSampleSize, options.inIsOpaque); 38 | mGifInfoHandle.initTexImageDescriptor(); 39 | } 40 | 41 | /** 42 | * See {@link GifDrawable#getFrameDuration(int)} 43 | * 44 | * @param index index of the frame 45 | * @return duration of the given frame in milliseconds 46 | * @throws IndexOutOfBoundsException if {@code index < 0 || index >= } 47 | */ 48 | public int getFrameDuration(@IntRange(from = 0) int index) { 49 | return mGifInfoHandle.getFrameDuration(index); 50 | } 51 | 52 | /** 53 | * Seeks to given frame 54 | * 55 | * @param index index of the frame 56 | * @throws IndexOutOfBoundsException if {@code index < 0 || index >= } 57 | */ 58 | public void seekToFrame(@IntRange(from = 0) int index) { 59 | mGifInfoHandle.seekToFrameGL(index); 60 | } 61 | 62 | /** 63 | * @return number of frames in GIF, at least one 64 | */ 65 | public int getNumberOfFrames() { 66 | return mGifInfoHandle.getNumberOfFrames(); 67 | } 68 | 69 | /** 70 | * Equivalent of {@link android.opengl.GLES20#glTexImage2D(int, int, int, int, int, int, int, int, Buffer)}. 71 | * Where Buffer contains pixels of the current frame. 72 | * 73 | * @param level level-of-detail number 74 | * @param target target texture 75 | */ 76 | public void glTexImage2D(int target, int level) { 77 | mGifInfoHandle.glTexImage2D(target, level); 78 | } 79 | 80 | /** 81 | * Equivalent of {@link android.opengl.GLES20#glTexSubImage2D(int, int, int, int, int, int, int, int, Buffer)}. 82 | * Where Buffer contains pixels of the current frame. 83 | * 84 | * @param level level-of-detail number 85 | * @param target target texture 86 | */ 87 | public void glTexSubImage2D(int target, int level) { 88 | mGifInfoHandle.glTexSubImage2D(target, level); 89 | } 90 | 91 | /** 92 | * Creates frame buffer and starts decoding thread. Does nothing if already started. 93 | */ 94 | public void startDecoderThread() { 95 | mGifInfoHandle.startDecoderThread(); 96 | } 97 | 98 | /** 99 | * Stops decoder thread and releases frame buffer. Does nothing if already stopped. 100 | */ 101 | public void stopDecoderThread() { 102 | mGifInfoHandle.stopDecoderThread(); 103 | } 104 | 105 | /** 106 | * See {@link GifDrawable#recycle()}. Decoder thread is stopped automatically. 107 | */ 108 | public void recycle() { 109 | if (mGifInfoHandle != null) { 110 | mGifInfoHandle.recycle(); 111 | } 112 | } 113 | 114 | /** 115 | * @return width of the GIF canvas, 0 if recycled 116 | */ 117 | public int getWidth() { 118 | return mGifInfoHandle.getWidth(); 119 | } 120 | 121 | /** 122 | * @return height of the GIF canvas, 0 if recycled 123 | */ 124 | public int getHeight() { 125 | return mGifInfoHandle.getHeight(); 126 | } 127 | 128 | @Override 129 | @SuppressWarnings("ThrowFromFinallyBlock") 130 | protected final void finalize() throws Throwable { 131 | try { 132 | recycle(); 133 | } finally { 134 | super.finalize(); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifViewSavedState.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | import android.support.annotation.NonNull; 7 | import android.view.View; 8 | 9 | class GifViewSavedState extends View.BaseSavedState { 10 | 11 | final long[][] mStates; 12 | 13 | GifViewSavedState(Parcelable superState, Drawable... drawables) { 14 | super(superState); 15 | mStates = new long[drawables.length][]; 16 | for (int i = 0; i < drawables.length; i++) { 17 | Drawable drawable = drawables[i]; 18 | if (drawable instanceof GifDrawable) { 19 | mStates[i] = ((GifDrawable) drawable).mNativeInfoHandle.getSavedState(); 20 | } else { 21 | mStates[i] = null; 22 | } 23 | } 24 | } 25 | 26 | private GifViewSavedState(Parcel in) { 27 | super(in); 28 | mStates = new long[in.readInt()][]; 29 | for (int i = 0; i < mStates.length; i++) 30 | mStates[i] = in.createLongArray(); 31 | } 32 | 33 | GifViewSavedState(Parcelable superState, long[] savedState) { 34 | super(superState); 35 | mStates = new long[1][]; 36 | mStates[0] = savedState; 37 | } 38 | 39 | @Override 40 | public void writeToParcel(@NonNull Parcel dest, int flags) { 41 | super.writeToParcel(dest, flags); 42 | dest.writeInt(mStates.length); 43 | for (long[] mState : mStates) 44 | dest.writeLongArray(mState); 45 | } 46 | 47 | public static final Creator CREATOR = new Creator() { 48 | 49 | public GifViewSavedState createFromParcel(Parcel in) { 50 | return new GifViewSavedState(in); 51 | } 52 | 53 | public GifViewSavedState[] newArray(int size) { 54 | return new GifViewSavedState[size]; 55 | } 56 | }; 57 | 58 | void restoreState(Drawable drawable, int i) { 59 | if (mStates[i] != null && drawable instanceof GifDrawable) { 60 | final GifDrawable gifDrawable = (GifDrawable) drawable; 61 | gifDrawable.startAnimation(gifDrawable.mNativeInfoHandle.restoreSavedState(mStates[i], gifDrawable.mBuffer)); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/GifViewUtils.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.res.Resources; 4 | import android.content.res.TypedArray; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.support.annotation.DrawableRes; 8 | import android.support.annotation.NonNull; 9 | import android.support.annotation.RawRes; 10 | import android.util.AttributeSet; 11 | import android.util.DisplayMetrics; 12 | import android.util.TypedValue; 13 | import android.view.View; 14 | import android.widget.ImageView; 15 | 16 | import java.io.IOException; 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | final class GifViewUtils { 21 | static final String ANDROID_NS = "http://schemas.android.com/apk/res/android"; 22 | static final List SUPPORTED_RESOURCE_TYPE_NAMES = Arrays.asList("raw", "drawable", "mipmap"); 23 | 24 | private GifViewUtils() { 25 | } 26 | 27 | static InitResult initImageView(ImageView view, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 28 | if (attrs != null && !view.isInEditMode()) { 29 | final int sourceResId = getResourceId(view, attrs, true); 30 | final int backgroundResId = getResourceId(view, attrs, false); 31 | final boolean freezesAnimation = isFreezingAnimation(view, attrs, defStyleAttr, defStyleRes); 32 | return new InitResult(sourceResId, backgroundResId, freezesAnimation); 33 | } 34 | return new InitResult(0, 0, false); 35 | } 36 | 37 | private static int getResourceId(ImageView view, AttributeSet attrs, final boolean isSrc) { 38 | final int resId = attrs.getAttributeResourceValue(ANDROID_NS, isSrc ? "src" : "background", 0); 39 | if (resId > 0) { 40 | final String resourceTypeName = view.getResources().getResourceTypeName(resId); 41 | if (SUPPORTED_RESOURCE_TYPE_NAMES.contains(resourceTypeName) && !setResource(view, isSrc, resId)) { 42 | return resId; 43 | } 44 | } 45 | return 0; 46 | } 47 | 48 | @SuppressWarnings("deprecation") 49 | static boolean setResource(ImageView view, boolean isSrc, int resId) { 50 | Resources res = view.getResources(); 51 | if (res != null) { 52 | try { 53 | GifDrawable d = new GifDrawable(res, resId); 54 | if (isSrc) { 55 | view.setImageDrawable(d); 56 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 57 | view.setBackground(d); 58 | } else { 59 | view.setBackgroundDrawable(d); 60 | } 61 | return true; 62 | } catch (IOException | Resources.NotFoundException ignored) { 63 | //ignored 64 | } 65 | } 66 | return false; 67 | } 68 | 69 | static boolean isFreezingAnimation(View view, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 70 | final TypedArray gifViewAttributes = view.getContext().obtainStyledAttributes(attrs, R.styleable.GifView, defStyleAttr, defStyleRes); 71 | boolean freezesAnimation = gifViewAttributes.getBoolean(R.styleable.GifView_freezesAnimation, false); 72 | gifViewAttributes.recycle(); 73 | return freezesAnimation; 74 | } 75 | 76 | static boolean setGifImageUri(ImageView imageView, Uri uri) { 77 | if (uri != null) { 78 | try { 79 | imageView.setImageDrawable(new GifDrawable(imageView.getContext().getContentResolver(), uri)); 80 | return true; 81 | } catch (IOException ignored) { 82 | //ignored 83 | } 84 | } 85 | return false; 86 | } 87 | 88 | static float getDensityScale(@NonNull Resources res, @DrawableRes @RawRes int id) { 89 | final TypedValue value = new TypedValue(); 90 | res.getValue(id, value, true); 91 | final int resourceDensity = value.density; 92 | final int density; 93 | if (resourceDensity == TypedValue.DENSITY_DEFAULT) { 94 | density = DisplayMetrics.DENSITY_DEFAULT; 95 | } else if (resourceDensity != TypedValue.DENSITY_NONE) { 96 | density = resourceDensity; 97 | } else { 98 | density = 0; 99 | } 100 | final int targetDensity = res.getDisplayMetrics().densityDpi; 101 | 102 | if (density > 0 && targetDensity > 0) { 103 | return (float) targetDensity / density; 104 | } 105 | return 1f; 106 | } 107 | 108 | static class InitResult { 109 | final int mSourceResId; 110 | final int mBackgroundResId; 111 | final boolean mFreezesAnimation; 112 | 113 | InitResult(int sourceResId, int backgroundResId, boolean freezesAnimation) { 114 | 115 | mSourceResId = sourceResId; 116 | mBackgroundResId = backgroundResId; 117 | mFreezesAnimation = freezesAnimation; 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/InputSource.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.res.AssetFileDescriptor; 5 | import android.content.res.AssetManager; 6 | import android.content.res.Resources; 7 | import android.net.Uri; 8 | import android.support.annotation.DrawableRes; 9 | import android.support.annotation.NonNull; 10 | import android.support.annotation.Nullable; 11 | import android.support.annotation.RawRes; 12 | 13 | import java.io.File; 14 | import java.io.FileDescriptor; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.nio.ByteBuffer; 18 | import java.util.concurrent.ScheduledThreadPoolExecutor; 19 | 20 | /** 21 | * Abstract class for all input sources, to be used with {@link GifTextureView} 22 | */ 23 | public abstract class InputSource { 24 | private InputSource() { 25 | } 26 | 27 | abstract GifInfoHandle open() throws IOException; 28 | 29 | final GifDrawable build(final GifDrawable oldDrawable, final ScheduledThreadPoolExecutor executor, 30 | final boolean isRenderingAlwaysEnabled, final GifOptions options) throws IOException { 31 | final GifInfoHandle handle = open(); 32 | handle.setOptions(options.inSampleSize, options.inIsOpaque); 33 | return new GifDrawable(handle, oldDrawable, executor, isRenderingAlwaysEnabled); 34 | } 35 | 36 | /** 37 | * Input using {@link ByteBuffer} as a source. It must be direct. 38 | */ 39 | public static final class DirectByteBufferSource extends InputSource { 40 | private final ByteBuffer byteBuffer; 41 | 42 | /** 43 | * Constructs new source. 44 | * Buffer can be larger than size of the GIF data. Bytes beyond GIF terminator are not accessed. 45 | * 46 | * @param byteBuffer source buffer, must be direct 47 | */ 48 | public DirectByteBufferSource(@NonNull ByteBuffer byteBuffer) { 49 | this.byteBuffer = byteBuffer; 50 | } 51 | 52 | @Override 53 | GifInfoHandle open() throws GifIOException { 54 | return new GifInfoHandle(byteBuffer); 55 | } 56 | } 57 | 58 | /** 59 | * Input using byte array as a source. 60 | */ 61 | public static final class ByteArraySource extends InputSource { 62 | private final byte[] bytes; 63 | 64 | /** 65 | * Constructs new source. 66 | * Array can be larger than size of the GIF data. Bytes beyond GIF terminator are not accessed. 67 | * 68 | * @param bytes source array 69 | */ 70 | public ByteArraySource(@NonNull byte[] bytes) { 71 | this.bytes = bytes; 72 | } 73 | 74 | @Override 75 | GifInfoHandle open() throws GifIOException { 76 | return new GifInfoHandle(bytes); 77 | } 78 | } 79 | 80 | /** 81 | * Input using {@link File} or path as source. 82 | */ 83 | public static final class FileSource extends InputSource { 84 | private final String mPath; 85 | 86 | /** 87 | * Constructs new source. 88 | * 89 | * @param file source file 90 | */ 91 | public FileSource(@NonNull File file) { 92 | mPath = file.getPath(); 93 | } 94 | 95 | /** 96 | * Constructs new source. 97 | * 98 | * @param filePath source file path 99 | */ 100 | public FileSource(@NonNull String filePath) { 101 | mPath = filePath; 102 | } 103 | 104 | @Override 105 | GifInfoHandle open() throws GifIOException { 106 | return new GifInfoHandle(mPath); 107 | } 108 | } 109 | 110 | /** 111 | * Input using {@link Uri} as source. 112 | */ 113 | public static final class UriSource extends InputSource { 114 | private final ContentResolver mContentResolver; 115 | private final Uri mUri; 116 | 117 | /** 118 | * Constructs new source. 119 | * 120 | * @param uri GIF Uri, cannot be null. 121 | * @param contentResolver resolver, null is allowed for file:// scheme Uris only 122 | */ 123 | public UriSource(@Nullable ContentResolver contentResolver, @NonNull Uri uri) { 124 | mContentResolver = contentResolver; 125 | mUri = uri; 126 | } 127 | 128 | @Override 129 | GifInfoHandle open() throws IOException { 130 | return GifInfoHandle.openUri(mContentResolver, mUri); 131 | } 132 | } 133 | 134 | /** 135 | * Input using android asset as source. 136 | */ 137 | public static final class AssetSource extends InputSource { 138 | private final AssetManager mAssetManager; 139 | private final String mAssetName; 140 | 141 | /** 142 | * Constructs new source. 143 | * 144 | * @param assetManager AssetManager to read from 145 | * @param assetName name of the asset 146 | */ 147 | public AssetSource(@NonNull AssetManager assetManager, @NonNull String assetName) { 148 | mAssetManager = assetManager; 149 | mAssetName = assetName; 150 | } 151 | 152 | @Override 153 | GifInfoHandle open() throws IOException { 154 | return new GifInfoHandle(mAssetManager.openFd(mAssetName)); 155 | } 156 | } 157 | 158 | /** 159 | * Input using {@link FileDescriptor} as a source. 160 | */ 161 | public static final class FileDescriptorSource extends InputSource { 162 | private final FileDescriptor mFd; 163 | 164 | /** 165 | * Constructs new source. 166 | * 167 | * @param fileDescriptor source file descriptor 168 | */ 169 | public FileDescriptorSource(@NonNull FileDescriptor fileDescriptor) { 170 | mFd = fileDescriptor; 171 | } 172 | 173 | @Override 174 | GifInfoHandle open() throws IOException { 175 | return new GifInfoHandle(mFd); 176 | } 177 | } 178 | 179 | /** 180 | * Input using {@link InputStream} as a source. 181 | */ 182 | public static final class InputStreamSource extends InputSource { 183 | private final InputStream inputStream; 184 | 185 | /** 186 | * Constructs new source. 187 | * 188 | * @param inputStream source input stream, it must support marking 189 | */ 190 | public InputStreamSource(@NonNull InputStream inputStream) { 191 | this.inputStream = inputStream; 192 | } 193 | 194 | @Override 195 | GifInfoHandle open() throws IOException { 196 | return new GifInfoHandle(inputStream); 197 | } 198 | } 199 | 200 | /** 201 | * Input using android resource (raw or drawable) as a source. 202 | */ 203 | public static class ResourcesSource extends InputSource { 204 | private final Resources mResources; 205 | private final int mResourceId; 206 | 207 | /** 208 | * Constructs new source. 209 | * 210 | * @param resources Resources to read from 211 | * @param resourceId resource id 212 | */ 213 | public ResourcesSource(@NonNull Resources resources, @RawRes @DrawableRes int resourceId) { 214 | mResources = resources; 215 | mResourceId = resourceId; 216 | } 217 | 218 | @Override 219 | GifInfoHandle open() throws IOException { 220 | return new GifInfoHandle(mResources.openRawResourceFd(mResourceId)); 221 | } 222 | } 223 | 224 | /** 225 | * Input using {@link AssetFileDescriptor} as a source. 226 | */ 227 | public static class AssetFileDescriptorSource extends InputSource { 228 | private final AssetFileDescriptor mAssetFileDescriptor; 229 | 230 | /** 231 | * Constructs new source. 232 | * 233 | * @param assetFileDescriptor source asset file descriptor. 234 | */ 235 | public AssetFileDescriptorSource(@NonNull AssetFileDescriptor assetFileDescriptor) { 236 | mAssetFileDescriptor = assetFileDescriptor; 237 | } 238 | 239 | @Override 240 | GifInfoHandle open() throws IOException { 241 | return new GifInfoHandle(mAssetFileDescriptor); 242 | } 243 | } 244 | 245 | } 246 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/InvalidationHandler.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.os.Message; 6 | 7 | import java.lang.ref.WeakReference; 8 | 9 | class InvalidationHandler extends Handler { 10 | 11 | static final int MSG_TYPE_INVALIDATION = -1; 12 | 13 | private final WeakReference mDrawableRef; 14 | 15 | public InvalidationHandler(final GifDrawable gifDrawable) { 16 | super(Looper.getMainLooper()); 17 | mDrawableRef = new WeakReference<>(gifDrawable); 18 | } 19 | 20 | @Override 21 | public void handleMessage(final Message msg) { 22 | final GifDrawable gifDrawable = mDrawableRef.get(); 23 | if (gifDrawable == null) { 24 | return; 25 | } 26 | if (msg.what == MSG_TYPE_INVALIDATION) { 27 | gifDrawable.invalidateSelf(); 28 | } else { 29 | for (AnimationListener listener : gifDrawable.mListeners) { 30 | listener.onAnimationCompleted(msg.what); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/LibraryLoader.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.support.annotation.NonNull; 6 | 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * Helper used to work around native libraries loading on some systems. 11 | * See ReLinker for more details. 12 | */ 13 | public class LibraryLoader { 14 | static final String SURFACE_LIBRARY_NAME = "pl_droidsonroids_gif_surface"; 15 | static final String BASE_LIBRARY_NAME = "pl_droidsonroids_gif"; 16 | @SuppressLint("StaticFieldLeak") //workaround for Android bug 17 | private static Context sAppContext; 18 | 19 | private LibraryLoader() { 20 | } 21 | 22 | /** 23 | * Initializes loader with given `Context`. Subsequent calls should have no effect since application Context is retrieved. 24 | * Libraries will not be loaded immediately but only when needed. 25 | * 26 | * @param context any Context except null 27 | */ 28 | public static void initialize(@NonNull final Context context) { 29 | sAppContext = context.getApplicationContext(); 30 | } 31 | 32 | private static Context getContext() { 33 | if (sAppContext == null) { 34 | try { 35 | final Class activityThread = Class.forName("android.app.ActivityThread"); 36 | final Method currentApplicationMethod = activityThread.getDeclaredMethod("currentApplication"); 37 | sAppContext = (Context) currentApplicationMethod.invoke(null); 38 | } catch (Exception e) { 39 | throw new IllegalStateException("LibraryLoader not initialized. Call LibraryLoader.initialize() before using library classes.", e); 40 | } 41 | } 42 | return sAppContext; 43 | } 44 | 45 | static void loadLibrary(Context context) { 46 | try { 47 | System.loadLibrary(BASE_LIBRARY_NAME); 48 | } catch (final UnsatisfiedLinkError e) { 49 | if (context == null) { 50 | context = getContext(); 51 | } 52 | ReLinker.loadLibrary(context); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/MultiCallback.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.graphics.drawable.Drawable.Callback; 5 | import android.support.annotation.NonNull; 6 | import android.view.View; 7 | import android.widget.TextView; 8 | 9 | import java.lang.ref.WeakReference; 10 | import java.util.concurrent.CopyOnWriteArrayList; 11 | 12 | /** 13 | * {@link Callback} which allows single {@link Drawable} to be associated with multiple callbacks, 14 | * eg. with multiple {@link View}s. 15 | * If drawable needs to be redrawn all currently associated callbacks are invoked. 16 | * If Callback is a View it is then invalidated. 17 | * 18 | * @author koral-- 19 | * @author Doctoror 20 | */ 21 | public class MultiCallback implements Callback { 22 | 23 | private final CopyOnWriteArrayList mCallbacks = new CopyOnWriteArrayList<>(); 24 | private final boolean mUseViewInvalidate; 25 | 26 | /** 27 | * Equivalent to {@link #MultiCallback(boolean)} with false value. 28 | */ 29 | public MultiCallback() { 30 | this(false); 31 | } 32 | 33 | /** 34 | * Set useViewInvalidate to true if displayed {@link Drawable} is not supported by 35 | * {@link Drawable.Callback#invalidateDrawable(Drawable)} of the target. For example if it is located inside {@link android.text.style.ImageSpan} 36 | * displayed in {@link TextView}. 37 | * 38 | * @param useViewInvalidate whether {@link View#invalidate()} should be used instead of {@link Drawable.Callback#invalidateDrawable(Drawable)} 39 | */ 40 | public MultiCallback(final boolean useViewInvalidate) { 41 | mUseViewInvalidate = useViewInvalidate; 42 | } 43 | 44 | @Override 45 | public void invalidateDrawable(@NonNull final Drawable who) { 46 | for (int i = 0; i < mCallbacks.size(); i++) { 47 | final CallbackWeakReference reference = mCallbacks.get(i); 48 | final Callback callback = reference.get(); 49 | if (callback != null) { 50 | if (mUseViewInvalidate && callback instanceof View) { 51 | ((View) callback).invalidate(); 52 | } else { 53 | callback.invalidateDrawable(who); 54 | } 55 | } else { 56 | // Always remove null references to reduce list size 57 | mCallbacks.remove(reference); 58 | } 59 | } 60 | } 61 | 62 | @Override 63 | public void scheduleDrawable(@NonNull final Drawable who, @NonNull final Runnable what, final long when) { 64 | for (int i = 0; i < mCallbacks.size(); i++) { 65 | final CallbackWeakReference reference = mCallbacks.get(i); 66 | final Callback callback = reference.get(); 67 | if (callback != null) { 68 | callback.scheduleDrawable(who, what, when); 69 | } else { 70 | // Always remove null references to reduce Set size 71 | mCallbacks.remove(reference); 72 | } 73 | } 74 | } 75 | 76 | @Override 77 | public void unscheduleDrawable(@NonNull final Drawable who, @NonNull final Runnable what) { 78 | for (int i = 0; i < mCallbacks.size(); i++) { 79 | final CallbackWeakReference reference = mCallbacks.get(i); 80 | final Callback callback = reference.get(); 81 | if (callback != null) { 82 | callback.unscheduleDrawable(who, what); 83 | } else { 84 | // Always remove null references to reduce list size 85 | mCallbacks.remove(reference); 86 | } 87 | } 88 | } 89 | 90 | /** 91 | * Associates given {@link Callback}. If callback has been already added, nothing happens. 92 | * 93 | * @param callback Callback to be associated 94 | */ 95 | public void addView(final Callback callback) { 96 | for (int i = 0; i < mCallbacks.size(); i++) { 97 | final CallbackWeakReference reference = mCallbacks.get(i); 98 | final Callback item = reference.get(); 99 | if (item == null) { 100 | // Always remove null references to reduce list size 101 | mCallbacks.remove(reference); 102 | } 103 | } 104 | mCallbacks.addIfAbsent(new CallbackWeakReference(callback)); 105 | } 106 | 107 | /** 108 | * Disassociates given {@link Callback}. If callback is not associated, nothing happens. 109 | * 110 | * @param callback Callback to be disassociated 111 | */ 112 | public void removeView(final Callback callback) { 113 | for (int i = 0; i < mCallbacks.size(); i++) { 114 | final CallbackWeakReference reference = mCallbacks.get(i); 115 | final Callback item = reference.get(); 116 | if (item == null || item == callback) { 117 | // Always remove null references to reduce list size 118 | mCallbacks.remove(reference); 119 | } 120 | } 121 | } 122 | 123 | static final class CallbackWeakReference extends WeakReference { 124 | CallbackWeakReference(final Callback r) { 125 | super(r); 126 | } 127 | 128 | @Override 129 | public boolean equals(final Object o) { 130 | if (this == o) { 131 | return true; 132 | } 133 | if (o == null || getClass() != o.getClass()) { 134 | return false; 135 | } 136 | 137 | return get() == ((CallbackWeakReference) o).get(); 138 | } 139 | 140 | @Override 141 | public int hashCode() { 142 | final Callback callback = get(); 143 | return callback != null ? callback.hashCode() : 0; 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/PlaceholderDrawingSurfaceTextureListener.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.Canvas; 4 | import android.graphics.SurfaceTexture; 5 | import android.os.Build; 6 | import android.support.annotation.RequiresApi; 7 | import android.view.Surface; 8 | import android.view.TextureView; 9 | 10 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 11 | class PlaceholderDrawingSurfaceTextureListener implements TextureView.SurfaceTextureListener { 12 | private final GifTextureView.PlaceholderDrawListener mDrawer; 13 | 14 | PlaceholderDrawingSurfaceTextureListener(GifTextureView.PlaceholderDrawListener drawer) { 15 | mDrawer = drawer; 16 | } 17 | 18 | @Override 19 | public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { 20 | final Surface surface = new Surface(surfaceTexture); 21 | final Canvas canvas = surface.lockCanvas(null); 22 | mDrawer.onDrawPlaceholder(canvas); 23 | surface.unlockCanvasAndPost(canvas); 24 | surface.release(); 25 | } 26 | 27 | @Override 28 | public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { 29 | //no-op 30 | } 31 | 32 | @Override 33 | public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { 34 | return false; 35 | } 36 | 37 | @Override 38 | public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { 39 | //no-op 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/RenderTask.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.os.SystemClock; 4 | 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import static pl.droidsonroids.gif.InvalidationHandler.MSG_TYPE_INVALIDATION; 8 | 9 | class RenderTask extends SafeRunnable { 10 | 11 | RenderTask(GifDrawable gifDrawable) { 12 | super(gifDrawable); 13 | } 14 | 15 | @Override 16 | public void doWork() { 17 | final long invalidationDelay = mGifDrawable.mNativeInfoHandle.renderFrame(mGifDrawable.mBuffer); 18 | if (invalidationDelay >= 0) { 19 | mGifDrawable.mNextFrameRenderTime = SystemClock.uptimeMillis() + invalidationDelay; 20 | if (mGifDrawable.isVisible() && mGifDrawable.mIsRunning && !mGifDrawable.mIsRenderingTriggeredOnDraw) { 21 | mGifDrawable.mExecutor.remove(this); 22 | mGifDrawable.mRenderTaskSchedule = mGifDrawable.mExecutor.schedule(this, invalidationDelay, TimeUnit.MILLISECONDS); 23 | } 24 | if (!mGifDrawable.mListeners.isEmpty() && mGifDrawable.getCurrentFrameIndex() == mGifDrawable.mNativeInfoHandle.getNumberOfFrames() - 1) { 25 | mGifDrawable.mInvalidationHandler.sendEmptyMessageAtTime(mGifDrawable.getCurrentLoop(), mGifDrawable.mNextFrameRenderTime); 26 | } 27 | } else { 28 | mGifDrawable.mNextFrameRenderTime = Long.MIN_VALUE; 29 | mGifDrawable.mIsRunning = false; 30 | } 31 | if (mGifDrawable.isVisible() && !mGifDrawable.mInvalidationHandler.hasMessages(MSG_TYPE_INVALIDATION)) { 32 | mGifDrawable.mInvalidationHandler.sendEmptyMessageAtTime(MSG_TYPE_INVALIDATION, 0); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/SafeRunnable.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | /** 4 | * Runnable for {@link java.util.concurrent.Executor} which propagates exceptions to default uncaught 5 | * exception handler. 6 | */ 7 | abstract class SafeRunnable implements Runnable { 8 | final GifDrawable mGifDrawable; 9 | 10 | SafeRunnable(GifDrawable gifDrawable) { 11 | mGifDrawable = gifDrawable; 12 | } 13 | 14 | @Override 15 | public final void run() { 16 | try { 17 | if (!mGifDrawable.isRecycled()) { 18 | doWork(); 19 | } 20 | } catch (Throwable throwable) { 21 | final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); 22 | if (uncaughtExceptionHandler != null) { 23 | uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), throwable); 24 | } 25 | throw throwable; 26 | } 27 | } 28 | 29 | abstract void doWork(); 30 | } 31 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/annotations/Beta.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Guava Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Originally from https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/annotations/Beta.java 17 | */ 18 | package pl.droidsonroids.gif.annotations; 19 | 20 | import java.lang.annotation.Documented; 21 | import java.lang.annotation.ElementType; 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | import java.lang.annotation.Target; 25 | 26 | /** 27 | * Signifies that a public API (public class, method or field) is subject to 28 | * incompatible changes, or even removal, in a future release. An API bearing 29 | * this annotation is exempt from any compatibility guarantees made by its 30 | * containing library. Note that the presence of this annotation implies nothing 31 | * about the quality or performance of the API in question, only the fact that 32 | * it is not "API-frozen." 33 | * 34 | *

It is generally safe for applications to depend on beta APIs, at 35 | * the cost of some extra work during upgrades. However it is generally 36 | * inadvisable for libraries (which get included on users' CLASSPATHs, 37 | * outside the library developers' control) to do so. 38 | * 39 | **/ 40 | @Retention(RetentionPolicy.CLASS) 41 | @Target({ 42 | ElementType.ANNOTATION_TYPE, 43 | ElementType.CONSTRUCTOR, 44 | ElementType.FIELD, 45 | ElementType.METHOD, 46 | ElementType.TYPE }) 47 | @Documented 48 | @Beta 49 | public @interface Beta { 50 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Animated GIF library for Android. See {@link pl.droidsonroids.gif.GifDrawable}, {@link pl.droidsonroids.gif.GifTextureView} 3 | * and {@link pl.droidsonroids.gif.GifTexImage2D} classes for more details. 4 | */ 5 | package pl.droidsonroids.gif; -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/transforms/CornerRadiusTransform.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.transforms; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapShader; 5 | import android.graphics.Canvas; 6 | import android.graphics.Matrix; 7 | import android.graphics.Paint; 8 | import android.graphics.Rect; 9 | import android.graphics.RectF; 10 | import android.graphics.Shader; 11 | import android.support.annotation.FloatRange; 12 | 13 | /** 14 | * {@link Transform} which adds rounded corners. 15 | */ 16 | public class CornerRadiusTransform implements Transform { 17 | 18 | private float mCornerRadius; 19 | private Shader mShader; 20 | private final RectF mDstRectF = new RectF(); 21 | 22 | /** 23 | * @param cornerRadius corner radius, may be 0. 24 | */ 25 | public CornerRadiusTransform(@FloatRange(from = 0) float cornerRadius) { 26 | setCornerRadius(cornerRadius); 27 | } 28 | 29 | /** 30 | * Sets the corner radius to be applied when drawing the bitmap. 31 | * 32 | * @param cornerRadius corner radius or 0 to remove rounding 33 | */ 34 | public void setCornerRadius(@FloatRange(from = 0) float cornerRadius) { 35 | cornerRadius = Math.max(0, cornerRadius); 36 | if (cornerRadius == mCornerRadius) { 37 | return; 38 | } 39 | mCornerRadius = cornerRadius; 40 | mShader = null; 41 | } 42 | 43 | /** 44 | * @return The corner radius applied when drawing this drawable. 0 when drawable is not rounded. 45 | */ 46 | @FloatRange(from = 0) 47 | public float getCornerRadius() { 48 | return mCornerRadius; 49 | } 50 | 51 | @Override 52 | public void onBoundsChange(Rect bounds) { 53 | mDstRectF.set(bounds); 54 | mShader = null; 55 | } 56 | 57 | @Override 58 | public void onDraw(Canvas canvas, Paint paint, Bitmap buffer) { 59 | if (mCornerRadius == 0) { 60 | canvas.drawBitmap(buffer, null, mDstRectF, paint); 61 | return; 62 | } 63 | if (mShader == null) { 64 | mShader = new BitmapShader(buffer, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); 65 | final Matrix shaderMatrix = new Matrix(); 66 | shaderMatrix.setTranslate(mDstRectF.left, mDstRectF.top); 67 | shaderMatrix.preScale(mDstRectF.width() / buffer.getWidth(), mDstRectF.height() / buffer.getHeight()); 68 | mShader.setLocalMatrix(shaderMatrix); 69 | } 70 | paint.setShader(mShader); 71 | canvas.drawRoundRect(mDstRectF, mCornerRadius, mCornerRadius, paint); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/transforms/Transform.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.transforms; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.Canvas; 5 | import android.graphics.Paint; 6 | import android.graphics.Rect; 7 | 8 | import pl.droidsonroids.gif.GifDrawable; 9 | 10 | /** 11 | * Interface to support clients performing custom transformations before the current GIF Bitmap is drawn. 12 | */ 13 | public interface Transform { 14 | 15 | /** 16 | * Called by {@link GifDrawable} when its {@link GifDrawable#onBoundsChange(Rect)} is called. 17 | * @param bounds new bounds 18 | */ 19 | void onBoundsChange(Rect bounds); 20 | 21 | /** 22 | * Called by {@link GifDrawable} when its {@link GifDrawable#draw(Canvas)} is called. 23 | * 24 | * @param canvas The canvas supplied by the system to draw on. 25 | * @param paint The paint to use for custom drawing. 26 | * @param buffer The current Bitmap for the GIF. 27 | */ 28 | void onDraw(Canvas canvas, Paint paint, Bitmap buffer); 29 | } 30 | -------------------------------------------------------------------------------- /android-gif-drawable/src/main/java/pl/droidsonroids/gif/transforms/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Transformations performed before drawing GIF frames. See {@link pl.droidsonroids.gif.transforms.Transform} 3 | */ 4 | package pl.droidsonroids.gif.transforms; -------------------------------------------------------------------------------- /android-gif-drawable/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/CallbackWeakReferenceTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.drawable.Drawable; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.mockito.Mock; 8 | import org.mockito.junit.MockitoJUnitRunner; 9 | 10 | import pl.droidsonroids.gif.MultiCallback.CallbackWeakReference; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | @RunWith(MockitoJUnitRunner.class) 15 | public class CallbackWeakReferenceTest { 16 | 17 | @Mock Drawable.Callback callback; 18 | @Mock Drawable.Callback anotherCallback; 19 | 20 | @Test 21 | public void testEquals() throws Exception { 22 | final CallbackWeakReference reference = new CallbackWeakReference(callback); 23 | final CallbackWeakReference anotherReference = new CallbackWeakReference(callback); 24 | assertThat(reference).isEqualTo(anotherReference); 25 | } 26 | 27 | @Test 28 | public void testNotEqualReferences() throws Exception { 29 | final CallbackWeakReference reference = new CallbackWeakReference(callback); 30 | final CallbackWeakReference anotherReference = new CallbackWeakReference(anotherCallback); 31 | assertThat(reference).isNotEqualTo(anotherReference); 32 | } 33 | 34 | @Test 35 | public void testNotEqualDifferentObjects() throws Exception { 36 | final CallbackWeakReference reference = new CallbackWeakReference(callback); 37 | assertThat(reference).isNotEqualTo(null); 38 | assertThat(reference).isNotEqualTo(callback); 39 | } 40 | 41 | @Test 42 | public void testHashCode() throws Exception { 43 | final CallbackWeakReference reference = new CallbackWeakReference(callback); 44 | final CallbackWeakReference anotherReference = new CallbackWeakReference(callback); 45 | assertThat(reference.hashCode()).isEqualTo(anotherReference.hashCode()); 46 | } 47 | 48 | @Test 49 | public void testHashCodeNull() throws Exception { 50 | final CallbackWeakReference reference = new CallbackWeakReference(callback); 51 | final CallbackWeakReference anotherReference = new CallbackWeakReference(null); 52 | assertThat(reference.hashCode()).isNotEqualTo(anotherReference.hashCode()); 53 | } 54 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/ConditionVariableTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import net.jodah.concurrentunit.Waiter; 4 | 5 | import org.junit.Before; 6 | import org.junit.Rule; 7 | import org.junit.Test; 8 | import org.junit.rules.Timeout; 9 | 10 | import java.util.concurrent.TimeUnit; 11 | import java.util.concurrent.TimeoutException; 12 | 13 | public class ConditionVariableTest { 14 | 15 | private static final int TEST_TIMEOUT = 500; 16 | private static final int BLOCK_DURATION = 200; 17 | 18 | @Rule 19 | public Timeout timeout = new Timeout(TEST_TIMEOUT, TimeUnit.MILLISECONDS); 20 | 21 | private ConditionVariable conditionVariable; 22 | private Waiter waiter; 23 | 24 | @Before 25 | public void setUp() { 26 | conditionVariable = new ConditionVariable(); 27 | waiter = new Waiter(); 28 | } 29 | 30 | @Test 31 | public void testBlock() throws Exception { 32 | blockAndWait(); 33 | } 34 | 35 | @Test 36 | public void testOpen() throws Exception { 37 | new Thread() { 38 | @Override 39 | public void run() { 40 | conditionVariable.open(); 41 | waiter.resume(); 42 | } 43 | }.start(); 44 | conditionVariable.block(); 45 | waiter.await(); 46 | } 47 | 48 | @Test 49 | public void testInitiallyOpened() throws Exception { 50 | conditionVariable.set(true); 51 | conditionVariable.block(); 52 | } 53 | 54 | @Test 55 | public void testInitiallyClosed() throws Exception { 56 | conditionVariable.set(false); 57 | blockAndWait(); 58 | } 59 | 60 | @Test 61 | public void testClose() throws Exception { 62 | conditionVariable.close(); 63 | blockAndWait(); 64 | } 65 | 66 | private void blockAndWait() throws InterruptedException, TimeoutException { 67 | final Thread thread = new Thread() { 68 | @Override 69 | public void run() { 70 | try { 71 | waiter.resume(); 72 | conditionVariable.block(); 73 | } catch (InterruptedException e) { 74 | Thread.currentThread().interrupt(); 75 | waiter.rethrow(e); 76 | } 77 | waiter.fail("ConditionVariable not blocked"); 78 | } 79 | }; 80 | thread.start(); 81 | thread.join(BLOCK_DURATION); 82 | waiter.await(); 83 | } 84 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/GifDrawableBuilderTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class GifDrawableBuilderTest { 8 | 9 | @Test 10 | public void testOptionsAndSampleSizeConflict() throws Exception { 11 | GifDrawableBuilder builder = new GifDrawableBuilder(); 12 | GifOptions options = new GifOptions(); 13 | builder.options(options); 14 | builder.sampleSize(3); 15 | assertThat(options.inSampleSize).isEqualTo((char) 1); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/GifOptionsTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class GifOptionsTest { 9 | 10 | private GifOptions gifOptions; 11 | 12 | @Before 13 | public void setUp() { 14 | gifOptions = new GifOptions(); 15 | } 16 | 17 | @Test 18 | public void testInitialValues() { 19 | assertThat(gifOptions.inSampleSize).isEqualTo((char) 1); 20 | assertThat(gifOptions.inIsOpaque).isFalse(); 21 | } 22 | 23 | @Test 24 | public void setInSampleSize() throws Exception { 25 | gifOptions.setInSampleSize(2); 26 | assertThat(gifOptions.inSampleSize).isEqualTo((char) 2); 27 | } 28 | 29 | @Test 30 | public void setInIsOpaque() throws Exception { 31 | gifOptions.setInIsOpaque(true); 32 | assertThat(gifOptions.inIsOpaque).isTrue(); 33 | } 34 | 35 | @Test 36 | public void copyFromNonNull() throws Exception { 37 | GifOptions source = new GifOptions(); 38 | source.setInIsOpaque(false); 39 | source.setInSampleSize(8); 40 | gifOptions.setFrom(source); 41 | assertThat(gifOptions).isEqualToComparingFieldByField(source); 42 | } 43 | 44 | @Test 45 | public void copyFromNull() throws Exception { 46 | GifOptions defaultOptions = new GifOptions(); 47 | gifOptions.setInIsOpaque(false); 48 | gifOptions.setInSampleSize(8); 49 | gifOptions.setFrom(null); 50 | assertThat(gifOptions).isEqualToComparingFieldByField(defaultOptions); 51 | } 52 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/GifViewUtilsDensityTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.content.res.Resources; 4 | import android.graphics.Bitmap; 5 | import android.os.Build; 6 | import android.support.annotation.RequiresApi; 7 | import android.util.DisplayMetrics; 8 | import android.util.TypedValue; 9 | 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.mockito.Mock; 13 | import org.mockito.invocation.InvocationOnMock; 14 | import org.mockito.junit.MockitoJUnitRunner; 15 | import org.mockito.stubbing.Answer; 16 | 17 | import static android.util.DisplayMetrics.DENSITY_DEFAULT; 18 | import static android.util.DisplayMetrics.DENSITY_HIGH; 19 | import static android.util.DisplayMetrics.DENSITY_LOW; 20 | import static android.util.DisplayMetrics.DENSITY_MEDIUM; 21 | import static android.util.DisplayMetrics.DENSITY_TV; 22 | import static android.util.DisplayMetrics.DENSITY_XHIGH; 23 | import static android.util.DisplayMetrics.DENSITY_XXHIGH; 24 | import static android.util.DisplayMetrics.DENSITY_XXXHIGH; 25 | import static org.assertj.core.api.Assertions.assertThat; 26 | import static org.mockito.ArgumentMatchers.any; 27 | import static org.mockito.ArgumentMatchers.anyBoolean; 28 | import static org.mockito.ArgumentMatchers.anyInt; 29 | import static org.mockito.Mockito.doAnswer; 30 | import static org.mockito.Mockito.when; 31 | import static pl.droidsonroids.gif.GifViewUtils.getDensityScale; 32 | 33 | @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 34 | @RunWith(MockitoJUnitRunner.class) 35 | public class GifViewUtilsDensityTest { 36 | 37 | @Mock 38 | Resources resources; 39 | 40 | private Resources getMockedResources(final int resourceDensity, final int displayDensity) { 41 | doAnswer(new Answer() { 42 | @Override 43 | public TypedValue answer(InvocationOnMock invocation) throws Throwable { 44 | final TypedValue outValue = invocation.getArgument(1); 45 | outValue.density = resourceDensity; 46 | return outValue; 47 | } 48 | }).when(resources).getValue(anyInt(), any(TypedValue.class), anyBoolean()); 49 | 50 | final DisplayMetrics displayMetrics = new DisplayMetrics(); 51 | displayMetrics.densityDpi = displayDensity; 52 | when(resources.getDisplayMetrics()).thenReturn(displayMetrics); 53 | return resources; 54 | } 55 | 56 | @Test 57 | public void testHighResourceDensities() throws Exception { 58 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_HIGH), 0)).isEqualTo(1); 59 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_LOW), 0)).isEqualTo(0.5f); 60 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_MEDIUM), 0)).isEqualTo(2f / 3); 61 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_XHIGH), 0)).isEqualTo(4f / 3); 62 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_XXHIGH), 0)).isEqualTo(2); 63 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_XXXHIGH), 0)).isEqualTo(8f / 3); 64 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, DENSITY_TV), 0)).isEqualTo(213f / 240); 65 | } 66 | 67 | @Test 68 | public void testLowHighDensity() throws Exception { 69 | assertThat(getDensityScale(getMockedResources(DENSITY_LOW, DENSITY_HIGH), 0)).isEqualTo(2); 70 | } 71 | 72 | @Test 73 | public void testNoneResourceDensities() throws Exception { 74 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_LOW), 0)).isEqualTo(1); 75 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_MEDIUM), 0)).isEqualTo(1); 76 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_DEFAULT), 0)).isEqualTo(1); 77 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_TV), 0)).isEqualTo(1); 78 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_HIGH), 0)).isEqualTo(1); 79 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_XXHIGH), 0)).isEqualTo(1); 80 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_NONE, DENSITY_XXXHIGH), 0)).isEqualTo(1); 81 | } 82 | 83 | @Test 84 | public void testNoneDisplayDensities() throws Exception { 85 | assertThat(getDensityScale(getMockedResources(DENSITY_LOW, Bitmap.DENSITY_NONE), 0)).isEqualTo(1); 86 | assertThat(getDensityScale(getMockedResources(DENSITY_MEDIUM, Bitmap.DENSITY_NONE), 0)).isEqualTo(1); 87 | assertThat(getDensityScale(getMockedResources(TypedValue.DENSITY_DEFAULT, Bitmap.DENSITY_NONE), 0)).isEqualTo(1); 88 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, Bitmap.DENSITY_NONE), 0)).isEqualTo(1); 89 | assertThat(getDensityScale(getMockedResources(DENSITY_XXHIGH, Bitmap.DENSITY_NONE), 0)).isEqualTo(1); 90 | } 91 | 92 | @Test 93 | public void testInvalidDensities() throws Exception { 94 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, -1), 0)).isEqualTo(1); 95 | assertThat(getDensityScale(getMockedResources(-1, DENSITY_HIGH), 0)).isEqualTo(1); 96 | assertThat(getDensityScale(getMockedResources(-1, -1), 0)).isEqualTo(1); 97 | assertThat(getDensityScale(getMockedResources(DENSITY_HIGH, 0), 0)).isEqualTo(1); 98 | } 99 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/GifViewUtilsTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.util.AttributeSet; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.robolectric.Robolectric; 8 | import org.robolectric.RobolectricTestRunner; 9 | import org.robolectric.RuntimeEnvironment; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | @RunWith(RobolectricTestRunner.class) 14 | public class GifViewUtilsTest { 15 | 16 | @Test 17 | public void testFreezesAnimationAttribute() { 18 | final AttributeSet attributeSet = Robolectric.buildAttributeSet() 19 | .addAttribute(R.attr.freezesAnimation, "true") 20 | .build(); 21 | 22 | final GifImageView gifImageView = new GifImageView(RuntimeEnvironment.application, attributeSet); 23 | assertThat(GifViewUtils.isFreezingAnimation(gifImageView, attributeSet, 0, 0)).isTrue(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /android-gif-drawable/src/test/java/pl/droidsonroids/gif/MultiCallbackTest.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.view.View; 5 | 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.Mock; 10 | import org.mockito.MockitoAnnotations; 11 | import org.mockito.Spy; 12 | import org.robolectric.RobolectricTestRunner; 13 | 14 | import static org.mockito.Mockito.verify; 15 | 16 | @RunWith(RobolectricTestRunner.class) 17 | public class MultiCallbackTest { 18 | 19 | @Mock View view; 20 | @Spy Drawable drawable; 21 | private Runnable action; 22 | private MultiCallback simpleMultiCallback; 23 | 24 | @Before 25 | public void setUp() { 26 | MockitoAnnotations.initMocks(this); 27 | simpleMultiCallback = new MultiCallback(); 28 | action = new Runnable() { 29 | @Override 30 | public void run() { 31 | //no-op 32 | } 33 | }; 34 | } 35 | 36 | @Test 37 | public void testInvalidateDrawable() { 38 | simpleMultiCallback.addView(view); 39 | drawable.setCallback(simpleMultiCallback); 40 | drawable.invalidateSelf(); 41 | verify(view).invalidateDrawable(drawable); 42 | } 43 | 44 | @Test 45 | public void testScheduleDrawable() { 46 | simpleMultiCallback.addView(view); 47 | drawable.setCallback(simpleMultiCallback); 48 | drawable.scheduleSelf(action, 0); 49 | verify(view).scheduleDrawable(drawable, action, 0); 50 | } 51 | 52 | @Test 53 | public void testUnscheduleDrawable() { 54 | simpleMultiCallback.addView(view); 55 | drawable.setCallback(simpleMultiCallback); 56 | drawable.unscheduleSelf(action); 57 | verify(view).unscheduleDrawable(drawable, action); 58 | } 59 | 60 | @Test 61 | public void testViewRemoval() { 62 | simpleMultiCallback.addView(view); 63 | drawable.setCallback(simpleMultiCallback); 64 | drawable.invalidateSelf(); 65 | simpleMultiCallback.removeView(view); 66 | drawable.invalidateSelf(); 67 | verify(view).invalidateDrawable(drawable); 68 | } 69 | 70 | @Test 71 | public void testViewInvalidate() { 72 | final MultiCallback viewInvalidateMultiCallback = new MultiCallback(true); 73 | viewInvalidateMultiCallback.addView(view); 74 | drawable.setCallback(viewInvalidateMultiCallback); 75 | drawable.invalidateSelf(); 76 | verify(view).invalidate(); 77 | } 78 | } -------------------------------------------------------------------------------- /android-gif-drawable/src/test/resources/pl/droidsonroids/gif/robolectric.properties: -------------------------------------------------------------------------------- 1 | constants=pl.droidsonroids.gif.BuildConfig 2 | sdk=23 -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | mavenCentral() 5 | } 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:2.2.3' 8 | classpath 'com.dicedmelon.gradle:jacoco-android:0.1.1' 9 | } 10 | } 11 | 12 | ext { 13 | versions = [ 14 | compileSdk: 25, 15 | targetSdk : 25, 16 | minSdk : 9, 17 | buildTools: '25.0.2', 18 | ] 19 | } 20 | 21 | subprojects { 22 | tasks.withType(JavaCompile) { 23 | options.compilerArgs << '-Xlint' 24 | } 25 | repositories { 26 | jcenter() 27 | mavenCentral() 28 | } 29 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Jan 15 01:05:56 CET 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/README.md: -------------------------------------------------------------------------------- 1 | android-gif-drawable-sample 2 | =========================== 3 | 4 | Sample project for [android-gif-drawable](https://github.com/koral--/android-gif-drawable) library. 5 | 6 | Used icons are either public domain, created by Dave Johnston or licensed under CC, GFDL available on 7 | [Wikimedia Commons](https://commons.wikimedia.org) 8 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion versions.compileSdk 5 | buildToolsVersion versions.buildTools 6 | 7 | compileOptions { 8 | sourceCompatibility JavaVersion.VERSION_1_7 9 | targetCompatibility JavaVersion.VERSION_1_7 10 | } 11 | 12 | defaultConfig { 13 | versionName project.version 14 | minSdkVersion versions.minSdk 15 | targetSdkVersion versions.targetSdk 16 | versionCode 1 17 | versionName '1.0' 18 | applicationId 'pl.droidsonroids.gif.sample' 19 | jackOptions { 20 | enabled true 21 | } 22 | } 23 | 24 | signingConfigs { 25 | release { 26 | storeFile new File("$System.env.HOME/.android/debug.keystore") 27 | storePassword 'android' 28 | keyAlias 'androiddebugkey' 29 | keyPassword 'android' 30 | } 31 | } 32 | 33 | buildTypes { 34 | release { 35 | minifyEnabled true 36 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 37 | signingConfig signingConfigs.release 38 | } 39 | debug { 40 | jniDebuggable true 41 | } 42 | } 43 | } 44 | 45 | dependencies { 46 | debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5' 47 | releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' 48 | compile 'com.android.support:design:25.1.1' 49 | compile 'com.android.support:appcompat-v7:25.1.1' 50 | compile project(':android-gif-drawable') 51 | //compile 'pl.droidsonroids.gif:android-gif-drawable:+' 52 | } 53 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | -keepattributes Signature, LineNumberTable 2 | 3 | #leakcanary 4 | -keep class org.eclipse.mat.** { *; } 5 | -dontwarn com.squareup.haha.guava.** 6 | -dontwarn com.squareup.haha.perflib.** 7 | -dontwarn com.squareup.haha.trove.** 8 | -dontwarn com.squareup.leakcanary.** 9 | -keep class com.squareup.haha.** { *; } 10 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 10 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Delaware.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Delaware.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Estonia.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Estonia.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Finland.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Finland.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-France.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-France.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Georgia.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Georgia.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Greece.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Greece.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Hungary.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Hungary.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Uruguay.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Uruguay.gif -------------------------------------------------------------------------------- /sample/src/main/assets/Animated-Flag-Virgin_Islands.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/assets/Animated-Flag-Virgin_Islands.gif -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/AboutFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Bundle; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | /** 9 | * Fragment with information about application 10 | * 11 | * @author koral-- 12 | */ 13 | public class AboutFragment extends BaseFragment { 14 | @Override 15 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 16 | return inflater.inflate(R.layout.about, container, false); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/AnimatedSelectorDrawableGenerator.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.content.res.Resources; 4 | import android.content.res.XmlResourceParser; 5 | import android.graphics.drawable.Drawable; 6 | import android.graphics.drawable.StateListDrawable; 7 | import android.support.annotation.DrawableRes; 8 | 9 | import org.xmlpull.v1.XmlPullParser; 10 | import org.xmlpull.v1.XmlPullParserException; 11 | 12 | import java.io.IOException; 13 | 14 | import pl.droidsonroids.gif.GifDrawable; 15 | 16 | class AnimatedSelectorDrawableGenerator { 17 | private static final String NAMESPACE = "http://schemas.android.com/apk/res/android"; 18 | 19 | static Drawable getDrawable(Resources resources, XmlResourceParser resourceParser) throws XmlPullParserException, IOException { 20 | final StateListDrawable stateListDrawable = new StateListDrawable(); 21 | resourceParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); 22 | 23 | int eventType = resourceParser.getEventType(); 24 | do { 25 | if (eventType == XmlPullParser.START_TAG && "item".equals(resourceParser.getName())) { 26 | @DrawableRes 27 | final int resourceId = resourceParser.getAttributeResourceValue(NAMESPACE, "drawable", 0); 28 | final boolean state_pressed = resourceParser.getAttributeBooleanValue(NAMESPACE, "state_pressed", false); 29 | final int[] stateSet = state_pressed ? new int[]{android.R.attr.state_pressed} : new int[0]; 30 | stateListDrawable.addState(stateSet, GifDrawable.createFromResource(resources, resourceId)); 31 | } 32 | eventType = resourceParser.next(); 33 | } while (eventType != XmlPullParser.END_DOCUMENT); 34 | 35 | return stateListDrawable; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/AnimatedSelectorFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.content.res.XmlResourceParser; 4 | import android.graphics.drawable.Drawable; 5 | import android.graphics.drawable.StateListDrawable; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.support.annotation.Nullable; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | 13 | import org.xmlpull.v1.XmlPullParserException; 14 | 15 | import java.io.IOException; 16 | 17 | import pl.droidsonroids.gif.GifDrawable; 18 | 19 | public class AnimatedSelectorFragment extends BaseFragment { 20 | 21 | @SuppressWarnings("deprecation") 22 | @Nullable 23 | @Override 24 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 25 | final View rootView = inflater.inflate(R.layout.animated_selector, container, false); 26 | final View buttonJava = rootView.findViewById(R.id.button_java); 27 | buttonJava.setBackgroundDrawable(getJavaAnimatedBackground()); 28 | 29 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { 30 | final View buttonXML = rootView.findViewById(R.id.button_xml); 31 | try { 32 | buttonXML.setBackgroundDrawable(getXMLAnimatedBackground()); 33 | } catch (XmlPullParserException | IOException e) { 34 | throw new IllegalStateException(e); 35 | } 36 | } 37 | 38 | return rootView; 39 | } 40 | 41 | @SuppressWarnings("ResourceType") 42 | private Drawable getXMLAnimatedBackground() throws XmlPullParserException, IOException { 43 | final XmlResourceParser resourceParser = getResources().getXml(R.drawable.selector); 44 | return AnimatedSelectorDrawableGenerator.getDrawable(getResources(), resourceParser); 45 | } 46 | 47 | private Drawable getJavaAnimatedBackground() { 48 | final StateListDrawable stateListDrawable = new StateListDrawable(); 49 | stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, GifDrawable.createFromResource(getResources(), R.drawable.anim_flag_chile)); 50 | stateListDrawable.addState(new int[0], GifDrawable.createFromResource(getResources(), R.drawable.anim_flag_england)); 51 | return stateListDrawable; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/AnimationControlFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.design.widget.Snackbar; 5 | import android.view.LayoutInflater; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.widget.ToggleButton; 9 | 10 | import pl.droidsonroids.gif.AnimationListener; 11 | import pl.droidsonroids.gif.GifDrawable; 12 | import pl.droidsonroids.gif.GifImageView; 13 | 14 | public class AnimationControlFragment extends BaseFragment implements View.OnClickListener, AnimationListener { 15 | 16 | private GifDrawable gifDrawable; 17 | private ToggleButton toggleButton; 18 | 19 | @Override 20 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 21 | final View view = inflater.inflate(R.layout.animation_control, container, false); 22 | final GifImageView gifImageView = (GifImageView) view.findViewById(R.id.gifImageView); 23 | view.findViewById(R.id.btn_reset).setOnClickListener(this); 24 | toggleButton = (ToggleButton) view.findViewById(R.id.btn_toggle); 25 | toggleButton.setOnClickListener(this); 26 | gifDrawable = (GifDrawable) gifImageView.getDrawable(); 27 | 28 | resetAnimation(); 29 | return view; 30 | } 31 | 32 | @Override 33 | public void onClick(View v) { 34 | if (v.getId() == R.id.btn_toggle) { 35 | toggleAnimation(); 36 | } else { 37 | resetAnimation(); 38 | } 39 | } 40 | 41 | private void resetAnimation() { 42 | gifDrawable.stop(); 43 | gifDrawable.setLoopCount(4); 44 | gifDrawable.seekToFrameAndGet(5); 45 | toggleButton.setChecked(false); 46 | } 47 | 48 | private void toggleAnimation() { 49 | if (gifDrawable.isPlaying()) { 50 | gifDrawable.stop(); 51 | } else { 52 | gifDrawable.start(); 53 | } 54 | } 55 | 56 | @Override 57 | public void onViewCreated(View view, Bundle savedInstanceState) { 58 | super.onViewCreated(view, savedInstanceState); 59 | gifDrawable.addAnimationListener(this); 60 | } 61 | 62 | @Override 63 | public void onDestroyView() { 64 | gifDrawable.removeAnimationListener(this); 65 | super.onDestroyView(); 66 | } 67 | 68 | @Override 69 | public void onAnimationCompleted(final int loopNumber) { 70 | final View view = getView(); 71 | if (view != null) { 72 | Snackbar.make(view, getString(R.string.animation_loop_completed, loopNumber), Snackbar.LENGTH_SHORT).show(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/BaseFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.support.v4.app.Fragment; 4 | 5 | import com.squareup.leakcanary.RefWatcher; 6 | 7 | public abstract class BaseFragment extends Fragment { 8 | @Override 9 | public void onDestroy() { 10 | super.onDestroy(); 11 | RefWatcher refWatcher = ((MainActivity) getContext()).getRefWatcher(); 12 | refWatcher.watch(this); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/GifLoadTask.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Build; 4 | import android.support.annotation.RequiresApi; 5 | 6 | import java.io.IOException; 7 | import java.lang.ref.WeakReference; 8 | import java.net.URL; 9 | import java.net.URLConnection; 10 | import java.nio.ByteBuffer; 11 | import java.nio.channels.Channels; 12 | import java.nio.channels.ReadableByteChannel; 13 | import java.util.concurrent.Callable; 14 | import java.util.concurrent.ExecutionException; 15 | import java.util.concurrent.FutureTask; 16 | 17 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 18 | class GifLoadTask extends FutureTask { 19 | private static final String GIF_URL = "https://raw.githubusercontent.com/koral--/android-gif-drawable-sample/cb2d1f42b3045b2790a886d1574d3e74281de743/sample/src/main/assets/Animated-Flag-Hungary.gif"; 20 | private final WeakReference mFragmentReference; 21 | 22 | GifLoadTask(HttpFragment httpFragment) { 23 | super(new Callable() { 24 | @Override 25 | public ByteBuffer call() throws Exception { 26 | URLConnection urlConnection = new URL(GIF_URL).openConnection(); 27 | urlConnection.connect(); 28 | final int contentLength = urlConnection.getContentLength(); 29 | if (contentLength < 0) { 30 | throw new IOException("Content-Length not present"); 31 | } 32 | ByteBuffer buffer = ByteBuffer.allocateDirect(contentLength); 33 | ReadableByteChannel channel = Channels.newChannel(urlConnection.getInputStream()); 34 | while (buffer.remaining() > 0) 35 | channel.read(buffer); 36 | channel.close(); 37 | return buffer; 38 | } 39 | }); 40 | mFragmentReference = new WeakReference<>(httpFragment); 41 | } 42 | 43 | @Override 44 | protected void done() { 45 | final HttpFragment httpFragment = mFragmentReference.get(); 46 | if (httpFragment == null) { 47 | return; 48 | } 49 | try { 50 | httpFragment.onGifDownloaded(get()); 51 | } catch (InterruptedException e) { 52 | Thread.currentThread().interrupt(); 53 | } catch (ExecutionException e) { 54 | httpFragment.onDownloadFailed(e); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/GifSelectorDrawable.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.content.res.Resources; 4 | import android.content.res.XmlResourceParser; 5 | import android.graphics.drawable.StateListDrawable; 6 | import android.support.annotation.DrawableRes; 7 | import android.util.AttributeSet; 8 | 9 | import org.xmlpull.v1.XmlPullParser; 10 | import org.xmlpull.v1.XmlPullParserException; 11 | 12 | import java.io.IOException; 13 | 14 | import pl.droidsonroids.gif.GifDrawable; 15 | 16 | public class GifSelectorDrawable extends StateListDrawable { 17 | 18 | private static final String NAMESPACE = "http://schemas.android.com/apk/res/android"; 19 | 20 | @Override 21 | public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme) throws XmlPullParserException, IOException { 22 | final XmlResourceParser resourceParser = (XmlResourceParser) parser; 23 | resourceParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); 24 | 25 | int eventType = resourceParser.getEventType(); 26 | do { 27 | if (eventType == XmlPullParser.START_TAG && "item".equals(resourceParser.getName())) { 28 | @DrawableRes 29 | final int resourceId = resourceParser.getAttributeResourceValue(NAMESPACE, "drawable", 0); 30 | final boolean state_pressed = resourceParser.getAttributeBooleanValue(NAMESPACE, "state_pressed", false); 31 | final int[] stateSet = state_pressed ? new int[]{android.R.attr.state_pressed} : new int[0]; 32 | addState(stateSet, GifDrawable.createFromResource(r, resourceId)); 33 | } 34 | eventType = resourceParser.next(); 35 | } while (eventType != XmlPullParser.END_DOCUMENT); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/GifTextViewFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Bundle; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | public class GifTextViewFragment extends BaseFragment { 9 | @Override 10 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 11 | return inflater.inflate(R.layout.compound_drawables, container, false); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/GifTextureFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Build; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import pl.droidsonroids.gif.GifTextureView; 11 | 12 | public class GifTextureFragment extends BaseFragment { 13 | 14 | @Override 15 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 16 | return inflater.inflate(R.layout.texture, container, false); 17 | } 18 | 19 | @Override 20 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 21 | super.onViewCreated(view, savedInstanceState); 22 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 23 | final GifTextureView gifTextureView = (GifTextureView) view.findViewById(R.id.gifTextureView); 24 | if (!gifTextureView.isHardwareAccelerated()) { 25 | view.findViewById(R.id.text_textureview_stub).setVisibility(View.VISIBLE); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/HttpFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Build; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.support.annotation.RequiresApi; 7 | import android.support.design.widget.Snackbar; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | 12 | import java.nio.ByteBuffer; 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.Executors; 15 | 16 | import pl.droidsonroids.gif.GifTextureView; 17 | import pl.droidsonroids.gif.InputSource; 18 | 19 | public class HttpFragment extends BaseFragment implements View.OnClickListener { 20 | 21 | private GifTextureView mGifTextureView; 22 | private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor(); 23 | 24 | @Nullable 25 | @Override 26 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 27 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 28 | if (container != null) { 29 | Snackbar.make(container, R.string.gif_texture_view_stub_api_level, Snackbar.LENGTH_LONG).show(); 30 | } 31 | return null; 32 | } else { 33 | mGifTextureView = (GifTextureView) inflater.inflate(R.layout.http, container, false); 34 | downloadGif(); 35 | return mGifTextureView; 36 | } 37 | } 38 | 39 | @Override 40 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 41 | super.onViewCreated(view, savedInstanceState); 42 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && !mGifTextureView.isHardwareAccelerated()) { 43 | Snackbar.make(mGifTextureView, R.string.gif_texture_view_stub_acceleration, Snackbar.LENGTH_LONG).show(); 44 | } 45 | } 46 | 47 | @Override 48 | public void onDestroy() { 49 | mExecutorService.shutdownNow(); 50 | super.onDestroy(); 51 | } 52 | 53 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 54 | void onGifDownloaded(ByteBuffer buffer) { 55 | mGifTextureView.setInputSource(new InputSource.DirectByteBufferSource(buffer)); 56 | } 57 | 58 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 59 | void onDownloadFailed(Exception e) { 60 | mGifTextureView.setOnClickListener(HttpFragment.this); 61 | if (isDetached()) { 62 | return; 63 | } 64 | final String message = getString(R.string.gif_texture_view_loading_failed, e.getMessage()); 65 | Snackbar.make(mGifTextureView, message, Snackbar.LENGTH_LONG).show(); 66 | 67 | } 68 | 69 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 70 | private void downloadGif() { 71 | mExecutorService.submit(new GifLoadTask(this)); 72 | } 73 | 74 | @Override 75 | @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 76 | public void onClick(View v) { 77 | downloadGif(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/ImageSpanFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.os.Build; 5 | import android.os.Bundle; 6 | import android.support.annotation.NonNull; 7 | import android.text.SpannableStringBuilder; 8 | import android.text.style.ImageSpan; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.widget.TextView; 13 | 14 | import pl.droidsonroids.gif.GifDrawable; 15 | 16 | public class ImageSpanFragment extends BaseFragment implements Drawable.Callback { 17 | 18 | private TextView mTextView; 19 | 20 | @Override 21 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 22 | mTextView = new TextView(getActivity()); 23 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 24 | mTextView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); 25 | mTextView.setTextIsSelectable(true); 26 | } 27 | final GifDrawable gifDrawable = GifDrawable.createFromResource(getResources(), R.drawable.anim_flag_england); 28 | final SpannableStringBuilder ssb = new SpannableStringBuilder("test\ufffc"); 29 | assert gifDrawable != null; 30 | gifDrawable.setBounds(0, 0, gifDrawable.getIntrinsicWidth(), gifDrawable.getIntrinsicHeight()); 31 | gifDrawable.setCallback(this); 32 | ssb.setSpan(new ImageSpan(gifDrawable), ssb.length() - 1, ssb.length(), 0); 33 | mTextView.setText(ssb); 34 | return mTextView; 35 | } 36 | 37 | @Override 38 | public void invalidateDrawable(@NonNull Drawable who) { 39 | mTextView.invalidate(); 40 | } 41 | 42 | @Override 43 | public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 44 | mTextView.postDelayed(what, when); 45 | } 46 | 47 | @Override 48 | public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 49 | mTextView.removeCallbacks(what); 50 | } 51 | } -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.app.FragmentActivity; 5 | import android.support.v4.view.ViewPager; 6 | 7 | import com.squareup.leakcanary.LeakCanary; 8 | import com.squareup.leakcanary.RefWatcher; 9 | 10 | /** 11 | * Main activity, hosts the pager 12 | * 13 | * @author koral-- 14 | */ 15 | public class MainActivity extends FragmentActivity { 16 | 17 | private RefWatcher mRefWatcher; 18 | 19 | @Override 20 | protected void onCreate(Bundle savedInstanceState) { 21 | mRefWatcher = LeakCanary.install(getApplication()); 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_main); 24 | ((ViewPager) findViewById(R.id.main_pager)).setAdapter(new MainPagerAdapter(this)); 25 | } 26 | 27 | RefWatcher getRefWatcher() { 28 | return mRefWatcher; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/MainPagerAdapter.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.support.v4.app.Fragment; 4 | import android.support.v4.app.FragmentActivity; 5 | import android.support.v4.app.FragmentStatePagerAdapter; 6 | 7 | import pl.droidsonroids.gif.sample.sources.GifSourcesFragment; 8 | 9 | class MainPagerAdapter extends FragmentStatePagerAdapter { 10 | private final String[] mPageTitles; 11 | 12 | MainPagerAdapter(FragmentActivity act) { 13 | super(act.getSupportFragmentManager()); 14 | mPageTitles = act.getResources().getStringArray(R.array.pages); 15 | } 16 | 17 | @Override 18 | public Fragment getItem(int position) { 19 | switch (position) { 20 | case 0: 21 | return new GifSourcesFragment(); 22 | case 1: 23 | return new GifTextViewFragment(); 24 | case 2: 25 | return new GifTextureFragment(); 26 | case 3: 27 | return new ImageSpanFragment(); 28 | case 4: 29 | return new AnimationControlFragment(); 30 | case 5: 31 | return new HttpFragment(); 32 | case 6: 33 | return new TexturePlaceholderFragment(); 34 | case 7: 35 | return new GifTexImage2DFragment(); 36 | case 8: 37 | return new AnimatedSelectorFragment(); 38 | case 9: 39 | return new AboutFragment(); 40 | default: 41 | throw new IndexOutOfBoundsException("Invalid page index"); 42 | } 43 | } 44 | 45 | @Override 46 | public int getCount() { 47 | return mPageTitles.length; 48 | } 49 | 50 | @Override 51 | public CharSequence getPageTitle(int position) { 52 | return mPageTitles[position]; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/TexturePlaceholderFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample; 2 | 3 | import android.content.res.AssetFileDescriptor; 4 | import android.graphics.Bitmap; 5 | import android.graphics.BitmapFactory; 6 | import android.graphics.Canvas; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.os.SystemClock; 10 | import android.support.annotation.NonNull; 11 | import android.support.annotation.Nullable; 12 | import android.support.design.widget.Snackbar; 13 | import android.view.LayoutInflater; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | 17 | import java.io.BufferedInputStream; 18 | import java.io.IOException; 19 | 20 | import pl.droidsonroids.gif.GifTextureView; 21 | import pl.droidsonroids.gif.InputSource; 22 | 23 | public class TexturePlaceholderFragment extends BaseFragment implements GifTextureView.PlaceholderDrawListener { 24 | 25 | @Nullable 26 | @Override 27 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 28 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 29 | if (container != null) { 30 | Snackbar.make(container, R.string.gif_texture_view_stub_api_level, Snackbar.LENGTH_LONG).show(); 31 | } 32 | return null; 33 | } else { 34 | final GifTextureView view = new GifTextureView(getContext()); 35 | try { 36 | final AssetFileDescriptor assetFileDescriptor = getContext().getAssets().openFd("Animated-Flag-Delaware.gif"); 37 | view.setInputSource(new InputSource.InputStreamSource(new SlowLoadingInputStream(assetFileDescriptor)), this); 38 | } catch (IOException e) { 39 | throw new RuntimeException(e); 40 | } 41 | return view; 42 | } 43 | } 44 | 45 | @Override 46 | public void onDrawPlaceholder(Canvas canvas) { 47 | final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 48 | canvas.drawBitmap(bitmap, 0, 0, null); 49 | bitmap.recycle(); 50 | } 51 | 52 | private static class SlowLoadingInputStream extends BufferedInputStream { 53 | 54 | private final AssetFileDescriptor mAssetFileDescriptor; 55 | private int mSleepTimeMillis = 5; 56 | 57 | SlowLoadingInputStream(AssetFileDescriptor assetFileDescriptor) throws IOException { 58 | super(assetFileDescriptor.createInputStream(), (int) assetFileDescriptor.getLength()); 59 | mAssetFileDescriptor = assetFileDescriptor; 60 | } 61 | 62 | @Override 63 | public int read(@NonNull byte[] buffer) throws IOException { 64 | SystemClock.sleep(mSleepTimeMillis); 65 | return super.read(buffer); 66 | } 67 | 68 | @Override 69 | public int read(@NonNull byte[] buffer, int off, int len) throws IOException { 70 | SystemClock.sleep(mSleepTimeMillis); 71 | return super.read(buffer, off, len); 72 | } 73 | 74 | @Override 75 | public int read() throws IOException { 76 | SystemClock.sleep(mSleepTimeMillis); 77 | return super.read(); 78 | } 79 | 80 | @Override 81 | public synchronized void reset() throws IOException { 82 | super.reset(); 83 | mSleepTimeMillis = 0; 84 | } 85 | 86 | @Override 87 | public void close() throws IOException { 88 | super.close(); 89 | mAssetFileDescriptor.close(); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/sources/GifSourceItemHolder.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample.sources; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.View; 5 | import android.widget.TextView; 6 | 7 | import pl.droidsonroids.gif.GifImageView; 8 | import pl.droidsonroids.gif.MultiCallback; 9 | import pl.droidsonroids.gif.sample.R; 10 | 11 | class GifSourceItemHolder extends RecyclerView.ViewHolder { 12 | final GifImageView gifImageViewOriginal; 13 | final GifImageView gifImageViewSampled; 14 | final TextView descriptionTextView; 15 | final MultiCallback multiCallback; 16 | 17 | GifSourceItemHolder(View itemView) { 18 | super(itemView); 19 | descriptionTextView = (TextView) itemView.findViewById(R.id.desc_tv); 20 | gifImageViewOriginal = (GifImageView) itemView.findViewById(R.id.image_original); 21 | gifImageViewSampled = (GifImageView) itemView.findViewById(R.id.image_subsampled); 22 | multiCallback= new MultiCallback(true); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/sources/GifSourcesAdapter.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample.sources; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.text.SpannableStringBuilder; 6 | import android.text.style.ImageSpan; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | import java.io.IOException; 12 | 13 | import pl.droidsonroids.gif.GifDrawable; 14 | import pl.droidsonroids.gif.GifDrawableBuilder; 15 | import pl.droidsonroids.gif.sample.R; 16 | 17 | class GifSourcesAdapter extends RecyclerView.Adapter { 18 | 19 | private final GifSourcesResolver mGifSourcesResolver; 20 | 21 | GifSourcesAdapter(final Context context) { 22 | mGifSourcesResolver = new GifSourcesResolver(context); 23 | } 24 | 25 | @Override 26 | public GifSourceItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { 27 | final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.source_item, parent, false); 28 | return new GifSourceItemHolder(itemView); 29 | } 30 | 31 | @Override 32 | public void onBindViewHolder(final GifSourceItemHolder holder, int position) { 33 | final String[] descriptions = holder.itemView.getResources().getStringArray(R.array.sources); 34 | position %= descriptions.length; 35 | 36 | final GifDrawable existingOriginalDrawable = (GifDrawable) holder.gifImageViewOriginal.getDrawable(); 37 | final GifDrawable existingSampledDrawable = (GifDrawable) holder.gifImageViewSampled.getDrawable(); 38 | final GifDrawableBuilder builder = new GifDrawableBuilder().with(existingOriginalDrawable); 39 | try { 40 | mGifSourcesResolver.bindSource(position, builder); 41 | final GifDrawable fullSizeDrawable = builder.build(); 42 | holder.gifImageViewOriginal.setImageDrawable(fullSizeDrawable); 43 | holder.gifImageViewOriginal.setOnClickListener(new View.OnClickListener() { 44 | @Override 45 | public void onClick(View v) { 46 | if (fullSizeDrawable.isPlaying()) 47 | fullSizeDrawable.stop(); 48 | else 49 | fullSizeDrawable.start(); 50 | } 51 | }); 52 | 53 | builder.with(existingSampledDrawable).sampleSize(3); 54 | mGifSourcesResolver.bindSource(position, builder); 55 | final GifDrawable subsampledDrawable = builder.build(); 56 | final SpannableStringBuilder stringBuilder = new SpannableStringBuilder(descriptions[position] + '\ufffc'); 57 | stringBuilder.setSpan(new ImageSpan(subsampledDrawable), stringBuilder.length() - 1, stringBuilder.length(), 0); 58 | holder.descriptionTextView.setText(stringBuilder); 59 | holder.gifImageViewSampled.setImageDrawable(subsampledDrawable); 60 | subsampledDrawable.setCallback(holder.multiCallback); 61 | holder.multiCallback.addView(holder.gifImageViewSampled); 62 | holder.multiCallback.addView(holder.descriptionTextView); 63 | } catch (IOException ex) { 64 | throw new RuntimeException(ex); 65 | } 66 | } 67 | 68 | @Override 69 | public int getItemCount() { 70 | return Integer.MAX_VALUE; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/sources/GifSourcesFragment.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample.sources; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.support.v7.widget.LinearLayoutManager; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | import pl.droidsonroids.gif.sample.BaseFragment; 12 | 13 | /** 14 | * Fragment with various GIF sources examples 15 | */ 16 | public class GifSourcesFragment extends BaseFragment { 17 | 18 | @Override 19 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 20 | final Context context = getContext(); 21 | RecyclerView recyclerView = new RecyclerView(context); 22 | recyclerView.setLayoutManager(new LinearLayoutManager(context)); 23 | recyclerView.setAdapter(new GifSourcesAdapter(context)); 24 | return recyclerView; 25 | } 26 | } -------------------------------------------------------------------------------- /sample/src/main/java/pl/droidsonroids/gif/sample/sources/GifSourcesResolver.java: -------------------------------------------------------------------------------- 1 | package pl.droidsonroids.gif.sample.sources; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.Context; 5 | import android.content.res.AssetFileDescriptor; 6 | import android.content.res.AssetManager; 7 | import android.content.res.Resources; 8 | import android.net.Uri; 9 | 10 | import java.io.File; 11 | import java.io.FileInputStream; 12 | import java.io.FileOutputStream; 13 | import java.io.IOException; 14 | import java.nio.ByteBuffer; 15 | 16 | import pl.droidsonroids.gif.GifDrawableBuilder; 17 | import pl.droidsonroids.gif.sample.R; 18 | 19 | class GifSourcesResolver { 20 | private final AssetManager mAssetManager; 21 | private final Resources mResources; 22 | private final ContentResolver mContentResolver; 23 | private final File mFileForUri; 24 | private final File mFile; 25 | private final String mFilePath; 26 | private final byte[] mByteArray; 27 | private final ByteBuffer mByteBuffer; 28 | 29 | GifSourcesResolver(Context context) { 30 | mResources = context.getResources(); 31 | mContentResolver = context.getContentResolver(); 32 | mAssetManager = mResources.getAssets(); 33 | mFileForUri = getFileFromAssets(context, "Animated-Flag-Uruguay.gif"); 34 | mFile = getFileFromAssets(context, "Animated-Flag-Virgin_Islands.gif"); 35 | mFilePath = getFileFromAssets(context, "Animated-Flag-Estonia.gif").getPath(); 36 | mByteArray = getBytesFromAssets(mAssetManager, "Animated-Flag-France.gif"); 37 | byte[] gifBytes = getBytesFromAssets(mAssetManager, "Animated-Flag-Georgia.gif"); 38 | mByteBuffer = ByteBuffer.allocateDirect(gifBytes.length); 39 | mByteBuffer.put(gifBytes); 40 | } 41 | 42 | void bindSource(final int position, final GifDrawableBuilder builder) throws IOException { 43 | switch (position) { 44 | case 0: //asset 45 | builder.from(mAssetManager, "Animated-Flag-Finland.gif"); 46 | break; 47 | case 1: //resource 48 | builder.from(mResources, R.drawable.anim_flag_england); 49 | break; 50 | case 2: //byte[] 51 | builder.from(mByteArray); 52 | break; 53 | case 3: //FileDescriptor 54 | builder.from(mAssetManager.openFd("Animated-Flag-Greece.gif")); 55 | break; 56 | case 4: //file path 57 | builder.from(mFilePath); 58 | break; 59 | case 5: //File 60 | builder.from(mFile); 61 | break; 62 | case 6: //AssetFileDescriptor 63 | builder.from(mResources.openRawResourceFd(R.raw.anim_flag_hungary)); 64 | break; 65 | case 7: //ByteBuffer 66 | builder.from(mByteBuffer); 67 | break; 68 | case 8: //Uri 69 | builder.from(mContentResolver, Uri.parse("file:///" + mFileForUri.getAbsolutePath())); 70 | break; 71 | case 9: //InputStream 72 | builder.from(mAssetManager.open("Animated-Flag-Delaware.gif", AssetManager.ACCESS_RANDOM)); 73 | break; 74 | default: 75 | throw new IndexOutOfBoundsException("Invalid source index"); 76 | } 77 | } 78 | 79 | private File getFileFromAssets(Context context, String filename) { 80 | try { 81 | File file = new File(context.getCacheDir(), filename); 82 | final AssetFileDescriptor assetFileDescriptor = context.getResources().getAssets().openFd(filename); 83 | FileInputStream input = assetFileDescriptor.createInputStream(); 84 | byte[] buf = new byte[(int) assetFileDescriptor.getDeclaredLength()]; 85 | int bytesRead = input.read(buf); 86 | input.close(); 87 | if (bytesRead != buf.length) { 88 | throw new IOException("Asset read failed"); 89 | } 90 | FileOutputStream output = new FileOutputStream(file); 91 | output.write(buf, 0, bytesRead); 92 | output.close(); 93 | return file; 94 | } catch (IOException ex) { 95 | throw new IllegalStateException(ex); 96 | } 97 | } 98 | 99 | private byte[] getBytesFromAssets(AssetManager assetManager, String filename) { 100 | try { 101 | final AssetFileDescriptor assetFileDescriptor = assetManager.openFd(filename); 102 | FileInputStream input = assetFileDescriptor.createInputStream(); 103 | byte[] buf = new byte[(int) assetFileDescriptor.getDeclaredLength()]; 104 | final int readBytes = input.read(buf); 105 | input.close(); 106 | if (readBytes != buf.length) { 107 | throw new IOException("Incorrect asset length"); 108 | } 109 | return buf; 110 | } catch (IOException ex) { 111 | throw new IllegalStateException(ex); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-nodpi/anim_flag_chile.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-nodpi/anim_flag_chile.gif -------------------------------------------------------------------------------- /sample/src/main/res/drawable-nodpi/anim_flag_england.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-nodpi/anim_flag_england.gif -------------------------------------------------------------------------------- /sample/src/main/res/drawable-nodpi/anim_flag_greenland.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-nodpi/anim_flag_greenland.gif -------------------------------------------------------------------------------- /sample/src/main/res/drawable-nodpi/anim_flag_iceland.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-nodpi/anim_flag_iceland.gif -------------------------------------------------------------------------------- /sample/src/main/res/drawable-nodpi/led7.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-nodpi/led7.gif -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DroidsOnRoids/android-gif-drawable/214666b676b73b3c8e8ec9c93c17cefe5b364b01/sample/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/layout-v14/http.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | -------------------------------------------------------------------------------- /sample/src/main/res/layout-v14/texture.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 | 21 | 22 | 30 | 31 | 32 | 39 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/about.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 13 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/animated_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 |