index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/PerformanceTrackerTest.java | package com.airbnb.lottie;
import androidx.core.util.Pair;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
public class PerformanceTrackerTest {
private PerformanceTracker performanceTracker;
@Before
public void setup() {
performanceTracker = new PerformanceTracker();
performanceTracker.setEnabled(true);
}
@Test
public void testDisabled() {
performanceTracker.setEnabled(false);
performanceTracker.recordRenderTime("Hello", 16f);
assertTrue(performanceTracker.getSortedRenderTimes().isEmpty());
}
@Test
public void testOneFrame() {
performanceTracker.recordRenderTime("Hello", 16f);
List<Pair<String, Float>> sortedRenderTimes = performanceTracker.getSortedRenderTimes();
assertThat(sortedRenderTimes.size(), equalTo(1));
assertThat(sortedRenderTimes.get(0).first, equalTo("Hello"));
assertThat(sortedRenderTimes.get(0).second, equalTo(16f));
}
@Test
public void testTwoFrames() {
performanceTracker.recordRenderTime("Hello", 16f);
performanceTracker.recordRenderTime("Hello", 8f);
List<Pair<String, Float>> sortedRenderTimes = performanceTracker.getSortedRenderTimes();
assertThat(sortedRenderTimes.size(), equalTo(1));
assertThat(sortedRenderTimes.get(0).first, equalTo("Hello"));
assertThat(sortedRenderTimes.get(0).second, equalTo(12f));
}
@Test
public void testTwoLayers() {
performanceTracker.recordRenderTime("Hello", 16f);
performanceTracker.recordRenderTime("World", 8f);
List<Pair<String, Float>> sortedRenderTimes = performanceTracker.getSortedRenderTimes();
assertThat(sortedRenderTimes.size(), equalTo(2));
assertThat(sortedRenderTimes.get(0).first, equalTo("Hello"));
assertThat(sortedRenderTimes.get(0).second, equalTo(16f));
assertThat(sortedRenderTimes.get(1).first, equalTo("World"));
assertThat(sortedRenderTimes.get(1).second, equalTo(8f));
}
@Test
public void testTwoLayersAlternatingFrames() {
performanceTracker.recordRenderTime("Hello", 16f);
performanceTracker.recordRenderTime("World", 8f);
performanceTracker.recordRenderTime("Hello", 32f);
performanceTracker.recordRenderTime("World", 4f);
List<Pair<String, Float>> sortedRenderTimes = performanceTracker.getSortedRenderTimes();
assertThat(sortedRenderTimes.size(), equalTo(2));
assertThat(sortedRenderTimes.get(0).first, equalTo("Hello"));
assertThat(sortedRenderTimes.get(0).second, equalTo(24f));
assertThat(sortedRenderTimes.get(1).first, equalTo("World"));
assertThat(sortedRenderTimes.get(1).second, equalTo(6f));
}
}
| 2,400 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/utils/GammaEvaluatorTest.java | package com.airbnb.lottie.utils;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class GammaEvaluatorTest {
@Test
public void testEvaluateForSameColorValues() {
for (int color = 0x000000; color <= 0xffffff; color++) {
int actual = GammaEvaluator.evaluate(0.3f, color, color);
assertThat(actual, is(color));
}
}
}
| 2,401 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/utils/LottieValueAnimatorTest.java | package com.airbnb.lottie.utils;
import android.animation.Animator;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.airbnb.lottie.BaseTest;
import org.junit.Test;
public class LottieValueAnimatorTest extends BaseTest {
@Test
public void callOfPauseAnimationShouldFireCallbackOnAnimationPause() {
// Set
Animator.AnimatorPauseListener listener = mock(Animator.AnimatorPauseListener.class);
LottieValueAnimator animator = new LottieValueAnimator();
animator.addPauseListener(listener);
// Do
animator.pauseAnimation();
// Check
verify(listener, times(1)).onAnimationPause(eq(animator));
verify(listener, times(0)).onAnimationResume(any());
}
@Test
public void callOfResumeAnimationShouldFireCallbackOnAnimationResume() {
// Set
Animator.AnimatorPauseListener listener = mock(Animator.AnimatorPauseListener.class);
LottieValueAnimator animator = new LottieValueAnimator();
animator.addPauseListener(listener);
// Do
animator.resumeAnimation();
// Check
verify(listener, times(0)).onAnimationPause(any());
verify(listener, times(1)).onAnimationResume(eq(animator));
}
}
| 2,402 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/parser/GradientColorParserTest.java | package com.airbnb.lottie.parser;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class GradientColorParserTest {
@Test public void testNoDistinctShort() {
assertMerged(new float[]{1}, new float[]{2}, new float[]{1, 2});
}
@Test public void testNoDistinct() {
assertMerged(new float[]{1, 2, 3}, new float[]{4, 5, 6}, new float[]{1, 2, 3, 4, 5, 6});
}
@Test public void testWithDistinct() {
assertMerged(new float[]{1, 2, 3, 5}, new float[]{4, 5, 6}, new float[]{1, 2, 3, 4, 5, 6});
}
@Test public void testWithDistinctInterleavingValues() {
assertMerged(new float[]{2, 4, 5, 6, 8, 10}, new float[]{1, 3, 4, 5, 7, 9}, new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
}
@Test public void testIdentical() {
assertMerged(new float[]{2, 3}, new float[]{2, 3}, new float[]{2, 3});
}
private void assertMerged(float[] arrayA, float[] arrayB, float[] merged) {
assertArrayEquals(merged, GradientColorParser.mergeUniqueElements(arrayA, arrayB), 0f);
}
} | 2,403 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/model/MarkerTest.java | package com.airbnb.lottie.model;
import org.junit.Test;
import static org.junit.Assert.*;
public class MarkerTest {
@Test
public void testMarkerWithCarriageReturn() {
Marker marker = new Marker("Foo\r", 0f, 0f);
assertTrue(marker.matchesName("foo"));
}
} | 2,404 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/model/LottieCompositionCacheTest.java | package com.airbnb.lottie.model;
import com.airbnb.lottie.BaseTest;
import com.airbnb.lottie.LottieComposition;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class LottieCompositionCacheTest extends BaseTest {
private LottieComposition composition;
private LottieCompositionCache cache;
@Before
public void setup() {
composition = Mockito.mock(LottieComposition.class);
cache = new LottieCompositionCache();
}
@Test
public void testEmpty() {
assertNull(cache.get("foo"));
}
@Test
public void testStrongAsset() {
cache.put("foo", composition);
assertEquals(composition, cache.get("foo"));
}
@Test
public void testWeakAsset() {
cache.put("foo", composition);
assertEquals(composition, cache.get("foo"));
}
}
| 2,405 |
0 | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/model | Create_ds/lottie-android/lottie/src/test/java/com/airbnb/lottie/model/animatable/AnimatableGradientColorValueTest.java | package com.airbnb.lottie.model.animatable;
import static org.junit.Assert.*;
import org.junit.Test;
public class AnimatableGradientColorValueTest {
@Test
public void testMergeTheSame() {
assertArrayEquals(new float[]{1, 2}, AnimatableGradientColorValue.mergePositions(new float[]{1, 2}, new float[]{1, 2}), 0f);
}
@Test
public void testMergeDifferent() {
assertArrayEquals(new float[]{1, 2, 3, 4}, AnimatableGradientColorValue.mergePositions(new float[]{1, 2}, new float[]{3, 4}), 0f);
}
@Test
public void testMergeOneOverlap() {
assertArrayEquals(new float[]{1, 2, 3}, AnimatableGradientColorValue.mergePositions(new float[]{1, 2}, new float[]{2, 3}), 0f);
}
} | 2,406 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieTask.java | package com.airbnb.lottie;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import com.airbnb.lottie.utils.Logger;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
/**
* Helper to run asynchronous tasks with a result.
* Results can be obtained with {@link #addListener(LottieListener)}.
* Failures can be obtained with {@link #addFailureListener(LottieListener)}.
* <p>
* A task will produce a single result or a single failure.
*/
@SuppressWarnings("UnusedReturnValue") public class LottieTask<T> {
/**
* Set this to change the executor that LottieTasks are run on. This will be the executor that composition parsing and url
* fetching happens on.
* <p>
* You may change this to run deserialization synchronously for testing.
*/
@SuppressWarnings("WeakerAccess")
public static Executor EXECUTOR = Executors.newCachedThreadPool();
/* Preserve add order. */
private final Set<LottieListener<T>> successListeners = new LinkedHashSet<>(1);
private final Set<LottieListener<Throwable>> failureListeners = new LinkedHashSet<>(1);
private final Handler handler = new Handler(Looper.getMainLooper());
@Nullable private volatile LottieResult<T> result = null;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public LottieTask(Callable<LottieResult<T>> runnable) {
this(runnable, false);
}
/**
* runNow is only used for testing.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY) LottieTask(Callable<LottieResult<T>> runnable, boolean runNow) {
if (runNow) {
try {
setResult(runnable.call());
} catch (Throwable e) {
setResult(new LottieResult<>(e));
}
} else {
EXECUTOR.execute(new LottieFutureTask(runnable));
}
}
private void setResult(@Nullable LottieResult<T> result) {
if (this.result != null) {
throw new IllegalStateException("A task may only be set once.");
}
this.result = result;
notifyListeners();
}
/**
* Add a task listener. If the task has completed, the listener will be called synchronously.
*
* @return the task for call chaining.
*/
public synchronized LottieTask<T> addListener(LottieListener<T> listener) {
LottieResult<T> result = this.result;
if (result != null && result.getValue() != null) {
listener.onResult(result.getValue());
}
successListeners.add(listener);
return this;
}
/**
* Remove a given task listener. The task will continue to execute so you can re-add
* a listener if necessary.
*
* @return the task for call chaining.
*/
public synchronized LottieTask<T> removeListener(LottieListener<T> listener) {
successListeners.remove(listener);
return this;
}
/**
* Add a task failure listener. This will only be called in the even that an exception
* occurs. If an exception has already occurred, the listener will be called immediately.
*
* @return the task for call chaining.
*/
public synchronized LottieTask<T> addFailureListener(LottieListener<Throwable> listener) {
LottieResult<T> result = this.result;
if (result != null && result.getException() != null) {
listener.onResult(result.getException());
}
failureListeners.add(listener);
return this;
}
/**
* Remove a given task failure listener. The task will continue to execute so you can re-add
* a listener if necessary.
*
* @return the task for call chaining.
*/
public synchronized LottieTask<T> removeFailureListener(LottieListener<Throwable> listener) {
failureListeners.remove(listener);
return this;
}
private void notifyListeners() {
// Listeners should be called on the main thread.
handler.post(() -> {
// Local reference in case it gets set on a background thread.
LottieResult<T> result = LottieTask.this.result;
if (result == null) {
return;
}
if (result.getValue() != null) {
notifySuccessListeners(result.getValue());
} else {
notifyFailureListeners(result.getException());
}
});
}
private synchronized void notifySuccessListeners(T value) {
// Allows listeners to remove themselves in onResult.
// Otherwise we risk ConcurrentModificationException.
List<LottieListener<T>> listenersCopy = new ArrayList<>(successListeners);
for (LottieListener<T> l : listenersCopy) {
l.onResult(value);
}
}
private synchronized void notifyFailureListeners(Throwable e) {
// Allows listeners to remove themselves in onResult.
// Otherwise we risk ConcurrentModificationException.
List<LottieListener<Throwable>> listenersCopy = new ArrayList<>(failureListeners);
if (listenersCopy.isEmpty()) {
Logger.warning("Lottie encountered an error but no failure listener was added:", e);
return;
}
for (LottieListener<Throwable> l : listenersCopy) {
l.onResult(e);
}
}
private class LottieFutureTask extends FutureTask<LottieResult<T>> {
LottieFutureTask(Callable<LottieResult<T>> callable) {
super(callable);
}
@Override
protected void done() {
if (isCancelled()) {
// We don't need to notify and listeners if the task is cancelled.
return;
}
try {
setResult(get());
} catch (InterruptedException | ExecutionException e) {
setResult(new LottieResult<>(e));
}
}
}
}
| 2,407 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/RenderMode.java | package com.airbnb.lottie;
import android.os.Build;
/**
* Controls how Lottie should render.
* Defaults to {@link RenderMode#AUTOMATIC}.
*
* @see LottieAnimationView#setRenderMode(RenderMode) for more information.
*/
public enum RenderMode {
AUTOMATIC,
HARDWARE,
SOFTWARE;
public boolean useSoftwareRendering(int sdkInt, boolean hasDashPattern, int numMasksAndMattes) {
switch (this) {
case HARDWARE:
return false;
case SOFTWARE:
return true;
case AUTOMATIC:
default:
if (hasDashPattern && sdkInt < Build.VERSION_CODES.P) {
// Hardware acceleration didn't support dash patterns until Pie.
return true;
} else if (numMasksAndMattes > 4) {
// This was chosen somewhat arbitrarily by trying a handful of animations.
// Animations with zero or few masks or mattes tend to perform much better with hardware
// acceleration. However, if there are many masks or mattes, it *may* perform worse.
// If you are hitting this case with AUTOMATIC set, please manually verify which one
// performs better.
return true;
}
// There have been many reported crashes from many device that are running Nougat or below.
// These devices also support far fewer hardware accelerated canvas operations.
// https://developer.android.com/guide/topics/graphics/hardware-accel#unsupported
return sdkInt <= Build.VERSION_CODES.N_MR1;
}
}
}
| 2,408 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/Lottie.java | package com.airbnb.lottie;
import androidx.annotation.NonNull;
/**
* Class for initializing the library with custom config
*/
public class Lottie {
private Lottie() {
}
/**
* Initialize Lottie with global configuration.
*
* @see LottieConfig.Builder
*/
public static void initialize(@NonNull final LottieConfig lottieConfig) {
L.setFetcher(lottieConfig.networkFetcher);
L.setCacheProvider(lottieConfig.cacheProvider);
L.setTraceEnabled(lottieConfig.enableSystraceMarkers);
L.setNetworkCacheEnabled(lottieConfig.enableNetworkCache);
L.setDisablePathInterpolatorCache(lottieConfig.disablePathInterpolatorCache);
L.setDefaultAsyncUpdates(lottieConfig.defaultAsyncUpdates);
}
}
| 2,409 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieOnCompositionLoadedListener.java | package com.airbnb.lottie;
public interface LottieOnCompositionLoadedListener {
void onCompositionLoaded(LottieComposition composition);
}
| 2,410 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieComposition.java | package com.airbnb.lottie;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.RestrictTo;
import androidx.annotation.WorkerThread;
import androidx.collection.LongSparseArray;
import androidx.collection.SparseArrayCompat;
import com.airbnb.lottie.model.Font;
import com.airbnb.lottie.model.FontCharacter;
import com.airbnb.lottie.model.Marker;
import com.airbnb.lottie.model.layer.Layer;
import com.airbnb.lottie.parser.moshi.JsonReader;
import com.airbnb.lottie.utils.Logger;
import com.airbnb.lottie.utils.MiscUtils;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* After Effects/Bodymovin composition model. This is the serialized model from which the
* animation will be created. It is designed to be stateless, cacheable, and shareable.
* <p>
* To create one, use {@link LottieCompositionFactory}.
* <p>
* It can be used with a {@link com.airbnb.lottie.LottieAnimationView} or
* {@link com.airbnb.lottie.LottieDrawable}.
*/
public class LottieComposition {
private final PerformanceTracker performanceTracker = new PerformanceTracker();
private final HashSet<String> warnings = new HashSet<>();
private Map<String, List<Layer>> precomps;
private Map<String, LottieImageAsset> images;
/**
* Map of font names to fonts
*/
private Map<String, Font> fonts;
private List<Marker> markers;
private SparseArrayCompat<FontCharacter> characters;
private LongSparseArray<Layer> layerMap;
private List<Layer> layers;
// This is stored as a set to avoid duplicates.
private Rect bounds;
private float startFrame;
private float endFrame;
private float frameRate;
/**
* Used to determine if an animation can be drawn with hardware acceleration.
*/
private boolean hasDashPattern;
/**
* Counts the number of mattes and masks. Before Android switched to SKIA
* for drawing in Oreo (API 28), using hardware acceleration with mattes and masks
* was only faster until you had ~4 masks after which it would actually become slower.
*/
private int maskAndMatteCount = 0;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void init(Rect bounds, float startFrame, float endFrame, float frameRate,
List<Layer> layers, LongSparseArray<Layer> layerMap, Map<String,
List<Layer>> precomps, Map<String, LottieImageAsset> images,
SparseArrayCompat<FontCharacter> characters, Map<String, Font> fonts,
List<Marker> markers) {
this.bounds = bounds;
this.startFrame = startFrame;
this.endFrame = endFrame;
this.frameRate = frameRate;
this.layers = layers;
this.layerMap = layerMap;
this.precomps = precomps;
this.images = images;
this.characters = characters;
this.fonts = fonts;
this.markers = markers;
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void addWarning(String warning) {
Logger.warning(warning);
warnings.add(warning);
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void setHasDashPattern(boolean hasDashPattern) {
this.hasDashPattern = hasDashPattern;
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void incrementMatteOrMaskCount(int amount) {
maskAndMatteCount += amount;
}
/**
* Used to determine if an animation can be drawn with hardware acceleration.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public boolean hasDashPattern() {
return hasDashPattern;
}
/**
* Used to determine if an animation can be drawn with hardware acceleration.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public int getMaskAndMatteCount() {
return maskAndMatteCount;
}
public ArrayList<String> getWarnings() {
return new ArrayList<>(Arrays.asList(warnings.toArray(new String[warnings.size()])));
}
@SuppressWarnings("WeakerAccess") public void setPerformanceTrackingEnabled(boolean enabled) {
performanceTracker.setEnabled(enabled);
}
public PerformanceTracker getPerformanceTracker() {
return performanceTracker;
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public Layer layerModelForId(long id) {
return layerMap.get(id);
}
@SuppressWarnings("WeakerAccess") public Rect getBounds() {
return bounds;
}
@SuppressWarnings("WeakerAccess") public float getDuration() {
return (long) (getDurationFrames() / frameRate * 1000);
}
public float getStartFrame() {
return startFrame;
}
public float getEndFrame() {
return endFrame;
}
public float getFrameForProgress(float progress) {
return MiscUtils.lerp(startFrame, endFrame, progress);
}
public float getProgressForFrame(float frame) {
float framesSinceStart = frame - startFrame;
float frameRange = endFrame - startFrame;
return framesSinceStart / frameRange;
}
public float getFrameRate() {
return frameRate;
}
public List<Layer> getLayers() {
return layers;
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
@Nullable
public List<Layer> getPrecomps(String id) {
return precomps.get(id);
}
public SparseArrayCompat<FontCharacter> getCharacters() {
return characters;
}
public Map<String, Font> getFonts() {
return fonts;
}
public List<Marker> getMarkers() {
return markers;
}
@Nullable
public Marker getMarker(String markerName) {
int size = markers.size();
for (int i = 0; i < size; i++) {
Marker marker = markers.get(i);
if (marker.matchesName(markerName)) {
return marker;
}
}
return null;
}
public boolean hasImages() {
return !images.isEmpty();
}
/**
* Returns a map of image asset id to {@link LottieImageAsset}. These assets contain image metadata exported
* from After Effects or other design tool. The resulting Bitmaps can be set directly on the image asset so
* they can be loaded once and reused across compositions.
*/
public Map<String, LottieImageAsset> getImages() {
return images;
}
public float getDurationFrames() {
return endFrame - startFrame;
}
@NonNull
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("LottieComposition:\n");
for (Layer layer : layers) {
sb.append(layer.toString("\t"));
}
return sb.toString();
}
/**
* This will be removed in the next version of Lottie. {@link LottieCompositionFactory} has improved
* API names, failure handlers, and will return in-progress tasks so you will never parse the same
* animation twice in parallel.
*
* @see LottieCompositionFactory
*/
@Deprecated
public static class Factory {
private Factory() {
}
/**
* @see LottieCompositionFactory#fromAsset(Context, String)
*/
@SuppressWarnings("deprecation")
@Deprecated
public static Cancellable fromAssetFileName(Context context, String fileName, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromAsset(context, fileName).addListener(listener);
return listener;
}
/**
* @see LottieCompositionFactory#fromRawRes(Context, int)
*/
@SuppressWarnings("deprecation")
@Deprecated
public static Cancellable fromRawFile(Context context, @RawRes int resId, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromRawRes(context, resId).addListener(listener);
return listener;
}
/**
* @see LottieCompositionFactory#fromJsonInputStream(InputStream, String)
*/
@SuppressWarnings("deprecation")
@Deprecated
public static Cancellable fromInputStream(InputStream stream, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromJsonInputStream(stream, null).addListener(listener);
return listener;
}
/**
* @see LottieCompositionFactory#fromJsonString(String, String)
*/
@SuppressWarnings("deprecation")
@Deprecated
public static Cancellable fromJsonString(String jsonString, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromJsonString(jsonString, null).addListener(listener);
return listener;
}
/**
* @see LottieCompositionFactory#fromJsonReader(JsonReader, String)
*/
@SuppressWarnings("deprecation")
@Deprecated
public static Cancellable fromJsonReader(JsonReader reader, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromJsonReader(reader, null).addListener(listener);
return listener;
}
/**
* @see LottieCompositionFactory#fromAssetSync(Context, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromFileSync(Context context, String fileName) {
return LottieCompositionFactory.fromAssetSync(context, fileName).getValue();
}
/**
* @see LottieCompositionFactory#fromJsonInputStreamSync(InputStream, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromInputStreamSync(InputStream stream) {
return LottieCompositionFactory.fromJsonInputStreamSync(stream, null).getValue();
}
/**
* This will now auto-close the input stream!
*
* @see LottieCompositionFactory#fromJsonInputStreamSync(InputStream, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromInputStreamSync(InputStream stream, boolean close) {
if (close) {
Logger.warning("Lottie now auto-closes input stream!");
}
return LottieCompositionFactory.fromJsonInputStreamSync(stream, null).getValue();
}
/**
* @see LottieCompositionFactory#fromJsonSync(JSONObject, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromJsonSync(@SuppressWarnings("unused") Resources res, JSONObject json) {
//noinspection deprecation
return LottieCompositionFactory.fromJsonSync(json, null).getValue();
}
/**
* @see LottieCompositionFactory#fromJsonStringSync(String, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromJsonSync(String json) {
return LottieCompositionFactory.fromJsonStringSync(json, null).getValue();
}
/**
* @see LottieCompositionFactory#fromJsonReaderSync(JsonReader, String)
*/
@Nullable
@WorkerThread
@Deprecated
public static LottieComposition fromJsonSync(JsonReader reader) {
return LottieCompositionFactory.fromJsonReaderSync(reader, null).getValue();
}
@SuppressWarnings("deprecation")
private static final class ListenerAdapter implements LottieListener<LottieComposition>, Cancellable {
private final OnCompositionLoadedListener listener;
private boolean cancelled = false;
private ListenerAdapter(OnCompositionLoadedListener listener) {
this.listener = listener;
}
@Override public void onResult(LottieComposition composition) {
if (cancelled) {
return;
}
listener.onCompositionLoaded(composition);
}
@Override public void cancel() {
cancelled = true;
}
}
}
} | 2,411 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieLogger.java | package com.airbnb.lottie;
/**
* Give ability to integrators to provide another logging mechanism.
*/
public interface LottieLogger {
void debug(String message);
void debug(String message, Throwable exception);
void warning(String message);
void warning(String message, Throwable exception);
void error(String message, Throwable exception);
}
| 2,412 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/ImageAssetDelegate.java | package com.airbnb.lottie;
import android.graphics.Bitmap;
import androidx.annotation.Nullable;
/**
* Delegate to handle the loading of bitmaps that are not packaged in the assets of your app.
*
* @see LottieDrawable#setImageAssetDelegate(ImageAssetDelegate)
*/
public interface ImageAssetDelegate {
@Nullable Bitmap fetchBitmap(LottieImageAsset asset);
}
| 2,413 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieTaskIdleListener.java | package com.airbnb.lottie;
/**
* Register this listener via {@link LottieCompositionFactory#registerLottieTaskIdleListener(LottieTaskIdleListener)}.
*
* Can be used to create an espresso idle resource. Refer to {@link LottieCompositionFactory#registerLottieTaskIdleListener(LottieTaskIdleListener)}
* for more information.
*/
public interface LottieTaskIdleListener {
void onIdleChanged(boolean idle);
}
| 2,414 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieListener.java | package com.airbnb.lottie;
/**
* Receive a result with either the value or exception for a {@link LottieTask}
*/
public interface LottieListener<T> {
void onResult(T result);
}
| 2,415 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java | package com.airbnb.lottie;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import androidx.annotation.AttrRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.FloatRange;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.RequiresApi;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.AppCompatImageView;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.utils.Logger;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieFrameInfo;
import com.airbnb.lottie.value.LottieValueCallback;
import com.airbnb.lottie.value.SimpleLottieValueCallback;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipInputStream;
/**
* This view will load, deserialize, and display an After Effects animation exported with
* bodymovin (https://github.com/bodymovin/bodymovin).
* <p>
* You may set the animation in one of two ways:
* 1) Attrs: {@link R.styleable#LottieAnimationView_lottie_fileName}
* 2) Programmatically:
* {@link #setAnimation(String)}
* {@link #setAnimation(int)}
* {@link #setAnimation(InputStream, String)}
* {@link #setAnimationFromJson(String, String)}
* {@link #setAnimationFromUrl(String)}
* {@link #setComposition(LottieComposition)}
* <p>
* You can set a default cache strategy with {@link R.attr#lottie_cacheComposition}.
* <p>
* You can manually set the progress of the animation with {@link #setProgress(float)} or
* {@link R.attr#lottie_progress}
*
* @see <a href="http://airbnb.io/lottie">Full Documentation</a>
*/
@SuppressWarnings({"WeakerAccess", "unused"}) public class LottieAnimationView extends AppCompatImageView {
private static final String TAG = LottieAnimationView.class.getSimpleName();
private static final LottieListener<Throwable> DEFAULT_FAILURE_LISTENER = throwable -> {
// By default, fail silently for network errors.
if (Utils.isNetworkException(throwable)) {
Logger.warning("Unable to load composition.", throwable);
return;
}
throw new IllegalStateException("Unable to parse composition", throwable);
};
private final LottieListener<LottieComposition> loadedListener = new WeakSuccessListener(this);
private static class WeakSuccessListener implements LottieListener<LottieComposition> {
private final WeakReference<LottieAnimationView> targetReference;
public WeakSuccessListener(LottieAnimationView target) {
this.targetReference = new WeakReference<>(target);
}
@Override public void onResult(LottieComposition result) {
LottieAnimationView targetView = targetReference.get();
if (targetView == null) {
return;
}
targetView.setComposition(result);
}
}
private final LottieListener<Throwable> wrappedFailureListener = new WeakFailureListener(this);
private static class WeakFailureListener implements LottieListener<Throwable> {
private final WeakReference<LottieAnimationView> targetReference;
public WeakFailureListener(LottieAnimationView target) {
this.targetReference = new WeakReference<>(target);
}
@Override public void onResult(Throwable result) {
LottieAnimationView targetView = targetReference.get();
if (targetView == null) {
return;
}
if (targetView.fallbackResource != 0) {
targetView.setImageResource(targetView.fallbackResource);
}
LottieListener<Throwable> l = targetView.failureListener == null ? DEFAULT_FAILURE_LISTENER : targetView.failureListener;
l.onResult(result);
}
}
@Nullable private LottieListener<Throwable> failureListener;
@DrawableRes private int fallbackResource = 0;
private final LottieDrawable lottieDrawable = new LottieDrawable();
private String animationName;
private @RawRes int animationResId;
/**
* When we set a new composition, we set LottieDrawable to null then back again so that ImageView re-checks its bounds.
* However, this causes the drawable to get unscheduled briefly. Normally, we would pause the animation but in this case, we don't want to.
*/
private boolean ignoreUnschedule = false;
private boolean autoPlay = false;
private boolean cacheComposition = true;
/**
* Keeps track of explicit user actions taken and prevents onRestoreInstanceState from overwriting already set values.
*/
private final Set<UserActionTaken> userActionsTaken = new HashSet<>();
private final Set<LottieOnCompositionLoadedListener> lottieOnCompositionLoadedListeners = new HashSet<>();
@Nullable private LottieTask<LottieComposition> compositionTask;
/**
* Can be null because it is created async
*/
@Nullable private LottieComposition composition;
public LottieAnimationView(Context context) {
super(context);
init(null, R.attr.lottieAnimationViewStyle);
}
public LottieAnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, R.attr.lottieAnimationViewStyle);
}
public LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr);
}
private void init(@Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.LottieAnimationView, defStyleAttr, 0);
cacheComposition = ta.getBoolean(R.styleable.LottieAnimationView_lottie_cacheComposition, true);
boolean hasRawRes = ta.hasValue(R.styleable.LottieAnimationView_lottie_rawRes);
boolean hasFileName = ta.hasValue(R.styleable.LottieAnimationView_lottie_fileName);
boolean hasUrl = ta.hasValue(R.styleable.LottieAnimationView_lottie_url);
if (hasRawRes && hasFileName) {
throw new IllegalArgumentException("lottie_rawRes and lottie_fileName cannot be used at " +
"the same time. Please use only one at once.");
} else if (hasRawRes) {
int rawResId = ta.getResourceId(R.styleable.LottieAnimationView_lottie_rawRes, 0);
if (rawResId != 0) {
setAnimation(rawResId);
}
} else if (hasFileName) {
String fileName = ta.getString(R.styleable.LottieAnimationView_lottie_fileName);
if (fileName != null) {
setAnimation(fileName);
}
} else if (hasUrl) {
String url = ta.getString(R.styleable.LottieAnimationView_lottie_url);
if (url != null) {
setAnimationFromUrl(url);
}
}
setFallbackResource(ta.getResourceId(R.styleable.LottieAnimationView_lottie_fallbackRes, 0));
if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_autoPlay, false)) {
autoPlay = true;
}
if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_loop, false)) {
lottieDrawable.setRepeatCount(LottieDrawable.INFINITE);
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatMode)) {
setRepeatMode(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatMode,
LottieDrawable.RESTART));
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatCount)) {
setRepeatCount(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatCount,
LottieDrawable.INFINITE));
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_speed)) {
setSpeed(ta.getFloat(R.styleable.LottieAnimationView_lottie_speed, 1f));
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_clipToCompositionBounds)) {
setClipToCompositionBounds(ta.getBoolean(R.styleable.LottieAnimationView_lottie_clipToCompositionBounds, true));
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_defaultFontFileExtension)) {
setDefaultFontFileExtension(ta.getString(R.styleable.LottieAnimationView_lottie_defaultFontFileExtension));
}
setImageAssetsFolder(ta.getString(R.styleable.LottieAnimationView_lottie_imageAssetsFolder));
boolean hasProgress = ta.hasValue(R.styleable.LottieAnimationView_lottie_progress);
setProgressInternal(ta.getFloat(R.styleable.LottieAnimationView_lottie_progress, 0f), hasProgress);
enableMergePathsForKitKatAndAbove(ta.getBoolean(
R.styleable.LottieAnimationView_lottie_enableMergePathsForKitKatAndAbove, false));
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_colorFilter)) {
int colorRes = ta.getResourceId(R.styleable.LottieAnimationView_lottie_colorFilter, -1);
ColorStateList csl = AppCompatResources.getColorStateList(getContext(), colorRes);
SimpleColorFilter filter = new SimpleColorFilter(csl.getDefaultColor());
KeyPath keyPath = new KeyPath("**");
LottieValueCallback<ColorFilter> callback = new LottieValueCallback<>(filter);
addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback);
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_renderMode)) {
int renderModeOrdinal = ta.getInt(R.styleable.LottieAnimationView_lottie_renderMode, RenderMode.AUTOMATIC.ordinal());
if (renderModeOrdinal >= RenderMode.values().length) {
renderModeOrdinal = RenderMode.AUTOMATIC.ordinal();
}
setRenderMode(RenderMode.values()[renderModeOrdinal]);
}
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_asyncUpdates)) {
int asyncUpdatesOrdinal = ta.getInt(R.styleable.LottieAnimationView_lottie_asyncUpdates, AsyncUpdates.AUTOMATIC.ordinal());
if (asyncUpdatesOrdinal >= RenderMode.values().length) {
asyncUpdatesOrdinal = AsyncUpdates.AUTOMATIC.ordinal();
}
setAsyncUpdates(AsyncUpdates.values()[asyncUpdatesOrdinal]);
}
setIgnoreDisabledSystemAnimations(
ta.getBoolean(
R.styleable.LottieAnimationView_lottie_ignoreDisabledSystemAnimations,
false
)
);
if (ta.hasValue(R.styleable.LottieAnimationView_lottie_useCompositionFrameRate)) {
setUseCompositionFrameRate(ta.getBoolean(R.styleable.LottieAnimationView_lottie_useCompositionFrameRate, false));
}
ta.recycle();
lottieDrawable.setSystemAnimationsAreEnabled(Utils.getAnimationScale(getContext()) != 0f);
}
@Override public void setImageResource(int resId) {
cancelLoaderTask();
super.setImageResource(resId);
}
@Override public void setImageDrawable(Drawable drawable) {
cancelLoaderTask();
super.setImageDrawable(drawable);
}
@Override public void setImageBitmap(Bitmap bm) {
cancelLoaderTask();
super.setImageBitmap(bm);
}
@Override public void unscheduleDrawable(Drawable who) {
if (!ignoreUnschedule && who == lottieDrawable && lottieDrawable.isAnimating()) {
pauseAnimation();
} else if (!ignoreUnschedule && who instanceof LottieDrawable && ((LottieDrawable) who).isAnimating()) {
((LottieDrawable) who).pauseAnimation();
}
super.unscheduleDrawable(who);
}
@Override public void invalidate() {
super.invalidate();
Drawable d = getDrawable();
if (d instanceof LottieDrawable && ((LottieDrawable) d).getRenderMode() == RenderMode.SOFTWARE) {
// This normally isn't needed. However, when using software rendering, Lottie caches rendered bitmaps
// and updates it when the animation changes internally.
// If you have dynamic properties with a value callback and want to update the value of the dynamic property, you need a way
// to tell Lottie that the bitmap is dirty and it needs to be re-rendered. Normal drawables always re-draw the actual shapes
// so this isn't an issue but for this path, we have to take the extra step of setting the dirty flag.
lottieDrawable.invalidateSelf();
}
}
@Override public void invalidateDrawable(@NonNull Drawable dr) {
if (getDrawable() == lottieDrawable) {
// We always want to invalidate the root drawable so it redraws the whole drawable.
// Eventually it would be great to be able to invalidate just the changed region.
super.invalidateDrawable(lottieDrawable);
} else {
// Otherwise work as regular ImageView
super.invalidateDrawable(dr);
}
}
@Override protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.animationName = animationName;
ss.animationResId = animationResId;
ss.progress = lottieDrawable.getProgress();
ss.isAnimating = lottieDrawable.isAnimatingOrWillAnimateOnVisible();
ss.imageAssetsFolder = lottieDrawable.getImageAssetsFolder();
ss.repeatMode = lottieDrawable.getRepeatMode();
ss.repeatCount = lottieDrawable.getRepeatCount();
return ss;
}
@Override protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
animationName = ss.animationName;
if (!userActionsTaken.contains(UserActionTaken.SET_ANIMATION) && !TextUtils.isEmpty(animationName)) {
setAnimation(animationName);
}
animationResId = ss.animationResId;
if (!userActionsTaken.contains(UserActionTaken.SET_ANIMATION) && animationResId != 0) {
setAnimation(animationResId);
}
if (!userActionsTaken.contains(UserActionTaken.SET_PROGRESS)) {
setProgressInternal(ss.progress, false);
}
if (!userActionsTaken.contains(UserActionTaken.PLAY_OPTION) && ss.isAnimating) {
playAnimation();
}
if (!userActionsTaken.contains(UserActionTaken.SET_IMAGE_ASSETS)) {
setImageAssetsFolder(ss.imageAssetsFolder);
}
if (!userActionsTaken.contains(UserActionTaken.SET_REPEAT_MODE)) {
setRepeatMode(ss.repeatMode);
}
if (!userActionsTaken.contains(UserActionTaken.SET_REPEAT_COUNT)) {
setRepeatCount(ss.repeatCount);
}
}
@Override protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!isInEditMode() && autoPlay) {
lottieDrawable.playAnimation();
}
}
/**
* Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled.
* <p>
* Defaults to false.
*
* @param ignore if true animations will run even when they are disabled in the system settings.
*/
public void setIgnoreDisabledSystemAnimations(boolean ignore) {
lottieDrawable.setIgnoreDisabledSystemAnimations(ignore);
}
/**
* Lottie files can specify a target frame rate. By default, Lottie ignores it and re-renders
* on every frame. If that behavior is undesirable, you can set this to true to use the composition
* frame rate instead.
* <p>
* Note: composition frame rates are usually lower than display frame rates
* so this will likely make your animation feel janky. However, it may be desirable
* for specific situations such as pixel art that are intended to have low frame rates.
*/
public void setUseCompositionFrameRate(boolean useCompositionFrameRate) {
lottieDrawable.setUseCompositionFrameRate(useCompositionFrameRate);
}
/**
* Enable this to get merge path support for devices running KitKat (19) and above.
* <p>
* Merge paths currently don't work if the the operand shape is entirely contained within the
* first shape. If you need to cut out one shape from another shape, use an even-odd fill type
* instead of using merge paths.
*/
public void enableMergePathsForKitKatAndAbove(boolean enable) {
lottieDrawable.enableMergePathsForKitKatAndAbove(enable);
}
/**
* Returns whether merge paths are enabled for KitKat and above.
*/
public boolean isMergePathsEnabledForKitKatAndAbove() {
return lottieDrawable.isMergePathsEnabledForKitKatAndAbove();
}
/**
* Sets whether or not Lottie should clip to the original animation composition bounds.
* <p>
* When set to true, the parent view may need to disable clipChildren so Lottie can render outside of the LottieAnimationView bounds.
* <p>
* Defaults to true.
*/
public void setClipToCompositionBounds(boolean clipToCompositionBounds) {
lottieDrawable.setClipToCompositionBounds(clipToCompositionBounds);
}
/**
* Gets whether or not Lottie should clip to the original animation composition bounds.
* <p>
* Defaults to true.
*/
public boolean getClipToCompositionBounds() {
return lottieDrawable.getClipToCompositionBounds();
}
/**
* If set to true, all future compositions that are set will be cached so that they don't need to be parsed
* next time they are loaded. This won't apply to compositions that have already been loaded.
* <p>
* Defaults to true.
* <p>
* {@link R.attr#lottie_cacheComposition}
*/
public void setCacheComposition(boolean cacheComposition) {
this.cacheComposition = cacheComposition;
}
/**
* Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will
* be proportional to the surface area of all of the masks/mattes combined.
* <p>
* DO NOT leave this enabled in production.
*/
public void setOutlineMasksAndMattes(boolean outline) {
lottieDrawable.setOutlineMasksAndMattes(outline);
}
/**
* Sets the animation from a file in the raw directory.
* This will load and deserialize the file asynchronously.
*/
public void setAnimation(@RawRes final int rawRes) {
this.animationResId = rawRes;
animationName = null;
setCompositionTask(fromRawRes(rawRes));
}
private LottieTask<LottieComposition> fromRawRes(@RawRes final int rawRes) {
if (isInEditMode()) {
return new LottieTask<>(() -> cacheComposition
? LottieCompositionFactory.fromRawResSync(getContext(), rawRes) : LottieCompositionFactory.fromRawResSync(getContext(), rawRes, null), true);
} else {
return cacheComposition ?
LottieCompositionFactory.fromRawRes(getContext(), rawRes) : LottieCompositionFactory.fromRawRes(getContext(), rawRes, null);
}
}
public void setAnimation(final String assetName) {
this.animationName = assetName;
animationResId = 0;
setCompositionTask(fromAssets(assetName));
}
private LottieTask<LottieComposition> fromAssets(final String assetName) {
if (isInEditMode()) {
return new LottieTask<>(() -> cacheComposition ?
LottieCompositionFactory.fromAssetSync(getContext(), assetName) : LottieCompositionFactory.fromAssetSync(getContext(), assetName, null), true);
} else {
return cacheComposition ?
LottieCompositionFactory.fromAsset(getContext(), assetName) : LottieCompositionFactory.fromAsset(getContext(), assetName, null);
}
}
/**
* @see #setAnimationFromJson(String, String)
*/
@Deprecated
public void setAnimationFromJson(String jsonString) {
setAnimationFromJson(jsonString, null);
}
/**
* Sets the animation from json string. This is the ideal API to use when loading an animation
* over the network because you can use the raw response body here and a conversion to a
* JSONObject never has to be done.
*/
public void setAnimationFromJson(String jsonString, @Nullable String cacheKey) {
setAnimation(new ByteArrayInputStream(jsonString.getBytes()), cacheKey);
}
/**
* Sets the animation from an arbitrary InputStream.
* This will load and deserialize the file asynchronously.
* <p>
* If this is a Zip file, wrap your InputStream with a ZipInputStream to use the overload
* designed for zip files.
* <p>
* This is particularly useful for animations loaded from the network. You can fetch the
* bodymovin json from the network and pass it directly here.
* <p>
* Auto-closes the stream.
*/
public void setAnimation(InputStream stream, @Nullable String cacheKey) {
setCompositionTask(LottieCompositionFactory.fromJsonInputStream(stream, cacheKey));
}
/**
* Sets the animation from a ZipInputStream.
* This will load and deserialize the file asynchronously.
* <p>
* This is particularly useful for animations loaded from the network. You can fetch the
* bodymovin json from the network and pass it directly here.
* <p>
* Auto-closes the stream.
*/
public void setAnimation(ZipInputStream stream, @Nullable String cacheKey) {
setCompositionTask(LottieCompositionFactory.fromZipStream(stream, cacheKey));
}
/**
* Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and
* lottie
* will unzip and link the images automatically.
* <p>
* Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file
* to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that
* can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted.
* <p>
* You can replace the default network stack or cache handling with a global {@link LottieConfig}
*
* @see LottieConfig.Builder
* @see Lottie#initialize(LottieConfig)
*/
public void setAnimationFromUrl(String url) {
LottieTask<LottieComposition> task = cacheComposition ?
LottieCompositionFactory.fromUrl(getContext(), url) : LottieCompositionFactory.fromUrl(getContext(), url, null);
setCompositionTask(task);
}
/**
* Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and
* lottie
* will unzip and link the images automatically.
* <p>
* Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file
* to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that
* can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted.
* <p>
* You can replace the default network stack or cache handling with a global {@link LottieConfig}
*
* @see LottieConfig.Builder
* @see Lottie#initialize(LottieConfig)
*/
public void setAnimationFromUrl(String url, @Nullable String cacheKey) {
LottieTask<LottieComposition> task = LottieCompositionFactory.fromUrl(getContext(), url, cacheKey);
setCompositionTask(task);
}
/**
* Set a default failure listener that will be called if any of the setAnimation APIs fail for any reason.
* This can be used to replace the default behavior.
* <p>
* The default behavior will log any network errors and rethrow all other exceptions.
* <p>
* If you are loading an animation from the network, errors may occur if your user has no internet.
* You can use this listener to retry the download or you can have it default to an error drawable
* with {@link #setFallbackResource(int)}.
* <p>
* Unless you are using {@link #setAnimationFromUrl(String)}, errors are unexpected.
* <p>
* Set the listener to null to revert to the default behavior.
*/
public void setFailureListener(@Nullable LottieListener<Throwable> failureListener) {
this.failureListener = failureListener;
}
/**
* Set a drawable that will be rendered if the LottieComposition fails to load for any reason.
* Unless you are using {@link #setAnimationFromUrl(String)}, this is an unexpected error and
* you should handle it with {@link #setFailureListener(LottieListener)}.
* <p>
* If this is a network animation, you may use this to show an error to the user or
* you can use a failure listener to retry the download.
*/
public void setFallbackResource(@DrawableRes int fallbackResource) {
this.fallbackResource = fallbackResource;
}
private void setCompositionTask(LottieTask<LottieComposition> compositionTask) {
userActionsTaken.add(UserActionTaken.SET_ANIMATION);
clearComposition();
cancelLoaderTask();
this.compositionTask = compositionTask
.addListener(loadedListener)
.addFailureListener(wrappedFailureListener);
}
private void cancelLoaderTask() {
if (compositionTask != null) {
compositionTask.removeListener(loadedListener);
compositionTask.removeFailureListener(wrappedFailureListener);
}
}
/**
* Sets a composition.
* You can set a default cache strategy if this view was inflated with xml by
* using {@link R.attr#lottie_cacheComposition}.
*/
public void setComposition(@NonNull LottieComposition composition) {
if (L.DBG) {
Log.v(TAG, "Set Composition \n" + composition);
}
lottieDrawable.setCallback(this);
this.composition = composition;
ignoreUnschedule = true;
boolean isNewComposition = lottieDrawable.setComposition(composition);
ignoreUnschedule = false;
if (getDrawable() == lottieDrawable && !isNewComposition) {
// We can avoid re-setting the drawable, and invalidating the view, since the composition
// hasn't changed.
return;
} else if (!isNewComposition) {
// The current drawable isn't lottieDrawable but the drawable already has the right composition.
setLottieDrawable();
}
// This is needed to makes sure that the animation is properly played/paused for the current visibility state.
// It is possible that the drawable had a lazy composition task to play the animation but this view subsequently
// became invisible. Comment this out and run the espresso tests to see a failing test.
onVisibilityChanged(this, getVisibility());
requestLayout();
for (LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener : lottieOnCompositionLoadedListeners) {
lottieOnCompositionLoadedListener.onCompositionLoaded(composition);
}
}
@Nullable public LottieComposition getComposition() {
return composition;
}
/**
* Returns whether or not any layers in this composition has masks.
*/
public boolean hasMasks() {
return lottieDrawable.hasMasks();
}
/**
* Returns whether or not any layers in this composition has a matte layer.
*/
public boolean hasMatte() {
return lottieDrawable.hasMatte();
}
/**
* Plays the animation from the beginning. If speed is {@literal <} 0, it will start at the end
* and play towards the beginning
*/
@MainThread
public void playAnimation() {
userActionsTaken.add(UserActionTaken.PLAY_OPTION);
lottieDrawable.playAnimation();
}
/**
* Continues playing the animation from its current position. If speed {@literal <} 0, it will play backwards
* from the current position.
*/
@MainThread
public void resumeAnimation() {
userActionsTaken.add(UserActionTaken.PLAY_OPTION);
lottieDrawable.resumeAnimation();
}
/**
* Sets the minimum frame that the animation will start from when playing or looping.
*/
public void setMinFrame(int startFrame) {
lottieDrawable.setMinFrame(startFrame);
}
/**
* Returns the minimum frame set by {@link #setMinFrame(int)} or {@link #setMinProgress(float)}
*/
public float getMinFrame() {
return lottieDrawable.getMinFrame();
}
/**
* Sets the minimum progress that the animation will start from when playing or looping.
*/
public void setMinProgress(float startProgress) {
lottieDrawable.setMinProgress(startProgress);
}
/**
* Sets the maximum frame that the animation will end at when playing or looping.
* <p>
* The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the same
* thing as composition.endFrame.
*/
public void setMaxFrame(int endFrame) {
lottieDrawable.setMaxFrame(endFrame);
}
/**
* Returns the maximum frame set by {@link #setMaxFrame(int)} or {@link #setMaxProgress(float)}
*/
public float getMaxFrame() {
return lottieDrawable.getMaxFrame();
}
/**
* Sets the maximum progress that the animation will end at when playing or looping.
*/
public void setMaxProgress(@FloatRange(from = 0f, to = 1f) float endProgress) {
lottieDrawable.setMaxProgress(endProgress);
}
/**
* Sets the minimum frame to the start time of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMinFrame(String markerName) {
lottieDrawable.setMinFrame(markerName);
}
/**
* Sets the maximum frame to the start time + duration of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMaxFrame(String markerName) {
lottieDrawable.setMaxFrame(markerName);
}
/**
* Sets the minimum and maximum frame to the start time and start time + duration
* of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMinAndMaxFrame(String markerName) {
lottieDrawable.setMinAndMaxFrame(markerName);
}
/**
* Sets the minimum and maximum frame to the start marker start and the maximum frame to the end marker start.
* playEndMarkerStartFrame determines whether or not to play the frame that the end marker is on. If the end marker
* represents the end of the section that you want, it should be true. If the marker represents the beginning of the
* next section, it should be false.
*
* @throws IllegalArgumentException if either marker is not found.
*/
public void setMinAndMaxFrame(final String startMarkerName, final String endMarkerName, final boolean playEndMarkerStartFrame) {
lottieDrawable.setMinAndMaxFrame(startMarkerName, endMarkerName, playEndMarkerStartFrame);
}
/**
* @see #setMinFrame(int)
* @see #setMaxFrame(int)
*/
public void setMinAndMaxFrame(int minFrame, int maxFrame) {
lottieDrawable.setMinAndMaxFrame(minFrame, maxFrame);
}
/**
* @see #setMinProgress(float)
* @see #setMaxProgress(float)
*/
public void setMinAndMaxProgress(
@FloatRange(from = 0f, to = 1f) float minProgress,
@FloatRange(from = 0f, to = 1f) float maxProgress) {
lottieDrawable.setMinAndMaxProgress(minProgress, maxProgress);
}
/**
* Reverses the current animation speed. This does NOT play the animation.
*
* @see #setSpeed(float)
* @see #playAnimation()
* @see #resumeAnimation()
*/
public void reverseAnimationSpeed() {
lottieDrawable.reverseAnimationSpeed();
}
/**
* Sets the playback speed. If speed {@literal <} 0, the animation will play backwards.
*/
public void setSpeed(float speed) {
lottieDrawable.setSpeed(speed);
}
/**
* Returns the current playback speed. This will be {@literal <} 0 if the animation is playing backwards.
*/
public float getSpeed() {
return lottieDrawable.getSpeed();
}
public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
lottieDrawable.addAnimatorUpdateListener(updateListener);
}
public void removeUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
lottieDrawable.removeAnimatorUpdateListener(updateListener);
}
public void removeAllUpdateListeners() {
lottieDrawable.removeAllUpdateListeners();
}
public void addAnimatorListener(Animator.AnimatorListener listener) {
lottieDrawable.addAnimatorListener(listener);
}
public void removeAnimatorListener(Animator.AnimatorListener listener) {
lottieDrawable.removeAnimatorListener(listener);
}
public void removeAllAnimatorListeners() {
lottieDrawable.removeAllAnimatorListeners();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void addAnimatorPauseListener(Animator.AnimatorPauseListener listener) {
lottieDrawable.addAnimatorPauseListener(listener);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener) {
lottieDrawable.removeAnimatorPauseListener(listener);
}
/**
* @see #setRepeatCount(int)
*/
@Deprecated
public void loop(boolean loop) {
lottieDrawable.setRepeatCount(loop ? ValueAnimator.INFINITE : 0);
}
/**
* Defines what this animation should do when it reaches the end. This
* setting is applied only when the repeat count is either greater than
* 0 or {@link LottieDrawable#INFINITE}. Defaults to {@link LottieDrawable#RESTART}.
*
* @param mode {@link LottieDrawable#RESTART} or {@link LottieDrawable#REVERSE}
*/
public void setRepeatMode(@LottieDrawable.RepeatMode int mode) {
userActionsTaken.add(UserActionTaken.SET_REPEAT_MODE);
lottieDrawable.setRepeatMode(mode);
}
/**
* Defines what this animation should do when it reaches the end.
*
* @return either one of {@link LottieDrawable#REVERSE} or {@link LottieDrawable#RESTART}
*/
@LottieDrawable.RepeatMode
public int getRepeatMode() {
return lottieDrawable.getRepeatMode();
}
/**
* Sets how many times the animation should be repeated. If the repeat
* count is 0, the animation is never repeated. If the repeat count is
* greater than 0 or {@link LottieDrawable#INFINITE}, the repeat mode will be taken
* into account. The repeat count is 0 by default.
*
* @param count the number of times the animation should be repeated
*/
public void setRepeatCount(int count) {
userActionsTaken.add(UserActionTaken.SET_REPEAT_COUNT);
lottieDrawable.setRepeatCount(count);
}
/**
* Defines how many times the animation should repeat. The default value
* is 0.
*
* @return the number of times the animation should repeat, or {@link LottieDrawable#INFINITE}
*/
public int getRepeatCount() {
return lottieDrawable.getRepeatCount();
}
public boolean isAnimating() {
return lottieDrawable.isAnimating();
}
/**
* If you use image assets, you must explicitly specify the folder in assets/ in which they are
* located because bodymovin uses the name filenames across all compositions (img_#).
* Do NOT rename the images themselves.
* <p>
* If your images are located in src/main/assets/airbnb_loader/ then call
* `setImageAssetsFolder("airbnb_loader/");`.
* <p>
* Be wary if you are using many images, however. Lottie is designed to work with vector shapes
* from After Effects. If your images look like they could be represented with vector shapes,
* see if it is possible to convert them to shape layers and re-export your animation. Check
* the documentation at http://airbnb.io/lottie for more information about importing shapes from
* Sketch or Illustrator to avoid this.
*/
public void setImageAssetsFolder(String imageAssetsFolder) {
lottieDrawable.setImagesAssetsFolder(imageAssetsFolder);
}
@Nullable
public String getImageAssetsFolder() {
return lottieDrawable.getImageAssetsFolder();
}
/**
* When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.
* When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
* <p>
* Defaults to false.
*/
public void setMaintainOriginalImageBounds(boolean maintainOriginalImageBounds) {
lottieDrawable.setMaintainOriginalImageBounds(maintainOriginalImageBounds);
}
/**
* When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.
* When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
* <p>
* Defaults to false.
*/
public boolean getMaintainOriginalImageBounds() {
return lottieDrawable.getMaintainOriginalImageBounds();
}
/**
* Allows you to modify or clear a bitmap that was loaded for an image either automatically
* through {@link #setImageAssetsFolder(String)} or with an {@link ImageAssetDelegate}.
*
* @return the previous Bitmap or null.
*/
@Nullable
public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) {
return lottieDrawable.updateBitmap(id, bitmap);
}
/**
* Use this if you can't bundle images with your app. This may be useful if you download the
* animations from the network or have the images saved to an SD Card. In that case, Lottie
* will defer the loading of the bitmap to this delegate.
* <p>
* Be wary if you are using many images, however. Lottie is designed to work with vector shapes
* from After Effects. If your images look like they could be represented with vector shapes,
* see if it is possible to convert them to shape layers and re-export your animation. Check
* the documentation at http://airbnb.io/lottie for more information about importing shapes from
* Sketch or Illustrator to avoid this.
*/
public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) {
lottieDrawable.setImageAssetDelegate(assetDelegate);
}
/**
* By default, Lottie will look in src/assets/fonts/FONT_NAME.ttf
* where FONT_NAME is the fFamily specified in your Lottie file.
* If your fonts have a different extension, you can override the
* default here.
* <p>
* Alternatively, you can use {@link #setFontAssetDelegate(FontAssetDelegate)}
* for more control.
*
* @see #setFontAssetDelegate(FontAssetDelegate)
*/
public void setDefaultFontFileExtension(String extension) {
lottieDrawable.setDefaultFontFileExtension(extension);
}
/**
* Use this to manually set fonts.
*/
public void setFontAssetDelegate(FontAssetDelegate assetDelegate) {
lottieDrawable.setFontAssetDelegate(assetDelegate);
}
/**
* Set a map from font name keys to Typefaces.
* The keys can be in the form:
* * fontFamily
* * fontFamily-fontStyle
* * fontName
* All 3 are defined as fName, fFamily, and fStyle in the Lottie file.
* <p>
* If you change a value in fontMap, create a new map or call
* {@link #invalidate()}. Setting the same map again will noop.
*/
public void setFontMap(@Nullable Map<String, Typeface> fontMap) {
lottieDrawable.setFontMap(fontMap);
}
/**
* Set this to replace animation text with custom text at runtime
*/
public void setTextDelegate(TextDelegate textDelegate) {
lottieDrawable.setTextDelegate(textDelegate);
}
/**
* Takes a {@link KeyPath}, potentially with wildcards or globstars and resolve it to a list of
* zero or more actual {@link KeyPath Keypaths} that exist in the current animation.
* <p>
* If you want to set value callbacks for any of these values, it is recommended to use the
* returned {@link KeyPath} objects because they will be internally resolved to their content
* and won't trigger a tree walk of the animation contents when applied.
*/
public List<KeyPath> resolveKeyPath(KeyPath keyPath) {
return lottieDrawable.resolveKeyPath(keyPath);
}
/**
* Clear the value callback for all nodes that match the given {@link KeyPath} and property.
*/
public <T> void clearValueCallback(KeyPath keyPath, T property) {
lottieDrawable.addValueCallback(keyPath, property, (LottieValueCallback<T>) null);
}
/**
* Add a property callback for the specified {@link KeyPath}. This {@link KeyPath} can resolve
* to multiple contents. In that case, the callback's value will apply to all of them.
* <p>
* Internally, this will check if the {@link KeyPath} has already been resolved with
* {@link #resolveKeyPath(KeyPath)} and will resolve it if it hasn't.
*/
public <T> void addValueCallback(KeyPath keyPath, T property, LottieValueCallback<T> callback) {
lottieDrawable.addValueCallback(keyPath, property, callback);
}
/**
* Overload of {@link #addValueCallback(KeyPath, Object, LottieValueCallback)} that takes an interface. This allows you to use a single abstract
* method code block in Kotlin such as:
* animationView.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor }
*/
public <T> void addValueCallback(KeyPath keyPath, T property,
final SimpleLottieValueCallback<T> callback) {
lottieDrawable.addValueCallback(keyPath, property, new LottieValueCallback<T>() {
@Override public T getValue(LottieFrameInfo<T> frameInfo) {
return callback.getValue(frameInfo);
}
});
}
@MainThread
public void cancelAnimation() {
userActionsTaken.add(UserActionTaken.PLAY_OPTION);
lottieDrawable.cancelAnimation();
}
@MainThread
public void pauseAnimation() {
autoPlay = false;
lottieDrawable.pauseAnimation();
}
/**
* Sets the progress to the specified frame.
* If the composition isn't set yet, the progress will be set to the frame when
* it is.
*/
public void setFrame(int frame) {
lottieDrawable.setFrame(frame);
}
/**
* Get the currently rendered frame.
*/
public int getFrame() {
return lottieDrawable.getFrame();
}
public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
setProgressInternal(progress, true);
}
private void setProgressInternal(
@FloatRange(from = 0f, to = 1f) float progress,
boolean fromUser) {
if (fromUser) {
userActionsTaken.add(UserActionTaken.SET_PROGRESS);
}
lottieDrawable.setProgress(progress);
}
@FloatRange(from = 0.0f, to = 1.0f) public float getProgress() {
return lottieDrawable.getProgress();
}
public long getDuration() {
return composition != null ? (long) composition.getDuration() : 0;
}
public void setPerformanceTrackingEnabled(boolean enabled) {
lottieDrawable.setPerformanceTrackingEnabled(enabled);
}
@Nullable
public PerformanceTracker getPerformanceTracker() {
return lottieDrawable.getPerformanceTracker();
}
private void clearComposition() {
composition = null;
lottieDrawable.clearComposition();
}
/**
* If you are experiencing a device specific crash that happens during drawing, you can set this to true
* for those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie to
* render an empty frame rather than crash your app.
* <p>
* Ideally, you will never need this and the vast majority of apps and animations won't. However, you may use
* this for very specific cases if absolutely necessary.
* <p>
* There is no XML attr for this because it should be set programmatically and only for specific devices that
* are known to be problematic.
*/
public void setSafeMode(boolean safeMode) {
lottieDrawable.setSafeMode(safeMode);
}
/**
* Call this to set whether or not to render with hardware or software acceleration.
* Lottie defaults to Automatic which will use hardware acceleration unless:
* 1) There are dash paths and the device is pre-Pie.
* 2) There are more than 4 masks and mattes.
* Hardware acceleration is generally faster for those devices unless
* there are many large mattes and masks in which case there is a lot
* of GPU uploadTexture thrashing which makes it much slower.
* <p>
* In most cases, hardware rendering will be faster, even if you have mattes and masks.
* However, if you have multiple mattes and masks (especially large ones), you
* should test both render modes. You should also test on pre-Pie and Pie+ devices
* because the underlying rendering engine changed significantly.
*
* @see <a href="https://developer.android.com/guide/topics/graphics/hardware-accel#unsupported">Android Hardware Acceleration</a>
*/
public void setRenderMode(RenderMode renderMode) {
lottieDrawable.setRenderMode(renderMode);
}
/**
* Returns the actual render mode being used. It will always be {@link RenderMode#HARDWARE} or {@link RenderMode#SOFTWARE}.
* When the render mode is set to AUTOMATIC, the value will be derived from {@link RenderMode#useSoftwareRendering(int, boolean, int)}.
*/
public RenderMode getRenderMode() {
return lottieDrawable.getRenderMode();
}
/**
* Returns the current value of {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info.
*/
public AsyncUpdates getAsyncUpdates() {
return lottieDrawable.getAsyncUpdates();
}
/**
* Similar to {@link #getAsyncUpdates()} except it returns the actual
* boolean value for whether async updates are enabled or not.
*/
public boolean getAsyncUpdatesEnabled() {
return lottieDrawable.getAsyncUpdatesEnabled();
}
/**
* **Note: this API is experimental and may changed.**
* <p/>
* Sets the current value for {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info.
*/
public void setAsyncUpdates(AsyncUpdates asyncUpdates) {
lottieDrawable.setAsyncUpdates(asyncUpdates);
}
/**
* Sets whether to apply opacity to the each layer instead of shape.
* <p>
* Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurate
* at the expense of performance.
* <p>
* The default value is false.
* <p>
* Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled.
*
* @see #setRenderMode(RenderMode)
*/
public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled) {
lottieDrawable.setApplyingOpacityToLayersEnabled(isApplyingOpacityToLayersEnabled);
}
/**
* This API no longer has any effect.
*/
@Deprecated
public void disableExtraScaleModeInFitXY() {
//noinspection deprecation
lottieDrawable.disableExtraScaleModeInFitXY();
}
public boolean addLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) {
LottieComposition composition = this.composition;
if (composition != null) {
lottieOnCompositionLoadedListener.onCompositionLoaded(composition);
}
return lottieOnCompositionLoadedListeners.add(lottieOnCompositionLoadedListener);
}
public boolean removeLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) {
return lottieOnCompositionLoadedListeners.remove(lottieOnCompositionLoadedListener);
}
public void removeAllLottieOnCompositionLoadedListener() {
lottieOnCompositionLoadedListeners.clear();
}
private void setLottieDrawable() {
boolean wasAnimating = isAnimating();
// Set the drawable to null first because the underlying LottieDrawable's intrinsic bounds can change
// if the composition changes.
setImageDrawable(null);
setImageDrawable(lottieDrawable);
if (wasAnimating) {
// This is necessary because lottieDrawable will get unscheduled and canceled when the drawable is set to null.
lottieDrawable.resumeAnimation();
}
}
private static class SavedState extends BaseSavedState {
String animationName;
int animationResId;
float progress;
boolean isAnimating;
String imageAssetsFolder;
int repeatMode;
int repeatCount;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
animationName = in.readString();
progress = in.readFloat();
isAnimating = in.readInt() == 1;
imageAssetsFolder = in.readString();
repeatMode = in.readInt();
repeatCount = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeString(animationName);
out.writeFloat(progress);
out.writeInt(isAnimating ? 1 : 0);
out.writeString(imageAssetsFolder);
out.writeInt(repeatMode);
out.writeInt(repeatCount);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
private enum UserActionTaken {
SET_ANIMATION,
SET_PROGRESS,
SET_REPEAT_MODE,
SET_REPEAT_COUNT,
SET_IMAGE_ASSETS,
PLAY_OPTION,
}
}
| 2,416 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/Cancellable.java | package com.airbnb.lottie;
@Deprecated
public interface Cancellable {
void cancel();
}
| 2,417 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/OnCompositionLoadedListener.java | package com.airbnb.lottie;
import androidx.annotation.Nullable;
/**
* @see LottieCompositionFactory
* @see LottieResult
*/
@Deprecated
public interface OnCompositionLoadedListener {
/**
* Composition will be null if there was an error loading it. Check logcat for more details.
*/
void onCompositionLoaded(@Nullable LottieComposition composition);
}
| 2,418 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/SimpleColorFilter.java | package com.airbnb.lottie;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import androidx.annotation.ColorInt;
/**
* A color filter with a predefined transfer mode that applies the specified color on top of the
* original color. As there are many other transfer modes, please take a look at the definition
* of PorterDuff.Mode.SRC_ATOP to find one that suits your needs.
* This site has a great explanation of Porter/Duff compositing algebra as well as a visual
* representation of many of the transfer modes:
* http://ssp.impulsetrain.com/porterduff.html
*/
@SuppressWarnings("WeakerAccess") public class SimpleColorFilter extends PorterDuffColorFilter {
public SimpleColorFilter(@ColorInt int color) {
super(color, PorterDuff.Mode.SRC_ATOP);
}
}
| 2,419 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/PerformanceTracker.java | package com.airbnb.lottie;
import android.util.Log;
import androidx.collection.ArraySet;
import androidx.core.util.Pair;
import com.airbnb.lottie.utils.MeanCalculator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PerformanceTracker {
public interface FrameListener {
void onFrameRendered(float renderTimeMs);
}
private boolean enabled = false;
private final Set<FrameListener> frameListeners = new ArraySet<>();
private final Map<String, MeanCalculator> layerRenderTimes = new HashMap<>();
private final Comparator<Pair<String, Float>> floatComparator =
new Comparator<Pair<String, Float>>() {
@Override public int compare(Pair<String, Float> o1, Pair<String, Float> o2) {
float r1 = o1.second;
float r2 = o2.second;
if (r2 > r1) {
return 1;
} else if (r1 > r2) {
return -1;
}
return 0;
}
};
void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void recordRenderTime(String layerName, float millis) {
if (!enabled) {
return;
}
MeanCalculator meanCalculator = layerRenderTimes.get(layerName);
if (meanCalculator == null) {
meanCalculator = new MeanCalculator();
layerRenderTimes.put(layerName, meanCalculator);
}
meanCalculator.add(millis);
if (layerName.equals("__container")) {
for (FrameListener listener : frameListeners) {
listener.onFrameRendered(millis);
}
}
}
public void addFrameListener(FrameListener frameListener) {
frameListeners.add(frameListener);
}
@SuppressWarnings("unused") public void removeFrameListener(FrameListener frameListener) {
frameListeners.remove(frameListener);
}
public void clearRenderTimes() {
layerRenderTimes.clear();
}
public void logRenderTimes() {
if (!enabled) {
return;
}
List<Pair<String, Float>> sortedRenderTimes = getSortedRenderTimes();
Log.d(L.TAG, "Render times:");
for (int i = 0; i < sortedRenderTimes.size(); i++) {
Pair<String, Float> layer = sortedRenderTimes.get(i);
Log.d(L.TAG, String.format("\t\t%30s:%.2f", layer.first, layer.second));
}
}
public List<Pair<String, Float>> getSortedRenderTimes() {
if (!enabled) {
return Collections.emptyList();
}
List<Pair<String, Float>> sortedRenderTimes = new ArrayList<>(layerRenderTimes.size());
for (Map.Entry<String, MeanCalculator> e : layerRenderTimes.entrySet()) {
sortedRenderTimes.add(new Pair<>(e.getKey(), e.getValue().getMean()));
}
Collections.sort(sortedRenderTimes, floatComparator);
return sortedRenderTimes;
}
}
| 2,420 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieProperty.java | package com.airbnb.lottie;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.graphics.PointF;
import android.graphics.Typeface;
import com.airbnb.lottie.value.LottieValueCallback;
import com.airbnb.lottie.value.ScaleXY;
/**
* Property values are the same type as the generic type of their corresponding
* {@link LottieValueCallback}. With this, we can use generics to maintain type safety
* of the callbacks.
* <p>
* Supported properties:
* Transform:
* {@link #TRANSFORM_ANCHOR_POINT}
* {@link #TRANSFORM_POSITION}
* {@link #TRANSFORM_OPACITY}
* {@link #TRANSFORM_SCALE}
* {@link #TRANSFORM_ROTATION}
* {@link #TRANSFORM_SKEW}
* {@link #TRANSFORM_SKEW_ANGLE}
* <p>
* Fill:
* {@link #COLOR} (non-gradient)
* {@link #OPACITY}
* {@link #COLOR_FILTER}
* <p>
* Stroke:
* {@link #COLOR} (non-gradient)
* {@link #STROKE_WIDTH}
* {@link #OPACITY}
* {@link #COLOR_FILTER}
* <p>
* Ellipse:
* {@link #POSITION}
* {@link #ELLIPSE_SIZE}
* <p>
* Polystar:
* {@link #POLYSTAR_POINTS}
* {@link #POLYSTAR_ROTATION}
* {@link #POSITION}
* {@link #POLYSTAR_INNER_RADIUS} (star)
* {@link #POLYSTAR_OUTER_RADIUS}
* {@link #POLYSTAR_INNER_ROUNDEDNESS} (star)
* {@link #POLYSTAR_OUTER_ROUNDEDNESS}
* <p>
* Repeater:
* All transform properties
* {@link #REPEATER_COPIES}
* {@link #REPEATER_OFFSET}
* {@link #TRANSFORM_ROTATION}
* {@link #TRANSFORM_START_OPACITY}
* {@link #TRANSFORM_END_OPACITY}
* <p>
* Layers:
* All transform properties
* {@link #TIME_REMAP} (composition layers only)
*/
public interface LottieProperty {
/**
* ColorInt
**/
Integer COLOR = 1;
Integer STROKE_COLOR = 2;
/**
* Opacity value are 0-100 to match after effects
**/
Integer TRANSFORM_OPACITY = 3;
/**
* [0,100]
*/
Integer OPACITY = 4;
Integer DROP_SHADOW_COLOR = 5;
/**
* In Px
*/
PointF TRANSFORM_ANCHOR_POINT = new PointF();
/**
* In Px
*/
PointF TRANSFORM_POSITION = new PointF();
/**
* When split dimensions is enabled. In Px
*/
Float TRANSFORM_POSITION_X = 15f;
/**
* When split dimensions is enabled. In Px
*/
Float TRANSFORM_POSITION_Y = 16f;
/**
* In Px
*/
Float BLUR_RADIUS = 17f;
/**
* In Px
*/
PointF ELLIPSE_SIZE = new PointF();
/**
* In Px
*/
PointF RECTANGLE_SIZE = new PointF();
/**
* In degrees
*/
Float CORNER_RADIUS = 0f;
/**
* In Px
*/
PointF POSITION = new PointF();
ScaleXY TRANSFORM_SCALE = new ScaleXY();
/**
* In degrees
*/
Float TRANSFORM_ROTATION = 1f;
/**
* 0-85
*/
Float TRANSFORM_SKEW = 0f;
/**
* In degrees
*/
Float TRANSFORM_SKEW_ANGLE = 0f;
/**
* In Px
*/
Float STROKE_WIDTH = 2f;
Float TEXT_TRACKING = 3f;
Float REPEATER_COPIES = 4f;
Float REPEATER_OFFSET = 5f;
Float POLYSTAR_POINTS = 6f;
/**
* In degrees
*/
Float POLYSTAR_ROTATION = 7f;
/**
* In Px
*/
Float POLYSTAR_INNER_RADIUS = 8f;
/**
* In Px
*/
Float POLYSTAR_OUTER_RADIUS = 9f;
/**
* [0,100]
*/
Float POLYSTAR_INNER_ROUNDEDNESS = 10f;
/**
* [0,100]
*/
Float POLYSTAR_OUTER_ROUNDEDNESS = 11f;
/**
* [0,100]
*/
Float TRANSFORM_START_OPACITY = 12f;
/**
* [0,100]
*/
Float TRANSFORM_END_OPACITY = 12.1f;
/**
* The time value in seconds
*/
Float TIME_REMAP = 13f;
/**
* In Dp
*/
Float TEXT_SIZE = 14f;
/**
* [0,100]
* Lottie Android resolved drop shadows on drawing content such as fills and strokes.
* If a drop shadow is applied to a layer, the dynamic properties must be set on all
* of its child elements that draw. The easiest way to do this is to append "**" to your
* Keypath after the layer name.
*/
Float DROP_SHADOW_OPACITY = 15f;
/**
* Degrees from 12 o'clock.
* Lottie Android resolved drop shadows on drawing content such as fills and strokes.
* If a drop shadow is applied to a layer, the dynamic properties must be set on all
* of its child elements that draw. The easiest way to do this is to append "**" to your
* Keypath after the layer name.
*/
Float DROP_SHADOW_DIRECTION = 16f;
/**
* In Px
* Lottie Android resolved drop shadows on drawing content such as fills and strokes.
* If a drop shadow is applied to a layer, the dynamic properties must be set on all
* of its child elements that draw. The easiest way to do this is to append "**" to your
* Keypath after the layer name.
*/
Float DROP_SHADOW_DISTANCE = 17f;
/**
* In Px
* Lottie Android resolved drop shadows on drawing content such as fills and strokes.
* If a drop shadow is applied to a layer, the dynamic properties must be set on all
* of its child elements that draw. The easiest way to do this is to append "**" to your
* Keypath after the layer name.
*/
Float DROP_SHADOW_RADIUS = 18f;
/**
* Set the color filter for an entire drawable content. Can be applied to fills, strokes, images, and solids.
*/
ColorFilter COLOR_FILTER = new ColorFilter();
/**
* Array of ARGB colors that map to position stops in the original gradient.
* For example, a gradient from red to blue could be remapped with [0xFF00FF00, 0xFFFF00FF] (green to purple).
*/
Integer[] GRADIENT_COLOR = new Integer[0];
/**
* Set on text layers.
*/
Typeface TYPEFACE = Typeface.DEFAULT;
/**
* Set on image layers.
*/
Bitmap IMAGE = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);
/**
* Replace the text for a text layer.
*/
CharSequence TEXT = "dynamic_text";
}
| 2,421 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieDrawable.java | package com.airbnb.lottie;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.manager.FontAssetManager;
import com.airbnb.lottie.manager.ImageAssetManager;
import com.airbnb.lottie.model.Font;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.Marker;
import com.airbnb.lottie.model.layer.CompositionLayer;
import com.airbnb.lottie.parser.LayerParser;
import com.airbnb.lottie.utils.Logger;
import com.airbnb.lottie.utils.LottieThreadFactory;
import com.airbnb.lottie.utils.LottieValueAnimator;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieFrameInfo;
import com.airbnb.lottie.value.LottieValueCallback;
import com.airbnb.lottie.value.SimpleLottieValueCallback;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* This can be used to show an lottie animation in any place that would normally take a drawable.
*
* @see <a href="http://airbnb.io/lottie">Full Documentation</a>
*/
@SuppressWarnings({"WeakerAccess"})
public class LottieDrawable extends Drawable implements Drawable.Callback, Animatable {
private interface LazyCompositionTask {
void run(LottieComposition composition);
}
/**
* Internal record keeping of the desired play state when {@link #isVisible()} transitions to or is false.
* <p>
* If the animation was playing when it becomes invisible or play/pause is called on it while it is invisible, it will
* store the state and then take the appropriate action when the drawable becomes visible again.
*/
private enum OnVisibleAction {
NONE,
PLAY,
RESUME,
}
/**
* Prior to Oreo, you could only call invalidateDrawable() from the main thread.
* This means that when async updates are enabled, we must post the invalidate call to the main thread.
* Newer devices can call invalidate directly from whatever thread asyncUpdates runs on.
*/
private static final boolean invalidateSelfOnMainThread = Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1;
private LottieComposition composition;
private final LottieValueAnimator animator = new LottieValueAnimator();
// Call animationsEnabled() instead of using these fields directly.
private boolean systemAnimationsEnabled = true;
private boolean ignoreSystemAnimationsDisabled = false;
private boolean safeMode = false;
private OnVisibleAction onVisibleAction = OnVisibleAction.NONE;
private final ArrayList<LazyCompositionTask> lazyCompositionTasks = new ArrayList<>();
/**
* ImageAssetManager created automatically by Lottie for views.
*/
@Nullable
private ImageAssetManager imageAssetManager;
@Nullable
private String imageAssetsFolder;
@Nullable
private ImageAssetDelegate imageAssetDelegate;
@Nullable
private FontAssetManager fontAssetManager;
@Nullable
private Map<String, Typeface> fontMap;
/**
* Will be set if manually overridden by {@link #setDefaultFontFileExtension(String)}.
* This must be stored as a field in case it is set before the font asset delegate
* has been created.
*/
@Nullable String defaultFontFileExtension;
@Nullable
FontAssetDelegate fontAssetDelegate;
@Nullable
TextDelegate textDelegate;
private boolean enableMergePaths;
private boolean maintainOriginalImageBounds = false;
private boolean clipToCompositionBounds = true;
@Nullable
private CompositionLayer compositionLayer;
private int alpha = 255;
private boolean performanceTrackingEnabled;
private boolean outlineMasksAndMattes;
private boolean isApplyingOpacityToLayersEnabled;
private RenderMode renderMode = RenderMode.AUTOMATIC;
/**
* The actual render mode derived from {@link #renderMode}.
*/
private boolean useSoftwareRendering = false;
private final Matrix renderingMatrix = new Matrix();
private Bitmap softwareRenderingBitmap;
private Canvas softwareRenderingCanvas;
private Rect canvasClipBounds;
private RectF canvasClipBoundsRectF;
private Paint softwareRenderingPaint;
private Rect softwareRenderingSrcBoundsRect;
private Rect softwareRenderingDstBoundsRect;
private RectF softwareRenderingDstBoundsRectF;
private RectF softwareRenderingTransformedBounds;
private Matrix softwareRenderingOriginalCanvasMatrix;
private Matrix softwareRenderingOriginalCanvasMatrixInverse;
/**
* True if the drawable has not been drawn since the last invalidateSelf.
* We can do this to prevent things like bounds from getting recalculated
* many times.
*/
private boolean isDirty = false;
/** Use the getter so that it can fall back to {@link L#getDefaultAsyncUpdates()}. */
@Nullable private AsyncUpdates asyncUpdates;
private final ValueAnimator.AnimatorUpdateListener progressUpdateListener = animation -> {
if (getAsyncUpdatesEnabled()) {
// Render a new frame.
// If draw is called while lastDrawnProgress is still recent enough, it will
// draw straight away and then enqueue a background setProgress immediately after draw
// finishes.
invalidateSelf();
} else if (compositionLayer != null) {
compositionLayer.setProgress(animator.getAnimatedValueAbsolute());
}
};
/**
* Ensures that setProgress and draw will never happen at the same time on different threads.
* If that were to happen, parts of the animation may be on one frame while other parts would
* be on another.
*/
private final Semaphore setProgressDrawLock = new Semaphore(1);
/**
* The executor that {@link AsyncUpdates} will be run on.
* <p/>
* Defaults to a core size of 0 so that when no animations are playing, there will be no
* idle cores consuming resources.
* <p/>
* Allows up to two active threads so that if there are many animations, they can all work in parallel.
* Two was arbitrarily chosen but should be sufficient for most uses cases. In the case of a single
* animation, this should never exceed one.
* <p/>
* Each thread will timeout after 35ms which gives it enough time to persist for one frame, one dropped frame
* and a few extra ms just in case.
*/
private static final Executor setProgressExecutor = new ThreadPoolExecutor(0, 2, 35, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(), new LottieThreadFactory());
private Handler mainThreadHandler;
private Runnable invalidateSelfRunnable;
private final Runnable updateProgressRunnable = () -> {
CompositionLayer compositionLayer = this.compositionLayer;
if (compositionLayer == null) {
return;
}
try {
setProgressDrawLock.acquire();
compositionLayer.setProgress(animator.getAnimatedValueAbsolute());
// Refer to invalidateSelfOnMainThread for more info.
if (invalidateSelfOnMainThread && isDirty) {
if (mainThreadHandler == null) {
mainThreadHandler = new Handler(Looper.getMainLooper());
invalidateSelfRunnable = () -> {
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateDrawable(this);
}
};
}
mainThreadHandler.post(invalidateSelfRunnable);
}
} catch (InterruptedException e) {
// Do nothing.
} finally {
setProgressDrawLock.release();
}
};
private float lastDrawnProgress = -Float.MAX_VALUE;
private static final float MAX_DELTA_MS_ASYNC_SET_PROGRESS = 3 / 60f * 1000;
@IntDef({RESTART, REVERSE})
@Retention(RetentionPolicy.SOURCE)
public @interface RepeatMode {
}
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation restarts from the beginning.
*/
public static final int RESTART = ValueAnimator.RESTART;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation reverses direction on every iteration.
*/
public static final int REVERSE = ValueAnimator.REVERSE;
/**
* This value used used with the {@link #setRepeatCount(int)} property to repeat
* the animation indefinitely.
*/
public static final int INFINITE = ValueAnimator.INFINITE;
public LottieDrawable() {
animator.addUpdateListener(progressUpdateListener);
}
/**
* Returns whether or not any layers in this composition has masks.
*/
public boolean hasMasks() {
return compositionLayer != null && compositionLayer.hasMasks();
}
/**
* Returns whether or not any layers in this composition has a matte layer.
*/
public boolean hasMatte() {
return compositionLayer != null && compositionLayer.hasMatte();
}
public boolean enableMergePathsForKitKatAndAbove() {
return enableMergePaths;
}
/**
* Enable this to get merge path support for devices running KitKat (19) and above.
* <p>
* Merge paths currently don't work if the the operand shape is entirely contained within the
* first shape. If you need to cut out one shape from another shape, use an even-odd fill type
* instead of using merge paths.
*/
public void enableMergePathsForKitKatAndAbove(boolean enable) {
if (enableMergePaths == enable) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Logger.warning("Merge paths are not supported pre-Kit Kat.");
return;
}
enableMergePaths = enable;
if (composition != null) {
buildCompositionLayer();
}
}
public boolean isMergePathsEnabledForKitKatAndAbove() {
return enableMergePaths;
}
/**
* Sets whether or not Lottie should clip to the original animation composition bounds.
* <p>
* Defaults to true.
*/
public void setClipToCompositionBounds(boolean clipToCompositionBounds) {
if (clipToCompositionBounds != this.clipToCompositionBounds) {
this.clipToCompositionBounds = clipToCompositionBounds;
CompositionLayer compositionLayer = this.compositionLayer;
if (compositionLayer != null) {
compositionLayer.setClipToCompositionBounds(clipToCompositionBounds);
}
invalidateSelf();
}
}
/**
* Gets whether or not Lottie should clip to the original animation composition bounds.
* <p>
* Defaults to true.
*/
public boolean getClipToCompositionBounds() {
return clipToCompositionBounds;
}
/**
* If you use image assets, you must explicitly specify the folder in assets/ in which they are
* located because bodymovin uses the name filenames across all compositions (img_#).
* Do NOT rename the images themselves.
* <p>
* If your images are located in src/main/assets/airbnb_loader/ then call
* `setImageAssetsFolder("airbnb_loader/");`.
* <p>
* <p>
* Be wary if you are using many images, however. Lottie is designed to work with vector shapes
* from After Effects. If your images look like they could be represented with vector shapes,
* see if it is possible to convert them to shape layers and re-export your animation. Check
* the documentation at <a href="http://airbnb.io/lottie">airbnb.io/lottie</a> for more information about importing shapes from
* Sketch or Illustrator to avoid this.
*/
public void setImagesAssetsFolder(@Nullable String imageAssetsFolder) {
this.imageAssetsFolder = imageAssetsFolder;
}
@Nullable
public String getImageAssetsFolder() {
return imageAssetsFolder;
}
/**
* When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.
* When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
* <p>
* Defaults to false.
*/
public void setMaintainOriginalImageBounds(boolean maintainOriginalImageBounds) {
this.maintainOriginalImageBounds = maintainOriginalImageBounds;
}
/**
* When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.
* When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
* <p>
* Defaults to false.
*/
public boolean getMaintainOriginalImageBounds() {
return maintainOriginalImageBounds;
}
/**
* Create a composition with {@link LottieCompositionFactory}
*
* @return True if the composition is different from the previously set composition, false otherwise.
*/
public boolean setComposition(LottieComposition composition) {
if (this.composition == composition) {
return false;
}
isDirty = true;
clearComposition();
this.composition = composition;
buildCompositionLayer();
animator.setComposition(composition);
setProgress(animator.getAnimatedFraction());
// We copy the tasks to a new ArrayList so that if this method is called from multiple threads,
// then there won't be two iterators iterating and removing at the same time.
Iterator<LazyCompositionTask> it = new ArrayList<>(lazyCompositionTasks).iterator();
while (it.hasNext()) {
LazyCompositionTask t = it.next();
// The task should never be null but it appears to happen in rare cases. Maybe it's an oem-specific or ART bug.
// https://github.com/airbnb/lottie-android/issues/1702
if (t != null) {
t.run(composition);
}
it.remove();
}
lazyCompositionTasks.clear();
composition.setPerformanceTrackingEnabled(performanceTrackingEnabled);
computeRenderMode();
// Ensure that ImageView updates the drawable width/height so it can
// properly calculate its drawable matrix.
Callback callback = getCallback();
if (callback instanceof ImageView) {
((ImageView) callback).setImageDrawable(null);
((ImageView) callback).setImageDrawable(this);
}
return true;
}
/**
* Call this to set whether or not to render with hardware or software acceleration.
* Lottie defaults to Automatic which will use hardware acceleration unless:
* 1) There are dash paths and the device is pre-Pie.
* 2) There are more than 4 masks and mattes and the device is pre-Pie.
* Hardware acceleration is generally faster for those devices unless
* there are many large mattes and masks in which case there is a lot
* of GPU uploadTexture thrashing which makes it much slower.
* <p>
* In most cases, hardware rendering will be faster, even if you have mattes and masks.
* However, if you have multiple mattes and masks (especially large ones), you
* should test both render modes. You should also test on pre-Pie and Pie+ devices
* because the underlying rendering engine changed significantly.
*
* @see <a href="https://developer.android.com/guide/topics/graphics/hardware-accel#unsupported">Android Hardware Acceleration</a>
*/
public void setRenderMode(RenderMode renderMode) {
this.renderMode = renderMode;
computeRenderMode();
}
/**
* Returns the current value of {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info.
*/
public AsyncUpdates getAsyncUpdates() {
AsyncUpdates asyncUpdates = this.asyncUpdates;
if (asyncUpdates != null) {
return asyncUpdates;
}
return L.getDefaultAsyncUpdates();
}
/**
* Similar to {@link #getAsyncUpdates()} except it returns the actual
* boolean value for whether async updates are enabled or not.
* This is useful when the mode is automatic and you want to know
* whether automatic is defaulting to enabled or not.
*/
public boolean getAsyncUpdatesEnabled() {
return getAsyncUpdates() == AsyncUpdates.ENABLED;
}
/**
* **Note: this API is experimental and may changed.**
* <p/>
* Sets the current value for {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info.
*/
public void setAsyncUpdates(@Nullable AsyncUpdates asyncUpdates) {
this.asyncUpdates = asyncUpdates;
}
/**
* Returns the actual render mode being used. It will always be {@link RenderMode#HARDWARE} or {@link RenderMode#SOFTWARE}.
* When the render mode is set to AUTOMATIC, the value will be derived from {@link RenderMode#useSoftwareRendering(int, boolean, int)}.
*/
public RenderMode getRenderMode() {
return useSoftwareRendering ? RenderMode.SOFTWARE : RenderMode.HARDWARE;
}
private void computeRenderMode() {
LottieComposition composition = this.composition;
if (composition == null) {
return;
}
useSoftwareRendering = renderMode.useSoftwareRendering(
Build.VERSION.SDK_INT, composition.hasDashPattern(), composition.getMaskAndMatteCount());
}
public void setPerformanceTrackingEnabled(boolean enabled) {
performanceTrackingEnabled = enabled;
if (composition != null) {
composition.setPerformanceTrackingEnabled(enabled);
}
}
/**
* Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will
* be proportional to the surface area of all of the masks/mattes combined.
* <p>
* DO NOT leave this enabled in production.
*/
public void setOutlineMasksAndMattes(boolean outline) {
if (outlineMasksAndMattes == outline) {
return;
}
outlineMasksAndMattes = outline;
if (compositionLayer != null) {
compositionLayer.setOutlineMasksAndMattes(outline);
}
}
@Nullable
public PerformanceTracker getPerformanceTracker() {
if (composition != null) {
return composition.getPerformanceTracker();
}
return null;
}
/**
* Sets whether to apply opacity to the each layer instead of shape.
* <p>
* Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurate
* at the expense of performance.
* <p>
* The default value is false.
* <p>
* Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled.
*
* @see android.view.View#setLayerType(int, android.graphics.Paint)
* @see LottieAnimationView#setRenderMode(RenderMode)
*/
public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled) {
this.isApplyingOpacityToLayersEnabled = isApplyingOpacityToLayersEnabled;
}
/**
* This API no longer has any effect.
*/
@Deprecated
public void disableExtraScaleModeInFitXY() {
}
public boolean isApplyingOpacityToLayersEnabled() {
return isApplyingOpacityToLayersEnabled;
}
private void buildCompositionLayer() {
LottieComposition composition = this.composition;
if (composition == null) {
return;
}
compositionLayer = new CompositionLayer(
this, LayerParser.parse(composition), composition.getLayers(), composition);
if (outlineMasksAndMattes) {
compositionLayer.setOutlineMasksAndMattes(true);
}
compositionLayer.setClipToCompositionBounds(clipToCompositionBounds);
}
public void clearComposition() {
if (animator.isRunning()) {
animator.cancel();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
composition = null;
compositionLayer = null;
imageAssetManager = null;
lastDrawnProgress = -Float.MAX_VALUE;
animator.clearComposition();
invalidateSelf();
}
/**
* If you are experiencing a device specific crash that happens during drawing, you can set this to true
* for those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie to
* render an empty frame rather than crash your app.
* <p>
* Ideally, you will never need this and the vast majority of apps and animations won't. However, you may use
* this for very specific cases if absolutely necessary.
*/
public void setSafeMode(boolean safeMode) {
this.safeMode = safeMode;
}
@Override
public void invalidateSelf() {
if (isDirty) {
return;
}
isDirty = true;
// Refer to invalidateSelfOnMainThread for more info.
if (invalidateSelfOnMainThread && Looper.getMainLooper() != Looper.myLooper()) {
return;
}
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateDrawable(this);
}
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
this.alpha = alpha;
invalidateSelf();
}
@Override
public int getAlpha() {
return alpha;
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
Logger.warning("Use addColorFilter instead.");
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/**
* Helper for the async execution path to potentially call setProgress
* before drawing if the current progress has drifted sufficiently far
* from the last set progress.
*
* @see AsyncUpdates
* @see #setAsyncUpdates(AsyncUpdates)
*/
private boolean shouldSetProgressBeforeDrawing() {
LottieComposition composition = this.composition;
if (composition == null) {
return false;
}
float lastDrawnProgress = this.lastDrawnProgress;
float currentProgress = animator.getAnimatedValueAbsolute();
this.lastDrawnProgress = currentProgress;
float duration = composition.getDuration();
float deltaProgress = Math.abs(currentProgress - lastDrawnProgress);
float deltaMs = deltaProgress * duration;
return deltaMs >= MAX_DELTA_MS_ASYNC_SET_PROGRESS;
}
@Override
public void draw(@NonNull Canvas canvas) {
CompositionLayer compositionLayer = this.compositionLayer;
if (compositionLayer == null) {
return;
}
boolean asyncUpdatesEnabled = getAsyncUpdatesEnabled();
try {
if (asyncUpdatesEnabled) {
setProgressDrawLock.acquire();
}
L.beginSection("Drawable#draw");
if (asyncUpdatesEnabled && shouldSetProgressBeforeDrawing()) {
setProgress(animator.getAnimatedValueAbsolute());
}
if (safeMode) {
try {
if (useSoftwareRendering) {
renderAndDrawAsBitmap(canvas, compositionLayer);
} else {
drawDirectlyToCanvas(canvas);
}
} catch (Throwable e) {
Logger.error("Lottie crashed in draw!", e);
}
} else {
if (useSoftwareRendering) {
renderAndDrawAsBitmap(canvas, compositionLayer);
} else {
drawDirectlyToCanvas(canvas);
}
}
isDirty = false;
} catch (InterruptedException e) {
// Do nothing.
} finally {
L.endSection("Drawable#draw");
if (asyncUpdatesEnabled) {
setProgressDrawLock.release();
if (compositionLayer.getProgress() != animator.getAnimatedValueAbsolute()) {
setProgressExecutor.execute(updateProgressRunnable);
}
}
}
}
/**
* To be used by lottie-compose only.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public void draw(Canvas canvas, Matrix matrix) {
CompositionLayer compositionLayer = this.compositionLayer;
LottieComposition composition = this.composition;
if (compositionLayer == null || composition == null) {
return;
}
boolean asyncUpdatesEnabled = getAsyncUpdatesEnabled();
try {
if (asyncUpdatesEnabled) {
setProgressDrawLock.acquire();
if (shouldSetProgressBeforeDrawing()) {
setProgress(animator.getAnimatedValueAbsolute());
}
}
if (useSoftwareRendering) {
canvas.save();
canvas.concat(matrix);
renderAndDrawAsBitmap(canvas, compositionLayer);
canvas.restore();
} else {
compositionLayer.draw(canvas, matrix, alpha);
}
isDirty = false;
} catch (InterruptedException e) {
// Do nothing.
} finally {
if (asyncUpdatesEnabled) {
setProgressDrawLock.release();
if (compositionLayer.getProgress() != animator.getAnimatedValueAbsolute()) {
setProgressExecutor.execute(updateProgressRunnable);
}
}
}
}
// <editor-fold desc="animator">
@MainThread
@Override
public void start() {
Callback callback = getCallback();
if (callback instanceof View && ((View) callback).isInEditMode()) {
// Don't auto play when in edit mode.
return;
}
playAnimation();
}
@MainThread
@Override
public void stop() {
endAnimation();
}
@Override
public boolean isRunning() {
return isAnimating();
}
/**
* Plays the animation from the beginning. If speed is {@literal <} 0, it will start at the end
* and play towards the beginning
*/
@MainThread
public void playAnimation() {
if (compositionLayer == null) {
lazyCompositionTasks.add(c -> playAnimation());
return;
}
computeRenderMode();
if (animationsEnabled() || getRepeatCount() == 0) {
if (isVisible()) {
animator.playAnimation();
onVisibleAction = OnVisibleAction.NONE;
} else {
onVisibleAction = OnVisibleAction.PLAY;
}
}
if (!animationsEnabled()) {
setFrame((int) (getSpeed() < 0 ? getMinFrame() : getMaxFrame()));
animator.endAnimation();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
}
@MainThread
public void endAnimation() {
lazyCompositionTasks.clear();
animator.endAnimation();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
/**
* Continues playing the animation from its current position. If speed {@literal <} 0, it will play backwards
* from the current position.
*/
@MainThread
public void resumeAnimation() {
if (compositionLayer == null) {
lazyCompositionTasks.add(c -> resumeAnimation());
return;
}
computeRenderMode();
if (animationsEnabled() || getRepeatCount() == 0) {
if (isVisible()) {
animator.resumeAnimation();
onVisibleAction = OnVisibleAction.NONE;
} else {
onVisibleAction = OnVisibleAction.RESUME;
}
}
if (!animationsEnabled()) {
setFrame((int) (getSpeed() < 0 ? getMinFrame() : getMaxFrame()));
animator.endAnimation();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
}
/**
* Sets the minimum frame that the animation will start from when playing or looping.
*/
public void setMinFrame(final int minFrame) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinFrame(minFrame));
return;
}
animator.setMinFrame(minFrame);
}
/**
* Returns the minimum frame set by {@link #setMinFrame(int)} or {@link #setMinProgress(float)}
*/
public float getMinFrame() {
return animator.getMinFrame();
}
/**
* Sets the minimum progress that the animation will start from when playing or looping.
*/
public void setMinProgress(final float minProgress) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinProgress(minProgress));
return;
}
setMinFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), minProgress));
}
/**
* Sets the maximum frame that the animation will end at when playing or looping.
* <p>
* The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the same
* thing as composition.endFrame.
*/
public void setMaxFrame(final int maxFrame) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMaxFrame(maxFrame));
return;
}
animator.setMaxFrame(maxFrame + 0.99f);
}
/**
* Returns the maximum frame set by {@link #setMaxFrame(int)} or {@link #setMaxProgress(float)}
*/
public float getMaxFrame() {
return animator.getMaxFrame();
}
/**
* Sets the maximum progress that the animation will end at when playing or looping.
*/
public void setMaxProgress(@FloatRange(from = 0f, to = 1f) final float maxProgress) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMaxProgress(maxProgress));
return;
}
animator.setMaxFrame(MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), maxProgress));
}
/**
* Sets the minimum frame to the start time of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMinFrame(final String markerName) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinFrame(markerName));
return;
}
Marker marker = composition.getMarker(markerName);
if (marker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + markerName + ".");
}
setMinFrame((int) marker.startFrame);
}
/**
* Sets the maximum frame to the start time + duration of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMaxFrame(final String markerName) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMaxFrame(markerName));
return;
}
Marker marker = composition.getMarker(markerName);
if (marker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + markerName + ".");
}
setMaxFrame((int) (marker.startFrame + marker.durationFrames));
}
/**
* Sets the minimum and maximum frame to the start time and start time + duration
* of the specified marker.
*
* @throws IllegalArgumentException if the marker is not found.
*/
public void setMinAndMaxFrame(final String markerName) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinAndMaxFrame(markerName));
return;
}
Marker marker = composition.getMarker(markerName);
if (marker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + markerName + ".");
}
int startFrame = (int) marker.startFrame;
setMinAndMaxFrame(startFrame, startFrame + (int) marker.durationFrames);
}
/**
* Sets the minimum and maximum frame to the start marker start and the maximum frame to the end marker start.
* playEndMarkerStartFrame determines whether or not to play the frame that the end marker is on. If the end marker
* represents the end of the section that you want, it should be true. If the marker represents the beginning of the
* next section, it should be false.
*
* @throws IllegalArgumentException if either marker is not found.
*/
public void setMinAndMaxFrame(final String startMarkerName, final String endMarkerName, final boolean playEndMarkerStartFrame) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinAndMaxFrame(startMarkerName, endMarkerName, playEndMarkerStartFrame));
return;
}
Marker startMarker = composition.getMarker(startMarkerName);
if (startMarker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + startMarkerName + ".");
}
int startFrame = (int) startMarker.startFrame;
final Marker endMarker = composition.getMarker(endMarkerName);
if (endMarker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + endMarkerName + ".");
}
int endFrame = (int) (endMarker.startFrame + (playEndMarkerStartFrame ? 1f : 0f));
setMinAndMaxFrame(startFrame, endFrame);
}
/**
* @see #setMinFrame(int)
* @see #setMaxFrame(int)
*/
public void setMinAndMaxFrame(final int minFrame, final int maxFrame) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinAndMaxFrame(minFrame, maxFrame));
return;
}
// Adding 0.99 ensures that the maxFrame itself gets played.
animator.setMinAndMaxFrames(minFrame, maxFrame + 0.99f);
}
/**
* @see #setMinProgress(float)
* @see #setMaxProgress(float)
*/
public void setMinAndMaxProgress(
@FloatRange(from = 0f, to = 1f) final float minProgress,
@FloatRange(from = 0f, to = 1f) final float maxProgress) {
if (composition == null) {
lazyCompositionTasks.add(c -> setMinAndMaxProgress(minProgress, maxProgress));
return;
}
setMinAndMaxFrame((int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), minProgress),
(int) MiscUtils.lerp(composition.getStartFrame(), composition.getEndFrame(), maxProgress));
}
/**
* Reverses the current animation speed. This does NOT play the animation.
*
* @see #setSpeed(float)
* @see #playAnimation()
* @see #resumeAnimation()
*/
public void reverseAnimationSpeed() {
animator.reverseAnimationSpeed();
}
/**
* Sets the playback speed. If speed {@literal <} 0, the animation will play backwards.
*/
public void setSpeed(float speed) {
animator.setSpeed(speed);
}
/**
* Returns the current playback speed. This will be {@literal <} 0 if the animation is playing backwards.
*/
public float getSpeed() {
return animator.getSpeed();
}
public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
animator.addUpdateListener(updateListener);
}
public void removeAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) {
animator.removeUpdateListener(updateListener);
}
public void removeAllUpdateListeners() {
animator.removeAllUpdateListeners();
animator.addUpdateListener(progressUpdateListener);
}
public void addAnimatorListener(Animator.AnimatorListener listener) {
animator.addListener(listener);
}
public void removeAnimatorListener(Animator.AnimatorListener listener) {
animator.removeListener(listener);
}
public void removeAllAnimatorListeners() {
animator.removeAllListeners();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void addAnimatorPauseListener(Animator.AnimatorPauseListener listener) {
animator.addPauseListener(listener);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener) {
animator.removePauseListener(listener);
}
/**
* Sets the progress to the specified frame.
* If the composition isn't set yet, the progress will be set to the frame when
* it is.
*/
public void setFrame(final int frame) {
if (composition == null) {
lazyCompositionTasks.add(c -> setFrame(frame));
return;
}
animator.setFrame(frame);
}
/**
* Get the currently rendered frame.
*/
public int getFrame() {
return (int) animator.getFrame();
}
public void setProgress(@FloatRange(from = 0f, to = 1f) final float progress) {
if (composition == null) {
lazyCompositionTasks.add(c -> setProgress(progress));
return;
}
L.beginSection("Drawable#setProgress");
animator.setFrame(composition.getFrameForProgress(progress));
L.endSection("Drawable#setProgress");
}
/**
* @see #setRepeatCount(int)
*/
@Deprecated
public void loop(boolean loop) {
animator.setRepeatCount(loop ? ValueAnimator.INFINITE : 0);
}
/**
* Defines what this animation should do when it reaches the end. This
* setting is applied only when the repeat count is either greater than
* 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
*
* @param mode {@link #RESTART} or {@link #REVERSE}
*/
public void setRepeatMode(@RepeatMode int mode) {
animator.setRepeatMode(mode);
}
/**
* Defines what this animation should do when it reaches the end.
*
* @return either one of {@link #REVERSE} or {@link #RESTART}
*/
@SuppressLint("WrongConstant")
@RepeatMode
public int getRepeatMode() {
return animator.getRepeatMode();
}
/**
* Sets how many times the animation should be repeated. If the repeat
* count is 0, the animation is never repeated. If the repeat count is
* greater than 0 or {@link #INFINITE}, the repeat mode will be taken
* into account. The repeat count is 0 by default.
*
* @param count the number of times the animation should be repeated
*/
public void setRepeatCount(int count) {
animator.setRepeatCount(count);
}
/**
* Defines how many times the animation should repeat. The default value
* is 0.
*
* @return the number of times the animation should repeat, or {@link #INFINITE}
*/
public int getRepeatCount() {
return animator.getRepeatCount();
}
@SuppressWarnings("unused")
public boolean isLooping() {
return animator.getRepeatCount() == ValueAnimator.INFINITE;
}
public boolean isAnimating() {
// On some versions of Android, this is called from the LottieAnimationView constructor, before animator was created.
// https://github.com/airbnb/lottie-android/issues/1430
//noinspection ConstantConditions
if (animator == null) {
return false;
}
return animator.isRunning();
}
boolean isAnimatingOrWillAnimateOnVisible() {
if (isVisible()) {
return animator.isRunning();
} else {
return onVisibleAction == OnVisibleAction.PLAY || onVisibleAction == OnVisibleAction.RESUME;
}
}
private boolean animationsEnabled() {
return systemAnimationsEnabled || ignoreSystemAnimationsDisabled;
}
/**
* Tell Lottie that system animations are disabled. When using {@link LottieAnimationView} or Compose {@code LottieAnimation}, this is done
* automatically. However, if you are using LottieDrawable on its own, you should set this to false when
* {@link com.airbnb.lottie.utils.Utils#getAnimationScale(Context)} is 0.
*/
public void setSystemAnimationsAreEnabled(Boolean areEnabled) {
systemAnimationsEnabled = areEnabled;
}
// </editor-fold>
/**
* Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled.
* <p>
* Defaults to false.
*
* @param ignore if true animations will run even when they are disabled in the system settings.
*/
public void setIgnoreDisabledSystemAnimations(boolean ignore) {
ignoreSystemAnimationsDisabled = ignore;
}
/**
* Lottie files can specify a target frame rate. By default, Lottie ignores it and re-renders
* on every frame. If that behavior is undesirable, you can set this to true to use the composition
* frame rate instead.
* <p>
* Note: composition frame rates are usually lower than display frame rates
* so this will likely make your animation feel janky. However, it may be desirable
* for specific situations such as pixel art that are intended to have low frame rates.
*/
public void setUseCompositionFrameRate(boolean useCompositionFrameRate) {
animator.setUseCompositionFrameRate(useCompositionFrameRate);
}
/**
* Use this if you can't bundle images with your app. This may be useful if you download the
* animations from the network or have the images saved to an SD Card. In that case, Lottie
* will defer the loading of the bitmap to this delegate.
* <p>
* Be wary if you are using many images, however. Lottie is designed to work with vector shapes
* from After Effects. If your images look like they could be represented with vector shapes,
* see if it is possible to convert them to shape layers and re-export your animation. Check
* the documentation at <a href="http://airbnb.io/lottie">http://airbnb.io/lottie</a> for more information about importing shapes from
* Sketch or Illustrator to avoid this.
*/
public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) {
this.imageAssetDelegate = assetDelegate;
if (imageAssetManager != null) {
imageAssetManager.setDelegate(assetDelegate);
}
}
/**
* Use this to manually set fonts.
*/
public void setFontAssetDelegate(FontAssetDelegate assetDelegate) {
this.fontAssetDelegate = assetDelegate;
if (fontAssetManager != null) {
fontAssetManager.setDelegate(assetDelegate);
}
}
/**
* Set a map from font name keys to Typefaces.
* The keys can be in the form:
* * fontFamily
* * fontFamily-fontStyle
* * fontName
* All 3 are defined as fName, fFamily, and fStyle in the Lottie file.
* <p>
* If you change a value in fontMap, create a new map or call
* {@link #invalidateSelf()}. Setting the same map again will noop.
*/
public void setFontMap(@Nullable Map<String, Typeface> fontMap) {
if (fontMap == this.fontMap) {
return;
}
this.fontMap = fontMap;
invalidateSelf();
}
public void setTextDelegate(@SuppressWarnings("NullableProblems") TextDelegate textDelegate) {
this.textDelegate = textDelegate;
}
@Nullable
public TextDelegate getTextDelegate() {
return textDelegate;
}
public boolean useTextGlyphs() {
return fontMap == null && textDelegate == null && composition.getCharacters().size() > 0;
}
public LottieComposition getComposition() {
return composition;
}
public void cancelAnimation() {
lazyCompositionTasks.clear();
animator.cancel();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
public void pauseAnimation() {
lazyCompositionTasks.clear();
animator.pauseAnimation();
if (!isVisible()) {
onVisibleAction = OnVisibleAction.NONE;
}
}
@FloatRange(from = 0f, to = 1f)
public float getProgress() {
return animator.getAnimatedValueAbsolute();
}
@Override
public int getIntrinsicWidth() {
return composition == null ? -1 : composition.getBounds().width();
}
@Override
public int getIntrinsicHeight() {
return composition == null ? -1 : composition.getBounds().height();
}
/**
* Takes a {@link KeyPath}, potentially with wildcards or globstars and resolve it to a list of
* zero or more actual {@link KeyPath Keypaths} that exist in the current animation.
* <p>
* If you want to set value callbacks for any of these values, it is recommend to use the
* returned {@link KeyPath} objects because they will be internally resolved to their content
* and won't trigger a tree walk of the animation contents when applied.
*/
public List<KeyPath> resolveKeyPath(KeyPath keyPath) {
if (compositionLayer == null) {
Logger.warning("Cannot resolve KeyPath. Composition is not set yet.");
return Collections.emptyList();
}
List<KeyPath> keyPaths = new ArrayList<>();
compositionLayer.resolveKeyPath(keyPath, 0, keyPaths, new KeyPath());
return keyPaths;
}
/**
* Add an property callback for the specified {@link KeyPath}. This {@link KeyPath} can resolve
* to multiple contents. In that case, the callback's value will apply to all of them.
* <p>
* Internally, this will check if the {@link KeyPath} has already been resolved with
* {@link #resolveKeyPath(KeyPath)} and will resolve it if it hasn't.
* <p>
* Set the callback to null to clear it.
*/
public <T> void addValueCallback(
final KeyPath keyPath, final T property, @Nullable final LottieValueCallback<T> callback) {
if (compositionLayer == null) {
lazyCompositionTasks.add(c -> addValueCallback(keyPath, property, callback));
return;
}
boolean invalidate;
if (keyPath == KeyPath.COMPOSITION) {
compositionLayer.addValueCallback(property, callback);
invalidate = true;
} else if (keyPath.getResolvedElement() != null) {
keyPath.getResolvedElement().addValueCallback(property, callback);
invalidate = true;
} else {
List<KeyPath> elements = resolveKeyPath(keyPath);
for (int i = 0; i < elements.size(); i++) {
//noinspection ConstantConditions
elements.get(i).getResolvedElement().addValueCallback(property, callback);
}
invalidate = !elements.isEmpty();
}
if (invalidate) {
invalidateSelf();
if (property == LottieProperty.TIME_REMAP) {
// Time remapping values are read in setProgress. In order for the new value
// to apply, we have to re-set the progress with the current progress so that the
// time remapping can be reapplied.
setProgress(getProgress());
}
}
}
/**
* Overload of {@link #addValueCallback(KeyPath, Object, LottieValueCallback)} that takes an interface. This allows you to use a single abstract
* method code block in Kotlin such as:
* drawable.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor }
*/
public <T> void addValueCallback(KeyPath keyPath, T property,
final SimpleLottieValueCallback<T> callback) {
addValueCallback(keyPath, property, new LottieValueCallback<T>() {
@Override
public T getValue(LottieFrameInfo<T> frameInfo) {
return callback.getValue(frameInfo);
}
});
}
/**
* Allows you to modify or clear a bitmap that was loaded for an image either automatically
* through {@link #setImagesAssetsFolder(String)} or with an {@link ImageAssetDelegate}.
*
* @return the previous Bitmap or null.
*/
@Nullable
public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) {
ImageAssetManager bm = getImageAssetManager();
if (bm == null) {
Logger.warning("Cannot update bitmap. Most likely the drawable is not added to a View " +
"which prevents Lottie from getting a Context.");
return null;
}
Bitmap ret = bm.updateBitmap(id, bitmap);
invalidateSelf();
return ret;
}
/**
* @deprecated use {@link #getBitmapForId(String)}.
*/
@Nullable
@Deprecated
public Bitmap getImageAsset(String id) {
ImageAssetManager bm = getImageAssetManager();
if (bm != null) {
return bm.bitmapForId(id);
}
LottieImageAsset imageAsset = composition == null ? null : composition.getImages().get(id);
if (imageAsset != null) {
return imageAsset.getBitmap();
}
return null;
}
/**
* Returns the bitmap that will be rendered for the given id in the Lottie animation file.
* The id is the asset reference id stored in the "id" property of each object in the "assets" array.
* <p>
* The returned bitmap could be from:
* * Embedded in the animation file as a base64 string.
* * In the same directory as the animation file.
* * In the same zip file as the animation file.
* * Returned from an {@link ImageAssetDelegate}.
* or null if the image doesn't exist from any of those places.
*/
@Nullable
public Bitmap getBitmapForId(String id) {
ImageAssetManager assetManager = getImageAssetManager();
if (assetManager != null) {
return assetManager.bitmapForId(id);
}
return null;
}
/**
* Returns the {@link LottieImageAsset} that will be rendered for the given id in the Lottie animation file.
* The id is the asset reference id stored in the "id" property of each object in the "assets" array.
* <p>
* The returned bitmap could be from:
* * Embedded in the animation file as a base64 string.
* * In the same directory as the animation file.
* * In the same zip file as the animation file.
* * Returned from an {@link ImageAssetDelegate}.
* or null if the image doesn't exist from any of those places.
*/
@Nullable
public LottieImageAsset getLottieImageAssetForId(String id) {
LottieComposition composition = this.composition;
if (composition == null) {
return null;
}
return composition.getImages().get(id);
}
private ImageAssetManager getImageAssetManager() {
if (imageAssetManager != null && !imageAssetManager.hasSameContext(getContext())) {
imageAssetManager = null;
}
if (imageAssetManager == null) {
imageAssetManager = new ImageAssetManager(getCallback(),
imageAssetsFolder, imageAssetDelegate, composition.getImages());
}
return imageAssetManager;
}
@Nullable
@RestrictTo(RestrictTo.Scope.LIBRARY)
public Typeface getTypeface(Font font) {
Map<String, Typeface> fontMap = this.fontMap;
if (fontMap != null) {
String key = font.getFamily();
if (fontMap.containsKey(key)) {
return fontMap.get(key);
}
key = font.getName();
if (fontMap.containsKey(key)) {
return fontMap.get(key);
}
key = font.getFamily() + "-" + font.getStyle();
if (fontMap.containsKey(key)) {
return fontMap.get(key);
}
}
FontAssetManager assetManager = getFontAssetManager();
if (assetManager != null) {
return assetManager.getTypeface(font);
}
return null;
}
private FontAssetManager getFontAssetManager() {
if (getCallback() == null) {
// We can't get a bitmap since we can't get a Context from the callback.
return null;
}
if (fontAssetManager == null) {
fontAssetManager = new FontAssetManager(getCallback(), fontAssetDelegate);
String defaultExtension = this.defaultFontFileExtension;
if (defaultExtension != null) {
fontAssetManager.setDefaultFontFileExtension(defaultFontFileExtension);
}
}
return fontAssetManager;
}
/**
* By default, Lottie will look in src/assets/fonts/FONT_NAME.ttf
* where FONT_NAME is the fFamily specified in your Lottie file.
* If your fonts have a different extension, you can override the
* default here.
* <p>
* Alternatively, you can use {@link #setFontAssetDelegate(FontAssetDelegate)}
* for more control.
*
* @see #setFontAssetDelegate(FontAssetDelegate)
*/
public void setDefaultFontFileExtension(String extension) {
defaultFontFileExtension = extension;
FontAssetManager fam = getFontAssetManager();
if (fam != null) {
fam.setDefaultFontFileExtension(extension);
}
}
@Nullable
private Context getContext() {
Callback callback = getCallback();
if (callback == null) {
return null;
}
if (callback instanceof View) {
return ((View) callback).getContext();
}
return null;
}
@Override public boolean setVisible(boolean visible, boolean restart) {
// Sometimes, setVisible(false) gets called twice in a row. If we don't check wasNotVisibleAlready, we could
// wind up clearing the onVisibleAction value for the second call.
boolean wasNotVisibleAlready = !isVisible();
boolean ret = super.setVisible(visible, restart);
if (visible) {
if (onVisibleAction == OnVisibleAction.PLAY) {
playAnimation();
} else if (onVisibleAction == OnVisibleAction.RESUME) {
resumeAnimation();
}
} else {
if (animator.isRunning()) {
pauseAnimation();
onVisibleAction = OnVisibleAction.RESUME;
} else if (!wasNotVisibleAlready) {
onVisibleAction = OnVisibleAction.NONE;
}
}
return ret;
}
/**
* These Drawable.Callback methods proxy the calls so that this is the drawable that is
* actually invalidated, not a child one which will not pass the view's validateDrawable check.
*/
@Override
public void invalidateDrawable(@NonNull Drawable who) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.invalidateDrawable(this);
}
@Override
public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.scheduleDrawable(this, what, when);
}
@Override
public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
Callback callback = getCallback();
if (callback == null) {
return;
}
callback.unscheduleDrawable(this, what);
}
/**
* Hardware accelerated render path.
*/
private void drawDirectlyToCanvas(Canvas canvas) {
CompositionLayer compositionLayer = this.compositionLayer;
LottieComposition composition = this.composition;
if (compositionLayer == null || composition == null) {
return;
}
renderingMatrix.reset();
Rect bounds = getBounds();
if (!bounds.isEmpty()) {
// In fitXY mode, the scale doesn't take effect.
float scaleX = bounds.width() / (float) composition.getBounds().width();
float scaleY = bounds.height() / (float) composition.getBounds().height();
renderingMatrix.preScale(scaleX, scaleY);
renderingMatrix.preTranslate(bounds.left, bounds.top);
}
compositionLayer.draw(canvas, renderingMatrix, alpha);
}
/**
* Software accelerated render path.
* <p>
* This draws the animation to an internally managed bitmap and then draws the bitmap to the original canvas.
*
* @see LottieAnimationView#setRenderMode(RenderMode)
*/
private void renderAndDrawAsBitmap(Canvas originalCanvas, CompositionLayer compositionLayer) {
if (composition == null || compositionLayer == null) {
return;
}
ensureSoftwareRenderingObjectsInitialized();
//noinspection deprecation
originalCanvas.getMatrix(softwareRenderingOriginalCanvasMatrix);
// Get the canvas clip bounds and map it to the coordinate space of canvas with it's current transform.
originalCanvas.getClipBounds(canvasClipBounds);
convertRect(canvasClipBounds, canvasClipBoundsRectF);
softwareRenderingOriginalCanvasMatrix.mapRect(canvasClipBoundsRectF);
convertRect(canvasClipBoundsRectF, canvasClipBounds);
if (clipToCompositionBounds) {
// Start with the intrinsic bounds. This will later be unioned with the clip bounds to find the
// smallest possible render area.
softwareRenderingTransformedBounds.set(0f, 0f, getIntrinsicWidth(), getIntrinsicHeight());
} else {
// Calculate the full bounds of the animation.
compositionLayer.getBounds(softwareRenderingTransformedBounds, null, false);
}
// Transform the animation bounds to the bounds that they will render to on the canvas.
softwareRenderingOriginalCanvasMatrix.mapRect(softwareRenderingTransformedBounds);
// The bounds are usually intrinsicWidth x intrinsicHeight. If they are different, an external source is scaling this drawable.
// This is how ImageView.ScaleType.FIT_XY works.
Rect bounds = getBounds();
float scaleX = bounds.width() / (float) getIntrinsicWidth();
float scaleY = bounds.height() / (float) getIntrinsicHeight();
scaleRect(softwareRenderingTransformedBounds, scaleX, scaleY);
if (!ignoreCanvasClipBounds()) {
softwareRenderingTransformedBounds.intersect(canvasClipBounds.left, canvasClipBounds.top, canvasClipBounds.right, canvasClipBounds.bottom);
}
int renderWidth = (int) Math.ceil(softwareRenderingTransformedBounds.width());
int renderHeight = (int) Math.ceil(softwareRenderingTransformedBounds.height());
if (renderWidth <= 0 || renderHeight <= 0) {
return;
}
ensureSoftwareRenderingBitmap(renderWidth, renderHeight);
if (isDirty) {
renderingMatrix.set(softwareRenderingOriginalCanvasMatrix);
renderingMatrix.preScale(scaleX, scaleY);
// We want to render the smallest bitmap possible. If the animation doesn't start at the top left, we translate the canvas and shrink the
// bitmap to avoid allocating and copying the empty space on the left and top. renderWidth and renderHeight take this into account.
renderingMatrix.postTranslate(-softwareRenderingTransformedBounds.left, -softwareRenderingTransformedBounds.top);
softwareRenderingBitmap.eraseColor(0);
compositionLayer.draw(softwareRenderingCanvas, renderingMatrix, alpha);
// Calculate the dst bounds.
// We need to map the rendered coordinates back to the canvas's coordinates. To do so, we need to invert the transform
// of the original canvas.
// Take the bounds of the rendered animation and map them to the canvas's coordinates.
// This is similar to the src rect above but the src bound may have a left and top offset.
softwareRenderingOriginalCanvasMatrix.invert(softwareRenderingOriginalCanvasMatrixInverse);
softwareRenderingOriginalCanvasMatrixInverse.mapRect(softwareRenderingDstBoundsRectF, softwareRenderingTransformedBounds);
convertRect(softwareRenderingDstBoundsRectF, softwareRenderingDstBoundsRect);
}
softwareRenderingSrcBoundsRect.set(0, 0, renderWidth, renderHeight);
originalCanvas.drawBitmap(softwareRenderingBitmap, softwareRenderingSrcBoundsRect, softwareRenderingDstBoundsRect, softwareRenderingPaint);
}
private void ensureSoftwareRenderingObjectsInitialized() {
if (softwareRenderingCanvas != null) {
return;
}
softwareRenderingCanvas = new Canvas();
softwareRenderingTransformedBounds = new RectF();
softwareRenderingOriginalCanvasMatrix = new Matrix();
softwareRenderingOriginalCanvasMatrixInverse = new Matrix();
canvasClipBounds = new Rect();
canvasClipBoundsRectF = new RectF();
softwareRenderingPaint = new LPaint();
softwareRenderingSrcBoundsRect = new Rect();
softwareRenderingDstBoundsRect = new Rect();
softwareRenderingDstBoundsRectF = new RectF();
}
private void ensureSoftwareRenderingBitmap(int renderWidth, int renderHeight) {
if (softwareRenderingBitmap == null ||
softwareRenderingBitmap.getWidth() < renderWidth ||
softwareRenderingBitmap.getHeight() < renderHeight) {
// The bitmap is larger. We need to create a new one.
softwareRenderingBitmap = Bitmap.createBitmap(renderWidth, renderHeight, Bitmap.Config.ARGB_8888);
softwareRenderingCanvas.setBitmap(softwareRenderingBitmap);
isDirty = true;
} else if (softwareRenderingBitmap.getWidth() > renderWidth || softwareRenderingBitmap.getHeight() > renderHeight) {
// The bitmap is smaller. Take subset of the original.
softwareRenderingBitmap = Bitmap.createBitmap(softwareRenderingBitmap, 0, 0, renderWidth, renderHeight);
softwareRenderingCanvas.setBitmap(softwareRenderingBitmap);
isDirty = true;
}
}
/**
* Convert a RectF to a Rect
*/
private void convertRect(RectF src, Rect dst) {
dst.set(
(int) Math.floor(src.left),
(int) Math.floor(src.top),
(int) Math.ceil(src.right),
(int) Math.ceil(src.bottom)
);
}
/**
* Convert a Rect to a RectF
*/
private void convertRect(Rect src, RectF dst) {
dst.set(
src.left,
src.top,
src.right,
src.bottom);
}
private void scaleRect(RectF rect, float scaleX, float scaleY) {
rect.set(
rect.left * scaleX,
rect.top * scaleY,
rect.right * scaleX,
rect.bottom * scaleY
);
}
/**
* When a View's parent has clipChildren set to false, it doesn't affect the clipBound
* of its child canvases so we should explicitly check for it and draw the full animation
* bounds instead.
*/
private boolean ignoreCanvasClipBounds() {
Callback callback = getCallback();
if (!(callback instanceof View)) {
// If the callback isn't a view then respect the canvas's clip bounds.
return false;
}
ViewParent parent = ((View) callback).getParent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && parent instanceof ViewGroup) {
return !((ViewGroup) parent).getClipChildren();
}
// Unlikely to ever happen. If the callback is a View, its parent should be a ViewGroup.
return false;
}
}
| 2,422 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieImageAsset.java | package com.airbnb.lottie;
import android.graphics.Bitmap;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
/**
* Data class describing an image asset embedded in a Lottie json file.
*/
public class LottieImageAsset {
private final int width;
private final int height;
private final String id;
private final String fileName;
private final String dirName;
/**
* Pre-set a bitmap for this asset
*/
@Nullable private Bitmap bitmap;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public LottieImageAsset(int width, int height, String id, String fileName, String dirName) {
this.width = width;
this.height = height;
this.id = id;
this.fileName = fileName;
this.dirName = dirName;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
/**
* The reference id in the json file.
*/
public String getId() {
return id;
}
public String getFileName() {
return fileName;
}
@SuppressWarnings("unused") public String getDirName() {
return dirName;
}
/**
* Returns the bitmap that has been stored for this image asset if one was explicitly set.
*/
@Nullable public Bitmap getBitmap() {
return bitmap;
}
/**
* Permanently sets the bitmap on this LottieImageAsset. This will:
* 1) Overwrite any existing Bitmaps.
* 2) Apply to *all* animations that use this LottieComposition.
*
* If you only want to replace the bitmap for this animation, use dynamic properties
* with {@link LottieProperty#IMAGE}.
*/
public void setBitmap(@Nullable Bitmap bitmap) {
this.bitmap = bitmap;
}
/**
* Returns whether this asset has an embedded Bitmap or whether the fileName is a base64 encoded bitmap.
*/
public boolean hasBitmap() {
return bitmap != null || (fileName.startsWith("data:") && fileName.indexOf("base64,") > 0);
}
}
| 2,423 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/FontAssetDelegate.java | package com.airbnb.lottie;
import android.graphics.Typeface;
/**
* Delegate to handle the loading of fonts that are not packaged in the assets of your app or don't
* have the same file name.
*
* @see LottieDrawable#setFontAssetDelegate(FontAssetDelegate)
*/
@SuppressWarnings({"unused", "WeakerAccess"}) public class FontAssetDelegate {
/**
* Override this if you want to return a Typeface from a font family.
*/
public Typeface fetchFont(String fontFamily) {
return null;
}
/**
* Override this if you want to return a Typeface from a font family and style.
*/
public Typeface fetchFont(String fontFamily, String fontStyle, String fontName) {
return null;
}
/**
* Override this if you want to specify the asset path for a given font family.
*/
public String getFontPath(String fontFamily) {
return null;
}
/**
* Override this if you want to specify the asset path for a given font family and style.
*/
public String getFontPath(String fontFamily, String fontStyle, String fontName) {
return null;
}
}
| 2,424 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieResult.java | package com.airbnb.lottie;
import androidx.annotation.Nullable;
import java.util.Arrays;
/**
* Contains class to hold the resulting value of an async task or an exception if it failed.
* <p>
* Either value or exception will be non-null.
*/
public final class LottieResult<V> {
@Nullable private final V value;
@Nullable private final Throwable exception;
public LottieResult(V value) {
this.value = value;
exception = null;
}
public LottieResult(Throwable exception) {
this.exception = exception;
value = null;
}
@Nullable public V getValue() {
return value;
}
@Nullable public Throwable getException() {
return exception;
}
@Override public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof LottieResult)) {
return false;
}
LottieResult<?> that = (LottieResult<?>) o;
if (getValue() != null && getValue().equals(that.getValue())) {
return true;
}
if (getException() != null && that.getException() != null) {
return getException().toString().equals(getException().toString());
}
return false;
}
@Override public int hashCode() {
return Arrays.hashCode(new Object[]{getValue(), getException()});
}
}
| 2,425 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieCompositionFactory.java | package com.airbnb.lottie;
import static com.airbnb.lottie.utils.Utils.closeQuietly;
import static okio.Okio.buffer;
import static okio.Okio.source;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.util.Base64;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.WorkerThread;
import com.airbnb.lottie.model.Font;
import com.airbnb.lottie.model.LottieCompositionCache;
import com.airbnb.lottie.network.NetworkCache;
import com.airbnb.lottie.parser.LottieCompositionMoshiParser;
import com.airbnb.lottie.parser.moshi.JsonReader;
import com.airbnb.lottie.utils.Logger;
import com.airbnb.lottie.utils.Utils;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import okio.BufferedSource;
import okio.Okio;
/**
* Helpers to create or cache a LottieComposition.
* <p>
* All factory methods take a cache key. The animation will be stored in an LRU cache for future use.
* In-progress tasks will also be held so they can be returned for subsequent requests for the same
* animation prior to the cache being populated.
*/
@SuppressWarnings({"WeakerAccess", "unused", "NullAway"})
public class LottieCompositionFactory {
/**
* Keep a map of cache keys to in-progress tasks and return them for new requests.
* Without this, simultaneous requests to parse a composition will trigger multiple parallel
* parse tasks prior to the cache getting populated.
*/
private static final Map<String, LottieTask<LottieComposition>> taskCache = new HashMap<>();
private static final Set<LottieTaskIdleListener> taskIdleListeners = new HashSet<>();
/**
* reference magic bytes for zip compressed files.
* useful to determine if an InputStream is a zip file or not
*/
private static final byte[] MAGIC = new byte[]{0x50, 0x4b, 0x03, 0x04};
private LottieCompositionFactory() {
}
/**
* Set the maximum number of compositions to keep cached in memory.
* This must be {@literal >} 0.
*/
public static void setMaxCacheSize(int size) {
LottieCompositionCache.getInstance().resize(size);
}
public static void clearCache(Context context) {
taskCache.clear();
LottieCompositionCache.getInstance().clear();
final NetworkCache networkCache = L.networkCache(context);
if (networkCache != null) {
networkCache.clear();
}
}
/**
* Use this to register a callback for when the composition factory is idle or not.
* This can be used to provide data to an espresso idling resource.
* Refer to FragmentVisibilityTests and its LottieIdlingResource in the Lottie repo for
* an example.
*/
public static void registerLottieTaskIdleListener(LottieTaskIdleListener listener) {
taskIdleListeners.add(listener);
listener.onIdleChanged(taskCache.size() == 0);
}
public static void unregisterLottieTaskIdleListener(LottieTaskIdleListener listener) {
taskIdleListeners.remove(listener);
}
/**
* Fetch an animation from an http url. Once it is downloaded once, Lottie will cache the file to disk for
* future use. Because of this, you may call `fromUrl` ahead of time to warm the cache if you think you
* might need an animation in the future.
* <p>
* To skip the cache, add null as a third parameter.
*/
public static LottieTask<LottieComposition> fromUrl(final Context context, final String url) {
return fromUrl(context, url, "url_" + url);
}
/**
* Fetch an animation from an http url. Once it is downloaded once, Lottie will cache the file to disk for
* future use. Because of this, you may call `fromUrl` ahead of time to warm the cache if you think you
* might need an animation in the future.
*/
public static LottieTask<LottieComposition> fromUrl(final Context context, final String url, @Nullable final String cacheKey) {
return cache(cacheKey, () -> {
LottieResult<LottieComposition> result = L.networkFetcher(context).fetchSync(context, url, cacheKey);
if (cacheKey != null && result.getValue() != null) {
LottieCompositionCache.getInstance().put(cacheKey, result.getValue());
}
return result;
}, null);
}
/**
* Fetch an animation from an http url. Once it is downloaded once, Lottie will cache the file to disk for
* future use. Because of this, you may call `fromUrl` ahead of time to warm the cache if you think you
* might need an animation in the future.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromUrlSync(Context context, String url) {
return fromUrlSync(context, url, url);
}
/**
* Fetch an animation from an http url. Once it is downloaded once, Lottie will cache the file to disk for
* future use. Because of this, you may call `fromUrl` ahead of time to warm the cache if you think you
* might need an animation in the future.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromUrlSync(Context context, String url, @Nullable String cacheKey) {
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
return new LottieResult<>(cachedComposition);
}
LottieResult<LottieComposition> result = L.networkFetcher(context).fetchSync(context, url, cacheKey);
if (cacheKey != null && result.getValue() != null) {
LottieCompositionCache.getInstance().put(cacheKey, result.getValue());
}
return result;
}
/**
* Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
* The asset file name will be used as a cache key so future usages won't have to parse the json again.
* However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
* <p>
* To skip the cache, add null as a third parameter.
*
* @see #fromZipStream(ZipInputStream, String)
*/
public static LottieTask<LottieComposition> fromAsset(Context context, final String fileName) {
String cacheKey = "asset_" + fileName;
return fromAsset(context, fileName, cacheKey);
}
/**
* Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
* The asset file name will be used as a cache key so future usages won't have to parse the json again.
* However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
* <p>
* Pass null as the cache key to skip the cache.
*
* @see #fromZipStream(ZipInputStream, String)
*/
public static LottieTask<LottieComposition> fromAsset(Context context, final String fileName, @Nullable final String cacheKey) {
// Prevent accidentally leaking an Activity.
final Context appContext = context.getApplicationContext();
return cache(cacheKey, () -> fromAssetSync(appContext, fileName, cacheKey), null);
}
/**
* Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
* The asset file name will be used as a cache key so future usages won't have to parse the json again.
* However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
* <p>
* To skip the cache, add null as a third parameter.
*
* @see #fromZipStreamSync(Context, ZipInputStream, String)
*/
@WorkerThread
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName) {
String cacheKey = "asset_" + fileName;
return fromAssetSync(context, fileName, cacheKey);
}
/**
* Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
* The asset file name will be used as a cache key so future usages won't have to parse the json again.
* However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
* <p>
* Pass null as the cache key to skip the cache.
*
* @see #fromZipStreamSync(Context, ZipInputStream, String)
*/
@WorkerThread
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName, @Nullable String cacheKey) {
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
return new LottieResult<>(cachedComposition);
}
try {
if (fileName.endsWith(".zip") || fileName.endsWith(".lottie")) {
return fromZipStreamSync(context, new ZipInputStream(context.getAssets().open(fileName)), cacheKey);
}
return fromJsonInputStreamSync(context.getAssets().open(fileName), cacheKey);
} catch (IOException e) {
return new LottieResult<>(e);
}
}
/**
* Parse an animation from raw/res. This is recommended over putting your animation in assets because
* it uses a hard reference to R.
* The resource id will be used as a cache key so future usages won't parse the json again.
* Note: to correctly load dark mode (-night) resources, make sure you pass Activity as a context (instead of e.g. the application context).
* The Activity won't be leaked.
* <p>
* To skip the cache, add null as a third parameter.
*/
public static LottieTask<LottieComposition> fromRawRes(Context context, @RawRes final int rawRes) {
return fromRawRes(context, rawRes, rawResCacheKey(context, rawRes));
}
/**
* Parse an animation from raw/res. This is recommended over putting your animation in assets because
* it uses a hard reference to R.
* The resource id will be used as a cache key so future usages won't parse the json again.
* Note: to correctly load dark mode (-night) resources, make sure you pass Activity as a context (instead of e.g. the application context).
* The Activity won't be leaked.
* <p>
* Pass null as the cache key to skip caching.
*/
public static LottieTask<LottieComposition> fromRawRes(Context context, @RawRes final int rawRes, @Nullable final String cacheKey) {
// Prevent accidentally leaking an Activity.
final WeakReference<Context> contextRef = new WeakReference<>(context);
final Context appContext = context.getApplicationContext();
return cache(cacheKey, () -> {
@Nullable Context originalContext = contextRef.get();
Context context1 = originalContext != null ? originalContext : appContext;
return fromRawResSync(context1, rawRes, cacheKey);
}, null);
}
/**
* Parse an animation from raw/res. This is recommended over putting your animation in assets because
* it uses a hard reference to R.
* The resource id will be used as a cache key so future usages won't parse the json again.
* Note: to correctly load dark mode (-night) resources, make sure you pass Activity as a context (instead of e.g. the application context).
* The Activity won't be leaked.
* <p>
* To skip the cache, add null as a third parameter.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromRawResSync(Context context, @RawRes int rawRes) {
return fromRawResSync(context, rawRes, rawResCacheKey(context, rawRes));
}
/**
* Parse an animation from raw/res. This is recommended over putting your animation in assets because
* it uses a hard reference to R.
* The resource id will be used as a cache key so future usages won't parse the json again.
* Note: to correctly load dark mode (-night) resources, make sure you pass Activity as a context (instead of e.g. the application context).
* The Activity won't be leaked.
* <p>
* Pass null as the cache key to skip caching.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromRawResSync(Context context, @RawRes int rawRes, @Nullable String cacheKey) {
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
return new LottieResult<>(cachedComposition);
}
try {
BufferedSource source = Okio.buffer(source(context.getResources().openRawResource(rawRes)));
if (isZipCompressed(source)) {
return fromZipStreamSync(context, new ZipInputStream(source.inputStream()), cacheKey);
}
return fromJsonInputStreamSync(source.inputStream(), cacheKey);
} catch (Resources.NotFoundException e) {
return new LottieResult<>(e);
}
}
private static String rawResCacheKey(Context context, @RawRes int resId) {
return "rawRes" + (isNightMode(context) ? "_night_" : "_day_") + resId;
}
/**
* It is important to include day/night in the cache key so that if it changes, the cache won't return an animation from the wrong bucket.
*/
private static boolean isNightMode(Context context) {
int nightModeMasked = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
return nightModeMasked == Configuration.UI_MODE_NIGHT_YES;
}
/**
* Auto-closes the stream.
*
* @see #fromJsonInputStreamSync(InputStream, String, boolean)
*/
public static LottieTask<LottieComposition> fromJsonInputStream(final InputStream stream, @Nullable final String cacheKey) {
return cache(cacheKey, () -> fromJsonInputStreamSync(stream, cacheKey), () -> closeQuietly(stream));
}
/**
* @see #fromJsonInputStreamSync(InputStream, String, boolean)
*/
public static LottieTask<LottieComposition> fromJsonInputStream(final InputStream stream, @Nullable final String cacheKey, boolean close) {
return cache(cacheKey, () -> fromJsonInputStreamSync(stream, cacheKey, close), () -> {
if (close) {
closeQuietly(stream);
}
});
}
/**
* Return a LottieComposition for the given InputStream to json.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromJsonInputStreamSync(InputStream stream, @Nullable String cacheKey) {
return fromJsonInputStreamSync(stream, cacheKey, true);
}
/**
* Return a LottieComposition for the given InputStream to json.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromJsonInputStreamSync(InputStream stream, @Nullable String cacheKey, boolean close) {
return fromJsonReaderSync(JsonReader.of(buffer(source(stream))), cacheKey, close);
}
/**
* @see #fromJsonSync(JSONObject, String)
*/
@Deprecated
public static LottieTask<LottieComposition> fromJson(final JSONObject json, @Nullable final String cacheKey) {
return cache(cacheKey, () -> {
//noinspection deprecation
return fromJsonSync(json, cacheKey);
}, null);
}
/**
* Prefer passing in the json string directly. This method just calls `toString()` on your JSONObject.
* If you are loading this animation from the network, just use the response body string instead of
* parsing it first for improved performance.
*/
@Deprecated
@WorkerThread
public static LottieResult<LottieComposition> fromJsonSync(JSONObject json, @Nullable String cacheKey) {
return fromJsonStringSync(json.toString(), cacheKey);
}
/**
* @see #fromJsonStringSync(String, String)
*/
public static LottieTask<LottieComposition> fromJsonString(final String json, @Nullable final String cacheKey) {
return cache(cacheKey, () -> fromJsonStringSync(json, cacheKey), null);
}
/**
* Return a LottieComposition for the specified raw json string.
* If loading from a file, it is preferable to use the InputStream or rawRes version.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromJsonStringSync(String json, @Nullable String cacheKey) {
ByteArrayInputStream stream = new ByteArrayInputStream(json.getBytes());
return fromJsonReaderSync(JsonReader.of(buffer(source(stream))), cacheKey);
}
public static LottieTask<LottieComposition> fromJsonReader(final JsonReader reader, @Nullable final String cacheKey) {
return cache(cacheKey, () -> fromJsonReaderSync(reader, cacheKey), () -> Utils.closeQuietly(reader));
}
@WorkerThread
public static LottieResult<LottieComposition> fromJsonReaderSync(com.airbnb.lottie.parser.moshi.JsonReader reader, @Nullable String cacheKey) {
return fromJsonReaderSync(reader, cacheKey, true);
}
@WorkerThread
public static LottieResult<LottieComposition> fromJsonReaderSync(com.airbnb.lottie.parser.moshi.JsonReader reader, @Nullable String cacheKey, boolean close) {
return fromJsonReaderSyncInternal(reader, cacheKey, close);
}
private static LottieResult<LottieComposition> fromJsonReaderSyncInternal(
com.airbnb.lottie.parser.moshi.JsonReader reader, @Nullable String cacheKey, boolean close) {
try {
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
return new LottieResult<>(cachedComposition);
}
LottieComposition composition = LottieCompositionMoshiParser.parse(reader);
if (cacheKey != null) {
LottieCompositionCache.getInstance().put(cacheKey, composition);
}
return new LottieResult<>(composition);
} catch (Exception e) {
return new LottieResult<>(e);
} finally {
if (close) {
closeQuietly(reader);
}
}
}
/**
* In this overload, embedded fonts will NOT be parsed. If your zip file has custom fonts, use the overload
* that takes Context as the first parameter.
*/
public static LottieTask<LottieComposition> fromZipStream(final ZipInputStream inputStream, @Nullable final String cacheKey) {
return fromZipStream(null, inputStream, cacheKey);
}
/**
* In this overload, embedded fonts will NOT be parsed. If your zip file has custom fonts, use the overload
* that takes Context as the first parameter.
*/
public static LottieTask<LottieComposition> fromZipStream(final ZipInputStream inputStream, @Nullable final String cacheKey, boolean close) {
return fromZipStream(null, inputStream, cacheKey, close);
}
/**
* @see #fromZipStreamSync(Context, ZipInputStream, String)
*/
public static LottieTask<LottieComposition> fromZipStream(Context context, final ZipInputStream inputStream, @Nullable final String cacheKey) {
return cache(cacheKey, () -> fromZipStreamSync(context, inputStream, cacheKey), () -> closeQuietly(inputStream));
}
/**
* @see #fromZipStreamSync(Context, ZipInputStream, String)
*/
public static LottieTask<LottieComposition> fromZipStream(Context context, final ZipInputStream inputStream,
@Nullable final String cacheKey, boolean close) {
return cache(cacheKey, () -> fromZipStreamSync(context, inputStream, cacheKey), close ? () -> closeQuietly(inputStream) : null);
}
/**
* Parses a zip input stream into a Lottie composition.
* Your zip file should just be a folder with your json file and images zipped together.
* It will automatically store and configure any images inside the animation if they exist.
* <p>
* In this overload, embedded fonts will NOT be parsed. If your zip file has custom fonts, use the overload
* that takes Context as the first parameter.
* <p>
* The ZipInputStream will be automatically closed at the end. If you would like to keep it open, use the overload
* with a close parameter and pass in false.
*/
public static LottieResult<LottieComposition> fromZipStreamSync(ZipInputStream inputStream, @Nullable String cacheKey) {
return fromZipStreamSync(inputStream, cacheKey, true);
}
/**
* Parses a zip input stream into a Lottie composition.
* Your zip file should just be a folder with your json file and images zipped together.
* It will automatically store and configure any images inside the animation if they exist.
* <p>
* In this overload, embedded fonts will NOT be parsed. If your zip file has custom fonts, use the overload
* that takes Context as the first parameter.
*/
public static LottieResult<LottieComposition> fromZipStreamSync(ZipInputStream inputStream, @Nullable String cacheKey, boolean close) {
return fromZipStreamSync(null, inputStream, cacheKey, close);
}
/**
* Parses a zip input stream into a Lottie composition.
* Your zip file should just be a folder with your json file and images zipped together.
* It will automatically store and configure any images inside the animation if they exist.
* <p>
* The ZipInputStream will be automatically closed at the end. If you would like to keep it open, use the overload
* with a close parameter and pass in false.
*
* @param context is optional and only needed if your zip file contains ttf or otf fonts. If yours doesn't, you may pass null.
* Embedded fonts may be .ttf or .otf files, can be in subdirectories, but must have the same name as the
* font family (fFamily) in your animation file.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromZipStreamSync(@Nullable Context context, ZipInputStream inputStream, @Nullable String cacheKey) {
return fromZipStreamSync(context, inputStream, cacheKey, true);
}
/**
* Parses a zip input stream into a Lottie composition.
* Your zip file should just be a folder with your json file and images zipped together.
* It will automatically store and configure any images inside the animation if they exist.
*
* @param context is optional and only needed if your zip file contains ttf or otf fonts. If yours doesn't, you may pass null.
* Embedded fonts may be .ttf or .otf files, can be in subdirectories, but must have the same name as the
* font family (fFamily) in your animation file.
*/
@WorkerThread
public static LottieResult<LottieComposition> fromZipStreamSync(@Nullable Context context, ZipInputStream inputStream,
@Nullable String cacheKey, boolean close) {
try {
return fromZipStreamSyncInternal(context, inputStream, cacheKey);
} finally {
if (close) {
closeQuietly(inputStream);
}
}
}
@WorkerThread
private static LottieResult<LottieComposition> fromZipStreamSyncInternal(Context context, ZipInputStream inputStream, @Nullable String cacheKey) {
LottieComposition composition = null;
Map<String, Bitmap> images = new HashMap<>();
Map<String, Typeface> fonts = new HashMap<>();
try {
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
return new LottieResult<>(cachedComposition);
}
ZipEntry entry = inputStream.getNextEntry();
while (entry != null) {
final String entryName = entry.getName();
if (entryName.contains("__MACOSX")) {
inputStream.closeEntry();
} else if (entry.getName().equalsIgnoreCase("manifest.json")) { //ignore .lottie manifest
inputStream.closeEntry();
} else if (entry.getName().contains(".json")) {
com.airbnb.lottie.parser.moshi.JsonReader reader = JsonReader.of(buffer(source(inputStream)));
composition = LottieCompositionFactory.fromJsonReaderSyncInternal(reader, null, false).getValue();
} else if (entryName.contains(".png") || entryName.contains(".webp") || entryName.contains(".jpg") || entryName.contains(".jpeg")) {
String[] splitName = entryName.split("/");
String name = splitName[splitName.length - 1];
images.put(name, BitmapFactory.decodeStream(inputStream));
} else if (entryName.contains(".ttf") || entryName.contains(".otf")) {
String[] splitName = entryName.split("/");
String fileName = splitName[splitName.length - 1];
String fontFamily = fileName.split("\\.")[0];
File tempFile = new File(context.getCacheDir(), fileName);
FileOutputStream fos = new FileOutputStream(tempFile);
try {
try (OutputStream output = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
}
} catch (Throwable e) {
Logger.warning("Unable to save font " + fontFamily + " to the temporary file: " + fileName + ". ", e);
}
Typeface typeface = Typeface.createFromFile(tempFile);
if (!tempFile.delete()) {
Logger.warning("Failed to delete temp font file " + tempFile.getAbsolutePath() + ".");
}
fonts.put(fontFamily, typeface);
} else {
inputStream.closeEntry();
}
entry = inputStream.getNextEntry();
}
} catch (IOException e) {
return new LottieResult<>(e);
}
if (composition == null) {
return new LottieResult<>(new IllegalArgumentException("Unable to parse composition"));
}
for (Map.Entry<String, Bitmap> e : images.entrySet()) {
LottieImageAsset imageAsset = findImageAssetForFileName(composition, e.getKey());
if (imageAsset != null) {
imageAsset.setBitmap(Utils.resizeBitmapIfNeeded(e.getValue(), imageAsset.getWidth(), imageAsset.getHeight()));
}
}
for (Map.Entry<String, Typeface> e : fonts.entrySet()) {
boolean found = false;
for (Font font : composition.getFonts().values()) {
if (font.getFamily().equals(e.getKey())) {
found = true;
font.setTypeface(e.getValue());
}
}
if (!found) {
Logger.warning("Parsed font for " + e.getKey() + " however it was not found in the animation.");
}
}
if (images.isEmpty()) {
for (Map.Entry<String, LottieImageAsset> entry : composition.getImages().entrySet()) {
LottieImageAsset asset = entry.getValue();
if (asset == null) {
return null;
}
String filename = asset.getFileName();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = true;
opts.inDensity = 160;
if (filename.startsWith("data:") && filename.indexOf("base64,") > 0) {
// Contents look like a base64 data URI, with the format data:image/png;base64,<data>.
byte[] data;
try {
data = Base64.decode(filename.substring(filename.indexOf(',') + 1), Base64.DEFAULT);
} catch (IllegalArgumentException e) {
Logger.warning("data URL did not have correct base64 format.", e);
return null;
}
asset.setBitmap(BitmapFactory.decodeByteArray(data, 0, data.length, opts));
}
}
}
if (cacheKey != null) {
LottieCompositionCache.getInstance().put(cacheKey, composition);
}
return new LottieResult<>(composition);
}
/**
* Check if a given InputStream points to a .zip compressed file
*/
private static Boolean isZipCompressed(BufferedSource inputSource) {
try {
BufferedSource peek = inputSource.peek();
for (byte b : MAGIC) {
if (peek.readByte() != b) {
return false;
}
}
peek.close();
return true;
} catch (NoSuchMethodError e) {
// This happens in the Android Studio layout preview.
return false;
} catch (Exception e) {
Logger.error("Failed to check zip file header", e);
return false;
}
}
@Nullable
private static LottieImageAsset findImageAssetForFileName(LottieComposition composition, String fileName) {
for (LottieImageAsset asset : composition.getImages().values()) {
if (asset.getFileName().equals(fileName)) {
return asset;
}
}
return null;
}
/**
* First, check to see if there are any in-progress tasks associated with the cache key and return it if there is.
* If not, create a new task for the callable.
* Then, add the new task to the task cache and set up listeners so it gets cleared when done.
*/
private static LottieTask<LottieComposition> cache(@Nullable final String cacheKey, Callable<LottieResult<LottieComposition>> callable,
@Nullable Runnable onCached) {
LottieTask<LottieComposition> task = null;
final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
if (cachedComposition != null) {
task = new LottieTask<>(() -> new LottieResult<>(cachedComposition));
}
if (cacheKey != null && taskCache.containsKey(cacheKey)) {
task = taskCache.get(cacheKey);
}
if (task != null) {
if (onCached != null) {
onCached.run();
}
return task;
}
task = new LottieTask<>(callable);
if (cacheKey != null) {
AtomicBoolean resultAlreadyCalled = new AtomicBoolean(false);
task.addListener(result -> {
taskCache.remove(cacheKey);
resultAlreadyCalled.set(true);
if (taskCache.size() == 0) {
notifyTaskCacheIdleListeners(true);
}
});
task.addFailureListener(result -> {
taskCache.remove(cacheKey);
resultAlreadyCalled.set(true);
if (taskCache.size() == 0) {
notifyTaskCacheIdleListeners(true);
}
});
// It is technically possible for the task to finish and for the listeners to get called
// before this code runs. If this happens, the task will be put in taskCache but never removed.
// This would require this thread to be sleeping at exactly this point in the code
// for long enough for the task to finish and call the listeners. Unlikely but not impossible.
if (!resultAlreadyCalled.get()) {
taskCache.put(cacheKey, task);
if (taskCache.size() == 1) {
notifyTaskCacheIdleListeners(false);
}
}
}
return task;
}
private static void notifyTaskCacheIdleListeners(boolean idle) {
List<LottieTaskIdleListener> listeners = new ArrayList<>(taskIdleListeners);
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onIdleChanged(idle);
}
}
}
| 2,426 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/AsyncUpdates.java | package com.airbnb.lottie;
/**
* **Note: this API is experimental and may changed.**
* <p/>
* When async updates are enabled, parts of animation updates will happen off of the main thread.
* <p/>
* At a high level, during the animation loop, there are two main code paths:
* 1. setProgress
* 2. draw
* <p/>
* setProgress is called on every frame when the internal animator updates or if you manually call setProgress.
* setProgress must then iterate through every single node in the animation (every shape, fill, mask, stroke, etc.)
* and call setProgress on it. When progress is set on a node, it will:
* 1. Call the dynamic property value callback if one has been set by you.
* 2. Recalculate what its own progress is. Various animation features like interpolators or time remapping
* will cause the progress value for a given node to be different than the top level progress.
* 3. If a node's progress has changed, it will call invalidate which will invalidate values that are
* cached and derived from that node's progress and then bubble up the invalidation to LottieDrawable
* to ensure that Android renders a new frame.
* <p/>
* draw is what actually draws your animation to a canvas. Many of Lottie's operations are completed or
* cached in the setProgress path. However, there are a few things (like parentMatrix) that Lottie only has access
* to in the draw path and it, of course, needs to actually execute the canvas operations to draw the animation.
* <p/>
* Without async updates, in a single main thread frame, Lottie will call setProgress immediately followed by draw.
* <p/>
* With async updates, Lottie will determine if the most recent setProgress is still close enough to be considered
* valid. An existing progress will be considered valid if it is within LottieDrawable.MAX_DELTA_MS_ASYNC_SET_PROGRESS
* milliseconds from the current actual progress.
* If the calculated progress is close enough, it will only execute draw. Once draw completes, it will schedule a
* setProgress to be run on a background thread immediately after draw finishes and it will likely complete well
* before the next frame starts.
* <p/>
* The background thread is created via LottieDrawable.setProgressExecutor. You can refer to it for the current default
* thread pool configuration.
*/
public enum AsyncUpdates {
/**
* Default value.
* <p/>
* This will default to DISABLED until this feature has had time to incubate.
* The behavior of AUTOMATIC may change over time.
*/
AUTOMATIC,
/**
* Use the async update path. Refer to the docs for {@link AsyncUpdates} for more details.
*/
ENABLED,
/**
* Do not use the async update path. Refer to the docs for {@link AsyncUpdates} for more details.
*/
DISABLED,
}
| 2,427 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/LottieConfig.java | package com.airbnb.lottie;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.network.LottieNetworkCacheProvider;
import com.airbnb.lottie.network.LottieNetworkFetcher;
import java.io.File;
/**
* Class for custom library configuration.
* <p>
* This should be constructed with {@link LottieConfig.Builder}
*/
public class LottieConfig {
@Nullable final LottieNetworkFetcher networkFetcher;
@Nullable final LottieNetworkCacheProvider cacheProvider;
final boolean enableSystraceMarkers;
final boolean enableNetworkCache;
final boolean disablePathInterpolatorCache;
final AsyncUpdates defaultAsyncUpdates;
private LottieConfig(@Nullable LottieNetworkFetcher networkFetcher, @Nullable LottieNetworkCacheProvider cacheProvider,
boolean enableSystraceMarkers, boolean enableNetworkCache, boolean disablePathInterpolatorCache,
AsyncUpdates defaultAsyncUpdates) {
this.networkFetcher = networkFetcher;
this.cacheProvider = cacheProvider;
this.enableSystraceMarkers = enableSystraceMarkers;
this.enableNetworkCache = enableNetworkCache;
this.disablePathInterpolatorCache = disablePathInterpolatorCache;
this.defaultAsyncUpdates = defaultAsyncUpdates;
}
public static final class Builder {
@Nullable
private LottieNetworkFetcher networkFetcher;
@Nullable
private LottieNetworkCacheProvider cacheProvider;
private boolean enableSystraceMarkers = false;
private boolean enableNetworkCache = true;
private boolean disablePathInterpolatorCache = true;
private AsyncUpdates defaultAsyncUpdates = AsyncUpdates.AUTOMATIC;
/**
* Lottie has a default network fetching stack built on {@link java.net.HttpURLConnection}. However, if you would like to hook into your own
* network stack for performance, caching, or analytics, you may replace the internal stack with your own.
*/
@NonNull
public Builder setNetworkFetcher(@NonNull LottieNetworkFetcher fetcher) {
this.networkFetcher = fetcher;
return this;
}
/**
* Provide your own network cache directory. By default, animations will be saved in your application's cacheDir/lottie_network_cache.
*
* @see #setNetworkCacheProvider(LottieNetworkCacheProvider)
*/
@NonNull
public Builder setNetworkCacheDir(@NonNull final File file) {
if (cacheProvider != null) {
throw new IllegalStateException("There is already a cache provider!");
}
cacheProvider = new LottieNetworkCacheProvider() {
@Override @NonNull public File getCacheDir() {
if (!file.isDirectory()) {
throw new IllegalArgumentException("cache file must be a directory");
}
return file;
}
};
return this;
}
/**
* Provide your own network cache provider. By default, animations will be saved in your application's cacheDir/lottie_network_cache.
*/
@NonNull
public Builder setNetworkCacheProvider(@NonNull final LottieNetworkCacheProvider fileCacheProvider) {
if (cacheProvider != null) {
throw new IllegalStateException("There is already a cache provider!");
}
cacheProvider = new LottieNetworkCacheProvider() {
@NonNull @Override public File getCacheDir() {
File file = fileCacheProvider.getCacheDir();
if (!file.isDirectory()) {
throw new IllegalArgumentException("cache file must be a directory");
}
return file;
}
};
return this;
}
/**
* Enable this if you want to run systrace to debug the performance of animations.
* <p/>
* DO NOT leave this enabled in production. The overhead is low but non-zero.
*
* @see <a href="https://developer.android.com/topic/performance/tracing/command-line">Systrace Docs</a>
*/
@NonNull
public Builder setEnableSystraceMarkers(boolean enable) {
enableSystraceMarkers = enable;
return this;
}
/**
* Disable this if you want to completely disable internal Lottie cache for retrieving network animations.
* Internal network cache is enabled by default.
*/
@NonNull
public Builder setEnableNetworkCache(boolean enable) {
enableNetworkCache = enable;
return this;
}
/**
* When parsing animations, Lottie has a path interpolator cache. This cache allows Lottie to reuse PathInterpolators
* across an animation. This is desirable in most cases. However, when shared across screenshot tests, it can cause slight
* deviations in the rendering due to underlying approximations in the PathInterpolator.
*
* The cache is enabled by default and should probably only be disabled for screenshot tests.
*/
@NonNull
public Builder setDisablePathInterpolatorCache(boolean disable) {
disablePathInterpolatorCache = disable;
return this;
}
/**
* Sets the default value for async updates.
* @see LottieDrawable#setAsyncUpdates(AsyncUpdates)
*/
@NonNull
public Builder setDefaultAsyncUpdates(AsyncUpdates asyncUpdates) {
defaultAsyncUpdates = asyncUpdates;
return this;
}
@NonNull
public LottieConfig build() {
return new LottieConfig(networkFetcher, cacheProvider, enableSystraceMarkers, enableNetworkCache, disablePathInterpolatorCache,
defaultAsyncUpdates);
}
}
}
| 2,428 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/L.java | package com.airbnb.lottie;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import com.airbnb.lottie.network.DefaultLottieNetworkFetcher;
import com.airbnb.lottie.network.LottieNetworkCacheProvider;
import com.airbnb.lottie.network.LottieNetworkFetcher;
import com.airbnb.lottie.network.NetworkCache;
import com.airbnb.lottie.network.NetworkFetcher;
import com.airbnb.lottie.utils.LottieTrace;
import java.io.File;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class L {
public static boolean DBG = false;
public static final String TAG = "LOTTIE";
private static boolean traceEnabled = false;
private static boolean networkCacheEnabled = true;
private static boolean disablePathInterpolatorCache = true;
private static AsyncUpdates defaultAsyncUpdates = AsyncUpdates.AUTOMATIC;
private static LottieNetworkFetcher fetcher;
private static LottieNetworkCacheProvider cacheProvider;
private static volatile NetworkFetcher networkFetcher;
private static volatile NetworkCache networkCache;
private static ThreadLocal<LottieTrace> lottieTrace;
private L() {
}
public static void setTraceEnabled(boolean enabled) {
if (traceEnabled == enabled) {
return;
}
traceEnabled = enabled;
if (traceEnabled && lottieTrace == null) {
lottieTrace = new ThreadLocal<>();
}
}
public static void setNetworkCacheEnabled(boolean enabled) {
networkCacheEnabled = enabled;
}
public static void beginSection(String section) {
if (!traceEnabled) {
return;
}
getTrace().beginSection(section);
}
public static float endSection(String section) {
if (!traceEnabled) {
return 0;
}
return getTrace().endSection(section);
}
private static LottieTrace getTrace() {
LottieTrace trace = lottieTrace.get();
if (trace == null) {
trace = new LottieTrace();
lottieTrace.set(trace);
}
return trace;
}
public static void setFetcher(LottieNetworkFetcher customFetcher) {
if ((fetcher == null && customFetcher == null) || (fetcher != null && fetcher.equals(customFetcher))) {
return;
}
fetcher = customFetcher;
networkFetcher = null;
}
public static void setCacheProvider(LottieNetworkCacheProvider customProvider) {
if ((cacheProvider == null && customProvider == null) || (cacheProvider != null && cacheProvider.equals(customProvider))) {
return;
}
cacheProvider = customProvider;
networkCache = null;
}
@NonNull
public static NetworkFetcher networkFetcher(@NonNull Context context) {
NetworkFetcher local = networkFetcher;
if (local == null) {
synchronized (NetworkFetcher.class) {
local = networkFetcher;
if (local == null) {
networkFetcher = local = new NetworkFetcher(networkCache(context), fetcher != null ? fetcher : new DefaultLottieNetworkFetcher());
}
}
}
return local;
}
@Nullable
public static NetworkCache networkCache(@NonNull final Context context) {
if (!networkCacheEnabled) {
return null;
}
final Context appContext = context.getApplicationContext();
NetworkCache local = networkCache;
if (local == null) {
synchronized (NetworkCache.class) {
local = networkCache;
if (local == null) {
networkCache = local = new NetworkCache(cacheProvider != null ? cacheProvider :
() -> new File(appContext.getCacheDir(), "lottie_network_cache"));
}
}
}
return local;
}
public static void setDisablePathInterpolatorCache(boolean disablePathInterpolatorCache) {
L.disablePathInterpolatorCache = disablePathInterpolatorCache;
}
public static boolean getDisablePathInterpolatorCache() {
return disablePathInterpolatorCache;
}
public static void setDefaultAsyncUpdates(AsyncUpdates asyncUpdates) {
L.defaultAsyncUpdates = asyncUpdates;
}
public static AsyncUpdates getDefaultAsyncUpdates() {
return L.defaultAsyncUpdates;
}
}
| 2,429 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/TextDelegate.java | package com.airbnb.lottie;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import java.util.HashMap;
import java.util.Map;
/**
* To replace static text in an animation at runtime, create an instance of this class and call {@link #setText(String, String)} to
* replace the hard coded animation text (input) with the text of your choosing (output).
* <p>
* Alternatively, extend this class and override {@link #getText(String)} and if the text hasn't already been set
* by {@link #setText(String, String)} then it will call {@link #getText(String)}.
*/
public class TextDelegate {
private final Map<String, String> stringMap = new HashMap<>();
@Nullable private final LottieAnimationView animationView;
@Nullable private final LottieDrawable drawable;
private boolean cacheText = true;
/**
* This normally needs to be able to invalidate the view/drawable but not for the test.
*/
@VisibleForTesting TextDelegate() {
animationView = null;
drawable = null;
}
public TextDelegate(
@SuppressWarnings("NullableProblems") LottieAnimationView animationView) {
this.animationView = animationView;
drawable = null;
}
@SuppressWarnings("unused")
public TextDelegate(@SuppressWarnings("NullableProblems") LottieDrawable drawable) {
this.drawable = drawable;
animationView = null;
}
/**
* Override this to replace the animation text with something dynamic. This can be used for
* translations or custom data.
* @param layerName the name of the layer with text
* @param input the string at the layer with text
* @return a String to use for the specific data, by default this is the same as getText(input)
*/
public String getText(String layerName, String input) {
return getText(input);
}
/**
* Override this to replace the animation text with something dynamic. This can be used for
* translations or custom data.
*/
public String getText(String input) {
return input;
}
/**
* Update the text that will be rendered for the given input text.
*/
public void setText(String input, String output) {
stringMap.put(input, output);
invalidate();
}
/**
* Sets whether or not {@link TextDelegate} will cache (memoize) the results of getText.
* If this isn't necessary then set it to false.
*/
public void setCacheText(boolean cacheText) {
this.cacheText = cacheText;
}
/**
* Invalidates a cached string with the given input.
*/
public void invalidateText(String input) {
stringMap.remove(input);
invalidate();
}
/**
* Invalidates all cached strings.
*/
public void invalidateAllText() {
stringMap.clear();
invalidate();
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public final String getTextInternal(String layerName, String input) {
if (cacheText && stringMap.containsKey(input)) {
return stringMap.get(input);
}
String text = getText(layerName, input);
if (cacheText) {
stringMap.put(input, text);
}
return text;
}
private void invalidate() {
if (animationView != null) {
animationView.invalidate();
}
if (drawable != null) {
drawable.invalidateSelf();
}
}
}
| 2,430 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/FileExtension.java | package com.airbnb.lottie.network;
import androidx.annotation.RestrictTo;
/**
* Helpers for known Lottie file types.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public enum FileExtension {
JSON(".json"),
ZIP(".zip");
public final String extension;
FileExtension(String extension) {
this.extension = extension;
}
public String tempExtension() {
return ".temp" + extension;
}
@Override public String toString() {
return extension;
}
}
| 2,431 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/NetworkCache.java | package com.airbnb.lottie.network;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.WorkerThread;
import com.airbnb.lottie.utils.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Helper class to save and restore animations fetched from an URL to the app disk cache.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class NetworkCache {
@NonNull
private final LottieNetworkCacheProvider cacheProvider;
public NetworkCache(@NonNull LottieNetworkCacheProvider cacheProvider) {
this.cacheProvider = cacheProvider;
}
public void clear() {
File parentDir = parentDir();
if (parentDir.exists()) {
File[] files = parentDir.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
file.delete();
}
}
parentDir.delete();
}
}
/**
* If the animation doesn't exist in the cache, null will be returned.
* <p>
* Once the animation is successfully parsed, {@link #renameTempFile(String, FileExtension)} must be
* called to move the file from a temporary location to its permanent cache location so it can
* be used in the future.
*/
@Nullable
@WorkerThread
Pair<FileExtension, InputStream> fetch(String url) {
File cachedFile;
try {
cachedFile = getCachedFile(url);
} catch (FileNotFoundException e) {
return null;
}
if (cachedFile == null) {
return null;
}
FileInputStream inputStream;
try {
inputStream = new FileInputStream(cachedFile);
} catch (FileNotFoundException e) {
return null;
}
FileExtension extension;
if (cachedFile.getAbsolutePath().endsWith(".zip")) {
extension = FileExtension.ZIP;
} else {
extension = FileExtension.JSON;
}
Logger.debug("Cache hit for " + url + " at " + cachedFile.getAbsolutePath());
return new Pair<>(extension, (InputStream) inputStream);
}
/**
* Writes an InputStream from a network response to a temporary file. If the file successfully parses
* to an composition, {@link #renameTempFile(String, FileExtension)} should be called to move the file
* to its final location for future cache hits.
*/
File writeTempCacheFile(String url, InputStream stream, FileExtension extension) throws IOException {
String fileName = filenameForUrl(url, extension, true);
File file = new File(parentDir(), fileName);
try {
OutputStream output = new FileOutputStream(file);
//noinspection TryFinallyCanBeTryWithResources
try {
byte[] buffer = new byte[1024];
int read;
while ((read = stream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} finally {
stream.close();
}
return file;
}
/**
* If the file created by {@link #writeTempCacheFile(String, InputStream, FileExtension)} was successfully parsed,
* this should be called to remove the temporary part of its name which will allow it to be a cache hit in the future.
*/
void renameTempFile(String url, FileExtension extension) {
String fileName = filenameForUrl(url, extension, true);
File file = new File(parentDir(), fileName);
String newFileName = file.getAbsolutePath().replace(".temp", "");
File newFile = new File(newFileName);
boolean renamed = file.renameTo(newFile);
Logger.debug("Copying temp file to real file (" + newFile + ")");
if (!renamed) {
Logger.warning("Unable to rename cache file " + file.getAbsolutePath() + " to " + newFile.getAbsolutePath() + ".");
}
}
/**
* Returns the cache file for the given url if it exists. Checks for both json and zip.
* Returns null if neither exist.
*/
@Nullable
private File getCachedFile(String url) throws FileNotFoundException {
File jsonFile = new File(parentDir(), filenameForUrl(url, FileExtension.JSON, false));
if (jsonFile.exists()) {
return jsonFile;
}
File zipFile = new File(parentDir(), filenameForUrl(url, FileExtension.ZIP, false));
if (zipFile.exists()) {
return zipFile;
}
return null;
}
private File parentDir() {
File file = cacheProvider.getCacheDir();
if (file.isFile()) {
file.delete();
}
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private static String filenameForUrl(String url, FileExtension extension, boolean isTemp) {
String prefix = "lottie_cache_";
String suffix = (isTemp ? extension.tempExtension() : extension.extension);
String sanitizedUrl = url.replaceAll("\\W+", "");
// The max filename on Android is 255 chars.
int maxUrlLength = 255 - prefix.length() - suffix.length();
if (sanitizedUrl.length() > maxUrlLength) {
// If the url is too long, use md5 as the cache key instead.
// md5 is preferable to substring because it is impossible to know
// which parts of the url are significant. If it is the end chars
// then substring could cause multiple animations to use the same
// cache key.
// md5 is probably better for everything but:
// 1. It is slower and unnecessary in most cases.
// 2. Upon upgrading, if the cache key algorithm changes,
// all old cached animations will get orphaned.
sanitizedUrl = getMD5(sanitizedUrl, maxUrlLength);
}
return prefix + sanitizedUrl + suffix;
}
private static String getMD5(String input, int maxLength) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// For some reason, md5 doesn't exist, return a substring.
// This should never happen.
return input.substring(0, maxLength);
}
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < messageDigest.length; i++) {
byte b = messageDigest[i];
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
| 2,432 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/LottieNetworkFetcher.java | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
import java.io.IOException;
/**
* Implement this interface to handle network fetching manually when animations are requested via url. By default, Lottie will use an
* {@link java.net.HttpURLConnection} under the hood but this enables you to hook into your own network stack. By default, Lottie will also handle
* caching the
* animations but if you want to provide your own cache directory, you may implement {@link LottieNetworkCacheProvider}.
*
* @see com.airbnb.lottie.Lottie#initialize
*/
public interface LottieNetworkFetcher {
@WorkerThread
@NonNull
LottieFetchResult fetchSync(@NonNull String url) throws IOException;
}
| 2,433 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/LottieFetchResult.java | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/**
* The result of the operation of obtaining a Lottie animation
*/
public interface LottieFetchResult extends Closeable {
/**
* @return Is the operation successful
*/
boolean isSuccessful();
/**
* @return Received content stream
*/
@NonNull
InputStream bodyByteStream() throws IOException;
/**
* @return Type of content received
*/
@Nullable
String contentType();
/**
* @return Operation error
*/
@Nullable
String error();
}
| 2,434 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/LottieNetworkCacheProvider.java | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import java.io.File;
/**
* Interface for providing the custom cache directory where animations downloaded via url are saved.
*
* @see com.airbnb.lottie.Lottie#initialize
*/
public interface LottieNetworkCacheProvider {
/**
* Called during cache operations
*
* @return cache directory
*/
@NonNull File getCacheDir();
} | 2,435 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/DefaultLottieFetchResult.java | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import com.airbnb.lottie.utils.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class DefaultLottieFetchResult implements LottieFetchResult {
@NonNull
private final HttpURLConnection connection;
public DefaultLottieFetchResult(@NonNull HttpURLConnection connection) {
this.connection = connection;
}
@Override public boolean isSuccessful() {
try {
return connection.getResponseCode() / 100 == 2;
} catch (IOException e) {
return false;
}
}
@NonNull @Override public InputStream bodyByteStream() throws IOException {
return connection.getInputStream();
}
@Nullable @Override public String contentType() {
return connection.getContentType();
}
@Nullable @Override public String error() {
try {
return isSuccessful() ? null :
"Unable to fetch " + connection.getURL() + ". Failed with " + connection.getResponseCode() + "\n" + getErrorFromConnection(connection);
} catch (IOException e) {
Logger.warning("get error failed ", e);
return e.getMessage();
}
}
@Override public void close() {
connection.disconnect();
}
private String getErrorFromConnection(HttpURLConnection connection) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
StringBuilder error = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
error.append(line).append('\n');
}
} finally {
try {
r.close();
} catch (Exception e) {
// Do nothing.
}
}
return error.toString();
}
}
| 2,436 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/DefaultLottieNetworkFetcher.java | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class DefaultLottieNetworkFetcher implements LottieNetworkFetcher {
@Override
@NonNull
public LottieFetchResult fetchSync(@NonNull String url) throws IOException {
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.connect();
return new DefaultLottieFetchResult(connection);
}
}
| 2,437 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/network/NetworkFetcher.java | package com.airbnb.lottie.network;
import android.content.Context;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.WorkerThread;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.airbnb.lottie.LottieResult;
import com.airbnb.lottie.utils.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipInputStream;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class NetworkFetcher {
@Nullable
private final NetworkCache networkCache;
@NonNull
private final LottieNetworkFetcher fetcher;
public NetworkFetcher(@Nullable NetworkCache networkCache, @NonNull LottieNetworkFetcher fetcher) {
this.networkCache = networkCache;
this.fetcher = fetcher;
}
@NonNull
@WorkerThread
public LottieResult<LottieComposition> fetchSync(Context context, @NonNull String url, @Nullable String cacheKey) {
LottieComposition result = fetchFromCache(context, url, cacheKey);
if (result != null) {
return new LottieResult<>(result);
}
Logger.debug("Animation for " + url + " not found in cache. Fetching from network.");
return fetchFromNetwork(context, url, cacheKey);
}
@Nullable
@WorkerThread
private LottieComposition fetchFromCache(Context context, @NonNull String url, @Nullable String cacheKey) {
if (cacheKey == null || networkCache == null) {
return null;
}
Pair<FileExtension, InputStream> cacheResult = networkCache.fetch(url);
if (cacheResult == null) {
return null;
}
FileExtension extension = cacheResult.first;
InputStream inputStream = cacheResult.second;
LottieResult<LottieComposition> result;
if (extension == FileExtension.ZIP) {
result = LottieCompositionFactory.fromZipStreamSync(context, new ZipInputStream(inputStream), cacheKey);
} else {
result = LottieCompositionFactory.fromJsonInputStreamSync(inputStream, cacheKey);
}
if (result.getValue() != null) {
return result.getValue();
}
return null;
}
@NonNull
@WorkerThread
private LottieResult<LottieComposition> fetchFromNetwork(Context context, @NonNull String url, @Nullable String cacheKey) {
Logger.debug("Fetching " + url);
LottieFetchResult fetchResult = null;
try {
fetchResult = fetcher.fetchSync(url);
if (fetchResult.isSuccessful()) {
InputStream inputStream = fetchResult.bodyByteStream();
String contentType = fetchResult.contentType();
LottieResult<LottieComposition> result = fromInputStream(context, url, inputStream, contentType, cacheKey);
Logger.debug("Completed fetch from network. Success: " + (result.getValue() != null));
return result;
} else {
return new LottieResult<>(new IllegalArgumentException(fetchResult.error()));
}
} catch (Exception e) {
return new LottieResult<>(e);
} finally {
if (fetchResult != null) {
try {
fetchResult.close();
} catch (IOException e) {
Logger.warning("LottieFetchResult close failed ", e);
}
}
}
}
@NonNull
private LottieResult<LottieComposition> fromInputStream(Context context, @NonNull String url, @NonNull InputStream inputStream, @Nullable String contentType,
@Nullable String cacheKey) throws IOException {
FileExtension extension;
LottieResult<LottieComposition> result;
if (contentType == null) {
// Assume JSON for best effort parsing. If it fails, it will just deliver the parse exception
// in the result which is more useful than failing here.
contentType = "application/json";
}
if (contentType.contains("application/zip") ||
contentType.contains("application/x-zip") ||
contentType.contains("application/x-zip-compressed") ||
url.split("\\?")[0].endsWith(".lottie")) {
Logger.debug("Handling zip response.");
extension = FileExtension.ZIP;
result = fromZipStream(context, url, inputStream, cacheKey);
} else {
Logger.debug("Received json response.");
extension = FileExtension.JSON;
result = fromJsonStream(url, inputStream, cacheKey);
}
if (cacheKey != null && result.getValue() != null && networkCache != null) {
networkCache.renameTempFile(url, extension);
}
return result;
}
@NonNull
private LottieResult<LottieComposition> fromZipStream(Context context, @NonNull String url, @NonNull InputStream inputStream, @Nullable String cacheKey)
throws IOException {
if (cacheKey == null || networkCache == null) {
return LottieCompositionFactory.fromZipStreamSync(context, new ZipInputStream(inputStream), null);
}
File file = networkCache.writeTempCacheFile(url, inputStream, FileExtension.ZIP);
return LottieCompositionFactory.fromZipStreamSync(context, new ZipInputStream(new FileInputStream(file)), url);
}
@NonNull
private LottieResult<LottieComposition> fromJsonStream(@NonNull String url, @NonNull InputStream inputStream, @Nullable String cacheKey)
throws IOException {
if (cacheKey == null || networkCache == null) {
return LottieCompositionFactory.fromJsonInputStreamSync(inputStream, null);
}
File file = networkCache.writeTempCacheFile(url, inputStream, FileExtension.JSON);
return LottieCompositionFactory.fromJsonInputStreamSync(new FileInputStream(file.getAbsolutePath()), url);
}
}
| 2,438 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieRelativeFloatValueCallback.java | package com.airbnb.lottie.value;
import androidx.annotation.NonNull;
import com.airbnb.lottie.utils.MiscUtils;
/**
* {@link LottieValueCallback} that provides a value offset from the original animation
* rather than an absolute value.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class LottieRelativeFloatValueCallback extends LottieValueCallback<Float> {
public LottieRelativeFloatValueCallback() {
}
public LottieRelativeFloatValueCallback(@NonNull Float staticValue) {
super(staticValue);
}
@Override
public Float getValue(LottieFrameInfo<Float> frameInfo) {
float originalValue = MiscUtils.lerp(
frameInfo.getStartValue(),
frameInfo.getEndValue(),
frameInfo.getInterpolatedKeyframeProgress()
);
float offset = getOffset(frameInfo);
return originalValue + offset;
}
public Float getOffset(LottieFrameInfo<Float> frameInfo) {
if (value == null) {
throw new IllegalArgumentException("You must provide a static value in the constructor " +
", call setValue, or override getValue.");
}
return value;
}
}
| 2,439 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieInterpolatedPointValue.java | package com.airbnb.lottie.value;
import android.graphics.PointF;
import android.view.animation.Interpolator;
import com.airbnb.lottie.utils.MiscUtils;
@SuppressWarnings("unused")
public class LottieInterpolatedPointValue extends LottieInterpolatedValue<PointF> {
private final PointF point = new PointF();
public LottieInterpolatedPointValue(PointF startValue, PointF endValue) {
super(startValue, endValue);
}
public LottieInterpolatedPointValue(PointF startValue, PointF endValue, Interpolator interpolator) {
super(startValue, endValue, interpolator);
}
@Override PointF interpolateValue(PointF startValue, PointF endValue, float progress) {
point.set(
MiscUtils.lerp(startValue.x, endValue.x, progress),
MiscUtils.lerp(startValue.y, endValue.y, progress)
);
return point;
}
}
| 2,440 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieRelativeIntegerValueCallback.java | package com.airbnb.lottie.value;
import com.airbnb.lottie.utils.MiscUtils;
/**
* {@link LottieValueCallback} that provides a value offset from the original animation
* rather than an absolute value.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class LottieRelativeIntegerValueCallback extends LottieValueCallback<Integer> {
@Override
public Integer getValue(LottieFrameInfo<Integer> frameInfo) {
int originalValue = MiscUtils.lerp(
frameInfo.getStartValue(),
frameInfo.getEndValue(),
frameInfo.getInterpolatedKeyframeProgress()
);
int newValue = getOffset(frameInfo);
return originalValue + newValue;
}
/**
* Override this to provide your own offset on every frame.
*/
public Integer getOffset(LottieFrameInfo<Integer> frameInfo) {
if (value == null) {
throw new IllegalArgumentException("You must provide a static value in the constructor " +
", call setValue, or override getValue.");
}
return value;
}
}
| 2,441 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieInterpolatedIntegerValue.java | package com.airbnb.lottie.value;
import android.view.animation.Interpolator;
import com.airbnb.lottie.utils.MiscUtils;
@SuppressWarnings("unused")
public class LottieInterpolatedIntegerValue extends LottieInterpolatedValue<Integer> {
public LottieInterpolatedIntegerValue(Integer startValue, Integer endValue) {
super(startValue, endValue);
}
public LottieInterpolatedIntegerValue(Integer startValue, Integer endValue, Interpolator interpolator) {
super(startValue, endValue, interpolator);
}
@Override Integer interpolateValue(Integer startValue, Integer endValue, float progress) {
return MiscUtils.lerp(startValue, endValue, progress);
}
}
| 2,442 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/Keyframe.java | package com.airbnb.lottie.value;
import android.graphics.PointF;
import android.view.animation.Interpolator;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieComposition;
public class Keyframe<T> {
private static final float UNSET_FLOAT = -3987645.78543923f;
private static final int UNSET_INT = 784923401;
@Nullable private final LottieComposition composition;
@Nullable public final T startValue;
@Nullable public T endValue;
@Nullable public final Interpolator interpolator;
@Nullable public final Interpolator xInterpolator;
@Nullable public final Interpolator yInterpolator;
public final float startFrame;
@Nullable public Float endFrame;
private float startValueFloat = UNSET_FLOAT;
private float endValueFloat = UNSET_FLOAT;
private int startValueInt = UNSET_INT;
private int endValueInt = UNSET_INT;
private float startProgress = Float.MIN_VALUE;
private float endProgress = Float.MIN_VALUE;
// Used by PathKeyframe but it has to be parsed by KeyFrame because we use a JsonReader to
// deserialzie the data so we have to parse everything in order
public PointF pathCp1 = null;
public PointF pathCp2 = null;
public Keyframe(@SuppressWarnings("NullableProblems") LottieComposition composition,
@Nullable T startValue, @Nullable T endValue,
@Nullable Interpolator interpolator, float startFrame, @Nullable Float endFrame) {
this.composition = composition;
this.startValue = startValue;
this.endValue = endValue;
this.interpolator = interpolator;
xInterpolator = null;
yInterpolator = null;
this.startFrame = startFrame;
this.endFrame = endFrame;
}
public Keyframe(@SuppressWarnings("NullableProblems") LottieComposition composition,
@Nullable T startValue, @Nullable T endValue,
@Nullable Interpolator xInterpolator, @Nullable Interpolator yInterpolator, float startFrame, @Nullable Float endFrame) {
this.composition = composition;
this.startValue = startValue;
this.endValue = endValue;
interpolator = null;
this.xInterpolator = xInterpolator;
this.yInterpolator = yInterpolator;
this.startFrame = startFrame;
this.endFrame = endFrame;
}
protected Keyframe(@SuppressWarnings("NullableProblems") LottieComposition composition,
@Nullable T startValue, @Nullable T endValue,
@Nullable Interpolator interpolator, @Nullable Interpolator xInterpolator, @Nullable Interpolator yInterpolator,
float startFrame, @Nullable Float endFrame) {
this.composition = composition;
this.startValue = startValue;
this.endValue = endValue;
this.interpolator = interpolator;
this.xInterpolator = xInterpolator;
this.yInterpolator = yInterpolator;
this.startFrame = startFrame;
this.endFrame = endFrame;
}
/**
* Non-animated value.
*/
public Keyframe(@SuppressWarnings("NullableProblems") T value) {
composition = null;
startValue = value;
endValue = value;
interpolator = null;
xInterpolator = null;
yInterpolator = null;
startFrame = Float.MIN_VALUE;
endFrame = Float.MAX_VALUE;
}
private Keyframe(T startValue, T endValue) {
composition = null;
this.startValue = startValue;
this.endValue = endValue;
interpolator = null;
xInterpolator = null;
yInterpolator = null;
startFrame = Float.MIN_VALUE;
endFrame = Float.MAX_VALUE;
}
public Keyframe<T> copyWith(T startValue, T endValue) {
return new Keyframe<T>(startValue, endValue);
}
public float getStartProgress() {
if (composition == null) {
return 0f;
}
if (startProgress == Float.MIN_VALUE) {
startProgress = (startFrame - composition.getStartFrame()) / composition.getDurationFrames();
}
return startProgress;
}
public float getEndProgress() {
if (composition == null) {
return 1f;
}
if (endProgress == Float.MIN_VALUE) {
if (endFrame == null) {
endProgress = 1f;
} else {
float startProgress = getStartProgress();
float durationFrames = endFrame - startFrame;
float durationProgress = durationFrames / composition.getDurationFrames();
endProgress = startProgress + durationProgress;
}
}
return endProgress;
}
public boolean isStatic() {
return interpolator == null && xInterpolator == null && yInterpolator == null;
}
public boolean containsProgress(@FloatRange(from = 0f, to = 1f) float progress) {
return progress >= getStartProgress() && progress < getEndProgress();
}
/**
* Optimization to avoid autoboxing.
*/
public float getStartValueFloat() {
if (startValueFloat == UNSET_FLOAT) {
startValueFloat = (float) (Float) startValue;
}
return startValueFloat;
}
/**
* Optimization to avoid autoboxing.
*/
public float getEndValueFloat() {
if (endValueFloat == UNSET_FLOAT) {
endValueFloat = (float) (Float) endValue;
}
return endValueFloat;
}
/**
* Optimization to avoid autoboxing.
*/
public int getStartValueInt() {
if (startValueInt == UNSET_INT) {
startValueInt = (int) (Integer) startValue;
}
return startValueInt;
}
/**
* Optimization to avoid autoboxing.
*/
public int getEndValueInt() {
if (endValueInt == UNSET_INT) {
endValueInt = (int) (Integer) endValue;
}
return endValueInt;
}
@Override public String toString() {
return "Keyframe{" + "startValue=" + startValue +
", endValue=" + endValue +
", startFrame=" + startFrame +
", endFrame=" + endFrame +
", interpolator=" + interpolator +
'}';
}
}
| 2,443 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/SimpleLottieValueCallback.java | package com.airbnb.lottie.value;
/**
* Delegate interface for {@link LottieValueCallback}. This is helpful for the Kotlin API because you can use a SAM conversion to write the
* callback as a single abstract method block like this:
* animationView.addValueCallback(keyPath, LottieProperty.TRANSFORM_OPACITY) { 50 }
*/
public interface SimpleLottieValueCallback<T> {
T getValue(LottieFrameInfo<T> frameInfo);
}
| 2,444 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieValueCallback.java | package com.airbnb.lottie.value;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
/**
* Allows you to set a callback on a resolved {@link com.airbnb.lottie.model.KeyPath} to modify
* its animation values at runtime.
*
* If your dynamic property does the following, you must call {@link LottieAnimationView#invalidate()} or
* {@link LottieDrawable#invalidateSelf()} each time you want to update this value.
* 1. Use {@link com.airbnb.lottie.RenderMode#SOFTWARE}
* 2. Rendering a static image (the animation is either paused or there are no values
* changing within the animation itself)
* When using software rendering, Lottie caches the internal rendering bitmap. Whenever the animation changes
* internally, Lottie knows to invalidate the bitmap and re-render it on the next frame. If the animation
* never changes but your dynamic property does outside of Lottie, Lottie must be notified that it changed
* in order to set the bitmap as dirty and re-render it on the next frame.
*/
public class LottieValueCallback<T> {
private final LottieFrameInfo<T> frameInfo = new LottieFrameInfo<>();
@Nullable private BaseKeyframeAnimation<?, ?> animation;
/**
* This can be set with {@link #setValue(Object)} to use a value instead of deferring
* to the callback.
**/
@Nullable protected T value = null;
public LottieValueCallback() {
}
public LottieValueCallback(@Nullable T staticValue) {
value = staticValue;
}
/**
* Override this if you haven't set a static value in the constructor or with setValue.
* <p>
* Return null to resort to the default value.
*
* Refer to the javadoc for this class for a special case that requires manual invalidation
* each time you want to return something different from this method.
*/
@Nullable
public T getValue(LottieFrameInfo<T> frameInfo) {
return value;
}
public final void setValue(@Nullable T value) {
this.value = value;
if (animation != null) {
animation.notifyListeners();
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
@Nullable
public final T getValueInternal(
float startFrame,
float endFrame,
T startValue,
T endValue,
float linearKeyframeProgress,
float interpolatedKeyframeProgress,
float overallProgress
) {
return getValue(
frameInfo.set(
startFrame,
endFrame,
startValue,
endValue,
linearKeyframeProgress,
interpolatedKeyframeProgress,
overallProgress
)
);
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
public final void setAnimation(@Nullable BaseKeyframeAnimation<?, ?> animation) {
this.animation = animation;
}
}
| 2,445 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieInterpolatedValue.java | package com.airbnb.lottie.value;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
abstract class LottieInterpolatedValue<T> extends LottieValueCallback<T> {
private final T startValue;
private final T endValue;
private final Interpolator interpolator;
LottieInterpolatedValue(T startValue, T endValue) {
this(startValue, endValue, new LinearInterpolator());
}
LottieInterpolatedValue(T startValue, T endValue, Interpolator interpolator) {
this.startValue = startValue;
this.endValue = endValue;
this.interpolator = interpolator;
}
@Override public T getValue(LottieFrameInfo<T> frameInfo) {
float progress = interpolator.getInterpolation(frameInfo.getOverallProgress());
return interpolateValue(this.startValue, this.endValue, progress);
}
abstract T interpolateValue(T startValue, T endValue, float progress);
}
| 2,446 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieFrameInfo.java | package com.airbnb.lottie.value;
import androidx.annotation.RestrictTo;
/**
* Data class for use with {@link LottieValueCallback}.
* You should *not* hold a reference to the frame info parameter passed to your callback. It will be reused.
*/
public class LottieFrameInfo<T> {
private float startFrame;
private float endFrame;
private T startValue;
private T endValue;
private float linearKeyframeProgress;
private float interpolatedKeyframeProgress;
private float overallProgress;
@RestrictTo(RestrictTo.Scope.LIBRARY)
public LottieFrameInfo<T> set(
float startFrame,
float endFrame,
T startValue,
T endValue,
float linearKeyframeProgress,
float interpolatedKeyframeProgress,
float overallProgress
) {
this.startFrame = startFrame;
this.endFrame = endFrame;
this.startValue = startValue;
this.endValue = endValue;
this.linearKeyframeProgress = linearKeyframeProgress;
this.interpolatedKeyframeProgress = interpolatedKeyframeProgress;
this.overallProgress = overallProgress;
return this;
}
public float getStartFrame() {
return startFrame;
}
public float getEndFrame() {
return endFrame;
}
public T getStartValue() {
return startValue;
}
public T getEndValue() {
return endValue;
}
public float getLinearKeyframeProgress() {
return linearKeyframeProgress;
}
public float getInterpolatedKeyframeProgress() {
return interpolatedKeyframeProgress;
}
public float getOverallProgress() {
return overallProgress;
}
}
| 2,447 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/ScaleXY.java | package com.airbnb.lottie.value;
public class ScaleXY {
private float scaleX;
private float scaleY;
public ScaleXY(float sx, float sy) {
this.scaleX = sx;
this.scaleY = sy;
}
public ScaleXY() {
this(1f, 1f);
}
public float getScaleX() {
return scaleX;
}
public float getScaleY() {
return scaleY;
}
public void set(float scaleX, float scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
}
public boolean equals(float scaleX, float scaleY) {
return this.scaleX == scaleX && this.scaleY == scaleY;
}
@Override public String toString() {
return getScaleX() + "x" + getScaleY();
}
}
| 2,448 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieInterpolatedFloatValue.java | package com.airbnb.lottie.value;
import android.view.animation.Interpolator;
import com.airbnb.lottie.utils.MiscUtils;
@SuppressWarnings("unused")
public class LottieInterpolatedFloatValue extends LottieInterpolatedValue<Float> {
public LottieInterpolatedFloatValue(Float startValue, Float endValue) {
super(startValue, endValue);
}
public LottieInterpolatedFloatValue(Float startValue, Float endValue, Interpolator interpolator) {
super(startValue, endValue, interpolator);
}
@Override Float interpolateValue(Float startValue, Float endValue, float progress) {
return MiscUtils.lerp(startValue, endValue, progress);
}
}
| 2,449 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/value/LottieRelativePointValueCallback.java | package com.airbnb.lottie.value;
import android.graphics.PointF;
import androidx.annotation.NonNull;
import com.airbnb.lottie.utils.MiscUtils;
/**
* {@link LottieValueCallback} that provides a value offset from the original animation
* rather than an absolute value.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class LottieRelativePointValueCallback extends LottieValueCallback<PointF> {
private final PointF point = new PointF();
public LottieRelativePointValueCallback() {
}
public LottieRelativePointValueCallback(@NonNull PointF staticValue) {
super(staticValue);
}
@Override
public final PointF getValue(LottieFrameInfo<PointF> frameInfo) {
point.set(
MiscUtils.lerp(
frameInfo.getStartValue().x,
frameInfo.getEndValue().x,
frameInfo.getInterpolatedKeyframeProgress()),
MiscUtils.lerp(
frameInfo.getStartValue().y,
frameInfo.getEndValue().y,
frameInfo.getInterpolatedKeyframeProgress())
);
PointF offset = getOffset(frameInfo);
point.offset(offset.x, offset.y);
return point;
}
/**
* Override this to provide your own offset on every frame.
*/
public PointF getOffset(LottieFrameInfo<PointF> frameInfo) {
if (value == null) {
throw new IllegalArgumentException("You must provide a static value in the constructor " +
", call setValue, or override getValue.");
}
return value;
}
}
| 2,450 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/LPaint.java | package com.airbnb.lottie.animation;
import static com.airbnb.lottie.utils.MiscUtils.clamp;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Build;
import android.os.LocaleList;
import androidx.annotation.NonNull;
/**
* Custom paint that doesn't set text locale.
* It takes ~1ms on initialization and isn't needed so removing it speeds up
* setComposition.
*/
public class LPaint extends Paint {
public LPaint() {
super();
}
public LPaint(int flags) {
super(flags);
}
public LPaint(PorterDuff.Mode porterDuffMode) {
super();
setXfermode(new PorterDuffXfermode(porterDuffMode));
}
public LPaint(int flags, PorterDuff.Mode porterDuffMode) {
super(flags);
setXfermode(new PorterDuffXfermode(porterDuffMode));
}
@Override
public void setTextLocales(@NonNull LocaleList locales) {
// Do nothing.
}
/**
* Overrides {@link android.graphics.Paint#setAlpha(int)} to avoid
* unnecessary {@link android.graphics.ColorSpace.Named ColorSpace$Named[] }
* allocations when calling this method in Android 29 or lower.
*
* @param alpha set the alpha component [0..255] of the paint's color.
*/
@Override
public void setAlpha(int alpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
int color = getColor();
setColor((clamp(alpha, 0, 255) << 24) | (color & 0xFFFFFF));
} else {
super.setAlpha(clamp(alpha, 0, 255));
}
}
}
| 2,451 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/package-info.java | @RestrictTo(LIBRARY)
package com.airbnb.lottie.animation;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import androidx.annotation.RestrictTo; | 2,452 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/DrawingContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
public interface DrawingContent extends Content {
void draw(Canvas canvas, Matrix parentMatrix, int alpha);
void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents);
}
| 2,453 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java | package com.airbnb.lottie.animation.content;
import static com.airbnb.lottie.utils.MiscUtils.clamp;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.DropShadowKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.ShapeFill;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
public class FillContent
implements DrawingContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent {
private final Path path = new Path();
private final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG);
private final BaseLayer layer;
private final String name;
private final boolean hidden;
private final List<PathContent> paths = new ArrayList<>();
private final BaseKeyframeAnimation<Integer, Integer> colorAnimation;
private final BaseKeyframeAnimation<Integer, Integer> opacityAnimation;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
private final LottieDrawable lottieDrawable;
@Nullable private BaseKeyframeAnimation<Float, Float> blurAnimation;
float blurMaskFilterRadius;
@Nullable private DropShadowKeyframeAnimation dropShadowAnimation;
public FillContent(final LottieDrawable lottieDrawable, BaseLayer layer, ShapeFill fill) {
this.layer = layer;
name = fill.getName();
hidden = fill.isHidden();
this.lottieDrawable = lottieDrawable;
if (layer.getBlurEffect() != null) {
blurAnimation = layer.getBlurEffect().getBlurriness().createAnimation();
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
if (layer.getDropShadowEffect() != null) {
dropShadowAnimation = new DropShadowKeyframeAnimation(this, layer, layer.getDropShadowEffect());
}
if (fill.getColor() == null || fill.getOpacity() == null) {
colorAnimation = null;
opacityAnimation = null;
return;
}
path.setFillType(fill.getFillType());
colorAnimation = fill.getColor().createAnimation();
colorAnimation.addUpdateListener(this);
layer.addAnimation(colorAnimation);
opacityAnimation = fill.getOpacity().createAnimation();
opacityAnimation.addUpdateListener(this);
layer.addAnimation(opacityAnimation);
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < contentsAfter.size(); i++) {
Content content = contentsAfter.get(i);
if (content instanceof PathContent) {
paths.add((PathContent) content);
}
}
}
@Override public String getName() {
return name;
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
L.beginSection("FillContent#draw");
int color = ((ColorKeyframeAnimation) this.colorAnimation).getIntValue();
int alpha = (int) ((parentAlpha / 255f * opacityAnimation.getValue() / 100f) * 255);
paint.setColor((clamp(alpha, 0, 255) << 24) | (color & 0xFFFFFF));
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
if (blurAnimation != null) {
float blurRadius = blurAnimation.getValue();
if (blurRadius == 0f) {
paint.setMaskFilter(null);
} else if (blurRadius != blurMaskFilterRadius) {
BlurMaskFilter blur = layer.getBlurMaskFilter(blurRadius);
paint.setMaskFilter(blur);
}
blurMaskFilterRadius = blurRadius;
}
if (dropShadowAnimation != null) {
dropShadowAnimation.applyTo(paint);
}
path.reset();
for (int i = 0; i < paths.size(); i++) {
path.addPath(paths.get(i).getPath(), parentMatrix);
}
canvas.drawPath(path, paint);
L.endSection("FillContent#draw");
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
path.reset();
for (int i = 0; i < paths.size(); i++) {
this.path.addPath(paths.get(i).getPath(), parentMatrix);
}
path.computeBounds(outBounds, false);
// Add padding to account for rounding errors.
outBounds.set(
outBounds.left - 1,
outBounds.top - 1,
outBounds.right + 1,
outBounds.bottom + 1
);
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.COLOR) {
colorAnimation.setValueCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.OPACITY) {
opacityAnimation.setValueCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.COLOR_FILTER) {
if (colorFilterAnimation != null) {
layer.removeAnimation(colorFilterAnimation);
}
if (callback == null) {
colorFilterAnimation = null;
} else {
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
colorFilterAnimation.addUpdateListener(this);
layer.addAnimation(colorFilterAnimation);
}
} else if (property == LottieProperty.BLUR_RADIUS) {
if (blurAnimation != null) {
blurAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else {
blurAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
} else if (property == LottieProperty.DROP_SHADOW_COLOR && dropShadowAnimation != null) {
dropShadowAnimation.setColorCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.DROP_SHADOW_OPACITY && dropShadowAnimation != null) {
dropShadowAnimation.setOpacityCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DIRECTION && dropShadowAnimation != null) {
dropShadowAnimation.setDirectionCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DISTANCE && dropShadowAnimation != null) {
dropShadowAnimation.setDistanceCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_RADIUS && dropShadowAnimation != null) {
dropShadowAnimation.setRadiusCallback((LottieValueCallback<Float>) callback);
}
}
}
| 2,454 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/RectangleContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.RectangleShape;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.List;
public class RectangleContent
implements BaseKeyframeAnimation.AnimationListener, KeyPathElementContent, PathContent {
private final Path path = new Path();
private final RectF rect = new RectF();
private final String name;
private final boolean hidden;
private final LottieDrawable lottieDrawable;
private final BaseKeyframeAnimation<?, PointF> positionAnimation;
private final BaseKeyframeAnimation<?, PointF> sizeAnimation;
private final BaseKeyframeAnimation<?, Float> cornerRadiusAnimation;
private final CompoundTrimPathContent trimPaths = new CompoundTrimPathContent();
/** This corner radius is from a layer item. The first one is from the roundedness on this specific rect. */
@Nullable private BaseKeyframeAnimation<Float, Float> roundedCornersAnimation = null;
private boolean isPathValid;
public RectangleContent(LottieDrawable lottieDrawable, BaseLayer layer, RectangleShape rectShape) {
name = rectShape.getName();
hidden = rectShape.isHidden();
this.lottieDrawable = lottieDrawable;
positionAnimation = rectShape.getPosition().createAnimation();
sizeAnimation = rectShape.getSize().createAnimation();
cornerRadiusAnimation = rectShape.getCornerRadius().createAnimation();
layer.addAnimation(positionAnimation);
layer.addAnimation(sizeAnimation);
layer.addAnimation(cornerRadiusAnimation);
positionAnimation.addUpdateListener(this);
sizeAnimation.addUpdateListener(this);
cornerRadiusAnimation.addUpdateListener(this);
}
@Override
public String getName() {
return name;
}
@Override
public void onValueChanged() {
invalidate();
}
private void invalidate() {
isPathValid = false;
lottieDrawable.invalidateSelf();
}
@Override
public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < contentsBefore.size(); i++) {
Content content = contentsBefore.get(i);
if (content instanceof TrimPathContent &&
((TrimPathContent) content).getType() == ShapeTrimPath.Type.SIMULTANEOUSLY) {
TrimPathContent trimPath = (TrimPathContent) content;
trimPaths.addTrimPath(trimPath);
trimPath.addListener(this);
} else if (content instanceof RoundedCornersContent) {
roundedCornersAnimation = ((RoundedCornersContent) content).getRoundedCorners();
}
}
}
@Override
public Path getPath() {
if (isPathValid) {
return path;
}
path.reset();
if (hidden) {
isPathValid = true;
return path;
}
PointF size = sizeAnimation.getValue();
float halfWidth = size.x / 2f;
float halfHeight = size.y / 2f;
float radius = cornerRadiusAnimation == null ?
0f : ((FloatKeyframeAnimation) cornerRadiusAnimation).getFloatValue();
if (radius == 0f && this.roundedCornersAnimation != null) {
radius = Math.min(roundedCornersAnimation.getValue(), Math.min(halfWidth, halfHeight));
}
float maxRadius = Math.min(halfWidth, halfHeight);
if (radius > maxRadius) {
radius = maxRadius;
}
// Draw the rectangle top right to bottom left.
PointF position = positionAnimation.getValue();
path.moveTo(position.x + halfWidth, position.y - halfHeight + radius);
path.lineTo(position.x + halfWidth, position.y + halfHeight - radius);
if (radius > 0) {
rect.set(position.x + halfWidth - 2 * radius,
position.y + halfHeight - 2 * radius,
position.x + halfWidth,
position.y + halfHeight);
path.arcTo(rect, 0, 90, false);
}
path.lineTo(position.x - halfWidth + radius, position.y + halfHeight);
if (radius > 0) {
rect.set(position.x - halfWidth,
position.y + halfHeight - 2 * radius,
position.x - halfWidth + 2 * radius,
position.y + halfHeight);
path.arcTo(rect, 90, 90, false);
}
path.lineTo(position.x - halfWidth, position.y - halfHeight + radius);
if (radius > 0) {
rect.set(position.x - halfWidth,
position.y - halfHeight,
position.x - halfWidth + 2 * radius,
position.y - halfHeight + 2 * radius);
path.arcTo(rect, 180, 90, false);
}
path.lineTo(position.x + halfWidth - radius, position.y - halfHeight);
if (radius > 0) {
rect.set(position.x + halfWidth - 2 * radius,
position.y - halfHeight,
position.x + halfWidth,
position.y - halfHeight + 2 * radius);
path.arcTo(rect, 270, 90, false);
}
path.close();
trimPaths.apply(path);
isPathValid = true;
return path;
}
@Override
public void resolveKeyPath(KeyPath keyPath, int depth, List<KeyPath> accumulator,
KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.RECTANGLE_SIZE) {
sizeAnimation.setValueCallback((LottieValueCallback<PointF>) callback);
} else if (property == LottieProperty.POSITION) {
positionAnimation.setValueCallback((LottieValueCallback<PointF>) callback);
} else if (property == LottieProperty.CORNER_RADIUS) {
cornerRadiusAnimation.setValueCallback((LottieValueCallback<Float>) callback);
}
}
}
| 2,455 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/MergePathsContent.java | package com.airbnb.lottie.animation.content;
import android.annotation.TargetApi;
import android.graphics.Path;
import android.os.Build;
import com.airbnb.lottie.model.content.MergePaths;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
@TargetApi(Build.VERSION_CODES.KITKAT)
public class MergePathsContent implements PathContent, GreedyContent {
private final Path firstPath = new Path();
private final Path remainderPath = new Path();
private final Path path = new Path();
private final String name;
private final List<PathContent> pathContents = new ArrayList<>();
private final MergePaths mergePaths;
public MergePathsContent(MergePaths mergePaths) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
throw new IllegalStateException("Merge paths are not supported pre-KitKat.");
}
name = mergePaths.getName();
this.mergePaths = mergePaths;
}
@Override public void absorbContent(ListIterator<Content> contents) {
// Fast forward the iterator until after this content.
//noinspection StatementWithEmptyBody
while (contents.hasPrevious() && contents.previous() != this) {
}
while (contents.hasPrevious()) {
Content content = contents.previous();
if (content instanceof PathContent) {
pathContents.add((PathContent) content);
contents.remove();
}
}
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < pathContents.size(); i++) {
pathContents.get(i).setContents(contentsBefore, contentsAfter);
}
}
@Override public Path getPath() {
path.reset();
if (mergePaths.isHidden()) {
return path;
}
switch (mergePaths.getMode()) {
case MERGE:
addPaths();
break;
case ADD:
opFirstPathWithRest(Path.Op.UNION);
break;
case SUBTRACT:
opFirstPathWithRest(Path.Op.REVERSE_DIFFERENCE);
break;
case INTERSECT:
opFirstPathWithRest(Path.Op.INTERSECT);
break;
case EXCLUDE_INTERSECTIONS:
opFirstPathWithRest(Path.Op.XOR);
break;
}
return path;
}
@Override public String getName() {
return name;
}
private void addPaths() {
for (int i = 0; i < pathContents.size(); i++) {
path.addPath(pathContents.get(i).getPath());
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void opFirstPathWithRest(Path.Op op) {
remainderPath.reset();
firstPath.reset();
for (int i = pathContents.size() - 1; i >= 1; i--) {
PathContent content = pathContents.get(i);
if (content instanceof ContentGroup) {
List<PathContent> pathList = ((ContentGroup) content).getPathList();
for (int j = pathList.size() - 1; j >= 0; j--) {
Path path = pathList.get(j).getPath();
path.transform(((ContentGroup) content).getTransformationMatrix());
this.remainderPath.addPath(path);
}
} else {
remainderPath.addPath(content.getPath());
}
}
PathContent lastContent = pathContents.get(0);
if (lastContent instanceof ContentGroup) {
List<PathContent> pathList = ((ContentGroup) lastContent).getPathList();
for (int j = 0; j < pathList.size(); j++) {
Path path = pathList.get(j).getPath();
path.transform(((ContentGroup) lastContent).getTransformationMatrix());
this.firstPath.addPath(path);
}
} else {
firstPath.set(lastContent.getPath());
}
path.op(firstPath, remainderPath, op);
}
}
| 2,456 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/ModifierContent.java | package com.airbnb.lottie.animation.content;
public interface ModifierContent {
}
| 2,457 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/StrokeContent.java | package com.airbnb.lottie.animation.content;
import static com.airbnb.lottie.LottieProperty.STROKE_COLOR;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.content.ShapeStroke;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.value.LottieValueCallback;
public class StrokeContent extends BaseStrokeContent {
private final BaseLayer layer;
private final String name;
private final boolean hidden;
private final BaseKeyframeAnimation<Integer, Integer> colorAnimation;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
public StrokeContent(final LottieDrawable lottieDrawable, BaseLayer layer, ShapeStroke stroke) {
super(lottieDrawable, layer, stroke.getCapType().toPaintCap(),
stroke.getJoinType().toPaintJoin(), stroke.getMiterLimit(), stroke.getOpacity(),
stroke.getWidth(), stroke.getLineDashPattern(), stroke.getDashOffset());
this.layer = layer;
name = stroke.getName();
hidden = stroke.isHidden();
colorAnimation = stroke.getColor().createAnimation();
colorAnimation.addUpdateListener(this);
layer.addAnimation(colorAnimation);
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
paint.setColor(((ColorKeyframeAnimation) colorAnimation).getIntValue());
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
super.draw(canvas, parentMatrix, parentAlpha);
}
@Override public String getName() {
return name;
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == STROKE_COLOR) {
colorAnimation.setValueCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.COLOR_FILTER) {
if (colorFilterAnimation != null) {
layer.removeAnimation(colorFilterAnimation);
}
if (callback == null) {
colorFilterAnimation = null;
} else {
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
colorFilterAnimation.addUpdateListener(this);
layer.addAnimation(colorAnimation);
}
}
}
}
| 2,458 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/PolystarContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.PolystarShape;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.List;
public class PolystarContent
implements PathContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent {
/**
* This was empirically derived by creating polystars, converting them to
* curves, and calculating a scale factor.
* It works best for polygons and stars with 3 points and needs more
* work otherwise.
*/
private static final float POLYSTAR_MAGIC_NUMBER = .47829f;
private static final float POLYGON_MAGIC_NUMBER = .25f;
private final Path path = new Path();
private final String name;
private final LottieDrawable lottieDrawable;
private final PolystarShape.Type type;
private final boolean hidden;
private final boolean isReversed;
private final BaseKeyframeAnimation<?, Float> pointsAnimation;
private final BaseKeyframeAnimation<?, PointF> positionAnimation;
private final BaseKeyframeAnimation<?, Float> rotationAnimation;
@Nullable private final BaseKeyframeAnimation<?, Float> innerRadiusAnimation;
private final BaseKeyframeAnimation<?, Float> outerRadiusAnimation;
@Nullable private final BaseKeyframeAnimation<?, Float> innerRoundednessAnimation;
private final BaseKeyframeAnimation<?, Float> outerRoundednessAnimation;
private final CompoundTrimPathContent trimPaths = new CompoundTrimPathContent();
private boolean isPathValid;
public PolystarContent(LottieDrawable lottieDrawable, BaseLayer layer,
PolystarShape polystarShape) {
this.lottieDrawable = lottieDrawable;
name = polystarShape.getName();
type = polystarShape.getType();
hidden = polystarShape.isHidden();
isReversed = polystarShape.isReversed();
pointsAnimation = polystarShape.getPoints().createAnimation();
positionAnimation = polystarShape.getPosition().createAnimation();
rotationAnimation = polystarShape.getRotation().createAnimation();
outerRadiusAnimation = polystarShape.getOuterRadius().createAnimation();
outerRoundednessAnimation = polystarShape.getOuterRoundedness().createAnimation();
if (type == PolystarShape.Type.STAR) {
innerRadiusAnimation = polystarShape.getInnerRadius().createAnimation();
innerRoundednessAnimation = polystarShape.getInnerRoundedness().createAnimation();
} else {
innerRadiusAnimation = null;
innerRoundednessAnimation = null;
}
layer.addAnimation(pointsAnimation);
layer.addAnimation(positionAnimation);
layer.addAnimation(rotationAnimation);
layer.addAnimation(outerRadiusAnimation);
layer.addAnimation(outerRoundednessAnimation);
if (type == PolystarShape.Type.STAR) {
layer.addAnimation(innerRadiusAnimation);
layer.addAnimation(innerRoundednessAnimation);
}
pointsAnimation.addUpdateListener(this);
positionAnimation.addUpdateListener(this);
rotationAnimation.addUpdateListener(this);
outerRadiusAnimation.addUpdateListener(this);
outerRoundednessAnimation.addUpdateListener(this);
if (type == PolystarShape.Type.STAR) {
innerRadiusAnimation.addUpdateListener(this);
innerRoundednessAnimation.addUpdateListener(this);
}
}
@Override public void onValueChanged() {
invalidate();
}
private void invalidate() {
isPathValid = false;
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < contentsBefore.size(); i++) {
Content content = contentsBefore.get(i);
if (content instanceof TrimPathContent &&
((TrimPathContent) content).getType() == ShapeTrimPath.Type.SIMULTANEOUSLY) {
TrimPathContent trimPath = (TrimPathContent) content;
trimPaths.addTrimPath(trimPath);
trimPath.addListener(this);
}
}
}
@Override public Path getPath() {
if (isPathValid) {
return path;
}
path.reset();
if (hidden) {
isPathValid = true;
return path;
}
switch (type) {
case STAR:
createStarPath();
break;
case POLYGON:
createPolygonPath();
break;
}
path.close();
trimPaths.apply(path);
isPathValid = true;
return path;
}
@Override public String getName() {
return name;
}
private void createStarPath() {
float points = pointsAnimation.getValue();
double currentAngle = rotationAnimation == null ? 0f : rotationAnimation.getValue();
// Start at +y instead of +x
currentAngle -= 90;
// convert to radians
currentAngle = Math.toRadians(currentAngle);
// adjust current angle for partial points
float anglePerPoint = (float) (2 * Math.PI / points);
if (isReversed) {
anglePerPoint *= -1;
}
float halfAnglePerPoint = anglePerPoint / 2.0f;
float partialPointAmount = points - (int) points;
if (partialPointAmount != 0) {
currentAngle += halfAnglePerPoint * (1f - partialPointAmount);
}
float outerRadius = outerRadiusAnimation.getValue();
//noinspection ConstantConditions
float innerRadius = innerRadiusAnimation.getValue();
float innerRoundedness = 0f;
if (innerRoundednessAnimation != null) {
innerRoundedness = innerRoundednessAnimation.getValue() / 100f;
}
float outerRoundedness = 0f;
if (outerRoundednessAnimation != null) {
outerRoundedness = outerRoundednessAnimation.getValue() / 100f;
}
float x;
float y;
float previousX;
float previousY;
float partialPointRadius = 0;
if (partialPointAmount != 0) {
partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius);
x = (float) (partialPointRadius * Math.cos(currentAngle));
y = (float) (partialPointRadius * Math.sin(currentAngle));
path.moveTo(x, y);
currentAngle += anglePerPoint * partialPointAmount / 2f;
} else {
x = (float) (outerRadius * Math.cos(currentAngle));
y = (float) (outerRadius * Math.sin(currentAngle));
path.moveTo(x, y);
currentAngle += halfAnglePerPoint;
}
// True means the line will go to outer radius. False means inner radius.
boolean longSegment = false;
double numPoints = Math.ceil(points) * 2;
for (int i = 0; i < numPoints; i++) {
float radius = longSegment ? outerRadius : innerRadius;
float dTheta = halfAnglePerPoint;
if (partialPointRadius != 0 && i == numPoints - 2) {
dTheta = anglePerPoint * partialPointAmount / 2f;
}
if (partialPointRadius != 0 && i == numPoints - 1) {
radius = partialPointRadius;
}
previousX = x;
previousY = y;
x = (float) (radius * Math.cos(currentAngle));
y = (float) (radius * Math.sin(currentAngle));
if (innerRoundedness == 0 && outerRoundedness == 0) {
path.lineTo(x, y);
} else {
float cp1Theta = (float) (Math.atan2(previousY, previousX) - Math.PI / 2f);
float cp1Dx = (float) Math.cos(cp1Theta);
float cp1Dy = (float) Math.sin(cp1Theta);
float cp2Theta = (float) (Math.atan2(y, x) - Math.PI / 2f);
float cp2Dx = (float) Math.cos(cp2Theta);
float cp2Dy = (float) Math.sin(cp2Theta);
float cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness;
float cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness;
float cp1Radius = longSegment ? innerRadius : outerRadius;
float cp2Radius = longSegment ? outerRadius : innerRadius;
float cp1x = cp1Radius * cp1Roundedness * POLYSTAR_MAGIC_NUMBER * cp1Dx;
float cp1y = cp1Radius * cp1Roundedness * POLYSTAR_MAGIC_NUMBER * cp1Dy;
float cp2x = cp2Radius * cp2Roundedness * POLYSTAR_MAGIC_NUMBER * cp2Dx;
float cp2y = cp2Radius * cp2Roundedness * POLYSTAR_MAGIC_NUMBER * cp2Dy;
if (partialPointAmount != 0) {
if (i == 0) {
cp1x *= partialPointAmount;
cp1y *= partialPointAmount;
} else if (i == numPoints - 1) {
cp2x *= partialPointAmount;
cp2y *= partialPointAmount;
}
}
path.cubicTo(previousX - cp1x, previousY - cp1y, x + cp2x, y + cp2y, x, y);
}
currentAngle += dTheta;
longSegment = !longSegment;
}
PointF position = positionAnimation.getValue();
path.offset(position.x, position.y);
path.close();
}
private void createPolygonPath() {
int points = (int) Math.floor(pointsAnimation.getValue());
double currentAngle = rotationAnimation == null ? 0f : rotationAnimation.getValue();
// Start at +y instead of +x
currentAngle -= 90;
// convert to radians
currentAngle = Math.toRadians(currentAngle);
// adjust current angle for partial points
float anglePerPoint = (float) (2 * Math.PI / points);
float roundedness = outerRoundednessAnimation.getValue() / 100f;
float radius = outerRadiusAnimation.getValue();
float x;
float y;
float previousX;
float previousY;
x = (float) (radius * Math.cos(currentAngle));
y = (float) (radius * Math.sin(currentAngle));
path.moveTo(x, y);
currentAngle += anglePerPoint;
double numPoints = Math.ceil(points);
for (int i = 0; i < numPoints; i++) {
previousX = x;
previousY = y;
x = (float) (radius * Math.cos(currentAngle));
y = (float) (radius * Math.sin(currentAngle));
if (roundedness != 0) {
float cp1Theta = (float) (Math.atan2(previousY, previousX) - Math.PI / 2f);
float cp1Dx = (float) Math.cos(cp1Theta);
float cp1Dy = (float) Math.sin(cp1Theta);
float cp2Theta = (float) (Math.atan2(y, x) - Math.PI / 2f);
float cp2Dx = (float) Math.cos(cp2Theta);
float cp2Dy = (float) Math.sin(cp2Theta);
float cp1x = radius * roundedness * POLYGON_MAGIC_NUMBER * cp1Dx;
float cp1y = radius * roundedness * POLYGON_MAGIC_NUMBER * cp1Dy;
float cp2x = radius * roundedness * POLYGON_MAGIC_NUMBER * cp2Dx;
float cp2y = radius * roundedness * POLYGON_MAGIC_NUMBER * cp2Dy;
path.cubicTo(previousX - cp1x, previousY - cp1y, x + cp2x, y + cp2y, x, y);
} else {
path.lineTo(x, y);
}
currentAngle += anglePerPoint;
}
PointF position = positionAnimation.getValue();
path.offset(position.x, position.y);
path.close();
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.POLYSTAR_POINTS) {
pointsAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.POLYSTAR_ROTATION) {
rotationAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.POSITION) {
positionAnimation.setValueCallback((LottieValueCallback<PointF>) callback);
} else if (property == LottieProperty.POLYSTAR_INNER_RADIUS && innerRadiusAnimation != null) {
innerRadiusAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.POLYSTAR_OUTER_RADIUS) {
outerRadiusAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.POLYSTAR_INNER_ROUNDEDNESS && innerRoundednessAnimation != null) {
innerRoundednessAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.POLYSTAR_OUTER_ROUNDEDNESS) {
outerRoundednessAnimation.setValueCallback((LottieValueCallback<Float>) callback);
}
}
}
| 2,459 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/GreedyContent.java | package com.airbnb.lottie.animation.content;
import java.util.ListIterator;
/**
* Content that may want to absorb and take ownership of the content around it.
* For example, merge paths will absorb the shapes above it and repeaters will absorb the content
* above it.
*/
interface GreedyContent {
/**
* An iterator of contents that can be used to take ownership of contents. If ownership is taken,
* the content should be removed from the iterator.
* <p>
* The contents should be iterated by calling hasPrevious() and previous() so that the list of
* contents is traversed from bottom to top which is the correct order for handling AE logic.
*/
void absorbContent(ListIterator<Content> contents);
}
| 2,460 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/ShapeContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ShapeKeyframeAnimation;
import com.airbnb.lottie.model.content.ShapePath;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import java.util.ArrayList;
import java.util.List;
public class ShapeContent implements PathContent, BaseKeyframeAnimation.AnimationListener {
private final Path path = new Path();
private final String name;
private final boolean hidden;
private final LottieDrawable lottieDrawable;
private final ShapeKeyframeAnimation shapeAnimation;
@Nullable private List<ShapeModifierContent> shapeModifierContents;
private boolean isPathValid;
private final CompoundTrimPathContent trimPaths = new CompoundTrimPathContent();
public ShapeContent(LottieDrawable lottieDrawable, BaseLayer layer, ShapePath shape) {
name = shape.getName();
hidden = shape.isHidden();
this.lottieDrawable = lottieDrawable;
shapeAnimation = shape.getShapePath().createAnimation();
layer.addAnimation(shapeAnimation);
shapeAnimation.addUpdateListener(this);
}
@Override public void onValueChanged() {
invalidate();
}
private void invalidate() {
isPathValid = false;
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
@Nullable List<ShapeModifierContent> shapeModifierContents = null;
for (int i = 0; i < contentsBefore.size(); i++) {
Content content = contentsBefore.get(i);
if (content instanceof TrimPathContent &&
((TrimPathContent) content).getType() == ShapeTrimPath.Type.SIMULTANEOUSLY) {
// Trim path individually will be handled by the stroke where paths are combined.
TrimPathContent trimPath = (TrimPathContent) content;
trimPaths.addTrimPath(trimPath);
trimPath.addListener(this);
} else if (content instanceof ShapeModifierContent) {
if (shapeModifierContents == null) {
shapeModifierContents = new ArrayList<>();
}
shapeModifierContents.add((ShapeModifierContent) content);
}
}
shapeAnimation.setShapeModifiers(shapeModifierContents);
}
@Override public Path getPath() {
if (isPathValid) {
return path;
}
path.reset();
if (hidden) {
isPathValid = true;
return path;
}
Path shapeAnimationPath = shapeAnimation.getValue();
if (shapeAnimationPath == null) {
// It is unclear why this ever returns null but it seems to in rare cases.
// https://github.com/airbnb/lottie-android/issues/1632
return path;
}
path.set(shapeAnimationPath);
path.setFillType(Path.FillType.EVEN_ODD);
trimPaths.apply(path);
isPathValid = true;
return path;
}
@Override public String getName() {
return name;
}
}
| 2,461 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/KeyPathElementContent.java | package com.airbnb.lottie.animation.content;
import com.airbnb.lottie.model.KeyPathElement;
public interface KeyPathElementContent extends KeyPathElement, Content {
}
| 2,462 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/CompoundTrimPathContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
import com.airbnb.lottie.utils.Utils;
import java.util.ArrayList;
import java.util.List;
public class CompoundTrimPathContent {
private final List<TrimPathContent> contents = new ArrayList<>();
void addTrimPath(TrimPathContent trimPath) {
contents.add(trimPath);
}
public void apply(Path path) {
for (int i = contents.size() - 1; i >= 0; i--) {
Utils.applyTrimPathIfNeeded(path, contents.get(i));
}
}
}
| 2,463 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/GradientStrokeContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.content.GradientColor;
import com.airbnb.lottie.model.content.GradientStroke;
import com.airbnb.lottie.model.content.GradientType;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.value.LottieValueCallback;
public class GradientStrokeContent extends BaseStrokeContent {
/**
* Cache the gradients such that it runs at 30fps.
*/
private static final int CACHE_STEPS_MS = 32;
private final String name;
private final boolean hidden;
private final LongSparseArray<LinearGradient> linearGradientCache = new LongSparseArray<>();
private final LongSparseArray<RadialGradient> radialGradientCache = new LongSparseArray<>();
private final RectF boundsRect = new RectF();
private final GradientType type;
private final int cacheSteps;
private final BaseKeyframeAnimation<GradientColor, GradientColor> colorAnimation;
private final BaseKeyframeAnimation<PointF, PointF> startPointAnimation;
private final BaseKeyframeAnimation<PointF, PointF> endPointAnimation;
@Nullable private ValueCallbackKeyframeAnimation colorCallbackAnimation;
public GradientStrokeContent(
final LottieDrawable lottieDrawable, BaseLayer layer, GradientStroke stroke) {
super(lottieDrawable, layer, stroke.getCapType().toPaintCap(),
stroke.getJoinType().toPaintJoin(), stroke.getMiterLimit(), stroke.getOpacity(),
stroke.getWidth(), stroke.getLineDashPattern(), stroke.getDashOffset());
name = stroke.getName();
type = stroke.getGradientType();
hidden = stroke.isHidden();
cacheSteps = (int) (lottieDrawable.getComposition().getDuration() / CACHE_STEPS_MS);
colorAnimation = stroke.getGradientColor().createAnimation();
colorAnimation.addUpdateListener(this);
layer.addAnimation(colorAnimation);
startPointAnimation = stroke.getStartPoint().createAnimation();
startPointAnimation.addUpdateListener(this);
layer.addAnimation(startPointAnimation);
endPointAnimation = stroke.getEndPoint().createAnimation();
endPointAnimation.addUpdateListener(this);
layer.addAnimation(endPointAnimation);
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
getBounds(boundsRect, parentMatrix, false);
Shader shader;
if (type == GradientType.LINEAR) {
shader = getLinearGradient();
} else {
shader = getRadialGradient();
}
shader.setLocalMatrix(parentMatrix);
paint.setShader(shader);
super.draw(canvas, parentMatrix, parentAlpha);
}
@Override public String getName() {
return name;
}
private LinearGradient getLinearGradient() {
int gradientHash = getGradientHash();
LinearGradient gradient = linearGradientCache.get(gradientHash);
if (gradient != null) {
return gradient;
}
PointF startPoint = startPointAnimation.getValue();
PointF endPoint = endPointAnimation.getValue();
GradientColor gradientColor = colorAnimation.getValue();
int[] colors = applyDynamicColorsIfNeeded(gradientColor.getColors());
float[] positions = gradientColor.getPositions();
float x0 = startPoint.x;
float y0 = startPoint.y;
float x1 = endPoint.x;
float y1 = endPoint.y;
gradient = new LinearGradient(x0, y0, x1, y1, colors, positions, Shader.TileMode.CLAMP);
linearGradientCache.put(gradientHash, gradient);
return gradient;
}
private RadialGradient getRadialGradient() {
int gradientHash = getGradientHash();
RadialGradient gradient = radialGradientCache.get(gradientHash);
if (gradient != null) {
return gradient;
}
PointF startPoint = startPointAnimation.getValue();
PointF endPoint = endPointAnimation.getValue();
GradientColor gradientColor = colorAnimation.getValue();
int[] colors = applyDynamicColorsIfNeeded(gradientColor.getColors());
float[] positions = gradientColor.getPositions();
float x0 = startPoint.x;
float y0 = startPoint.y;
float x1 = endPoint.x;
float y1 = endPoint.y;
float r = (float) Math.hypot(x1 - x0, y1 - y0);
gradient = new RadialGradient(x0, y0, r, colors, positions, Shader.TileMode.CLAMP);
radialGradientCache.put(gradientHash, gradient);
return gradient;
}
private int getGradientHash() {
int startPointProgress = Math.round(startPointAnimation.getProgress() * cacheSteps);
int endPointProgress = Math.round(endPointAnimation.getProgress() * cacheSteps);
int colorProgress = Math.round(colorAnimation.getProgress() * cacheSteps);
int hash = 17;
if (startPointProgress != 0) {
hash = hash * 31 * startPointProgress;
}
if (endPointProgress != 0) {
hash = hash * 31 * endPointProgress;
}
if (colorProgress != 0) {
hash = hash * 31 * colorProgress;
}
return hash;
}
private int[] applyDynamicColorsIfNeeded(int[] colors) {
if (colorCallbackAnimation != null) {
Integer[] dynamicColors = (Integer[]) colorCallbackAnimation.getValue();
if (colors.length == dynamicColors.length) {
for (int i = 0; i < colors.length; i++) {
colors[i] = dynamicColors[i];
}
} else {
colors = new int[dynamicColors.length];
for (int i = 0; i < dynamicColors.length; i++) {
colors[i] = dynamicColors[i];
}
}
}
return colors;
}
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
super.addValueCallback(property, callback);
if (property == LottieProperty.GRADIENT_COLOR) {
if (colorCallbackAnimation != null) {
layer.removeAnimation(colorCallbackAnimation);
}
if (callback == null) {
colorCallbackAnimation = null;
} else {
colorCallbackAnimation = new ValueCallbackKeyframeAnimation<>(callback);
colorCallbackAnimation.addUpdateListener(this);
layer.addAnimation(colorCallbackAnimation);
}
}
}
}
| 2,464 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/EllipseContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.CircleShape;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.List;
public class EllipseContent
implements PathContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent {
private static final float ELLIPSE_CONTROL_POINT_PERCENTAGE = 0.55228f;
private final Path path = new Path();
private final String name;
private final LottieDrawable lottieDrawable;
private final BaseKeyframeAnimation<?, PointF> sizeAnimation;
private final BaseKeyframeAnimation<?, PointF> positionAnimation;
private final CircleShape circleShape;
private final CompoundTrimPathContent trimPaths = new CompoundTrimPathContent();
private boolean isPathValid;
public EllipseContent(LottieDrawable lottieDrawable, BaseLayer layer, CircleShape circleShape) {
name = circleShape.getName();
this.lottieDrawable = lottieDrawable;
sizeAnimation = circleShape.getSize().createAnimation();
positionAnimation = circleShape.getPosition().createAnimation();
this.circleShape = circleShape;
layer.addAnimation(sizeAnimation);
layer.addAnimation(positionAnimation);
sizeAnimation.addUpdateListener(this);
positionAnimation.addUpdateListener(this);
}
@Override public void onValueChanged() {
invalidate();
}
private void invalidate() {
isPathValid = false;
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < contentsBefore.size(); i++) {
Content content = contentsBefore.get(i);
if (content instanceof TrimPathContent && ((TrimPathContent) content).getType() == ShapeTrimPath.Type.SIMULTANEOUSLY) {
TrimPathContent trimPath = (TrimPathContent) content;
trimPaths.addTrimPath(trimPath);
trimPath.addListener(this);
}
}
}
@Override public String getName() {
return name;
}
@Override public Path getPath() {
if (isPathValid) {
return path;
}
path.reset();
if (circleShape.isHidden()) {
isPathValid = true;
return path;
}
PointF size = sizeAnimation.getValue();
float halfWidth = size.x / 2f;
float halfHeight = size.y / 2f;
// TODO: handle bounds
float cpW = halfWidth * ELLIPSE_CONTROL_POINT_PERCENTAGE;
float cpH = halfHeight * ELLIPSE_CONTROL_POINT_PERCENTAGE;
path.reset();
if (circleShape.isReversed()) {
path.moveTo(0, -halfHeight);
path.cubicTo(0 - cpW, -halfHeight, -halfWidth, 0 - cpH, -halfWidth, 0);
path.cubicTo(-halfWidth, 0 + cpH, 0 - cpW, halfHeight, 0, halfHeight);
path.cubicTo(0 + cpW, halfHeight, halfWidth, 0 + cpH, halfWidth, 0);
path.cubicTo(halfWidth, 0 - cpH, 0 + cpW, -halfHeight, 0, -halfHeight);
} else {
path.moveTo(0, -halfHeight);
path.cubicTo(0 + cpW, -halfHeight, halfWidth, 0 - cpH, halfWidth, 0);
path.cubicTo(halfWidth, 0 + cpH, 0 + cpW, halfHeight, 0, halfHeight);
path.cubicTo(0 - cpW, halfHeight, -halfWidth, 0 + cpH, -halfWidth, 0);
path.cubicTo(-halfWidth, 0 - cpH, 0 - cpW, -halfHeight, 0, -halfHeight);
}
PointF position = positionAnimation.getValue();
path.offset(position.x, position.y);
path.close();
trimPaths.apply(path);
isPathValid = true;
return path;
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.ELLIPSE_SIZE) {
sizeAnimation.setValueCallback((LottieValueCallback<PointF>) callback);
} else if (property == LottieProperty.POSITION) {
positionAnimation.setValueCallback((LottieValueCallback<PointF>) callback);
}
}
}
| 2,465 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/PathContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Path;
interface PathContent extends Content {
Path getPath();
}
| 2,466 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/RoundedCornersContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.PointF;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.model.CubicCurveData;
import com.airbnb.lottie.model.content.RoundedCorners;
import com.airbnb.lottie.model.content.ShapeData;
import com.airbnb.lottie.model.layer.BaseLayer;
import java.util.ArrayList;
import java.util.List;
public class RoundedCornersContent implements ShapeModifierContent, BaseKeyframeAnimation.AnimationListener {
/**
* Copied from:
* https://github.com/airbnb/lottie-web/blob/bb71072a26e03f1ca993da60915860f39aae890b/player/js/utils/common.js#L47
*/
private static final float ROUNDED_CORNER_MAGIC_NUMBER = 0.5519f;
private final LottieDrawable lottieDrawable;
private final String name;
private final BaseKeyframeAnimation<Float, Float> roundedCorners;
@Nullable private ShapeData shapeData;
public RoundedCornersContent(LottieDrawable lottieDrawable, BaseLayer layer, RoundedCorners roundedCorners) {
this.lottieDrawable = lottieDrawable;
this.name = roundedCorners.getName();
this.roundedCorners = roundedCorners.getCornerRadius().createAnimation();
layer.addAnimation(this.roundedCorners);
this.roundedCorners.addUpdateListener(this);
}
@Override public String getName() {
return name;
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
// Do nothing.
}
public BaseKeyframeAnimation<Float, Float> getRoundedCorners() {
return roundedCorners;
}
/**
* Rounded corner algorithm:
* Iterate through each vertex.
* If a vertex is a sharp corner, it rounds it.
* If a vertex has control points, it is already rounded, so it does nothing.
* <p>
* To round a vertex:
* Split the vertex into two.
* Move vertex 1 directly towards the previous vertex.
* Set vertex 1's in control point to itself so it is not rounded on that side.
* Extend vertex 1's out control point towards the original vertex.
* <p>
* Repeat for vertex 2:
* Move vertex 2 directly towards the next vertex.
* Set vertex 2's out point to itself so it is not rounded on that side.
* Extend vertex 2's in control point towards the original vertex.
* <p>
* The distance that the vertices and control points are moved are relative to the
* shape's vertex distances and the roundedness set in the animation.
*/
@Override public ShapeData modifyShape(ShapeData startingShapeData) {
List<CubicCurveData> startingCurves = startingShapeData.getCurves();
if (startingCurves.size() <= 2) {
return startingShapeData;
}
float roundedness = roundedCorners.getValue();
if (roundedness == 0f) {
return startingShapeData;
}
ShapeData modifiedShapeData = getShapeData(startingShapeData);
modifiedShapeData.setInitialPoint(startingShapeData.getInitialPoint().x, startingShapeData.getInitialPoint().y);
List<CubicCurveData> modifiedCurves = modifiedShapeData.getCurves();
int modifiedCurvesIndex = 0;
boolean isClosed = startingShapeData.isClosed();
// i represents which vertex we are currently on. Refer to the docs of CubicCurveData prior to working with
// this code.
// When i == 0
// vertex=ShapeData.initialPoint
// inCp=if closed vertex else curves[size - 1].cp2
// outCp=curves[0].cp1
// When i == 1
// vertex=curves[0].vertex
// inCp=curves[0].cp2
// outCp=curves[1].cp1.
// When i == size - 1
// vertex=curves[size - 1].vertex
// inCp=curves[size - 1].cp2
// outCp=if closed vertex else curves[0].cp1
for (int i = 0; i < startingCurves.size(); i++) {
CubicCurveData startingCurve = startingCurves.get(i);
CubicCurveData previousCurve = startingCurves.get(floorMod(i - 1, startingCurves.size()));
CubicCurveData previousPreviousCurve = startingCurves.get(floorMod(i - 2, startingCurves.size()));
PointF vertex = (i == 0 && !isClosed) ? startingShapeData.getInitialPoint() : previousCurve.getVertex();
PointF inPoint = (i == 0 && !isClosed) ? vertex : previousCurve.getControlPoint2();
PointF outPoint = startingCurve.getControlPoint1();
PointF previousVertex = previousPreviousCurve.getVertex();
PointF nextVertex = startingCurve.getVertex();
// We can't round the corner of the end of a non-closed curve.
boolean isEndOfCurve = !startingShapeData.isClosed() && (i == 0 || i == startingCurves.size() - 1);
if (inPoint.equals(vertex) && outPoint.equals(vertex) && !isEndOfCurve) {
// This vertex is a point. Round its corners
float dxToPreviousVertex = vertex.x - previousVertex.x;
float dyToPreviousVertex = vertex.y - previousVertex.y;
float dxToNextVertex = nextVertex.x - vertex.x;
float dyToNextVertex = nextVertex.y - vertex.y;
float dToPreviousVertex = (float) Math.hypot(dxToPreviousVertex, dyToPreviousVertex);
float dToNextVertex = (float) Math.hypot(dxToNextVertex, dyToNextVertex);
float previousVertexPercent = Math.min(roundedness / dToPreviousVertex, 0.5f);
float nextVertexPercent = Math.min(roundedness / dToNextVertex, 0.5f);
// Split the vertex into two and move each vertex towards the previous/next vertex.
float newVertex1X = vertex.x + (previousVertex.x - vertex.x) * previousVertexPercent;
float newVertex1Y = vertex.y + (previousVertex.y - vertex.y) * previousVertexPercent;
float newVertex2X = vertex.x + (nextVertex.x - vertex.x) * nextVertexPercent;
float newVertex2Y = vertex.y + (nextVertex.y - vertex.y) * nextVertexPercent;
// Extend the new vertex control point towards the original vertex.
float newVertex1OutPointX = newVertex1X - (newVertex1X - vertex.x) * ROUNDED_CORNER_MAGIC_NUMBER;
float newVertex1OutPointY = newVertex1Y - (newVertex1Y - vertex.y) * ROUNDED_CORNER_MAGIC_NUMBER;
float newVertex2InPointX = newVertex2X - (newVertex2X - vertex.x) * ROUNDED_CORNER_MAGIC_NUMBER;
float newVertex2InPointY = newVertex2Y - (newVertex2Y - vertex.y) * ROUNDED_CORNER_MAGIC_NUMBER;
// Remap vertex/in/out point to CubicCurveData.
// Refer to the docs for CubicCurveData for more info on the difference.
CubicCurveData previousCurveData = modifiedCurves.get(floorMod(modifiedCurvesIndex - 1, modifiedCurves.size()));
CubicCurveData currentCurveData = modifiedCurves.get(modifiedCurvesIndex);
previousCurveData.setControlPoint2(newVertex1X, newVertex1Y);
previousCurveData.setVertex(newVertex1X, newVertex1Y);
if (i == 0) {
modifiedShapeData.setInitialPoint(newVertex1X, newVertex1Y);
}
currentCurveData.setControlPoint1(newVertex1OutPointX, newVertex1OutPointY);
modifiedCurvesIndex++;
previousCurveData = currentCurveData;
currentCurveData = modifiedCurves.get(modifiedCurvesIndex);
previousCurveData.setControlPoint2(newVertex2InPointX, newVertex2InPointY);
previousCurveData.setVertex(newVertex2X, newVertex2Y);
currentCurveData.setControlPoint1(newVertex2X, newVertex2Y);
modifiedCurvesIndex++;
} else {
// This vertex is not a point. Don't modify it. Refer to the documentation above and for CubicCurveData for mapping a vertex
// oriented point to CubicCurveData (path segments).
CubicCurveData previousCurveData = modifiedCurves.get(floorMod(modifiedCurvesIndex - 1, modifiedCurves.size()));
CubicCurveData currentCurveData = modifiedCurves.get(modifiedCurvesIndex);
previousCurveData.setControlPoint2(previousCurve.getControlPoint2().x, previousCurve.getControlPoint2().y);
previousCurveData.setVertex(previousCurve.getVertex().x, previousCurve.getVertex().y);
currentCurveData.setControlPoint1(startingCurve.getControlPoint1().x, startingCurve.getControlPoint1().y);
modifiedCurvesIndex++;
}
}
return modifiedShapeData;
}
/**
* Returns a shape data with the correct number of vertices for the rounded corners shape.
* This just returns the object. It does not update any values within the shape.
*/
@NonNull
private ShapeData getShapeData(ShapeData startingShapeData) {
List<CubicCurveData> startingCurves = startingShapeData.getCurves();
boolean isClosed = startingShapeData.isClosed();
int vertices = 0;
for (int i = startingCurves.size() - 1; i >= 0; i--) {
CubicCurveData startingCurve = startingCurves.get(i);
CubicCurveData previousCurve = startingCurves.get(floorMod(i - 1, startingCurves.size()));
PointF vertex = (i == 0 && !isClosed) ? startingShapeData.getInitialPoint() : previousCurve.getVertex();
PointF inPoint = (i == 0 && !isClosed) ? vertex : previousCurve.getControlPoint2();
PointF outPoint = startingCurve.getControlPoint1();
boolean isEndOfCurve = !startingShapeData.isClosed() && (i == 0 || i == startingCurves.size() - 1);
if (inPoint.equals(vertex) && outPoint.equals(vertex) && !isEndOfCurve) {
vertices += 2;
} else {
vertices += 1;
}
}
if (shapeData == null || shapeData.getCurves().size() != vertices) {
List<CubicCurveData> newCurves = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
newCurves.add(new CubicCurveData());
}
shapeData = new ShapeData(new PointF(0f, 0f), false, newCurves);
}
shapeData.setClosed(isClosed);
return shapeData;
}
/**
* Copied from the API 24+ AOSP source.
*/
private static int floorMod(int x, int y) {
return x - floorDiv(x, y) * y;
}
/**
* Copied from the API 24+ AOSP source.
*/
private static int floorDiv(int x, int y) {
int r = x / y;
// if the signs are different and modulo not zero, round down
if ((x ^ y) < 0 && (r * y != x)) {
r--;
}
return r;
}
}
| 2,467 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/ContentGroup.java | package com.airbnb.lottie.animation.content;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.KeyPathElement;
import com.airbnb.lottie.model.animatable.AnimatableTransform;
import com.airbnb.lottie.model.content.ContentModel;
import com.airbnb.lottie.model.content.ShapeGroup;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
public class ContentGroup implements DrawingContent, PathContent,
BaseKeyframeAnimation.AnimationListener, KeyPathElement {
private final Paint offScreenPaint = new LPaint();
private final RectF offScreenRectF = new RectF();
private static List<Content> contentsFromModels(LottieDrawable drawable, LottieComposition composition, BaseLayer layer,
List<ContentModel> contentModels) {
List<Content> contents = new ArrayList<>(contentModels.size());
for (int i = 0; i < contentModels.size(); i++) {
Content content = contentModels.get(i).toContent(drawable, composition, layer);
if (content != null) {
contents.add(content);
}
}
return contents;
}
@Nullable static AnimatableTransform findTransform(List<ContentModel> contentModels) {
for (int i = 0; i < contentModels.size(); i++) {
ContentModel contentModel = contentModels.get(i);
if (contentModel instanceof AnimatableTransform) {
return (AnimatableTransform) contentModel;
}
}
return null;
}
private final Matrix matrix = new Matrix();
private final Path path = new Path();
private final RectF rect = new RectF();
private final String name;
private final boolean hidden;
private final List<Content> contents;
private final LottieDrawable lottieDrawable;
@Nullable private List<PathContent> pathContents;
@Nullable private TransformKeyframeAnimation transformAnimation;
public ContentGroup(final LottieDrawable lottieDrawable, BaseLayer layer, ShapeGroup shapeGroup, LottieComposition composition) {
this(lottieDrawable, layer, shapeGroup.getName(),
shapeGroup.isHidden(), contentsFromModels(lottieDrawable, composition, layer, shapeGroup.getItems()),
findTransform(shapeGroup.getItems()));
}
ContentGroup(final LottieDrawable lottieDrawable, BaseLayer layer,
String name, boolean hidden, List<Content> contents, @Nullable AnimatableTransform transform) {
this.name = name;
this.lottieDrawable = lottieDrawable;
this.hidden = hidden;
this.contents = contents;
if (transform != null) {
transformAnimation = transform.createAnimation();
transformAnimation.addAnimationsToLayer(layer);
transformAnimation.addListener(this);
}
List<GreedyContent> greedyContents = new ArrayList<>();
for (int i = contents.size() - 1; i >= 0; i--) {
Content content = contents.get(i);
if (content instanceof GreedyContent) {
greedyContents.add((GreedyContent) content);
}
}
for (int i = greedyContents.size() - 1; i >= 0; i--) {
greedyContents.get(i).absorbContent(contents.listIterator(contents.size()));
}
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public String getName() {
return name;
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
// Do nothing with contents after.
List<Content> myContentsBefore = new ArrayList<>(contentsBefore.size() + contents.size());
myContentsBefore.addAll(contentsBefore);
for (int i = contents.size() - 1; i >= 0; i--) {
Content content = contents.get(i);
content.setContents(myContentsBefore, contents.subList(0, i));
myContentsBefore.add(content);
}
}
public List<Content> getContents() {
return contents;
}
List<PathContent> getPathList() {
if (pathContents == null) {
pathContents = new ArrayList<>();
for (int i = 0; i < contents.size(); i++) {
Content content = contents.get(i);
if (content instanceof PathContent) {
pathContents.add((PathContent) content);
}
}
}
return pathContents;
}
Matrix getTransformationMatrix() {
if (transformAnimation != null) {
return transformAnimation.getMatrix();
}
matrix.reset();
return matrix;
}
@Override public Path getPath() {
// TODO: cache this somehow.
matrix.reset();
if (transformAnimation != null) {
matrix.set(transformAnimation.getMatrix());
}
path.reset();
if (hidden) {
return path;
}
for (int i = contents.size() - 1; i >= 0; i--) {
Content content = contents.get(i);
if (content instanceof PathContent) {
path.addPath(((PathContent) content).getPath(), matrix);
}
}
return path;
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
matrix.set(parentMatrix);
int layerAlpha;
if (transformAnimation != null) {
matrix.preConcat(transformAnimation.getMatrix());
int opacity = transformAnimation.getOpacity() == null ? 100 : transformAnimation.getOpacity().getValue();
layerAlpha = (int) ((opacity / 100f * parentAlpha / 255f) * 255);
} else {
layerAlpha = parentAlpha;
}
// Apply off-screen rendering only when needed in order to improve rendering performance.
boolean isRenderingWithOffScreen = lottieDrawable.isApplyingOpacityToLayersEnabled() && hasTwoOrMoreDrawableContent() && layerAlpha != 255;
if (isRenderingWithOffScreen) {
offScreenRectF.set(0, 0, 0, 0);
getBounds(offScreenRectF, matrix, true);
offScreenPaint.setAlpha(layerAlpha);
Utils.saveLayerCompat(canvas, offScreenRectF, offScreenPaint);
}
int childAlpha = isRenderingWithOffScreen ? 255 : layerAlpha;
for (int i = contents.size() - 1; i >= 0; i--) {
Object content = contents.get(i);
if (content instanceof DrawingContent) {
((DrawingContent) content).draw(canvas, matrix, childAlpha);
}
}
if (isRenderingWithOffScreen) {
canvas.restore();
}
}
private boolean hasTwoOrMoreDrawableContent() {
int drawableContentCount = 0;
for (int i = 0; i < contents.size(); i++) {
if (contents.get(i) instanceof DrawingContent) {
drawableContentCount += 1;
if (drawableContentCount >= 2) {
return true;
}
}
}
return false;
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
matrix.set(parentMatrix);
if (transformAnimation != null) {
matrix.preConcat(transformAnimation.getMatrix());
}
rect.set(0, 0, 0, 0);
for (int i = contents.size() - 1; i >= 0; i--) {
Content content = contents.get(i);
if (content instanceof DrawingContent) {
((DrawingContent) content).getBounds(rect, matrix, applyParents);
outBounds.union(rect);
}
}
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
if (!keyPath.matches(getName(), depth) && !"__container".equals(getName())) {
return;
}
if (!"__container".equals(getName())) {
currentPartialKeyPath = currentPartialKeyPath.addKey(getName());
if (keyPath.fullyResolvesTo(getName(), depth)) {
accumulator.add(currentPartialKeyPath.resolve(this));
}
}
if (keyPath.propagateToChildren(getName(), depth)) {
int newDepth = depth + keyPath.incrementDepthBy(getName(), depth);
for (int i = 0; i < contents.size(); i++) {
Content content = contents.get(i);
if (content instanceof KeyPathElement) {
KeyPathElement element = (KeyPathElement) content;
element.resolveKeyPath(keyPath, newDepth, accumulator, currentPartialKeyPath);
}
}
}
}
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (transformAnimation != null) {
transformAnimation.applyValueCallback(property, callback);
}
}
}
| 2,468 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/TrimPathContent.java | package com.airbnb.lottie.animation.content;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import java.util.ArrayList;
import java.util.List;
public class TrimPathContent implements Content, BaseKeyframeAnimation.AnimationListener {
private final String name;
private final boolean hidden;
private final List<BaseKeyframeAnimation.AnimationListener> listeners = new ArrayList<>();
private final ShapeTrimPath.Type type;
private final BaseKeyframeAnimation<?, Float> startAnimation;
private final BaseKeyframeAnimation<?, Float> endAnimation;
private final BaseKeyframeAnimation<?, Float> offsetAnimation;
public TrimPathContent(BaseLayer layer, ShapeTrimPath trimPath) {
name = trimPath.getName();
hidden = trimPath.isHidden();
type = trimPath.getType();
startAnimation = trimPath.getStart().createAnimation();
endAnimation = trimPath.getEnd().createAnimation();
offsetAnimation = trimPath.getOffset().createAnimation();
layer.addAnimation(startAnimation);
layer.addAnimation(endAnimation);
layer.addAnimation(offsetAnimation);
startAnimation.addUpdateListener(this);
endAnimation.addUpdateListener(this);
offsetAnimation.addUpdateListener(this);
}
@Override public void onValueChanged() {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onValueChanged();
}
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
// Do nothing.
}
@Override public String getName() {
return name;
}
void addListener(BaseKeyframeAnimation.AnimationListener listener) {
listeners.add(listener);
}
ShapeTrimPath.Type getType() {
return type;
}
public BaseKeyframeAnimation<?, Float> getStart() {
return startAnimation;
}
public BaseKeyframeAnimation<?, Float> getEnd() {
return endAnimation;
}
public BaseKeyframeAnimation<?, Float> getOffset() {
return offsetAnimation;
}
public boolean isHidden() {
return hidden;
}
}
| 2,469 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/RepeaterContent.java | package com.airbnb.lottie.animation.content;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.Repeater;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class RepeaterContent implements DrawingContent, PathContent, GreedyContent,
BaseKeyframeAnimation.AnimationListener, KeyPathElementContent {
private final Matrix matrix = new Matrix();
private final Path path = new Path();
private final LottieDrawable lottieDrawable;
private final BaseLayer layer;
private final String name;
private final boolean hidden;
private final BaseKeyframeAnimation<Float, Float> copies;
private final BaseKeyframeAnimation<Float, Float> offset;
private final TransformKeyframeAnimation transform;
private ContentGroup contentGroup;
public RepeaterContent(LottieDrawable lottieDrawable, BaseLayer layer, Repeater repeater) {
this.lottieDrawable = lottieDrawable;
this.layer = layer;
name = repeater.getName();
this.hidden = repeater.isHidden();
copies = repeater.getCopies().createAnimation();
layer.addAnimation(copies);
copies.addUpdateListener(this);
offset = repeater.getOffset().createAnimation();
layer.addAnimation(offset);
offset.addUpdateListener(this);
transform = repeater.getTransform().createAnimation();
transform.addAnimationsToLayer(layer);
transform.addListener(this);
}
@Override public void absorbContent(ListIterator<Content> contentsIter) {
// This check prevents a repeater from getting added twice.
// This can happen in the following situation:
// RECTANGLE
// REPEATER 1
// FILL
// REPEATER 2
// In this case, the expected structure would be:
// REPEATER 2
// REPEATER 1
// RECTANGLE
// FILL
// Without this check, REPEATER 1 will try and absorb contents once it is already inside of
// REPEATER 2.
if (contentGroup != null) {
return;
}
// Fast forward the iterator until after this content.
//noinspection StatementWithEmptyBody
while (contentsIter.hasPrevious() && contentsIter.previous() != this) {
}
List<Content> contents = new ArrayList<>();
while (contentsIter.hasPrevious()) {
contents.add(contentsIter.previous());
contentsIter.remove();
}
Collections.reverse(contents);
contentGroup = new ContentGroup(lottieDrawable, layer, "Repeater", hidden, contents, null);
}
@Override public String getName() {
return name;
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
contentGroup.setContents(contentsBefore, contentsAfter);
}
@Override public Path getPath() {
Path contentPath = contentGroup.getPath();
path.reset();
float copies = this.copies.getValue();
float offset = this.offset.getValue();
for (int i = (int) copies - 1; i >= 0; i--) {
matrix.set(transform.getMatrixForRepeater(i + offset));
path.addPath(contentPath, matrix);
}
return path;
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int alpha) {
float copies = this.copies.getValue();
float offset = this.offset.getValue();
//noinspection ConstantConditions
float startOpacity = this.transform.getStartOpacity().getValue() / 100f;
//noinspection ConstantConditions
float endOpacity = this.transform.getEndOpacity().getValue() / 100f;
for (int i = (int) copies - 1; i >= 0; i--) {
matrix.set(parentMatrix);
matrix.preConcat(transform.getMatrixForRepeater(i + offset));
float newAlpha = alpha * MiscUtils.lerp(startOpacity, endOpacity, i / copies);
contentGroup.draw(canvas, matrix, (int) newAlpha);
}
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
contentGroup.getBounds(outBounds, parentMatrix, applyParents);
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
for (int i = 0; i < contentGroup.getContents().size(); i++) {
Content content = contentGroup.getContents().get(i);
if (content instanceof KeyPathElementContent) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, (KeyPathElementContent) content);
}
}
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (transform.applyValueCallback(property, callback)) {
return;
}
if (property == LottieProperty.REPEATER_COPIES) {
copies.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.REPEATER_OFFSET) {
offset.setValueCallback((LottieValueCallback<Float>) callback);
}
}
}
| 2,470 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/GradientFillContent.java | package com.airbnb.lottie.animation.content;
import static com.airbnb.lottie.utils.MiscUtils.clamp;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.DropShadowKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.content.GradientColor;
import com.airbnb.lottie.model.content.GradientFill;
import com.airbnb.lottie.model.content.GradientType;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
public class GradientFillContent
implements DrawingContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent {
/**
* Cache the gradients such that it runs at 30fps.
*/
private static final int CACHE_STEPS_MS = 32;
@NonNull private final String name;
private final boolean hidden;
private final BaseLayer layer;
private final LongSparseArray<LinearGradient> linearGradientCache = new LongSparseArray<>();
private final LongSparseArray<RadialGradient> radialGradientCache = new LongSparseArray<>();
private final Path path = new Path();
private final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG);
private final RectF boundsRect = new RectF();
private final List<PathContent> paths = new ArrayList<>();
private final GradientType type;
private final BaseKeyframeAnimation<GradientColor, GradientColor> colorAnimation;
private final BaseKeyframeAnimation<Integer, Integer> opacityAnimation;
private final BaseKeyframeAnimation<PointF, PointF> startPointAnimation;
private final BaseKeyframeAnimation<PointF, PointF> endPointAnimation;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
@Nullable private ValueCallbackKeyframeAnimation colorCallbackAnimation;
private final LottieDrawable lottieDrawable;
private final int cacheSteps;
@Nullable private BaseKeyframeAnimation<Float, Float> blurAnimation;
float blurMaskFilterRadius = 0f;
@Nullable private DropShadowKeyframeAnimation dropShadowAnimation;
public GradientFillContent(final LottieDrawable lottieDrawable, LottieComposition composition, BaseLayer layer, GradientFill fill) {
this.layer = layer;
name = fill.getName();
hidden = fill.isHidden();
this.lottieDrawable = lottieDrawable;
type = fill.getGradientType();
path.setFillType(fill.getFillType());
cacheSteps = (int) (composition.getDuration() / CACHE_STEPS_MS);
colorAnimation = fill.getGradientColor().createAnimation();
colorAnimation.addUpdateListener(this);
layer.addAnimation(colorAnimation);
opacityAnimation = fill.getOpacity().createAnimation();
opacityAnimation.addUpdateListener(this);
layer.addAnimation(opacityAnimation);
startPointAnimation = fill.getStartPoint().createAnimation();
startPointAnimation.addUpdateListener(this);
layer.addAnimation(startPointAnimation);
endPointAnimation = fill.getEndPoint().createAnimation();
endPointAnimation.addUpdateListener(this);
layer.addAnimation(endPointAnimation);
if (layer.getBlurEffect() != null) {
blurAnimation = layer.getBlurEffect().getBlurriness().createAnimation();
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
if (layer.getDropShadowEffect() != null) {
dropShadowAnimation = new DropShadowKeyframeAnimation(this, layer, layer.getDropShadowEffect());
}
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
for (int i = 0; i < contentsAfter.size(); i++) {
Content content = contentsAfter.get(i);
if (content instanceof PathContent) {
paths.add((PathContent) content);
}
}
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
L.beginSection("GradientFillContent#draw");
path.reset();
for (int i = 0; i < paths.size(); i++) {
path.addPath(paths.get(i).getPath(), parentMatrix);
}
path.computeBounds(boundsRect, false);
Shader shader;
if (type == GradientType.LINEAR) {
shader = getLinearGradient();
} else {
shader = getRadialGradient();
}
shader.setLocalMatrix(parentMatrix);
paint.setShader(shader);
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
if (blurAnimation != null) {
float blurRadius = blurAnimation.getValue();
if (blurRadius == 0f) {
paint.setMaskFilter(null);
} else if (blurRadius != blurMaskFilterRadius){
BlurMaskFilter blur = new BlurMaskFilter(blurRadius, BlurMaskFilter.Blur.NORMAL);
paint.setMaskFilter(blur);
}
blurMaskFilterRadius = blurRadius;
}
if (dropShadowAnimation != null) {
dropShadowAnimation.applyTo(paint);
}
int alpha = (int) ((parentAlpha / 255f * opacityAnimation.getValue() / 100f) * 255);
paint.setAlpha(clamp(alpha, 0, 255));
canvas.drawPath(path, paint);
L.endSection("GradientFillContent#draw");
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
path.reset();
for (int i = 0; i < paths.size(); i++) {
path.addPath(paths.get(i).getPath(), parentMatrix);
}
path.computeBounds(outBounds, false);
// Add padding to account for rounding errors.
outBounds.set(
outBounds.left - 1,
outBounds.top - 1,
outBounds.right + 1,
outBounds.bottom + 1
);
}
@Override public String getName() {
return name;
}
private LinearGradient getLinearGradient() {
int gradientHash = getGradientHash();
LinearGradient gradient = linearGradientCache.get(gradientHash);
if (gradient != null) {
return gradient;
}
PointF startPoint = startPointAnimation.getValue();
PointF endPoint = endPointAnimation.getValue();
GradientColor gradientColor = colorAnimation.getValue();
int[] colors = applyDynamicColorsIfNeeded(gradientColor.getColors());
float[] positions = gradientColor.getPositions();
gradient = new LinearGradient(startPoint.x, startPoint.y, endPoint.x, endPoint.y, colors,
positions, Shader.TileMode.CLAMP);
linearGradientCache.put(gradientHash, gradient);
return gradient;
}
private RadialGradient getRadialGradient() {
int gradientHash = getGradientHash();
RadialGradient gradient = radialGradientCache.get(gradientHash);
if (gradient != null) {
return gradient;
}
PointF startPoint = startPointAnimation.getValue();
PointF endPoint = endPointAnimation.getValue();
GradientColor gradientColor = colorAnimation.getValue();
int[] colors = applyDynamicColorsIfNeeded(gradientColor.getColors());
float[] positions = gradientColor.getPositions();
float x0 = startPoint.x;
float y0 = startPoint.y;
float x1 = endPoint.x;
float y1 = endPoint.y;
float r = (float) Math.hypot(x1 - x0, y1 - y0);
if (r <= 0) {
r = 0.001f;
}
gradient = new RadialGradient(x0, y0, r, colors, positions, Shader.TileMode.CLAMP);
radialGradientCache.put(gradientHash, gradient);
return gradient;
}
private int getGradientHash() {
int startPointProgress = Math.round(startPointAnimation.getProgress() * cacheSteps);
int endPointProgress = Math.round(endPointAnimation.getProgress() * cacheSteps);
int colorProgress = Math.round(colorAnimation.getProgress() * cacheSteps);
int hash = 17;
if (startPointProgress != 0) {
hash = hash * 31 * startPointProgress;
}
if (endPointProgress != 0) {
hash = hash * 31 * endPointProgress;
}
if (colorProgress != 0) {
hash = hash * 31 * colorProgress;
}
return hash;
}
private int[] applyDynamicColorsIfNeeded(int[] colors) {
if (colorCallbackAnimation != null) {
Integer[] dynamicColors = (Integer[]) colorCallbackAnimation.getValue();
if (colors.length == dynamicColors.length) {
for (int i = 0; i < colors.length; i++) {
colors[i] = dynamicColors[i];
}
} else {
colors = new int[dynamicColors.length];
for (int i = 0; i < dynamicColors.length; i++) {
colors[i] = dynamicColors[i];
}
}
}
return colors;
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@SuppressWarnings("unchecked")
@Override
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.OPACITY) {
opacityAnimation.setValueCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.COLOR_FILTER) {
if (colorFilterAnimation != null) {
layer.removeAnimation(colorFilterAnimation);
}
if (callback == null) {
colorFilterAnimation = null;
} else {
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
colorFilterAnimation.addUpdateListener(this);
layer.addAnimation(colorFilterAnimation);
}
} else if (property == LottieProperty.GRADIENT_COLOR) {
if (colorCallbackAnimation != null) {
layer.removeAnimation(colorCallbackAnimation);
}
if (callback == null) {
colorCallbackAnimation = null;
} else {
linearGradientCache.clear();
radialGradientCache.clear();
colorCallbackAnimation = new ValueCallbackKeyframeAnimation<>(callback);
colorCallbackAnimation.addUpdateListener(this);
layer.addAnimation(colorCallbackAnimation);
}
} else if (property == LottieProperty.BLUR_RADIUS) {
if (blurAnimation != null) {
blurAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else {
blurAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
} else if (property == LottieProperty.DROP_SHADOW_COLOR && dropShadowAnimation != null) {
dropShadowAnimation.setColorCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.DROP_SHADOW_OPACITY && dropShadowAnimation != null) {
dropShadowAnimation.setOpacityCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DIRECTION && dropShadowAnimation != null) {
dropShadowAnimation.setDirectionCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DISTANCE && dropShadowAnimation != null) {
dropShadowAnimation.setDistanceCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_RADIUS && dropShadowAnimation != null) {
dropShadowAnimation.setRadiusCallback((LottieValueCallback<Float>) callback);
}
}
}
| 2,471 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/BaseStrokeContent.java | package com.airbnb.lottie.animation.content;
import static com.airbnb.lottie.utils.MiscUtils.clamp;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.DropShadowKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.IntegerKeyframeAnimation;
import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.model.animatable.AnimatableFloatValue;
import com.airbnb.lottie.model.animatable.AnimatableIntegerValue;
import com.airbnb.lottie.model.content.ShapeTrimPath;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseStrokeContent
implements BaseKeyframeAnimation.AnimationListener, KeyPathElementContent, DrawingContent {
private final PathMeasure pm = new PathMeasure();
private final Path path = new Path();
private final Path trimPathPath = new Path();
private final RectF rect = new RectF();
private final LottieDrawable lottieDrawable;
protected final BaseLayer layer;
private final List<PathGroup> pathGroups = new ArrayList<>();
private final float[] dashPatternValues;
final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG);
private final BaseKeyframeAnimation<?, Float> widthAnimation;
private final BaseKeyframeAnimation<?, Integer> opacityAnimation;
private final List<BaseKeyframeAnimation<?, Float>> dashPatternAnimations;
@Nullable private final BaseKeyframeAnimation<?, Float> dashPatternOffsetAnimation;
@Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation;
@Nullable private BaseKeyframeAnimation<Float, Float> blurAnimation;
float blurMaskFilterRadius = 0f;
@Nullable private DropShadowKeyframeAnimation dropShadowAnimation;
BaseStrokeContent(final LottieDrawable lottieDrawable, BaseLayer layer, Paint.Cap cap,
Paint.Join join, float miterLimit, AnimatableIntegerValue opacity, AnimatableFloatValue width,
List<AnimatableFloatValue> dashPattern, AnimatableFloatValue offset) {
this.lottieDrawable = lottieDrawable;
this.layer = layer;
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(cap);
paint.setStrokeJoin(join);
paint.setStrokeMiter(miterLimit);
opacityAnimation = opacity.createAnimation();
widthAnimation = width.createAnimation();
if (offset == null) {
dashPatternOffsetAnimation = null;
} else {
dashPatternOffsetAnimation = offset.createAnimation();
}
dashPatternAnimations = new ArrayList<>(dashPattern.size());
dashPatternValues = new float[dashPattern.size()];
for (int i = 0; i < dashPattern.size(); i++) {
dashPatternAnimations.add(dashPattern.get(i).createAnimation());
}
layer.addAnimation(opacityAnimation);
layer.addAnimation(widthAnimation);
for (int i = 0; i < dashPatternAnimations.size(); i++) {
layer.addAnimation(dashPatternAnimations.get(i));
}
if (dashPatternOffsetAnimation != null) {
layer.addAnimation(dashPatternOffsetAnimation);
}
opacityAnimation.addUpdateListener(this);
widthAnimation.addUpdateListener(this);
for (int i = 0; i < dashPattern.size(); i++) {
dashPatternAnimations.get(i).addUpdateListener(this);
}
if (dashPatternOffsetAnimation != null) {
dashPatternOffsetAnimation.addUpdateListener(this);
}
if (layer.getBlurEffect() != null) {
blurAnimation = layer.getBlurEffect().getBlurriness().createAnimation();
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
if (layer.getDropShadowEffect() != null) {
dropShadowAnimation = new DropShadowKeyframeAnimation(this, layer, layer.getDropShadowEffect());
}
}
@Override public void onValueChanged() {
lottieDrawable.invalidateSelf();
}
@Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) {
TrimPathContent trimPathContentBefore = null;
for (int i = contentsBefore.size() - 1; i >= 0; i--) {
Content content = contentsBefore.get(i);
if (content instanceof TrimPathContent &&
((TrimPathContent) content).getType() == ShapeTrimPath.Type.INDIVIDUALLY) {
trimPathContentBefore = (TrimPathContent) content;
}
}
if (trimPathContentBefore != null) {
trimPathContentBefore.addListener(this);
}
PathGroup currentPathGroup = null;
for (int i = contentsAfter.size() - 1; i >= 0; i--) {
Content content = contentsAfter.get(i);
if (content instanceof TrimPathContent &&
((TrimPathContent) content).getType() == ShapeTrimPath.Type.INDIVIDUALLY) {
if (currentPathGroup != null) {
pathGroups.add(currentPathGroup);
}
currentPathGroup = new PathGroup((TrimPathContent) content);
((TrimPathContent) content).addListener(this);
} else if (content instanceof PathContent) {
if (currentPathGroup == null) {
currentPathGroup = new PathGroup(trimPathContentBefore);
}
currentPathGroup.paths.add((PathContent) content);
}
}
if (currentPathGroup != null) {
pathGroups.add(currentPathGroup);
}
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
L.beginSection("StrokeContent#draw");
if (Utils.hasZeroScaleAxis(parentMatrix)) {
L.endSection("StrokeContent#draw");
return;
}
int alpha = (int) ((parentAlpha / 255f * ((IntegerKeyframeAnimation) opacityAnimation).getIntValue() / 100f) * 255);
paint.setAlpha(clamp(alpha, 0, 255));
paint.setStrokeWidth(((FloatKeyframeAnimation) widthAnimation).getFloatValue() * Utils.getScale(parentMatrix));
if (paint.getStrokeWidth() <= 0) {
// Android draws a hairline stroke for 0, After Effects doesn't.
L.endSection("StrokeContent#draw");
return;
}
applyDashPatternIfNeeded(parentMatrix);
if (colorFilterAnimation != null) {
paint.setColorFilter(colorFilterAnimation.getValue());
}
if (blurAnimation != null) {
float blurRadius = blurAnimation.getValue();
if (blurRadius == 0f) {
paint.setMaskFilter(null);
} else if (blurRadius != blurMaskFilterRadius){
BlurMaskFilter blur = layer.getBlurMaskFilter(blurRadius);
paint.setMaskFilter(blur);
}
blurMaskFilterRadius = blurRadius;
}
if (dropShadowAnimation != null) {
dropShadowAnimation.applyTo(paint);
}
for (int i = 0; i < pathGroups.size(); i++) {
PathGroup pathGroup = pathGroups.get(i);
if (pathGroup.trimPath != null) {
applyTrimPath(canvas, pathGroup, parentMatrix);
} else {
L.beginSection("StrokeContent#buildPath");
path.reset();
for (int j = pathGroup.paths.size() - 1; j >= 0; j--) {
path.addPath(pathGroup.paths.get(j).getPath(), parentMatrix);
}
L.endSection("StrokeContent#buildPath");
L.beginSection("StrokeContent#drawPath");
canvas.drawPath(path, paint);
L.endSection("StrokeContent#drawPath");
}
}
L.endSection("StrokeContent#draw");
}
private void applyTrimPath(Canvas canvas, PathGroup pathGroup, Matrix parentMatrix) {
L.beginSection("StrokeContent#applyTrimPath");
if (pathGroup.trimPath == null) {
L.endSection("StrokeContent#applyTrimPath");
return;
}
path.reset();
for (int j = pathGroup.paths.size() - 1; j >= 0; j--) {
path.addPath(pathGroup.paths.get(j).getPath(), parentMatrix);
}
float animStartValue = pathGroup.trimPath.getStart().getValue() / 100f;
float animEndValue = pathGroup.trimPath.getEnd().getValue() / 100f;
float animOffsetValue = pathGroup.trimPath.getOffset().getValue() / 360f;
// If the start-end is ~100, consider it to be the full path.
if (animStartValue < 0.01f && animEndValue > 0.99f) {
canvas.drawPath(path, paint);
L.endSection("StrokeContent#applyTrimPath");
return;
}
pm.setPath(path, false);
float totalLength = pm.getLength();
while (pm.nextContour()) {
totalLength += pm.getLength();
}
float offsetLength = totalLength * animOffsetValue;
float startLength = totalLength * animStartValue + offsetLength;
float endLength = Math.min(totalLength * animEndValue + offsetLength, startLength + totalLength - 1f);
float currentLength = 0;
for (int j = pathGroup.paths.size() - 1; j >= 0; j--) {
trimPathPath.set(pathGroup.paths.get(j).getPath());
trimPathPath.transform(parentMatrix);
pm.setPath(trimPathPath, false);
float length = pm.getLength();
if (endLength > totalLength && endLength - totalLength < currentLength + length &&
currentLength < endLength - totalLength) {
// Draw the segment when the end is greater than the length which wraps around to the
// beginning.
float startValue;
if (startLength > totalLength) {
startValue = (startLength - totalLength) / length;
} else {
startValue = 0;
}
float endValue = Math.min((endLength - totalLength) / length, 1);
Utils.applyTrimPathIfNeeded(trimPathPath, startValue, endValue, 0);
canvas.drawPath(trimPathPath, paint);
} else
//noinspection StatementWithEmptyBody
if (currentLength + length < startLength || currentLength > endLength) {
// Do nothing
} else if (currentLength + length <= endLength && startLength < currentLength) {
canvas.drawPath(trimPathPath, paint);
} else {
float startValue;
if (startLength < currentLength) {
startValue = 0;
} else {
startValue = (startLength - currentLength) / length;
}
float endValue;
if (endLength > currentLength + length) {
endValue = 1f;
} else {
endValue = (endLength - currentLength) / length;
}
Utils.applyTrimPathIfNeeded(trimPathPath, startValue, endValue, 0);
canvas.drawPath(trimPathPath, paint);
}
currentLength += length;
}
L.endSection("StrokeContent#applyTrimPath");
}
@Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) {
L.beginSection("StrokeContent#getBounds");
path.reset();
for (int i = 0; i < pathGroups.size(); i++) {
PathGroup pathGroup = pathGroups.get(i);
for (int j = 0; j < pathGroup.paths.size(); j++) {
path.addPath(pathGroup.paths.get(j).getPath(), parentMatrix);
}
}
path.computeBounds(rect, false);
float width = ((FloatKeyframeAnimation) widthAnimation).getFloatValue();
rect.set(rect.left - width / 2f, rect.top - width / 2f,
rect.right + width / 2f, rect.bottom + width / 2f);
outBounds.set(rect);
// Add padding to account for rounding errors.
outBounds.set(
outBounds.left - 1,
outBounds.top - 1,
outBounds.right + 1,
outBounds.bottom + 1
);
L.endSection("StrokeContent#getBounds");
}
private void applyDashPatternIfNeeded(Matrix parentMatrix) {
L.beginSection("StrokeContent#applyDashPattern");
if (dashPatternAnimations.isEmpty()) {
L.endSection("StrokeContent#applyDashPattern");
return;
}
float scale = Utils.getScale(parentMatrix);
for (int i = 0; i < dashPatternAnimations.size(); i++) {
dashPatternValues[i] = dashPatternAnimations.get(i).getValue();
// If the value of the dash pattern or gap is too small, the number of individual sections
// approaches infinity as the value approaches 0.
// To mitigate this, we essentially put a minimum value on the dash pattern size of 1px
// and a minimum gap size of 0.01.
if (i % 2 == 0) {
if (dashPatternValues[i] < 1f) {
dashPatternValues[i] = 1f;
}
} else {
if (dashPatternValues[i] < 0.1f) {
dashPatternValues[i] = 0.1f;
}
}
dashPatternValues[i] *= scale;
}
float offset = dashPatternOffsetAnimation == null ? 0f : dashPatternOffsetAnimation.getValue() * scale;
paint.setPathEffect(new DashPathEffect(dashPatternValues, offset));
L.endSection("StrokeContent#applyDashPattern");
}
@Override public void resolveKeyPath(
KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) {
MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
@SuppressWarnings("unchecked")
@Override
@CallSuper
public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == LottieProperty.OPACITY) {
opacityAnimation.setValueCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.STROKE_WIDTH) {
widthAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.COLOR_FILTER) {
if (colorFilterAnimation != null) {
layer.removeAnimation(colorFilterAnimation);
}
if (callback == null) {
colorFilterAnimation = null;
} else {
colorFilterAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback);
colorFilterAnimation.addUpdateListener(this);
layer.addAnimation(colorFilterAnimation);
}
} else if (property == LottieProperty.BLUR_RADIUS) {
if (blurAnimation != null) {
blurAnimation.setValueCallback((LottieValueCallback<Float>) callback);
} else {
blurAnimation =
new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback);
blurAnimation.addUpdateListener(this);
layer.addAnimation(blurAnimation);
}
} else if (property == LottieProperty.DROP_SHADOW_COLOR && dropShadowAnimation != null) {
dropShadowAnimation.setColorCallback((LottieValueCallback<Integer>) callback);
} else if (property == LottieProperty.DROP_SHADOW_OPACITY && dropShadowAnimation != null) {
dropShadowAnimation.setOpacityCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DIRECTION && dropShadowAnimation != null) {
dropShadowAnimation.setDirectionCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_DISTANCE && dropShadowAnimation != null) {
dropShadowAnimation.setDistanceCallback((LottieValueCallback<Float>) callback);
} else if (property == LottieProperty.DROP_SHADOW_RADIUS && dropShadowAnimation != null) {
dropShadowAnimation.setRadiusCallback((LottieValueCallback<Float>) callback);
}
}
/**
* Data class to help drawing trim paths individually.
*/
private static final class PathGroup {
private final List<PathContent> paths = new ArrayList<>();
@Nullable private final TrimPathContent trimPath;
private PathGroup(@Nullable TrimPathContent trimPath) {
this.trimPath = trimPath;
}
}
}
| 2,472 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/package-info.java | @RestrictTo(LIBRARY)
package com.airbnb.lottie.animation.content;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import androidx.annotation.RestrictTo; | 2,473 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/ShapeModifierContent.java | package com.airbnb.lottie.animation.content;
import com.airbnb.lottie.model.content.ShapeData;
public interface ShapeModifierContent extends Content {
ShapeData modifyShape(ShapeData shapeData);
}
| 2,474 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/content/Content.java | package com.airbnb.lottie.animation.content;
import java.util.List;
public interface Content {
String getName();
void setContents(List<Content> contentsBefore, List<Content> contentsAfter);
}
| 2,475 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/TextKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.model.DocumentData;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.LottieFrameInfo;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.List;
public class TextKeyframeAnimation extends KeyframeAnimation<DocumentData> {
public TextKeyframeAnimation(List<Keyframe<DocumentData>> keyframes) {
super(keyframes);
}
@Override DocumentData getValue(Keyframe<DocumentData> keyframe, float keyframeProgress) {
if (valueCallback != null) {
return valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame == null ? Float.MAX_VALUE : keyframe.endFrame,
keyframe.startValue, keyframe.endValue == null ? keyframe.startValue : keyframe.endValue, keyframeProgress,
getInterpolatedCurrentKeyframeProgress(), getProgress());
} else if (keyframeProgress != 1.0f || keyframe.endValue == null) {
return keyframe.startValue;
} else {
return keyframe.endValue;
}
}
public void setStringValueCallback(LottieValueCallback<String> valueCallback) {
final LottieFrameInfo<String> stringFrameInfo = new LottieFrameInfo<>();
final DocumentData documentData = new DocumentData();
super.setValueCallback(new LottieValueCallback<DocumentData>() {
@Override
public DocumentData getValue(LottieFrameInfo<DocumentData> frameInfo) {
stringFrameInfo.set(frameInfo.getStartFrame(), frameInfo.getEndFrame(), frameInfo.getStartValue().text,
frameInfo.getEndValue().text, frameInfo.getLinearKeyframeProgress(), frameInfo.getInterpolatedKeyframeProgress(),
frameInfo.getOverallProgress());
String text = valueCallback.getValue(stringFrameInfo);
DocumentData baseDocumentData = frameInfo.getInterpolatedKeyframeProgress() == 1f ? frameInfo.getEndValue() : frameInfo.getStartValue();
documentData.set(text, baseDocumentData.fontName, baseDocumentData.size, baseDocumentData.justification, baseDocumentData.tracking,
baseDocumentData.lineHeight, baseDocumentData.baselineShift, baseDocumentData.color, baseDocumentData.strokeColor,
baseDocumentData.strokeWidth, baseDocumentData.strokeOverFill, baseDocumentData.boxPosition, baseDocumentData.boxSize);
return documentData;
}
});
}
}
| 2,476 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/FloatKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class FloatKeyframeAnimation extends KeyframeAnimation<Float> {
public FloatKeyframeAnimation(List<Keyframe<Float>> keyframes) {
super(keyframes);
}
@Override Float getValue(Keyframe<Float> keyframe, float keyframeProgress) {
return getFloatValue(keyframe, keyframeProgress);
}
/**
* Optimization to avoid autoboxing.
*/
float getFloatValue(Keyframe<Float> keyframe, float keyframeProgress) {
if (keyframe.startValue == null || keyframe.endValue == null) {
throw new IllegalStateException("Missing values for keyframe.");
}
if (valueCallback != null) {
//noinspection ConstantConditions
Float value = valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame,
keyframe.startValue, keyframe.endValue,
keyframeProgress, getLinearCurrentKeyframeProgress(), getProgress());
if (value != null) {
return value;
}
}
return MiscUtils.lerp(keyframe.getStartValueFloat(), keyframe.getEndValueFloat(), keyframeProgress);
}
/**
* Optimization to avoid autoboxing.
*/
public float getFloatValue() {
return getFloatValue(getCurrentKeyframe(), getInterpolatedCurrentKeyframeProgress());
}
}
| 2,477 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/GradientColorKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.model.content.GradientColor;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class GradientColorKeyframeAnimation extends KeyframeAnimation<GradientColor> {
private final GradientColor gradientColor;
public GradientColorKeyframeAnimation(List<Keyframe<GradientColor>> keyframes) {
super(keyframes);
// Not all keyframes that this GradientColor are used for will have the same length.
// AnimatableGradientColorValue.ensureInterpolatableKeyframes may add extra positions
// for some keyframes but not others to ensure that it is interpolatable.
// Ensure that there is enough space for the largest keyframe.
int size = 0;
for (int i = 0; i < keyframes.size(); i++) {
GradientColor startValue = keyframes.get(i).startValue;
if (startValue != null) {
size = Math.max(size, startValue.getSize());
}
}
gradientColor = new GradientColor(new float[size], new int[size]);
}
@Override GradientColor getValue(Keyframe<GradientColor> keyframe, float keyframeProgress) {
//noinspection DataFlowIssue
gradientColor.lerp(keyframe.startValue, keyframe.endValue, keyframeProgress);
return gradientColor;
}
}
| 2,478 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/PointKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.PointF;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class PointKeyframeAnimation extends KeyframeAnimation<PointF> {
private final PointF point = new PointF();
public PointKeyframeAnimation(List<Keyframe<PointF>> keyframes) {
super(keyframes);
}
@Override public PointF getValue(Keyframe<PointF> keyframe, float keyframeProgress) {
return getValue(keyframe, keyframeProgress, keyframeProgress, keyframeProgress);
}
@Override protected PointF getValue(Keyframe<PointF> keyframe, float linearKeyframeProgress, float xKeyframeProgress, float yKeyframeProgress) {
if (keyframe.startValue == null || keyframe.endValue == null) {
throw new IllegalStateException("Missing values for keyframe.");
}
PointF startPoint = keyframe.startValue;
PointF endPoint = keyframe.endValue;
if (valueCallback != null) {
//noinspection ConstantConditions
PointF value = valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame, startPoint,
endPoint, linearKeyframeProgress, getLinearCurrentKeyframeProgress(), getProgress());
if (value != null) {
return value;
}
}
point.set(startPoint.x + xKeyframeProgress * (endPoint.x - startPoint.x),
startPoint.y + yKeyframeProgress * (endPoint.y - startPoint.y));
return point;
}
}
| 2,479 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/MaskKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.Path;
import com.airbnb.lottie.model.animatable.AnimatableIntegerValue;
import com.airbnb.lottie.model.content.Mask;
import com.airbnb.lottie.model.content.ShapeData;
import java.util.ArrayList;
import java.util.List;
public class MaskKeyframeAnimation {
private final List<BaseKeyframeAnimation<ShapeData, Path>> maskAnimations;
private final List<BaseKeyframeAnimation<Integer, Integer>> opacityAnimations;
private final List<Mask> masks;
public MaskKeyframeAnimation(List<Mask> masks) {
this.masks = masks;
this.maskAnimations = new ArrayList<>(masks.size());
this.opacityAnimations = new ArrayList<>(masks.size());
for (int i = 0; i < masks.size(); i++) {
this.maskAnimations.add(masks.get(i).getMaskPath().createAnimation());
AnimatableIntegerValue opacity = masks.get(i).getOpacity();
opacityAnimations.add(opacity.createAnimation());
}
}
public List<Mask> getMasks() {
return masks;
}
public List<BaseKeyframeAnimation<ShapeData, Path>> getMaskAnimations() {
return maskAnimations;
}
public List<BaseKeyframeAnimation<Integer, Integer>> getOpacityAnimations() {
return opacityAnimations;
}
}
| 2,480 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/KeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
abstract class KeyframeAnimation<T> extends BaseKeyframeAnimation<T, T> {
KeyframeAnimation(List<? extends Keyframe<T>> keyframes) {
super(keyframes);
}
}
| 2,481 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/DropShadowKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.parser.DropShadowEffect;
import com.airbnb.lottie.value.LottieFrameInfo;
import com.airbnb.lottie.value.LottieValueCallback;
public class DropShadowKeyframeAnimation implements BaseKeyframeAnimation.AnimationListener {
private static final double DEG_TO_RAD = Math.PI / 180.0;
private final BaseKeyframeAnimation.AnimationListener listener;
private final BaseKeyframeAnimation<Integer, Integer> color;
private final BaseKeyframeAnimation<Float, Float> opacity;
private final BaseKeyframeAnimation<Float, Float> direction;
private final BaseKeyframeAnimation<Float, Float> distance;
private final BaseKeyframeAnimation<Float, Float> radius;
private boolean isDirty = true;
public DropShadowKeyframeAnimation(BaseKeyframeAnimation.AnimationListener listener, BaseLayer layer, DropShadowEffect dropShadowEffect) {
this.listener = listener;
color = dropShadowEffect.getColor().createAnimation();
color.addUpdateListener(this);
layer.addAnimation(color);
opacity = dropShadowEffect.getOpacity().createAnimation();
opacity.addUpdateListener(this);
layer.addAnimation(opacity);
direction = dropShadowEffect.getDirection().createAnimation();
direction.addUpdateListener(this);
layer.addAnimation(direction);
distance = dropShadowEffect.getDistance().createAnimation();
distance.addUpdateListener(this);
layer.addAnimation(distance);
radius = dropShadowEffect.getRadius().createAnimation();
radius.addUpdateListener(this);
layer.addAnimation(radius);
}
@Override public void onValueChanged() {
isDirty = true;
listener.onValueChanged();
}
public void applyTo(Paint paint) {
if (!isDirty) {
return;
}
isDirty = false;
double directionRad = ((double) direction.getValue()) * DEG_TO_RAD;
float distance = this.distance.getValue();
float x = ((float) Math.sin(directionRad)) * distance;
float y = ((float) Math.cos(directionRad + Math.PI)) * distance;
int baseColor = color.getValue();
int opacity = Math.round(this.opacity.getValue());
int color = Color.argb(opacity, Color.red(baseColor), Color.green(baseColor), Color.blue(baseColor));
float radius = this.radius.getValue();
paint.setShadowLayer(radius, x, y, color);
}
public void setColorCallback(@Nullable LottieValueCallback<Integer> callback) {
color.setValueCallback(callback);
}
public void setOpacityCallback(@Nullable final LottieValueCallback<Float> callback) {
if (callback == null) {
opacity.setValueCallback(null);
return;
}
opacity.setValueCallback(new LottieValueCallback<Float>() {
@Nullable
@Override
public Float getValue(LottieFrameInfo<Float> frameInfo) {
Float value = callback.getValue(frameInfo);
if (value == null) {
return null;
}
// Convert [0,100] to [0,255] because other dynamic properties use [0,100].
return value * 2.55f;
}
});
}
public void setDirectionCallback(@Nullable LottieValueCallback<Float> callback) {
direction.setValueCallback(callback);
}
public void setDistanceCallback(@Nullable LottieValueCallback<Float> callback) {
distance.setValueCallback(callback);
}
public void setRadiusCallback(@Nullable LottieValueCallback<Float> callback) {
radius.setValueCallback(callback);
}
}
| 2,482 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/BaseKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.L;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.ArrayList;
import java.util.List;
/**
* @param <K> Keyframe type
* @param <A> Animation type
*/
public abstract class BaseKeyframeAnimation<K, A> {
public interface AnimationListener {
void onValueChanged();
}
// This is not a Set because we don't want to create an iterator object on every setProgress.
final List<AnimationListener> listeners = new ArrayList<>(1);
private boolean isDiscrete = false;
private final KeyframesWrapper<K> keyframesWrapper;
protected float progress = 0f;
@Nullable protected LottieValueCallback<A> valueCallback;
@Nullable private A cachedGetValue = null;
private float cachedStartDelayProgress = -1f;
private float cachedEndProgress = -1f;
BaseKeyframeAnimation(List<? extends Keyframe<K>> keyframes) {
keyframesWrapper = wrap(keyframes);
}
public void setIsDiscrete() {
isDiscrete = true;
}
public void addUpdateListener(AnimationListener listener) {
listeners.add(listener);
}
public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
L.beginSection("BaseKeyframeAnimation#setProgress");
if (keyframesWrapper.isEmpty()) {
L.endSection("BaseKeyframeAnimation#setProgress");
return;
}
if (progress < getStartDelayProgress()) {
progress = getStartDelayProgress();
} else if (progress > getEndProgress()) {
progress = getEndProgress();
}
if (progress == this.progress) {
L.endSection("BaseKeyframeAnimation#setProgress");
return;
}
this.progress = progress;
if (keyframesWrapper.isValueChanged(progress)) {
notifyListeners();
}
L.endSection("BaseKeyframeAnimation#setProgress");
}
public void notifyListeners() {
L.beginSection("BaseKeyframeAnimation#notifyListeners");
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onValueChanged();
}
L.endSection("BaseKeyframeAnimation#notifyListeners");
}
protected Keyframe<K> getCurrentKeyframe() {
L.beginSection("BaseKeyframeAnimation#getCurrentKeyframe");
final Keyframe<K> keyframe = keyframesWrapper.getCurrentKeyframe();
L.endSection("BaseKeyframeAnimation#getCurrentKeyframe");
return keyframe;
}
/**
* Returns the progress into the current keyframe between 0 and 1. This does not take into account
* any interpolation that the keyframe may have.
*/
float getLinearCurrentKeyframeProgress() {
if (isDiscrete) {
return 0f;
}
Keyframe<K> keyframe = getCurrentKeyframe();
if (keyframe.isStatic()) {
return 0f;
}
float progressIntoFrame = progress - keyframe.getStartProgress();
float keyframeProgress = keyframe.getEndProgress() - keyframe.getStartProgress();
return progressIntoFrame / keyframeProgress;
}
/**
* Takes the value of {@link #getLinearCurrentKeyframeProgress()} and interpolates it with
* the current keyframe's interpolator.
*/
protected float getInterpolatedCurrentKeyframeProgress() {
Keyframe<K> keyframe = getCurrentKeyframe();
// Keyframe should not be null here but there seems to be a Xiaomi Android 10 specific crash.
// https://github.com/airbnb/lottie-android/issues/2050
if (keyframe == null || keyframe.isStatic()) {
return 0f;
}
//noinspection ConstantConditions
return keyframe.interpolator.getInterpolation(getLinearCurrentKeyframeProgress());
}
@FloatRange(from = 0f, to = 1f)
private float getStartDelayProgress() {
if (cachedStartDelayProgress == -1f) {
cachedStartDelayProgress = keyframesWrapper.getStartDelayProgress();
}
return cachedStartDelayProgress;
}
@FloatRange(from = 0f, to = 1f)
float getEndProgress() {
if (cachedEndProgress == -1f) {
cachedEndProgress = keyframesWrapper.getEndProgress();
}
return cachedEndProgress;
}
public A getValue() {
A value;
float linearProgress = getLinearCurrentKeyframeProgress();
if (valueCallback == null && keyframesWrapper.isCachedValueEnabled(linearProgress)) {
return cachedGetValue;
}
final Keyframe<K> keyframe = getCurrentKeyframe();
if (keyframe.xInterpolator != null && keyframe.yInterpolator != null) {
float xProgress = keyframe.xInterpolator.getInterpolation(linearProgress);
float yProgress = keyframe.yInterpolator.getInterpolation(linearProgress);
value = getValue(keyframe, linearProgress, xProgress, yProgress);
} else {
float progress = getInterpolatedCurrentKeyframeProgress();
value = getValue(keyframe, progress);
}
cachedGetValue = value;
return value;
}
public float getProgress() {
return progress;
}
public void setValueCallback(@Nullable LottieValueCallback<A> valueCallback) {
if (this.valueCallback != null) {
this.valueCallback.setAnimation(null);
}
this.valueCallback = valueCallback;
if (valueCallback != null) {
valueCallback.setAnimation(this);
}
}
/**
* keyframeProgress will be [0, 1] unless the interpolator has overshoot in which case, this
* should be able to handle values outside of that range.
*/
abstract A getValue(Keyframe<K> keyframe, float keyframeProgress);
/**
* Similar to {@link #getValue(Keyframe, float)} but used when an animation has separate interpolators for the X and Y axis.
*/
protected A getValue(Keyframe<K> keyframe, float linearKeyframeProgress, float xKeyframeProgress, float yKeyframeProgress) {
throw new UnsupportedOperationException("This animation does not support split dimensions!");
}
private static <T> KeyframesWrapper<T> wrap(List<? extends Keyframe<T>> keyframes) {
if (keyframes.isEmpty()) {
return new EmptyKeyframeWrapper<>();
}
if (keyframes.size() == 1) {
return new SingleKeyframeWrapper<>(keyframes);
}
return new KeyframesWrapperImpl<>(keyframes);
}
private interface KeyframesWrapper<T> {
boolean isEmpty();
boolean isValueChanged(float progress);
Keyframe<T> getCurrentKeyframe();
@FloatRange(from = 0f, to = 1f)
float getStartDelayProgress();
@FloatRange(from = 0f, to = 1f)
float getEndProgress();
boolean isCachedValueEnabled(float progress);
}
private static final class EmptyKeyframeWrapper<T> implements KeyframesWrapper<T> {
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean isValueChanged(float progress) {
return false;
}
@Override
public Keyframe<T> getCurrentKeyframe() {
throw new IllegalStateException("not implemented");
}
@Override
public float getStartDelayProgress() {
return 0f;
}
@Override
public float getEndProgress() {
return 1f;
}
@Override
public boolean isCachedValueEnabled(float progress) {
throw new IllegalStateException("not implemented");
}
}
private static final class SingleKeyframeWrapper<T> implements KeyframesWrapper<T> {
@NonNull
private final Keyframe<T> keyframe;
private float cachedInterpolatedProgress = -1f;
SingleKeyframeWrapper(List<? extends Keyframe<T>> keyframes) {
this.keyframe = keyframes.get(0);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isValueChanged(float progress) {
return !keyframe.isStatic();
}
@Override
public Keyframe<T> getCurrentKeyframe() {
return keyframe;
}
@Override
public float getStartDelayProgress() {
return keyframe.getStartProgress();
}
@Override
public float getEndProgress() {
return keyframe.getEndProgress();
}
@Override
public boolean isCachedValueEnabled(float progress) {
if (cachedInterpolatedProgress == progress) {
return true;
}
cachedInterpolatedProgress = progress;
return false;
}
}
private static final class KeyframesWrapperImpl<T> implements KeyframesWrapper<T> {
private final List<? extends Keyframe<T>> keyframes;
@NonNull
private Keyframe<T> currentKeyframe;
private Keyframe<T> cachedCurrentKeyframe = null;
private float cachedInterpolatedProgress = -1f;
KeyframesWrapperImpl(List<? extends Keyframe<T>> keyframes) {
this.keyframes = keyframes;
currentKeyframe = findKeyframe(0);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isValueChanged(float progress) {
if (currentKeyframe.containsProgress(progress)) {
return !currentKeyframe.isStatic();
}
currentKeyframe = findKeyframe(progress);
return true;
}
private Keyframe<T> findKeyframe(float progress) {
Keyframe<T> keyframe = keyframes.get(keyframes.size() - 1);
if (progress >= keyframe.getStartProgress()) {
return keyframe;
}
for (int i = keyframes.size() - 2; i >= 1; i--) {
keyframe = keyframes.get(i);
if (currentKeyframe == keyframe) {
continue;
}
if (keyframe.containsProgress(progress)) {
return keyframe;
}
}
return keyframes.get(0);
}
@Override
@NonNull
public Keyframe<T> getCurrentKeyframe() {
return currentKeyframe;
}
@Override
public float getStartDelayProgress() {
return keyframes.get(0).getStartProgress();
}
@Override
public float getEndProgress() {
return keyframes.get(keyframes.size() - 1).getEndProgress();
}
@Override
public boolean isCachedValueEnabled(float progress) {
if (cachedCurrentKeyframe == currentKeyframe
&& cachedInterpolatedProgress == progress) {
return true;
}
cachedCurrentKeyframe = currentKeyframe;
cachedInterpolatedProgress = progress;
return false;
}
}
}
| 2,483 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/SplitDimensionPathKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.Collections;
public class SplitDimensionPathKeyframeAnimation extends BaseKeyframeAnimation<PointF, PointF> {
private final PointF point = new PointF();
private final PointF pointWithCallbackValues = new PointF();
private final BaseKeyframeAnimation<Float, Float> xAnimation;
private final BaseKeyframeAnimation<Float, Float> yAnimation;
@Nullable protected LottieValueCallback<Float> xValueCallback;
@Nullable protected LottieValueCallback<Float> yValueCallback;
public SplitDimensionPathKeyframeAnimation(
BaseKeyframeAnimation<Float, Float> xAnimation,
BaseKeyframeAnimation<Float, Float> yAnimation) {
super(Collections.<Keyframe<PointF>>emptyList());
this.xAnimation = xAnimation;
this.yAnimation = yAnimation;
// We need to call an initial setProgress so point gets set with the initial value.
setProgress(getProgress());
}
public void setXValueCallback(@Nullable LottieValueCallback<Float> xValueCallback) {
if (this.xValueCallback != null) {
this.xValueCallback.setAnimation(null);
}
this.xValueCallback = xValueCallback;
if (xValueCallback != null) {
xValueCallback.setAnimation(this);
}
}
public void setYValueCallback(@Nullable LottieValueCallback<Float> yValueCallback) {
if (this.yValueCallback != null) {
this.yValueCallback.setAnimation(null);
}
this.yValueCallback = yValueCallback;
if (yValueCallback != null) {
yValueCallback.setAnimation(this);
}
}
@Override public void setProgress(float progress) {
xAnimation.setProgress(progress);
yAnimation.setProgress(progress);
point.set(xAnimation.getValue(), yAnimation.getValue());
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onValueChanged();
}
}
@Override public PointF getValue() {
return getValue(null, 0);
}
@Override PointF getValue(Keyframe<PointF> keyframe, float keyframeProgress) {
Float xCallbackValue = null;
Float yCallbackValue = null;
if (xValueCallback != null) {
Keyframe<Float> xKeyframe = xAnimation.getCurrentKeyframe();
if (xKeyframe != null) {
float progress = xAnimation.getInterpolatedCurrentKeyframeProgress();
Float endFrame = xKeyframe.endFrame;
xCallbackValue =
xValueCallback.getValueInternal(xKeyframe.startFrame, endFrame == null ? xKeyframe.startFrame : endFrame, xKeyframe.startValue,
xKeyframe.endValue, keyframeProgress, keyframeProgress, progress);
}
}
if (yValueCallback != null) {
Keyframe<Float> yKeyframe = yAnimation.getCurrentKeyframe();
if (yKeyframe != null) {
float progress = yAnimation.getInterpolatedCurrentKeyframeProgress();
Float endFrame = yKeyframe.endFrame;
yCallbackValue =
yValueCallback.getValueInternal(yKeyframe.startFrame, endFrame == null ? yKeyframe.startFrame : endFrame, yKeyframe.startValue,
yKeyframe.endValue, keyframeProgress, keyframeProgress, progress);
}
}
if (xCallbackValue == null) {
pointWithCallbackValues.set(point.x, 0f);
} else {
pointWithCallbackValues.set(xCallbackValue, 0f);
}
if (yCallbackValue == null) {
pointWithCallbackValues.set(pointWithCallbackValues.x, point.y);
} else {
pointWithCallbackValues.set(pointWithCallbackValues.x, yCallbackValue);
}
return pointWithCallbackValues;
}
}
| 2,484 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/ShapeKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.Path;
import androidx.annotation.Nullable;
import com.airbnb.lottie.animation.content.ShapeModifierContent;
import com.airbnb.lottie.model.content.ShapeData;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class ShapeKeyframeAnimation extends BaseKeyframeAnimation<ShapeData, Path> {
private final ShapeData tempShapeData = new ShapeData();
private final Path tempPath = new Path();
private List<ShapeModifierContent> shapeModifiers;
public ShapeKeyframeAnimation(List<Keyframe<ShapeData>> keyframes) {
super(keyframes);
}
@Override public Path getValue(Keyframe<ShapeData> keyframe, float keyframeProgress) {
ShapeData startShapeData = keyframe.startValue;
ShapeData endShapeData = keyframe.endValue;
tempShapeData.interpolateBetween(startShapeData, endShapeData, keyframeProgress);
ShapeData modifiedShapeData = tempShapeData;
if (shapeModifiers != null) {
for (int i = shapeModifiers.size() - 1; i >= 0; i--) {
modifiedShapeData = shapeModifiers.get(i).modifyShape(modifiedShapeData);
}
}
MiscUtils.getPathFromData(modifiedShapeData, tempPath);
return tempPath;
}
public void setShapeModifiers(@Nullable List<ShapeModifierContent> shapeModifiers) {
this.shapeModifiers = shapeModifiers;
}
}
| 2,485 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/PathKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class PathKeyframeAnimation extends KeyframeAnimation<PointF> {
private final PointF point = new PointF();
private final float[] pos = new float[2];
private final PathMeasure pathMeasure = new PathMeasure();
private PathKeyframe pathMeasureKeyframe;
public PathKeyframeAnimation(List<? extends Keyframe<PointF>> keyframes) {
super(keyframes);
}
@Override public PointF getValue(Keyframe<PointF> keyframe, float keyframeProgress) {
PathKeyframe pathKeyframe = (PathKeyframe) keyframe;
Path path = pathKeyframe.getPath();
if (path == null) {
return keyframe.startValue;
}
if (valueCallback != null) {
PointF value = valueCallback.getValueInternal(pathKeyframe.startFrame, pathKeyframe.endFrame,
pathKeyframe.startValue, pathKeyframe.endValue, getLinearCurrentKeyframeProgress(),
keyframeProgress, getProgress());
if (value != null) {
return value;
}
}
if (pathMeasureKeyframe != pathKeyframe) {
pathMeasure.setPath(path, false);
pathMeasureKeyframe = pathKeyframe;
}
pathMeasure.getPosTan(keyframeProgress * pathMeasure.getLength(), pos, null);
point.set(pos[0], pos[1]);
return point;
}
}
| 2,486 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/PathKeyframe.java | package com.airbnb.lottie.animation.keyframe;
import android.graphics.Path;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.utils.Utils;
import com.airbnb.lottie.value.Keyframe;
public class PathKeyframe extends Keyframe<PointF> {
@Nullable private Path path;
private final Keyframe<PointF> pointKeyFrame;
public PathKeyframe(LottieComposition composition, Keyframe<PointF> keyframe) {
super(composition, keyframe.startValue, keyframe.endValue, keyframe.interpolator, keyframe.xInterpolator, keyframe.yInterpolator,
keyframe.startFrame, keyframe.endFrame);
this.pointKeyFrame = keyframe;
createPath();
}
public void createPath() {
// This must use equals(float, float) because PointF didn't have an equals(PathF) method
// until KitKat...
boolean equals = endValue != null && startValue != null &&
startValue.equals(endValue.x, endValue.y);
if (startValue != null && endValue != null && !equals) {
path = Utils.createPath(startValue, endValue, pointKeyFrame.pathCp1, pointKeyFrame.pathCp2);
}
}
/**
* This will be null if the startValue and endValue are the same.
*/
@Nullable Path getPath() {
return path;
}
}
| 2,487 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/TransformKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_ANCHOR_POINT;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_END_OPACITY;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_OPACITY;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_POSITION;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_POSITION_X;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_POSITION_Y;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_ROTATION;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_SCALE;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_SKEW;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_SKEW_ANGLE;
import static com.airbnb.lottie.LottieProperty.TRANSFORM_START_OPACITY;
import android.graphics.Matrix;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import com.airbnb.lottie.model.animatable.AnimatableTransform;
import com.airbnb.lottie.model.layer.BaseLayer;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.LottieValueCallback;
import com.airbnb.lottie.value.ScaleXY;
import java.util.Collections;
public class TransformKeyframeAnimation {
private final Matrix matrix = new Matrix();
private final Matrix skewMatrix1;
private final Matrix skewMatrix2;
private final Matrix skewMatrix3;
private final float[] skewValues;
@Nullable private BaseKeyframeAnimation<PointF, PointF> anchorPoint;
@Nullable private BaseKeyframeAnimation<?, PointF> position;
@Nullable private BaseKeyframeAnimation<ScaleXY, ScaleXY> scale;
@Nullable private BaseKeyframeAnimation<Float, Float> rotation;
@Nullable private BaseKeyframeAnimation<Integer, Integer> opacity;
@Nullable private FloatKeyframeAnimation skew;
@Nullable private FloatKeyframeAnimation skewAngle;
// Used for repeaters
@Nullable private BaseKeyframeAnimation<?, Float> startOpacity;
@Nullable private BaseKeyframeAnimation<?, Float> endOpacity;
public TransformKeyframeAnimation(AnimatableTransform animatableTransform) {
anchorPoint = animatableTransform.getAnchorPoint() == null ? null : animatableTransform.getAnchorPoint().createAnimation();
position = animatableTransform.getPosition() == null ? null : animatableTransform.getPosition().createAnimation();
scale = animatableTransform.getScale() == null ? null : animatableTransform.getScale().createAnimation();
rotation = animatableTransform.getRotation() == null ? null : animatableTransform.getRotation().createAnimation();
skew = animatableTransform.getSkew() == null ? null : (FloatKeyframeAnimation) animatableTransform.getSkew().createAnimation();
if (skew != null) {
skewMatrix1 = new Matrix();
skewMatrix2 = new Matrix();
skewMatrix3 = new Matrix();
skewValues = new float[9];
} else {
skewMatrix1 = null;
skewMatrix2 = null;
skewMatrix3 = null;
skewValues = null;
}
skewAngle = animatableTransform.getSkewAngle() == null ? null : (FloatKeyframeAnimation) animatableTransform.getSkewAngle().createAnimation();
if (animatableTransform.getOpacity() != null) {
opacity = animatableTransform.getOpacity().createAnimation();
}
if (animatableTransform.getStartOpacity() != null) {
startOpacity = animatableTransform.getStartOpacity().createAnimation();
} else {
startOpacity = null;
}
if (animatableTransform.getEndOpacity() != null) {
endOpacity = animatableTransform.getEndOpacity().createAnimation();
} else {
endOpacity = null;
}
}
public void addAnimationsToLayer(BaseLayer layer) {
layer.addAnimation(opacity);
layer.addAnimation(startOpacity);
layer.addAnimation(endOpacity);
layer.addAnimation(anchorPoint);
layer.addAnimation(position);
layer.addAnimation(scale);
layer.addAnimation(rotation);
layer.addAnimation(skew);
layer.addAnimation(skewAngle);
}
public void addListener(final BaseKeyframeAnimation.AnimationListener listener) {
if (opacity != null) {
opacity.addUpdateListener(listener);
}
if (startOpacity != null) {
startOpacity.addUpdateListener(listener);
}
if (endOpacity != null) {
endOpacity.addUpdateListener(listener);
}
if (anchorPoint != null) {
anchorPoint.addUpdateListener(listener);
}
if (position != null) {
position.addUpdateListener(listener);
}
if (scale != null) {
scale.addUpdateListener(listener);
}
if (rotation != null) {
rotation.addUpdateListener(listener);
}
if (skew != null) {
skew.addUpdateListener(listener);
}
if (skewAngle != null) {
skewAngle.addUpdateListener(listener);
}
}
public void setProgress(float progress) {
if (opacity != null) {
opacity.setProgress(progress);
}
if (startOpacity != null) {
startOpacity.setProgress(progress);
}
if (endOpacity != null) {
endOpacity.setProgress(progress);
}
if (anchorPoint != null) {
anchorPoint.setProgress(progress);
}
if (position != null) {
position.setProgress(progress);
}
if (scale != null) {
scale.setProgress(progress);
}
if (rotation != null) {
rotation.setProgress(progress);
}
if (skew != null) {
skew.setProgress(progress);
}
if (skewAngle != null) {
skewAngle.setProgress(progress);
}
}
@Nullable public BaseKeyframeAnimation<?, Integer> getOpacity() {
return opacity;
}
@Nullable public BaseKeyframeAnimation<?, Float> getStartOpacity() {
return startOpacity;
}
@Nullable public BaseKeyframeAnimation<?, Float> getEndOpacity() {
return endOpacity;
}
public Matrix getMatrix() {
matrix.reset();
BaseKeyframeAnimation<?, PointF> position = this.position;
if (position != null) {
PointF positionValue = position.getValue();
if (positionValue != null && (positionValue.x != 0 || positionValue.y != 0)) {
matrix.preTranslate(positionValue.x, positionValue.y);
}
}
BaseKeyframeAnimation<Float, Float> rotation = this.rotation;
if (rotation != null) {
float rotationValue;
if (rotation instanceof ValueCallbackKeyframeAnimation) {
rotationValue = rotation.getValue();
} else {
rotationValue = ((FloatKeyframeAnimation) rotation).getFloatValue();
}
if (rotationValue != 0f) {
matrix.preRotate(rotationValue);
}
}
FloatKeyframeAnimation skew = this.skew;
if (skew != null) {
float mCos = skewAngle == null ? 0f : (float) Math.cos(Math.toRadians(-skewAngle.getFloatValue() + 90));
float mSin = skewAngle == null ? 1f : (float) Math.sin(Math.toRadians(-skewAngle.getFloatValue() + 90));
float aTan = (float) Math.tan(Math.toRadians(skew.getFloatValue()));
clearSkewValues();
skewValues[0] = mCos;
skewValues[1] = mSin;
skewValues[3] = -mSin;
skewValues[4] = mCos;
skewValues[8] = 1f;
skewMatrix1.setValues(skewValues);
clearSkewValues();
skewValues[0] = 1f;
skewValues[3] = aTan;
skewValues[4] = 1f;
skewValues[8] = 1f;
skewMatrix2.setValues(skewValues);
clearSkewValues();
skewValues[0] = mCos;
skewValues[1] = -mSin;
skewValues[3] = mSin;
skewValues[4] = mCos;
skewValues[8] = 1;
skewMatrix3.setValues(skewValues);
skewMatrix2.preConcat(skewMatrix1);
skewMatrix3.preConcat(skewMatrix2);
matrix.preConcat(skewMatrix3);
}
BaseKeyframeAnimation<ScaleXY, ScaleXY> scale = this.scale;
if (scale != null) {
ScaleXY scaleTransform = scale.getValue();
if (scaleTransform != null && (scaleTransform.getScaleX() != 1f || scaleTransform.getScaleY() != 1f)) {
matrix.preScale(scaleTransform.getScaleX(), scaleTransform.getScaleY());
}
}
BaseKeyframeAnimation<PointF, PointF> anchorPoint = this.anchorPoint;
if (anchorPoint != null) {
PointF anchorPointValue = anchorPoint.getValue();
if (anchorPointValue != null && (anchorPointValue.x != 0 || anchorPointValue.y != 0)) {
matrix.preTranslate(-anchorPointValue.x, -anchorPointValue.y);
}
}
return matrix;
}
private void clearSkewValues() {
for (int i = 0; i < 9; i++) {
skewValues[i] = 0f;
}
}
/**
* TODO: see if we can use this for the main {@link #getMatrix()} method.
*/
public Matrix getMatrixForRepeater(float amount) {
PointF position = this.position == null ? null : this.position.getValue();
ScaleXY scale = this.scale == null ? null : this.scale.getValue();
matrix.reset();
if (position != null) {
matrix.preTranslate(position.x * amount, position.y * amount);
}
if (scale != null) {
matrix.preScale(
(float) Math.pow(scale.getScaleX(), amount),
(float) Math.pow(scale.getScaleY(), amount));
}
if (this.rotation != null) {
float rotation = this.rotation.getValue();
PointF anchorPoint = this.anchorPoint == null ? null : this.anchorPoint.getValue();
matrix.preRotate(rotation * amount, anchorPoint == null ? 0f : anchorPoint.x, anchorPoint == null ? 0f : anchorPoint.y);
}
return matrix;
}
/**
* Returns whether the callback was applied.
*/
@SuppressWarnings("unchecked")
public <T> boolean applyValueCallback(T property, @Nullable LottieValueCallback<T> callback) {
if (property == TRANSFORM_ANCHOR_POINT) {
if (anchorPoint == null) {
anchorPoint = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<PointF>) callback, new PointF());
} else {
anchorPoint.setValueCallback((LottieValueCallback<PointF>) callback);
}
} else if (property == TRANSFORM_POSITION) {
if (position == null) {
position = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<PointF>) callback, new PointF());
} else {
position.setValueCallback((LottieValueCallback<PointF>) callback);
}
} else if (property == TRANSFORM_POSITION_X && position instanceof SplitDimensionPathKeyframeAnimation) {
((SplitDimensionPathKeyframeAnimation) position).setXValueCallback((LottieValueCallback<Float>) callback);
} else if (property == TRANSFORM_POSITION_Y && position instanceof SplitDimensionPathKeyframeAnimation) {
((SplitDimensionPathKeyframeAnimation) position).setYValueCallback((LottieValueCallback<Float>) callback);
} else if (property == TRANSFORM_SCALE) {
if (scale == null) {
scale = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ScaleXY>) callback, new ScaleXY());
} else {
scale.setValueCallback((LottieValueCallback<ScaleXY>) callback);
}
} else if (property == TRANSFORM_ROTATION) {
if (rotation == null) {
rotation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback, 0f);
} else {
rotation.setValueCallback((LottieValueCallback<Float>) callback);
}
} else if (property == TRANSFORM_OPACITY) {
if (opacity == null) {
opacity = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Integer>) callback, 100);
} else {
opacity.setValueCallback((LottieValueCallback<Integer>) callback);
}
} else if (property == TRANSFORM_START_OPACITY) {
if (startOpacity == null) {
startOpacity = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback, 100f);
} else {
startOpacity.setValueCallback((LottieValueCallback<Float>) callback);
}
} else if (property == TRANSFORM_END_OPACITY) {
if (endOpacity == null) {
endOpacity = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback, 100f);
} else {
endOpacity.setValueCallback((LottieValueCallback<Float>) callback);
}
} else if (property == TRANSFORM_SKEW) {
if (skew == null) {
skew = new FloatKeyframeAnimation(Collections.singletonList(new Keyframe<>(0f)));
}
skew.setValueCallback((LottieValueCallback<Float>) callback);
} else if (property == TRANSFORM_SKEW_ANGLE) {
if (skewAngle == null) {
skewAngle = new FloatKeyframeAnimation(Collections.singletonList(new Keyframe<>(0f)));
}
skewAngle.setValueCallback((LottieValueCallback<Float>) callback);
} else {
return false;
}
return true;
}
}
| 2,488 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/ColorKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.utils.GammaEvaluator;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class ColorKeyframeAnimation extends KeyframeAnimation<Integer> {
public ColorKeyframeAnimation(List<Keyframe<Integer>> keyframes) {
super(keyframes);
}
@Override
Integer getValue(Keyframe<Integer> keyframe, float keyframeProgress) {
return getIntValue(keyframe, keyframeProgress);
}
/**
* Optimization to avoid autoboxing.
*/
public int getIntValue(Keyframe<Integer> keyframe, float keyframeProgress) {
if (keyframe.startValue == null || keyframe.endValue == null) {
throw new IllegalStateException("Missing values for keyframe.");
}
// keyframe.endFrame should not be null under normal operation.
// It is not clear why this would be null and when it does, it seems to be extremely rare.
// https://github.com/airbnb/lottie-android/issues/2361
if (valueCallback != null && keyframe.endFrame != null) {
//noinspection ConstantConditions
Integer value = valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame, keyframe.startValue,
keyframe.endValue, keyframeProgress, getLinearCurrentKeyframeProgress(), getProgress());
if (value != null) {
return value;
}
}
return GammaEvaluator.evaluate(MiscUtils.clamp(keyframeProgress, 0f, 1f), keyframe.startValue, keyframe.endValue);
}
/**
* Optimization to avoid autoboxing.
*/
public int getIntValue() {
return getIntValue(getCurrentKeyframe(), getInterpolatedCurrentKeyframeProgress());
}
}
| 2,489 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/ValueCallbackKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import androidx.annotation.Nullable;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.LottieValueCallback;
import java.util.Collections;
public class ValueCallbackKeyframeAnimation<K, A> extends BaseKeyframeAnimation<K, A> {
private final A valueCallbackValue;
public ValueCallbackKeyframeAnimation(LottieValueCallback<A> valueCallback) {
this(valueCallback, null);
}
public ValueCallbackKeyframeAnimation(LottieValueCallback<A> valueCallback, @Nullable A valueCallbackValue) {
super(Collections.emptyList());
setValueCallback(valueCallback);
this.valueCallbackValue = valueCallbackValue;
}
@Override public void setProgress(float progress) {
this.progress = progress;
}
/**
* If this doesn't return 1, then {@link #setProgress(float)} will always clamp the progress
* to 0.
*/
@Override float getEndProgress() {
return 1f;
}
@Override public void notifyListeners() {
if (this.valueCallback != null) {
super.notifyListeners();
}
}
@Override public A getValue() {
//noinspection ConstantConditions
return valueCallback.getValueInternal(0f, 0f, valueCallbackValue, valueCallbackValue, getProgress(), getProgress(), getProgress());
}
@Override A getValue(Keyframe<K> keyframe, float keyframeProgress) {
return getValue();
}
}
| 2,490 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/package-info.java | @RestrictTo(LIBRARY)
package com.airbnb.lottie.animation.keyframe;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import androidx.annotation.RestrictTo; | 2,491 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/ScaleKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.Keyframe;
import com.airbnb.lottie.value.ScaleXY;
import java.util.List;
public class ScaleKeyframeAnimation extends KeyframeAnimation<ScaleXY> {
private final ScaleXY scaleXY = new ScaleXY();
public ScaleKeyframeAnimation(List<Keyframe<ScaleXY>> keyframes) {
super(keyframes);
}
@Override public ScaleXY getValue(Keyframe<ScaleXY> keyframe, float keyframeProgress) {
if (keyframe.startValue == null || keyframe.endValue == null) {
throw new IllegalStateException("Missing values for keyframe.");
}
ScaleXY startTransform = keyframe.startValue;
ScaleXY endTransform = keyframe.endValue;
if (valueCallback != null) {
//noinspection ConstantConditions
ScaleXY value = valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame,
startTransform, endTransform,
keyframeProgress, getLinearCurrentKeyframeProgress(), getProgress());
if (value != null) {
return value;
}
}
scaleXY.set(
MiscUtils.lerp(startTransform.getScaleX(), endTransform.getScaleX(), keyframeProgress),
MiscUtils.lerp(startTransform.getScaleY(), endTransform.getScaleY(), keyframeProgress)
);
return scaleXY;
}
}
| 2,492 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/animation/keyframe/IntegerKeyframeAnimation.java | package com.airbnb.lottie.animation.keyframe;
import com.airbnb.lottie.utils.MiscUtils;
import com.airbnb.lottie.value.Keyframe;
import java.util.List;
public class IntegerKeyframeAnimation extends KeyframeAnimation<Integer> {
public IntegerKeyframeAnimation(List<Keyframe<Integer>> keyframes) {
super(keyframes);
}
@Override
Integer getValue(Keyframe<Integer> keyframe, float keyframeProgress) {
return getIntValue(keyframe, keyframeProgress);
}
/**
* Optimization to avoid autoboxing.
*/
int getIntValue(Keyframe<Integer> keyframe, float keyframeProgress) {
if (keyframe.startValue == null || keyframe.endValue == null) {
throw new IllegalStateException("Missing values for keyframe.");
}
if (valueCallback != null) {
//noinspection ConstantConditions
Integer value = valueCallback.getValueInternal(keyframe.startFrame, keyframe.endFrame,
keyframe.startValue, keyframe.endValue,
keyframeProgress, getLinearCurrentKeyframeProgress(), getProgress());
if (value != null) {
return value;
}
}
return MiscUtils.lerp(keyframe.getStartValueInt(), keyframe.getEndValueInt(), keyframeProgress);
}
/**
* Optimization to avoid autoboxing.
*/
public int getIntValue() {
return getIntValue(getCurrentKeyframe(), getInterpolatedCurrentKeyframeProgress());
}
}
| 2,493 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/BaseLottieAnimator.java | package com.airbnb.lottie.utils;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.os.Build;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public abstract class BaseLottieAnimator extends ValueAnimator {
private final Set<ValueAnimator.AnimatorUpdateListener> updateListeners = new CopyOnWriteArraySet<>();
private final Set<AnimatorListener> listeners = new CopyOnWriteArraySet<>();
private final Set<Animator.AnimatorPauseListener> pauseListeners = new CopyOnWriteArraySet<>();
@Override public long getStartDelay() {
throw new UnsupportedOperationException("LottieAnimator does not support getStartDelay.");
}
@Override public void setStartDelay(long startDelay) {
throw new UnsupportedOperationException("LottieAnimator does not support setStartDelay.");
}
@Override public ValueAnimator setDuration(long duration) {
throw new UnsupportedOperationException("LottieAnimator does not support setDuration.");
}
@Override public void setInterpolator(TimeInterpolator value) {
throw new UnsupportedOperationException("LottieAnimator does not support setInterpolator.");
}
public void addUpdateListener(ValueAnimator.AnimatorUpdateListener listener) {
updateListeners.add(listener);
}
public void removeUpdateListener(ValueAnimator.AnimatorUpdateListener listener) {
updateListeners.remove(listener);
}
public void removeAllUpdateListeners() {
updateListeners.clear();
}
public void addListener(Animator.AnimatorListener listener) {
listeners.add(listener);
}
public void removeListener(Animator.AnimatorListener listener) {
listeners.remove(listener);
}
public void removeAllListeners() {
listeners.clear();
}
void notifyStart(boolean isReverse) {
for (Animator.AnimatorListener listener : listeners) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
listener.onAnimationStart(this, isReverse);
} else {
listener.onAnimationStart(this);
}
}
}
@Override public void addPauseListener(AnimatorPauseListener listener) {
pauseListeners.add(listener);
}
@Override public void removePauseListener(AnimatorPauseListener listener) {
pauseListeners.remove(listener);
}
void notifyRepeat() {
for (Animator.AnimatorListener listener : listeners) {
listener.onAnimationRepeat(this);
}
}
void notifyEnd(boolean isReverse) {
for (Animator.AnimatorListener listener : listeners) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
listener.onAnimationEnd(this, isReverse);
} else {
listener.onAnimationEnd(this);
}
}
}
void notifyCancel() {
for (Animator.AnimatorListener listener : listeners) {
listener.onAnimationCancel(this);
}
}
void notifyUpdate() {
for (ValueAnimator.AnimatorUpdateListener listener : updateListeners) {
listener.onAnimationUpdate(this);
}
}
void notifyPause() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
for (AnimatorPauseListener pauseListener : pauseListeners) {
pauseListener.onAnimationPause(this);
}
}
}
void notifyResume() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
for (AnimatorPauseListener pauseListener : pauseListeners) {
pauseListener.onAnimationResume(this);
}
}
}
}
| 2,494 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/LottieValueAnimator.java | package com.airbnb.lottie.utils;
import android.animation.ValueAnimator;
import android.view.Choreographer;
import androidx.annotation.FloatRange;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieComposition;
/**
* This is a slightly modified {@link ValueAnimator} that allows us to update start and end values
* easily optimizing for the fact that we know that it's a value animator with 2 floats.
*/
public class LottieValueAnimator extends BaseLottieAnimator implements Choreographer.FrameCallback {
private float speed = 1f;
private boolean speedReversedForRepeatMode = false;
private long lastFrameTimeNs = 0;
private float frameRaw = 0;
private float frame = 0;
private int repeatCount = 0;
private float minFrame = Integer.MIN_VALUE;
private float maxFrame = Integer.MAX_VALUE;
@Nullable private LottieComposition composition;
@VisibleForTesting protected boolean running = false;
private boolean useCompositionFrameRate = false;
public LottieValueAnimator() {
}
/**
* Returns a float representing the current value of the animation from 0 to 1
* regardless of the animation speed, direction, or min and max frames.
*/
@Override public Object getAnimatedValue() {
return getAnimatedValueAbsolute();
}
/**
* Returns the current value of the animation from 0 to 1 regardless
* of the animation speed, direction, or min and max frames.
*/
@FloatRange(from = 0f, to = 1f) public float getAnimatedValueAbsolute() {
if (composition == null) {
return 0;
}
return (frame - composition.getStartFrame()) / (composition.getEndFrame() - composition.getStartFrame());
}
/**
* Returns the current value of the currently playing animation taking into
* account direction, min and max frames.
*/
@Override @FloatRange(from = 0f, to = 1f) public float getAnimatedFraction() {
if (composition == null) {
return 0;
}
if (isReversed()) {
return (getMaxFrame() - frame) / (getMaxFrame() - getMinFrame());
} else {
return (frame - getMinFrame()) / (getMaxFrame() - getMinFrame());
}
}
@Override public long getDuration() {
return composition == null ? 0 : (long) composition.getDuration();
}
public float getFrame() {
return frame;
}
@Override public boolean isRunning() {
return running;
}
public void setUseCompositionFrameRate(boolean useCompositionFrameRate) {
this.useCompositionFrameRate = useCompositionFrameRate;
}
@Override public void doFrame(long frameTimeNanos) {
postFrameCallback();
if (composition == null || !isRunning()) {
return;
}
L.beginSection("LottieValueAnimator#doFrame");
long timeSinceFrame = lastFrameTimeNs == 0 ? 0 : frameTimeNanos - lastFrameTimeNs;
float frameDuration = getFrameDurationNs();
float dFrames = timeSinceFrame / frameDuration;
float newFrameRaw = frameRaw + (isReversed() ? -dFrames : dFrames);
boolean ended = !MiscUtils.contains(newFrameRaw, getMinFrame(), getMaxFrame());
float previousFrameRaw = frameRaw;
frameRaw = MiscUtils.clamp(newFrameRaw, getMinFrame(), getMaxFrame());
frame = useCompositionFrameRate ? (float) Math.floor(frameRaw) : frameRaw;
lastFrameTimeNs = frameTimeNanos;
if (!useCompositionFrameRate || frameRaw != previousFrameRaw) {
notifyUpdate();
}
if (ended) {
if (getRepeatCount() != INFINITE && repeatCount >= getRepeatCount()) {
frameRaw = speed < 0 ? getMinFrame() : getMaxFrame();
frame = frameRaw;
removeFrameCallback();
notifyEnd(isReversed());
} else {
notifyRepeat();
repeatCount++;
if (getRepeatMode() == REVERSE) {
speedReversedForRepeatMode = !speedReversedForRepeatMode;
reverseAnimationSpeed();
} else {
frameRaw = isReversed() ? getMaxFrame() : getMinFrame();
frame = frameRaw;
}
lastFrameTimeNs = frameTimeNanos;
}
}
verifyFrame();
L.endSection("LottieValueAnimator#doFrame");
}
private float getFrameDurationNs() {
if (composition == null) {
return Float.MAX_VALUE;
}
return Utils.SECOND_IN_NANOS / composition.getFrameRate() / Math.abs(speed);
}
public void clearComposition() {
this.composition = null;
minFrame = Integer.MIN_VALUE;
maxFrame = Integer.MAX_VALUE;
}
public void setComposition(LottieComposition composition) {
// Because the initial composition is loaded async, the first min/max frame may be set
boolean keepMinAndMaxFrames = this.composition == null;
this.composition = composition;
if (keepMinAndMaxFrames) {
setMinAndMaxFrames(
Math.max(this.minFrame, composition.getStartFrame()),
Math.min(this.maxFrame, composition.getEndFrame())
);
} else {
setMinAndMaxFrames((int) composition.getStartFrame(), (int) composition.getEndFrame());
}
float frame = this.frame;
this.frame = 0f;
this.frameRaw = 0f;
setFrame((int) frame);
notifyUpdate();
}
public void setFrame(float frame) {
if (this.frameRaw == frame) {
return;
}
this.frameRaw = MiscUtils.clamp(frame, getMinFrame(), getMaxFrame());
this.frame = useCompositionFrameRate ? ((float) Math.floor(frameRaw)) : frameRaw;
lastFrameTimeNs = 0;
notifyUpdate();
}
public void setMinFrame(int minFrame) {
setMinAndMaxFrames(minFrame, (int) maxFrame);
}
public void setMaxFrame(float maxFrame) {
setMinAndMaxFrames(minFrame, maxFrame);
}
public void setMinAndMaxFrames(float minFrame, float maxFrame) {
if (minFrame > maxFrame) {
throw new IllegalArgumentException(String.format("minFrame (%s) must be <= maxFrame (%s)", minFrame, maxFrame));
}
float compositionMinFrame = composition == null ? -Float.MAX_VALUE : composition.getStartFrame();
float compositionMaxFrame = composition == null ? Float.MAX_VALUE : composition.getEndFrame();
float newMinFrame = MiscUtils.clamp(minFrame, compositionMinFrame, compositionMaxFrame);
float newMaxFrame = MiscUtils.clamp(maxFrame, compositionMinFrame, compositionMaxFrame);
if (newMinFrame != this.minFrame || newMaxFrame != this.maxFrame) {
this.minFrame = newMinFrame;
this.maxFrame = newMaxFrame;
setFrame((int) MiscUtils.clamp(frame, newMinFrame, newMaxFrame));
}
}
public void reverseAnimationSpeed() {
setSpeed(-getSpeed());
}
public void setSpeed(float speed) {
this.speed = speed;
}
/**
* Returns the current speed. This will be affected by repeat mode REVERSE.
*/
public float getSpeed() {
return speed;
}
@Override public void setRepeatMode(int value) {
super.setRepeatMode(value);
if (value != REVERSE && speedReversedForRepeatMode) {
speedReversedForRepeatMode = false;
reverseAnimationSpeed();
}
}
@MainThread
public void playAnimation() {
running = true;
notifyStart(isReversed());
setFrame((int) (isReversed() ? getMaxFrame() : getMinFrame()));
lastFrameTimeNs = 0;
repeatCount = 0;
postFrameCallback();
}
@MainThread
public void endAnimation() {
removeFrameCallback();
notifyEnd(isReversed());
}
@MainThread
public void pauseAnimation() {
removeFrameCallback();
notifyPause();
}
@MainThread
public void resumeAnimation() {
running = true;
postFrameCallback();
lastFrameTimeNs = 0;
if (isReversed() && getFrame() == getMinFrame()) {
setFrame(getMaxFrame());
} else if (!isReversed() && getFrame() == getMaxFrame()) {
setFrame(getMinFrame());
}
notifyResume();
}
@MainThread
@Override public void cancel() {
notifyCancel();
removeFrameCallback();
}
private boolean isReversed() {
return getSpeed() < 0;
}
public float getMinFrame() {
if (composition == null) {
return 0;
}
return minFrame == Integer.MIN_VALUE ? composition.getStartFrame() : minFrame;
}
public float getMaxFrame() {
if (composition == null) {
return 0;
}
return maxFrame == Integer.MAX_VALUE ? composition.getEndFrame() : maxFrame;
}
@Override void notifyCancel() {
super.notifyCancel();
notifyEnd(isReversed());
}
protected void postFrameCallback() {
if (isRunning()) {
removeFrameCallback(false);
Choreographer.getInstance().postFrameCallback(this);
}
}
@MainThread
protected void removeFrameCallback() {
this.removeFrameCallback(true);
}
@MainThread
protected void removeFrameCallback(boolean stopRunning) {
Choreographer.getInstance().removeFrameCallback(this);
if (stopRunning) {
running = false;
}
}
private void verifyFrame() {
if (composition == null) {
return;
}
if (frame < minFrame || frame > maxFrame) {
throw new IllegalStateException(String.format("Frame must be [%f,%f]. It is %f", minFrame, maxFrame, frame));
}
}
}
| 2,495 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/Logger.java | package com.airbnb.lottie.utils;
import com.airbnb.lottie.LottieLogger;
/**
* Singleton object for logging. If you want to provide a custom logger implementation,
* implements LottieLogger interface in a custom class and replace Logger.instance
*/
public class Logger {
private static LottieLogger INSTANCE = new LogcatLogger();
public static void setInstance(LottieLogger instance) {
Logger.INSTANCE = instance;
}
public static void debug(String message) {
INSTANCE.debug(message);
}
public static void debug(String message, Throwable exception) {
INSTANCE.debug(message, exception);
}
public static void warning(String message) {
INSTANCE.warning(message);
}
public static void warning(String message, Throwable exception) {
INSTANCE.warning(message, exception);
}
public static void error(String message, Throwable exception) {
INSTANCE.error(message, exception);
}
}
| 2,496 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/MeanCalculator.java | package com.airbnb.lottie.utils;
/**
* Class to calculate the average in a stream of numbers on a continuous basis.
*/
public class MeanCalculator {
private float sum;
private int n;
public void add(float number) {
sum += number;
n++;
if (n == Integer.MAX_VALUE) {
sum /= 2f;
n /= 2;
}
}
public float getMean() {
if (n == 0) {
return 0;
}
return sum / (float) n;
}
}
| 2,497 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/LottieTrace.java | package com.airbnb.lottie.utils;
import androidx.core.os.TraceCompat;
public class LottieTrace {
private static final int MAX_DEPTH = 5;
private final String[] sections = new String[MAX_DEPTH];
private final long[] startTimeNs = new long[MAX_DEPTH];
private int traceDepth = 0;
private int depthPastMaxDepth = 0;
public void beginSection(String section) {
if (traceDepth == MAX_DEPTH) {
depthPastMaxDepth++;
return;
}
sections[traceDepth] = section;
startTimeNs[traceDepth] = System.nanoTime();
//noinspection deprecation
TraceCompat.beginSection(section);
traceDepth++;
}
public float endSection(String section) {
if (depthPastMaxDepth > 0) {
depthPastMaxDepth--;
return 0;
}
traceDepth--;
if (traceDepth == -1) {
throw new IllegalStateException("Can't end trace section. There are none.");
}
if (!section.equals(sections[traceDepth])) {
throw new IllegalStateException("Unbalanced trace call " + section +
". Expected " + sections[traceDepth] + ".");
}
//noinspection deprecation
TraceCompat.endSection();
return (System.nanoTime() - startTimeNs[traceDepth]) / 1000000f;
}
}
| 2,498 |
0 | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie | Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/Utils.java | package com.airbnb.lottie.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import android.provider.Settings;
import androidx.annotation.Nullable;
import com.airbnb.lottie.L;
import com.airbnb.lottie.animation.LPaint;
import com.airbnb.lottie.animation.content.TrimPathContent;
import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation;
import java.io.Closeable;
import java.io.InterruptedIOException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.nio.channels.ClosedChannelException;
import javax.net.ssl.SSLException;
public final class Utils {
public static final int SECOND_IN_NANOS = 1000000000;
/**
* Wrap in Local Thread is necessary for prevent race condition in multi-threaded mode
*/
private static final ThreadLocal<PathMeasure> threadLocalPathMeasure = new ThreadLocal<PathMeasure>() {
@Override
protected PathMeasure initialValue() {
return new PathMeasure();
}
};
private static final ThreadLocal<Path> threadLocalTempPath = new ThreadLocal<Path>() {
@Override
protected Path initialValue() {
return new Path();
}
};
private static final ThreadLocal<Path> threadLocalTempPath2 = new ThreadLocal<Path>() {
@Override
protected Path initialValue() {
return new Path();
}
};
private static final ThreadLocal<float[]> threadLocalPoints = new ThreadLocal<float[]>() {
@Override
protected float[] initialValue() {
return new float[4];
}
};
private static final float INV_SQRT_2 = (float) (Math.sqrt(2) / 2.0);
private Utils() {
}
public static Path createPath(PointF startPoint, PointF endPoint, PointF cp1, PointF cp2) {
Path path = new Path();
path.moveTo(startPoint.x, startPoint.y);
if (cp1 != null && cp2 != null && (cp1.length() != 0 || cp2.length() != 0)) {
path.cubicTo(
startPoint.x + cp1.x, startPoint.y + cp1.y,
endPoint.x + cp2.x, endPoint.y + cp2.y,
endPoint.x, endPoint.y);
} else {
path.lineTo(endPoint.x, endPoint.y);
}
return path;
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
// Ignore.
}
}
}
public static float getScale(Matrix matrix) {
final float[] points = threadLocalPoints.get();
points[0] = 0;
points[1] = 0;
// Use 1/sqrt(2) so that the hypotenuse is of length 1.
points[2] = INV_SQRT_2;
points[3] = INV_SQRT_2;
matrix.mapPoints(points);
float dx = points[2] - points[0];
float dy = points[3] - points[1];
return (float) Math.hypot(dx, dy);
}
public static boolean hasZeroScaleAxis(Matrix matrix) {
final float[] points = threadLocalPoints.get();
points[0] = 0;
points[1] = 0;
// Random numbers. The only way these should map to the same thing as 0,0 is if the scale is 0.
points[2] = 37394.729378f;
points[3] = 39575.2343807f;
matrix.mapPoints(points);
return points[0] == points[2] || points[1] == points[3];
}
public static void applyTrimPathIfNeeded(Path path, @Nullable TrimPathContent trimPath) {
if (trimPath == null || trimPath.isHidden()) {
return;
}
float start = ((FloatKeyframeAnimation) trimPath.getStart()).getFloatValue();
float end = ((FloatKeyframeAnimation) trimPath.getEnd()).getFloatValue();
float offset = ((FloatKeyframeAnimation) trimPath.getOffset()).getFloatValue();
applyTrimPathIfNeeded(path, start / 100f, end / 100f, offset / 360f);
}
public static void applyTrimPathIfNeeded(
Path path, float startValue, float endValue, float offsetValue) {
L.beginSection("applyTrimPathIfNeeded");
final PathMeasure pathMeasure = threadLocalPathMeasure.get();
final Path tempPath = threadLocalTempPath.get();
final Path tempPath2 = threadLocalTempPath2.get();
pathMeasure.setPath(path, false);
float length = pathMeasure.getLength();
if (startValue == 1f && endValue == 0f) {
L.endSection("applyTrimPathIfNeeded");
return;
}
if (length < 1f || Math.abs(endValue - startValue - 1) < .01) {
L.endSection("applyTrimPathIfNeeded");
return;
}
float start = length * startValue;
float end = length * endValue;
float newStart = Math.min(start, end);
float newEnd = Math.max(start, end);
float offset = offsetValue * length;
newStart += offset;
newEnd += offset;
// If the trim path has rotated around the path, we need to shift it back.
if (newStart >= length && newEnd >= length) {
newStart = MiscUtils.floorMod(newStart, length);
newEnd = MiscUtils.floorMod(newEnd, length);
}
if (newStart < 0) {
newStart = MiscUtils.floorMod(newStart, length);
}
if (newEnd < 0) {
newEnd = MiscUtils.floorMod(newEnd, length);
}
// If the start and end are equals, return an empty path.
if (newStart == newEnd) {
path.reset();
L.endSection("applyTrimPathIfNeeded");
return;
}
if (newStart >= newEnd) {
newStart -= length;
}
tempPath.reset();
pathMeasure.getSegment(
newStart,
newEnd,
tempPath,
true);
if (newEnd > length) {
tempPath2.reset();
pathMeasure.getSegment(
0,
newEnd % length,
tempPath2,
true);
tempPath.addPath(tempPath2);
} else if (newStart < 0) {
tempPath2.reset();
pathMeasure.getSegment(
length + newStart,
length,
tempPath2,
true);
tempPath.addPath(tempPath2);
}
path.set(tempPath);
L.endSection("applyTrimPathIfNeeded");
}
@SuppressWarnings("SameParameterValue")
public static boolean isAtLeastVersion(int major, int minor, int patch, int minMajor, int minMinor, int
minPatch) {
if (major < minMajor) {
return false;
} else if (major > minMajor) {
return true;
}
if (minor < minMinor) {
return false;
} else if (minor > minMinor) {
return true;
}
return patch >= minPatch;
}
public static int hashFor(float a, float b, float c, float d) {
int result = 17;
if (a != 0) {
result = (int) (31 * result * a);
}
if (b != 0) {
result = (int) (31 * result * b);
}
if (c != 0) {
result = (int) (31 * result * c);
}
if (d != 0) {
result = (int) (31 * result * d);
}
return result;
}
public static float dpScale() {
return Resources.getSystem().getDisplayMetrics().density;
}
public static float getAnimationScale(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getFloat(context.getContentResolver(),
Settings.Global.ANIMATOR_DURATION_SCALE, 1.0f);
} else {
//noinspection deprecation
return Settings.System.getFloat(context.getContentResolver(),
Settings.System.ANIMATOR_DURATION_SCALE, 1.0f);
}
}
/**
* Resize the bitmap to exactly the same size as the specified dimension, changing the aspect ratio if needed.
* Returns the original bitmap if the dimensions already match.
*/
public static Bitmap resizeBitmapIfNeeded(Bitmap bitmap, int width, int height) {
if (bitmap.getWidth() == width && bitmap.getHeight() == height) {
return bitmap;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
bitmap.recycle();
return resizedBitmap;
}
/**
* From http://vaibhavblogs.org/2012/12/common-java-networking-exceptions/
*/
public static boolean isNetworkException(Throwable e) {
return e instanceof SocketException || e instanceof ClosedChannelException ||
e instanceof InterruptedIOException || e instanceof ProtocolException ||
e instanceof SSLException || e instanceof UnknownHostException ||
e instanceof UnknownServiceException;
}
public static void saveLayerCompat(Canvas canvas, RectF rect, Paint paint) {
saveLayerCompat(canvas, rect, paint, Canvas.ALL_SAVE_FLAG);
}
public static void saveLayerCompat(Canvas canvas, RectF rect, Paint paint, int flag) {
L.beginSection("Utils#saveLayer");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// This method was deprecated in API level 26 and not recommended since 22, but its
// 2-parameter replacement is only available starting at API level 21.
canvas.saveLayer(rect, paint, flag);
} else {
canvas.saveLayer(rect, paint);
}
L.endSection("Utils#saveLayer");
}
/**
* For testing purposes only. DO NOT USE IN PRODUCTION.
*/
@SuppressWarnings("unused")
public static Bitmap renderPath(Path path) {
RectF bounds = new RectF();
path.computeBounds(bounds, false);
Bitmap bitmap = Bitmap.createBitmap((int) bounds.right, (int) bounds.bottom, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new LPaint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
canvas.drawPath(path, paint);
return bitmap;
}
}
| 2,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.